diff --git a/.github/javadoc/javadoc-footer.html b/.github/javadoc/javadoc-footer.html new file mode 100644 index 000000000..487326dfc --- /dev/null +++ b/.github/javadoc/javadoc-footer.html @@ -0,0 +1,44 @@ + diff --git a/.github/javadoc/javadoc-header.html b/.github/javadoc/javadoc-header.html new file mode 100644 index 000000000..782ae85db --- /dev/null +++ b/.github/javadoc/javadoc-header.html @@ -0,0 +1,11 @@ +
+ +
+ CustomNPC+ + Javadoc Reference +
+
+ + Back to Index + +
diff --git a/.github/javadoc/javadoc-theme.css b/.github/javadoc/javadoc-theme.css new file mode 100644 index 000000000..d7ceb8275 --- /dev/null +++ b/.github/javadoc/javadoc-theme.css @@ -0,0 +1,954 @@ +/* ============================================================ + CustomNPC+ — Javadoc Theme (Javadoc 11) + Tokyo Night — Styled Edition + ============================================================ */ + +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap'); + +:root { + /* ── Tokyo Night palette ── */ + --bg: #1a1b26; + --bg2: #1f2335; + --bg3: #24283b; + --bg-elevated: #292e42; + --border: #3b4261; + --border2: #414868; + --text: #c0caf5; + --text-mid: #a9b1d6; + --text-dim: #565f89; + --green: #9ece6a; + --green-dim: rgba(158, 206, 106, 0.12); + --blue: #7aa2f7; + --blue-dim: rgba(122, 162, 247, 0.12); + --amber: #e0af68; + --amber-dim: rgba(224, 175, 104, 0.10); + --purple: #bb9af7; + --purple-dim: rgba(187, 154, 247, 0.10); + --cyan: #7dcfff; + --cyan-dim: rgba(125, 207, 255, 0.10); + --red: #f7768e; + --highlight-bg: rgba(122, 162, 247, 0.08); + --hover-bg: rgba(187, 154, 247, 0.08); + --nav-h: 44px; + --subnav-h: 36px; + + /* ── Font stacks ── */ + --font-ui: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + --font-mono: 'JetBrains Mono', 'Cascadia Code', 'Fira Code', monospace; +} + +* { box-sizing: border-box !important; } + +html, body { + height: 100%; +} + +body { + background: var(--bg) !important; + color: var(--text) !important; + font-family: var(--font-mono) !important; + font-size: 13px !important; + line-height: 1.6 !important; + margin: 0 !important; + padding: 0 !important; + min-height: 100vh !important; + display: flex !important; + flex-direction: column !important; +} + +.skipNav { display: none !important; } + +/* ══════════════════════════════════════════════ + NAVIGATION + ══════════════════════════════════════════════ */ + +.fixedNav { + position: fixed !important; + top: 0 !important; left: 0 !important; right: 0 !important; + z-index: 100 !important; +} + +/* Top bar — gradient accent stripe on top */ +.topNav { + position: relative !important; + background: var(--bg2) !important; + border-bottom: 1px solid var(--border) !important; + height: var(--nav-h) !important; + margin: 0 !important; padding: 0 !important; + display: flex !important; + align-items: stretch !important; + overflow: visible !important; +} + +/* Gradient accent line across the very top */ +.topNav::before { + content: '' !important; + position: absolute !important; + top: 0 !important; left: 0 !important; right: 0 !important; + height: 2px !important; + background: linear-gradient(90deg, var(--blue), var(--purple), var(--cyan)) !important; + z-index: 10 !important; +} + +/* Nav list — leave room on right for brand */ +.topNav > ul.navList { + list-style: none !important; + margin: 0 !important; + padding: 2px 0 0 8px !important; + padding-right: 320px !important; + display: flex !important; + align-items: stretch !important; + flex-shrink: 0 !important; +} + +.topNav > ul.navList > li { + display: flex !important; + align-items: center !important; + margin: 0 !important; + padding: 0 16px !important; + height: var(--nav-h) !important; + font-family: var(--font-ui) !important; + font-size: 12px !important; + font-weight: 500 !important; + white-space: nowrap !important; + text-transform: none !important; + letter-spacing: 0.01em !important; + color: var(--text-dim) !important; + border-bottom: 2px solid transparent !important; + transition: color 0.2s !important; +} + +.topNav > ul.navList > li > a { + display: flex !important; + align-items: center !important; + height: var(--nav-h) !important; + margin: 0 -16px !important; + padding: 0 16px !important; + color: var(--text-dim) !important; + font-family: var(--font-ui) !important; + font-size: 12px !important; + font-weight: 500 !important; + text-decoration: none !important; + text-transform: none !important; + letter-spacing: 0.01em !important; + white-space: nowrap !important; + border-bottom: 2px solid transparent !important; + transition: color 0.2s, border-color 0.2s !important; +} + +.topNav > ul.navList > li > a:hover { + color: var(--text) !important; + border-bottom-color: var(--purple) !important; + background: transparent !important; + text-shadow: none !important; + text-decoration: none !important; +} + +/* Active item — gradient underline */ +.topNav > ul.navList > li.navBarCell1Rev { + color: var(--text) !important; + border-image: linear-gradient(90deg, var(--blue), var(--purple)) 1 !important; + border-bottom-width: 2px !important; + border-bottom-style: solid !important; +} + +/* ── Brand — pinned to far right of topNav ── */ +.topNav > .aboutLanguage { + position: absolute !important; + top: 0 !important; right: 0 !important; + height: var(--nav-h) !important; + display: flex !important; + align-items: center !important; + gap: 12px !important; + padding: 0 16px !important; + background: var(--bg2) !important; + border-left: 1px solid var(--border) !important; + z-index: 5 !important; +} + +/* Hide the duplicate in bottom nav */ +.bottomNav > .aboutLanguage, +.bottomNav .aboutLanguage { + display: none !important; +} + +#javadoc-header { + display: flex !important; + align-items: center !important; + gap: 12px !important; +} + +.header-brand { text-decoration: none !important; } + +/* Brand title — gradient text */ +.header-title { + font-family: var(--font-ui) !important; + font-size: 14px !important; + font-weight: 700 !important; + background: linear-gradient(135deg, var(--blue), var(--purple)) !important; + -webkit-background-clip: text !important; + -webkit-text-fill-color: transparent !important; + background-clip: text !important; + line-height: 1.4 !important; + white-space: nowrap !important; +} + +.header-title span { + display: block !important; + font-family: var(--font-mono) !important; + font-size: 9px !important; + font-weight: 400 !important; + background: none !important; + -webkit-text-fill-color: var(--text-dim) !important; + color: var(--text-dim) !important; + margin-top: 1px !important; + letter-spacing: 0.1em !important; + text-transform: uppercase !important; +} + +.header-back { + display: inline-flex !important; + align-items: center !important; + text-decoration: none !important; + color: var(--text-dim) !important; + font-family: var(--font-ui) !important; + font-size: 11px !important; + font-weight: 500 !important; + padding: 5px 12px !important; + border: 1px solid var(--border2) !important; + border-radius: 6px !important; + white-space: nowrap !important; + transition: all 0.2s !important; +} + +.header-back:hover { + color: var(--text) !important; + border-color: var(--purple) !important; + background: var(--purple-dim) !important; + text-decoration: none !important; + text-shadow: none !important; +} + +/* ── Sub nav ── */ +.subNav { + background: var(--bg3) !important; + border-bottom: 1px solid var(--border) !important; + height: var(--subnav-h) !important; + margin: 0 !important; + padding: 0 14px !important; + display: flex !important; + align-items: center !important; + gap: 12px !important; + overflow: hidden !important; +} + +/* Search first */ +.subNav > ul.navListSearch { + order: -1 !important; +} + +.subNav ul, +.subNav ul.navList, +.subNav ul.subNavList, +.subNav ul.navListSearch { + list-style: none !important; + margin: 0 !important; + padding: 0 !important; + display: flex !important; + align-items: center !important; + gap: 0 !important; +} + +.subNav li { + display: flex !important; + align-items: center !important; + font-family: var(--font-ui) !important; + font-size: 11px !important; + color: var(--text-dim) !important; + padding: 0 6px !important; + white-space: nowrap !important; + border: none !important; + height: auto !important; + text-transform: none !important; +} + +.subNav a { + color: var(--blue) !important; + text-decoration: none !important; + font-size: 11px !important; + font-family: var(--font-ui) !important; + transition: color 0.15s !important; +} + +.subNav a:hover { color: var(--purple) !important; text-shadow: none !important; } + +.subNav label { + font-family: var(--font-ui) !important; + font-size: 11px !important; + color: var(--text-dim) !important; + text-transform: none !important; + margin-right: 4px !important; +} + +/* ══════════════════════════════════════════════ + CONTENT + ══════════════════════════════════════════════ */ + +main { + background: var(--bg) !important; + padding: 28px !important; + flex: 1 0 auto !important; +} + +.contentContainer, div.contentContainer { + background: var(--bg) !important; + padding: 0 28px 0px !important; +} + +.header { + padding: 0 28px 0 !important; + margin-bottom: 20px !important; +} + +/* Subtitle under h1 on help/overview pages */ +.header .subTitle, +div.subTitle { + color: var(--text-mid) !important; + font-family: var(--font-ui) !important; + font-size: 13px !important; + line-height: 1.7 !important; + margin-top: 8px !important; +} + +.packageLabelInType { + font-family: var(--font-mono) !important; + font-size: 11px !important; + color: var(--text-dim) !important; +} + +/* ── Headings ── */ +h1, h2, h3, h4, h5, h6 { + font-family: var(--font-ui) !important; + font-weight: 600 !important; + line-height: 1.5 !important; + text-transform: none !important; + letter-spacing: -0.01em !important; +} + +/* Page title — gradient accent bar */ +h1.title, h2.title { + font-size: 22px !important; + font-weight: 700 !important; + color: var(--text) !important; + border-bottom: none !important; + padding-bottom: 16px !important; + padding-left: 16px !important; + margin-bottom: 24px !important; + margin-top: 0 !important; + border-left: 4px solid transparent !important; + border-image: linear-gradient(180deg, var(--blue), var(--purple)) 1 !important; +} + +/* Section h2 — colored panel */ +section > h2, +li.blockList > section > h2 { + font-size: 14px !important; + color: var(--green) !important; + border-left: 3px solid var(--green) !important; + border-bottom: none !important; + padding: 10px 14px !important; + margin: 0 !important; + background: var(--green-dim) !important; +} + +/* Generic h2 (table section headers like "Method Summary") */ +h2 { + font-size: 14px !important; + color: var(--amber) !important; + border-bottom: none !important; + border-left: 3px solid var(--amber) !important; + padding: 8px 12px !important; + margin-top: 28px !important; + margin-bottom: 12px !important; + background: var(--amber-dim) !important; +} + +/* h3 — table section headers inside blockList */ +h3 { + font-size: 12px !important; + color: var(--text-mid) !important; + margin: 0 !important; + padding: 10px 14px !important; + background: var(--bg3) !important; + border-bottom: 1px solid var(--border) !important; +} + +/* h4 — method detail names */ +h4 { + font-size: 13px !important; + font-weight: 600 !important; + color: var(--cyan) !important; + margin: 0 !important; + padding: 10px 14px !important; + background: var(--bg3) !important; + border-bottom: 1px solid var(--border) !important; + border-left: 3px solid var(--cyan) !important; +} + +/* ── blockList sections — card-like containers ── */ +ul.blockList > li.blockList, +ul.blockListLast > li.blockList { + border: 1px solid var(--border) !important; + border-radius: 6px !important; + margin-bottom: 14px !important; + padding: 0 !important; + background: var(--bg2) !important; + overflow: hidden !important; +} + +/* Help page: section cards with padding around their content */ +ul.blockList > li.blockList > section { + padding: 0 !important; +} + +ul.blockList > li.blockList > section > p, +ul.blockList > li.blockList > section > ul:not(.blockList):not(.blockListLast) { + padding: 14px 18px !important; + margin: 0 !important; + color: var(--text-mid) !important; + font-family: var(--font-ui) !important; + font-size: 13px !important; + line-height: 1.7 !important; +} + +/* Nested lists inside section content */ +ul.blockList > li.blockList > section > ul:not(.blockList):not(.blockListLast) > li { + color: var(--text-mid) !important; + font-family: var(--font-ui) !important; + font-size: 13px !important; + padding: 3px 0 !important; + list-style: none !important; +} + +ul.blockList > li.blockList > section > ul:not(.blockList):not(.blockListLast) > li::before { + content: '\203A' !important; + color: var(--purple) !important; + margin-right: 8px !important; + font-weight: 700 !important; +} + +/* ── Inherited methods block ── */ +ul.blockList > li.blockList > h3, +ul.blockList > li.blockList > ul.blockList > li.blockList > h3 { + font-size: 11px !important; + color: var(--text-dim) !important; + padding: 8px 14px !important; + background: var(--bg3) !important; + border-bottom: 1px solid var(--border) !important; + margin: 0 !important; +} + +/* The comma-separated code block of inherited method names */ +ul.blockList > li.blockList > code, +li.blockList > code { + display: block !important; + padding: 10px 16px !important; + color: var(--text-dim) !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + background: var(--bg) !important; + border: none !important; + line-height: 1.8 !important; +} + +/* ── Inheritance chain ── */ +ul.inheritance { + list-style: none !important; + padding: 0 !important; + margin: 0 0 16px !important; + font-size: 12px !important; + color: var(--text-dim) !important; +} +ul.inheritance li { padding-left: 16px !important; } +ul.inheritance li:first-child { padding-left: 0 !important; } + +/* ── General content lists (help page) ── */ +main ul:not(.blockList):not(.blockListLast):not(.navList):not(.subNavList):not(.navListSearch):not(.inheritance) { + padding-left: 0 !important; + margin: 4px 0 4px 12px !important; + list-style: none !important; +} +main ul:not(.blockList):not(.blockListLast):not(.navList):not(.subNavList):not(.navListSearch):not(.inheritance) > li { + color: var(--text-mid) !important; + font-family: var(--font-ui) !important; + font-size: 13px !important; + padding: 3px 0 !important; + line-height: 1.7 !important; +} +main ul:not(.blockList):not(.blockListLast):not(.navList):not(.subNavList):not(.navListSearch):not(.inheritance) > li::before { + content: '\203A' !important; + color: var(--purple) !important; + margin-right: 8px !important; + font-weight: 700 !important; +} + +/* General paragraphs in content */ +main > div p, .contentContainer p { + color: var(--text-mid) !important; + font-family: var(--font-ui) !important; + font-size: 13px !important; + line-height: 1.7 !important; + margin: 8px 0 !important; +} + +/* Emphasized phrase */ +.emphasizedPhrase { + display: block !important; + color: var(--text-dim) !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + font-style: italic !important; + border-left: 2px solid var(--purple) !important; + padding: 8px 14px !important; + margin-top: 16px !important; + background: var(--purple-dim) !important; + border-radius: 0 4px 4px 0 !important; +} + +/* Bottom footer subNav */ +footer { + /*margin-top: auto;*/ +} +footer .subNav { + background: var(--bg3) !important; + border-top: 1px solid var(--border) !important; + border-bottom: none !important; + height: var(--subnav-h) !important; + padding: 0 14px !important; + display: flex !important; + align-items: center !important; + gap: 12px !important; + overflow: hidden !important; +} + +/* ══════════════════════════════════════════════ + TABLES + ══════════════════════════════════════════════ */ + +table { + width: 100% !important; + border-collapse: collapse !important; + border: 1px solid var(--border) !important; + border-radius: 6px !important; + margin: 16px 0 !important; + font-size: 13px !important; + overflow: hidden !important; +} + +caption { + background: var(--bg3) !important; + padding: 8px 14px !important; + text-align: left !important; + border-bottom: 1px solid var(--border2) !important; + caption-side: top !important; +} + +/* Table tabs — pill style */ +.activeTableTab, .tableTab { + font-family: var(--font-ui) !important; + font-size: 11px !important; + font-weight: 500 !important; + text-transform: none !important; + padding: 4px 12px !important; + border: 1px solid var(--border2) !important; + border-radius: 20px !important; + display: inline-block !important; + margin-right: 6px !important; + cursor: pointer !important; + transition: all 0.2s !important; +} + +.activeTableTab { + color: var(--text) !important; + border-color: var(--blue) !important; + background: var(--blue-dim) !important; +} + +.tableTab { color: var(--text-dim) !important; background: var(--bg3) !important; } +.tableTab a { color: var(--text-dim) !important; text-decoration: none !important; } +.tableTab a:hover { color: var(--text) !important; text-shadow: none !important; } + +/* Column headers */ +th[scope="col"] { + background: var(--bg-elevated) !important; + color: var(--text-dim) !important; + font-family: var(--font-ui) !important; + font-size: 10px !important; + font-weight: 600 !important; + letter-spacing: 0.06em !important; + text-transform: uppercase !important; + padding: 10px 14px !important; + border-bottom: 2px solid var(--border2) !important; + text-align: left !important; +} + +/* Data cells */ +th[scope="row"], td { + background: var(--bg2) !important; + color: var(--text) !important; + padding: 10px 14px !important; + border-bottom: 1px solid var(--border) !important; + vertical-align: top !important; + text-align: left !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + font-weight: 400 !important; + text-transform: none !important; + letter-spacing: 0 !important; + transition: background 0.15s !important; +} + +/* Stronger alternating row contrast */ +tr.altColor > td, tr.altColor > th[scope="row"] { background: var(--bg) !important; } +tr.rowColor > td, tr.rowColor > th[scope="row"] { background: var(--bg2) !important; } + +tr:hover > td, tr:hover > th[scope="row"] { + background: var(--purple-dim) !important; + border-bottom-color: rgba(187, 154, 247, 0.25) !important; +} +tr:hover > td a, tr:hover > th[scope="row"] a { + color: var(--purple) !important; +} + +/* ── Links ── */ +a, a:visited { color: var(--blue) !important; text-decoration: none !important; transition: color 0.15s !important; } +a:hover { color: var(--purple) !important; text-decoration: none !important; } +.memberNameLink a { color: var(--cyan) !important; font-weight: 500 !important; } +.memberNameLink a:hover { color: var(--purple) !important; } +.externalLink { color: var(--blue) !important; } + +/* ── Description blocks ── */ +div.block { + color: var(--text-mid) !important; + font-family: var(--font-ui) !important; + font-size: 13px !important; + line-height: 1.7 !important; + padding: 4px 0 !important; +} +ul.blockList > li.blockList > div.block{ padding: 12px 16px !important; margin: 0 !important; } + +/* ── Method detail ── */ +ul.blockList, ul.blockListLast { list-style: none !important; padding: 0 !important; margin: 0 !important; } +ul.blockList > li.blockList, ul.blockListLast > li.blockList { + border: 1px solid var(--border) !important; + border-radius: 6px !important; + margin-bottom: 12px !important; + padding: 0 !important; + overflow: hidden !important; +} + +/* Method/type signatures — accent left bar */ +pre.methodSignature, pre.typeSignature { + background: var(--bg2) !important; + border: none !important; + border-bottom: 1px solid var(--border) !important; + border-left: 3px solid var(--cyan) !important; + margin: 0 !important; + padding: 14px 18px !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + color: var(--text) !important; + overflow-x: auto !important; + white-space: pre-wrap !important; +} + +pre { + background: var(--bg2) !important; + border: 1px solid var(--border) !important; + border-left: 3px solid var(--blue) !important; + border-radius: 6px !important; + padding: 14px 18px !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + color: var(--text) !important; + overflow-x: auto !important; + margin: 0 !important; + white-space: pre-wrap !important; +} + +code { + font-family: var(--font-mono) !important; + font-size: 12px !important; + color: var(--cyan) !important; + background: var(--bg3) !important; + padding: 2px 6px !important; + border-radius: 4px !important; +} + +dl { padding: 12px 16px !important; margin: 0 !important; } +dt { margin-bottom: 4px !important; } +dd { margin: 0 0 8px 16px !important; color: var(--text-mid) !important; font-size: 12px !important; } + +.paramLabel, .returnLabel, .throwsLabel, .seeLabel, .simpleTagLabel { + font-family: var(--font-ui) !important; + font-size: 10px !important; + font-weight: 600 !important; + color: var(--purple) !important; + text-transform: uppercase !important; + letter-spacing: 0.06em !important; +} + +.typeNameLabel { color: var(--cyan) !important; } + +.deprecationBlock { + background: var(--amber-dim) !important; + border-left: 3px solid var(--amber) !important; + border-radius: 0 6px 6px 0 !important; + padding: 10px 14px !important; + color: var(--amber) !important; + font-size: 12px !important; +} + +/* ── Inputs ── */ +input[type="text"] { + background: var(--bg) !important; + border: 1px solid var(--border2) !important; + color: var(--text) !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + padding: 5px 12px !important; + outline: none !important; + border-radius: 6px !important; + transition: border-color 0.2s, box-shadow 0.2s !important; +} +input[type="text"]:focus { + border-color: var(--blue) !important; + box-shadow: 0 0 0 2px var(--blue-dim) !important; +} +input[type="reset"] { + background: var(--bg3) !important; + border: 1px solid var(--border2) !important; + color: var(--text-dim) !important; + font-family: var(--font-ui) !important; + font-size: 11px !important; + padding: 5px 12px !important; + cursor: pointer !important; + border-radius: 6px !important; + transition: all 0.2s !important; +} +input[type="reset"]:hover { + border-color: var(--text-dim) !important; + color: var(--text-mid) !important; +} + +/* ══════════════════════════════════════════════ + BOTTOM NAV + ══════════════════════════════════════════════ */ + +.bottomNav { + background: var(--bg2) !important; + border-top: 1px solid var(--border) !important; + min-height: var(--nav-h) !important; + padding: 0 !important; + margin-top: 32px !important; + overflow: hidden !important; + position: relative !important; +} + +/* Gradient accent line on bottom nav too */ +.bottomNav::after { + content: '' !important; + position: absolute !important; + bottom: 0 !important; left: 0 !important; right: 0 !important; + height: 2px !important; + background: linear-gradient(90deg, var(--blue), var(--purple), var(--cyan)) !important; +} + +.bottomNav ul.navList[title="Navigation"] { + list-style: none !important; + margin: 0 !important; + padding: 0 0 0 8px !important; + display: flex !important; + align-items: stretch !important; + height: var(--nav-h) !important; +} + +.bottomNav ul.navList[title="Navigation"] li { + display: flex !important; + align-items: center !important; + margin: 0 !important; + padding: 0 16px !important; + height: var(--nav-h) !important; + font-family: var(--font-ui) !important; + font-size: 12px !important; + font-weight: 500 !important; + white-space: nowrap !important; + text-transform: none !important; + letter-spacing: 0.01em !important; + color: var(--text-dim) !important; + border-top: 2px solid transparent !important; + transition: color 0.2s !important; +} + +.bottomNav ul.navList[title="Navigation"] li > a { + display: flex !important; + align-items: center !important; + height: var(--nav-h) !important; + margin: 0 -16px !important; + padding: 0 16px !important; + color: var(--text-dim) !important; + text-decoration: none !important; + font-family: var(--font-ui) !important; + font-size: 12px !important; + font-weight: 500 !important; + transition: color 0.2s !important; +} + +.bottomNav ul.navList[title="Navigation"] li > a:hover { + color: var(--text) !important; + text-shadow: none !important; +} + +.bottomNav ul.navList[title="Navigation"] li.navBarCell1Rev { + color: var(--text) !important; + border-image: linear-gradient(90deg, var(--blue), var(--purple)) 1 !important; + border-top-width: 2px !important; + border-top-style: solid !important; +} + +.bottomNav .aboutLanguage { + display: none !important; +} + +.legalCopy { + background: var(--bg2) !important; + color: var(--text-dim) !important; + font-size: 11px !important; + font-family: var(--font-ui) !important; + padding: 14px 18px !important; + text-align: center !important; + border-top: 1px solid var(--border) !important; +} + +/* ══════════════════════════════════════════════ + SEARCH RESULTS DROPDOWN (jQuery UI Autocomplete) + ══════════════════════════════════════════════ */ + +.ui-autocomplete { + background: var(--bg2) !important; + border: 1px solid var(--border2) !important; + border-radius: 8px !important; + max-height: 400px !important; + overflow-y: auto !important; + overflow-x: hidden !important; + z-index: 9999 !important; + list-style: none !important; + padding: 4px 0 !important; + margin: 4px 0 0 !important; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(122, 162, 247, 0.05) !important; +} + +/* Category headers */ +.ui-autocomplete .ui-autocomplete-category { + background: var(--bg-elevated) !important; + color: var(--text-dim) !important; + font-family: var(--font-ui) !important; + font-size: 10px !important; + font-weight: 600 !important; + text-transform: uppercase !important; + letter-spacing: 0.06em !important; + padding: 6px 14px !important; + border-bottom: 1px solid var(--border) !important; + border-top: 1px solid var(--border) !important; + cursor: default !important; +} + +/* Individual result items */ +.ui-autocomplete .ui-menu-item { + background: var(--bg2) !important; + margin: 0 !important; + list-style: none !important; +} + +.ui-autocomplete .ui-menu-item > div, +.ui-autocomplete .ui-menu-item-wrapper { + background: var(--bg2) !important; + color: var(--text) !important; + font-family: var(--font-mono) !important; + font-size: 12px !important; + padding: 7px 14px !important; + border: none !important; + border-left: 2px solid transparent !important; + cursor: pointer !important; + line-height: 1.5 !important; + transition: all 0.1s !important; +} + +/* Hover / focus state */ +.ui-autocomplete .ui-menu-item > div.ui-state-active, +.ui-autocomplete .ui-menu-item > div.ui-state-focus, +.ui-autocomplete .ui-menu-item-wrapper.ui-state-active, +.ui-autocomplete .ui-menu-item-wrapper.ui-state-focus, +.ui-autocomplete .ui-state-active, +.ui-autocomplete .ui-state-focus { + background: var(--purple-dim) !important; + color: var(--text) !important; + border: none !important; + border-left: 2px solid var(--purple) !important; + margin: 0 !important; +} + +/* Highlighted matching text */ +.resultHighlight { + color: var(--cyan) !important; + font-weight: 600 !important; +} + +/* Search tag result extras */ +.searchTagHolderResult { + color: var(--text-dim) !important; + font-size: 11px !important; +} + +.searchTagDescResult { + color: var(--text-dim) !important; + font-size: 11px !important; + font-style: italic !important; +} + +/* "No results found" */ +.ui-autocomplete .ui-menu-item:only-child > div { + color: var(--text-dim) !important; + font-style: italic !important; +} + +/* Override jQuery UI defaults */ +.ui-widget { + font-family: var(--font-mono) !important; +} + +.ui-widget-content { + background: var(--bg2) !important; + color: var(--text) !important; + border-color: var(--border2) !important; +} + +.ui-menu .ui-menu-item { + padding: 0 !important; +} + +/* Watermark style for search input placeholder */ +.watermark { + color: var(--text-dim) !important; +} + +/* ══════════════════════════════════════════════ + MISC + ══════════════════════════════════════════════ */ + +::-webkit-scrollbar { width: 8px; height: 8px; } +::-webkit-scrollbar-track { background: var(--bg); } +::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 4px; } +::-webkit-scrollbar-thumb:hover { background: var(--text-dim); } +::selection { background: rgba(187, 154, 247, 0.25); color: var(--text); } +hr { border: none !important; border-top: 1px solid var(--border) !important; margin: 24px 0 !important; } diff --git a/.github/pages/index.html b/.github/pages/index.html new file mode 100644 index 000000000..5e467c986 --- /dev/null +++ b/.github/pages/index.html @@ -0,0 +1,14 @@ + + + + + + Javadoc Index + + + + +
+ + + diff --git a/.github/pages/package-lock.json b/.github/pages/package-lock.json new file mode 100644 index 000000000..3e8db3276 --- /dev/null +++ b/.github/pages/package-lock.json @@ -0,0 +1,1679 @@ +{ + "name": "javadoc-index", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "javadoc-index", + "version": "1.0.0", + "dependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.2.1", + "vite": "^7.3.1" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", + "dev": true, + "dependencies": { + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", + "dev": true, + "dependencies": { + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.6.tgz", + "integrity": "sha512-xOBvwq86HHdB7WUDTfKfT/Vuxh7gElQ+Sfti2Cy6yIWNW05P8iUslOVcZ4/sKbE+/jQaukQAdz/gf3724kYdqw==", + "dev": true, + "dependencies": { + "@babel/template": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz", + "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==", + "dev": true, + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz", + "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz", + "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz", + "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz", + "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz", + "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz", + "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz", + "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz", + "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz", + "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz", + "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz", + "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz", + "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz", + "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz", + "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz", + "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz", + "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz", + "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz", + "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz", + "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz", + "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz", + "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz", + "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz", + "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz", + "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz", + "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz", + "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz", + "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz", + "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz", + "integrity": "sha512-lIyg0szRfYbiy67j9KN8IyeD7q7hcmqnJ1ddWmNt19ItGpNN64mnllmxUNFIOdOm6by97jlL6wfpTTJrmnjWAA==", + "dev": true, + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001777", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001777.tgz", + "integrity": "sha512-tmN+fJxroPndC74efCdp12j+0rk0RHwV5Jwa1zWaFVyw2ZxAuPeG8ZgWC3Wz7uSjT3qMRQ5XHZ4COgQmsCMJAQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.307", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.307.tgz", + "integrity": "sha512-5z3uFKBWjiNR44nFcYdkcXjKMbg5KXNdciu7mhTPo9tB7NbqSNP2sSnGR+fqknZSCwKkBN+oxiiajWs4dT6ORg==", + "dev": true + }, + "node_modules/esbuild": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz", + "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.3", + "@esbuild/android-arm": "0.27.3", + "@esbuild/android-arm64": "0.27.3", + "@esbuild/android-x64": "0.27.3", + "@esbuild/darwin-arm64": "0.27.3", + "@esbuild/darwin-x64": "0.27.3", + "@esbuild/freebsd-arm64": "0.27.3", + "@esbuild/freebsd-x64": "0.27.3", + "@esbuild/linux-arm": "0.27.3", + "@esbuild/linux-arm64": "0.27.3", + "@esbuild/linux-ia32": "0.27.3", + "@esbuild/linux-loong64": "0.27.3", + "@esbuild/linux-mips64el": "0.27.3", + "@esbuild/linux-ppc64": "0.27.3", + "@esbuild/linux-riscv64": "0.27.3", + "@esbuild/linux-s390x": "0.27.3", + "@esbuild/linux-x64": "0.27.3", + "@esbuild/netbsd-arm64": "0.27.3", + "@esbuild/netbsd-x64": "0.27.3", + "@esbuild/openbsd-arm64": "0.27.3", + "@esbuild/openbsd-x64": "0.27.3", + "@esbuild/openharmony-arm64": "0.27.3", + "@esbuild/sunos-x64": "0.27.3", + "@esbuild/win32-arm64": "0.27.3", + "@esbuild/win32-ia32": "0.27.3", + "@esbuild/win32-x64": "0.27.3" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.36", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.36.tgz", + "integrity": "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==", + "dev": true + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", + "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", + "dev": true, + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + } + } +} diff --git a/.github/pages/package.json b/.github/pages/package.json new file mode 100644 index 000000000..c7ccaf335 --- /dev/null +++ b/.github/pages/package.json @@ -0,0 +1,19 @@ +{ + "name": "javadoc-index", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.2.1", + "vite": "^7.3.1" + } +} diff --git a/.github/pages/src/App.jsx b/.github/pages/src/App.jsx new file mode 100644 index 000000000..b306112fa --- /dev/null +++ b/.github/pages/src/App.jsx @@ -0,0 +1,64 @@ +import styles from './App.module.css' +import { useDocs } from './useDocs' +import TerminalHeader from './components/TerminalHeader' +import Section from './components/Section' +import { ReleaseCard, ExperimentalCard } from './components/Card' +import { LoadingState, ErrorState, EmptyState } from './components/States' +import Footer from './components/Footer' + +export default function App() { + const { data, loading, error } = useDocs() + + const releases = data?.releases || [] + const experimental = data?.experimental || [] + + return ( +
+ + + {/* ── Releases ── */} +
+ {loading ? ( + + ) : error ? ( + + ) : releases.length === 0 ? ( + + ) : ( +
+ {releases.map((r, i) => ( + + ))} +
+ )} +
+ + {/* ── Experimental ── */} +
+ {loading ? ( + + ) : error ? null : experimental.length === 0 ? ( + + ) : ( +
+ {experimental.map((b, i) => ( + + ))} +
+ )} +
+ + {!loading && !error && ( +
+ ) +} diff --git a/.github/pages/src/App.module.css b/.github/pages/src/App.module.css new file mode 100644 index 000000000..395790dac --- /dev/null +++ b/.github/pages/src/App.module.css @@ -0,0 +1,16 @@ +.root { + max-width: 1100px; + margin: 0 auto; + padding: 48px 32px 96px; +} + +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 10px; +} + +@media (max-width: 600px) { + .root { padding: 24px 16px 64px; } + .grid { grid-template-columns: 1fr; } +} diff --git a/.github/pages/src/components/Card.jsx b/.github/pages/src/components/Card.jsx new file mode 100644 index 000000000..73b1f7cf0 --- /dev/null +++ b/.github/pages/src/components/Card.jsx @@ -0,0 +1,97 @@ +import styles from './Card.module.css' +import { REPO_NAME } from '../config' + +const BASE_PATH = `/${REPO_NAME}` + +function formatDate(iso) { + if (!iso) return null + try { + return new Intl.DateTimeFormat('en-GB', { + day: '2-digit', month: 'short', year: 'numeric' + }).format(new Date(iso)) + } catch (e) { return null } +} + +export function ReleaseCard({ release, index }) { + const isLatest = release.isLatest + const date = formatDate(release.date) + const cardClass = isLatest + ? styles.card + ' ' + styles.latest + : styles.card + ' ' + styles.release + + return ( + +
+
+ {isLatest && ( + ● latest + )} + release +
+ → +
+ +
+ v{release.version} +
+
+ {date && ( +
+ date + {date} +
+ )} +
+ path + {release.path}/ +
+
+
+ ) +} + +export function ExperimentalCard({ branch, index }) { + const date = formatDate(branch.date) + + return ( + +
+ + experimental + + → +
+ +
+ {branch.branch} +
+ +
+ {date && ( +
+ date + {date} +
+ )} + {branch.hash && ( +
+ sha + {branch.hash} +
+ )} +
+ path + {branch.path}/ +
+
+
+ ) +} diff --git a/.github/pages/src/components/Card.module.css b/.github/pages/src/components/Card.module.css new file mode 100644 index 000000000..b19f37f72 --- /dev/null +++ b/.github/pages/src/components/Card.module.css @@ -0,0 +1,143 @@ +.card { + display: block; + text-decoration: none; + background: var(--bg2); + border: 1px solid var(--border); + border-radius: 6px; + padding: 20px 22px; + transition: border-color 0.15s, background 0.15s, transform 0.15s; + position: relative; + overflow: hidden; + animation: fadeUp 0.35s ease both; +} + +.card::before { + content: ''; + position: absolute; + top: 0; left: 0; right: 0; + height: 2px; + opacity: 0; + transition: opacity 0.15s; +} + +.release::before { background: var(--green); } +.latest::before { background: linear-gradient(90deg, var(--green), var(--blue)); } +.experimental::before { background: var(--amber); } + +.card:hover { + border-color: var(--border2); + background: var(--bg3); + transform: translateY(-2px); +} + +.card:hover::before { opacity: 1; } + +/* ── Header ── */ +.header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 14px; +} + +.badges { + display: flex; + align-items: center; + gap: 6px; +} + +.badge { + font-size: 9px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; + padding: 2px 8px; + border-radius: 2px; + border: 1px solid; +} + +.badgeLatest { + color: var(--green); + border-color: var(--green-dim); + background: rgba(57, 211, 83, 0.08); + animation: pulseBorder 2s ease infinite; +} + +.badgeRelease { + color: var(--text-dim); + border-color: var(--border2); + background: transparent; +} + +.badgeExperimental { + color: var(--amber); + border-color: var(--amber-dim); + background: rgba(240, 160, 48, 0.08); +} + +.arrow { + font-size: 14px; + color: var(--border2); + transition: color 0.15s, transform 0.15s; +} + +.card:hover .arrow { + color: var(--text-mid); + transform: translateX(3px); +} + +/* ── Version ── */ +.version { + font-size: 20px; + font-weight: 500; + color: var(--text); + margin-bottom: 4px; + letter-spacing: -0.01em; +} + +.latest .version { color: var(--green); } +.versionBranch { font-size: 16px; color: var(--amber); } + +/* ── Meta ── */ +.meta { + display: flex; + flex-direction: column; + gap: 3px; + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid var(--border); +} + +.metaRow { + display: flex; + align-items: center; + gap: 8px; + font-size: 10px; + color: var(--text-dim); +} + +.metaKey { + min-width: 36px; + color: var(--text-dim); +} + +.metaVal { + color: var(--text-mid); + font-family: 'IBM Plex Mono', monospace; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.hash { color: var(--blue); } + +/* ── Animations ── */ +@keyframes fadeUp { + from { opacity: 0; transform: translateY(10px); } + to { opacity: 1; transform: translateY(0); } +} + +@keyframes pulseBorder { + 0%, 100% { border-color: var(--green-dim); } + 50% { border-color: var(--green); } +} diff --git a/.github/pages/src/components/Footer.jsx b/.github/pages/src/components/Footer.jsx new file mode 100644 index 000000000..503f5e0f4 --- /dev/null +++ b/.github/pages/src/components/Footer.jsx @@ -0,0 +1,29 @@ +import styles from './Footer.module.css' +import { REPO_OWNER, REPO_NAME } from '../useDocs' + +export default function Footer({ source }) { + const now = new Intl.DateTimeFormat('en-GB', { + day: '2-digit', month: 'short', year: 'numeric', + hour: '2-digit', minute: '2-digit', timeZoneName: 'short' + }).format(new Date()) + + return ( + + ) +} diff --git a/.github/pages/src/components/Footer.module.css b/.github/pages/src/components/Footer.module.css new file mode 100644 index 000000000..26424d3b6 --- /dev/null +++ b/.github/pages/src/components/Footer.module.css @@ -0,0 +1,36 @@ +.footer { + margin-top: 64px; + padding-top: 20px; + border-top: 1px solid var(--border); + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; + gap: 8px; + font-size: 11px; + color: var(--text-dim); +} + +.dot { + display: inline-block; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--green); + margin-right: 6px; + animation: blink 2s ease infinite; +} + +.link { + color: var(--blue); + text-decoration: none; +} + +.link:hover { + text-decoration: underline; +} + +@keyframes blink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.3; } +} diff --git a/.github/pages/src/components/Section.jsx b/.github/pages/src/components/Section.jsx new file mode 100644 index 000000000..dc28e1dbd --- /dev/null +++ b/.github/pages/src/components/Section.jsx @@ -0,0 +1,18 @@ +import styles from './Section.module.css' + +export default function Section({ label, count, variant, children }) { + return ( +
+
+ {label} +
+ {count !== undefined && ( + + {count} {label.toLowerCase()}{count !== 1 ? 's' : ''} + + )} +
+ {children} +
+ ) +} diff --git a/.github/pages/src/components/Section.module.css b/.github/pages/src/components/Section.module.css new file mode 100644 index 000000000..00f90a81a --- /dev/null +++ b/.github/pages/src/components/Section.module.css @@ -0,0 +1,46 @@ +.section { + margin-top: 40px; + margin-bottom: 8px; +} + +.header { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 16px; +} + +.tag { + font-size: 10px; + font-weight: 600; + letter-spacing: 0.15em; + text-transform: uppercase; + padding: 3px 10px; + border-radius: 3px; + border: 1px solid; + white-space: nowrap; +} + +.releases { + color: var(--green); + border-color: var(--green-dim); + background: rgba(57, 211, 83, 0.06); +} + +.experimental { + color: var(--amber); + border-color: var(--amber-dim); + background: rgba(240, 160, 48, 0.06); +} + +.line { + flex: 1; + height: 1px; + background: var(--border); +} + +.count { + font-size: 11px; + color: var(--text-dim); + white-space: nowrap; +} diff --git a/.github/pages/src/components/States.jsx b/.github/pages/src/components/States.jsx new file mode 100644 index 000000000..2827d401a --- /dev/null +++ b/.github/pages/src/components/States.jsx @@ -0,0 +1,30 @@ +import styles from './States.module.css' + +export function LoadingState() { + return ( +
+
+

Fetching documentation index...

+
+ ) +} + +export function ErrorState({ message }) { + return ( +
+
⚠
+

{message}

+

+ Check that the gh-pages branch exists and is publicly accessible. +

+
+ ) +} + +export function EmptyState({ label }) { + return ( +
+

No {label} found.

+
+ ) +} diff --git a/.github/pages/src/components/States.module.css b/.github/pages/src/components/States.module.css new file mode 100644 index 000000000..319fc6e52 --- /dev/null +++ b/.github/pages/src/components/States.module.css @@ -0,0 +1,47 @@ +.box { + border: 1px solid var(--border); + border-radius: 6px; + padding: 48px; + text-align: center; + background: var(--bg2); +} + +.empty { + padding: 24px; +} + +.spinner { + width: 22px; + height: 22px; + border: 2px solid var(--border2); + border-top-color: var(--green); + border-radius: 50%; + animation: spin 0.75s linear infinite; + margin: 0 auto 14px; +} + +.label { + font-size: 12px; + color: var(--text-dim); +} + +.errorIcon { + font-size: 22px; + margin-bottom: 10px; + color: var(--red); +} + +.errorMsg { + font-size: 13px; + color: var(--red); + margin-bottom: 6px; +} + +.errorSub { + font-size: 11px; + color: var(--text-dim); +} + +@keyframes spin { + to { transform: rotate(360deg); } +} diff --git a/.github/pages/src/components/TerminalHeader.jsx b/.github/pages/src/components/TerminalHeader.jsx new file mode 100644 index 000000000..e2efb2779 --- /dev/null +++ b/.github/pages/src/components/TerminalHeader.jsx @@ -0,0 +1,186 @@ +import { useState, useEffect } from 'react' +import styles from './TerminalHeader.module.css' +import { PROJECT_NAME, REPO_NAME, LINKS, AUTHORS } from '../config' + +function useGitHubProfile(username) { + const [profile, setProfile] = useState(null) + const [loading, setLoading] = useState(true) + + useEffect(() => { + const cacheKey = 'gh-profile-' + username + + // Check sessionStorage first — avoids hammering the API on every render + try { + const cached = sessionStorage.getItem(cacheKey) + if (cached) { + setProfile(JSON.parse(cached)) + setLoading(false) + return + } + } catch (e) {} + + fetch('https://api.github.com/users/' + username) + .then(r => { + if (!r.ok) throw new Error('HTTP ' + r.status) + return r.json() + }) + .then(d => { + // Don't cache error responses like rate limit messages + if (!d.message) { + try { sessionStorage.setItem(cacheKey, JSON.stringify(d)) } catch (e) {} + } + setProfile(d) + setLoading(false) + }) + .catch(() => setLoading(false)) + }, [username]) + + return { profile, loading } +} + +function AuthorTile({ username, active }) { + const { profile, loading } = useGitHubProfile(username) + const tileClass = styles.authorTile + (active ? ' ' + styles.authorTileActive : '') + + if (loading) { + return ( +
+
+
+
+
+
+
+
+ ) + } + + if (!profile || profile.message) { + return ( + +
+
+ {username} + @{username} +
+
+
+ ) + } + + return ( + + {profile.login} +
+ {profile.name || profile.login} + @{profile.login} + {profile.bio + ? {profile.bio} + :
+ } +
+
+ ) +} + +function AuthorsTiles() { + const [active, setActive] = useState(0) + + useEffect(() => { + if (AUTHORS.length <= 1) return + const t = setInterval(() => { + setActive(i => (i + 1) % AUTHORS.length) + }, 4000) + return () => clearInterval(t) + }, []) + + return ( +
+
+ › Authors: +
+
+ {AUTHORS.map((username, i) => ( + + ))} +
+
+ ) +} + +export default function TerminalHeader() { + return ( +
+
+
+
+
+ javadoc-index — bash +
+
+

+ {PROJECT_NAME} +

+ +
+ $ + browse-docs + {REPO_NAME} + --all-versions +
+ +
+ › Fetching available documentation builds... +
+
+ › Found project links: +
+ +
+ {LINKS.map(function(l) { + return ( + + + {l.tag} + + {l.label} + ↗ + + ) + })} +
+ + + +
+ $ + +
+
+
+ ) +} diff --git a/.github/pages/src/components/TerminalHeader.module.css b/.github/pages/src/components/TerminalHeader.module.css new file mode 100644 index 000000000..84853abac --- /dev/null +++ b/.github/pages/src/components/TerminalHeader.module.css @@ -0,0 +1,303 @@ +.wrap { + margin-bottom: 48px; +} + +.bar { + display: flex; + align-items: center; + gap: 6px; + background: var(--bg3); + border: 1px solid var(--border2); + border-bottom: none; + border-radius: 8px 8px 0 0; + padding: 10px 16px; +} + +.dot { + width: 12px; + height: 12px; + border-radius: 50%; +} +.red { background: #ff5f57; } +.amber { background: #febc2e; } +.green { background: #28c840; } + +.title { + margin-left: 8px; + font-size: 11px; + color: var(--text-dim); + letter-spacing: 0.05em; +} + +.body { + background: var(--bg2); + border: 1px solid var(--border2); + border-radius: 0 0 8px 8px; + padding: 16px 36px 36px; +} + +/* ── Heading ── */ +.heading { + font-family: 'IBM Plex Sans', sans-serif; + font-size: clamp(28px, 5vw, 52px); + font-weight: 300; + letter-spacing: -0.02em; + color: var(--text); + line-height: 1.05; + margin-bottom: 20px; +} + +.heading strong { + font-weight: 600; + color: var(--green); +} + +/* ── Prompt ── */ +.promptLine { + display: flex; + align-items: baseline; + gap: 10px; + margin-bottom: 6px; + font-size: 13px; + flex-wrap: wrap; +} + +.prompt { color: var(--green); font-weight: 600; } +.cmd { color: var(--text); } +.arg { color: var(--blue); } +.flag { color: var(--amber); } + +/* ── Output lines ── */ +.outputLine { + font-size: 12px; + color: var(--text-dim); + line-height: 1.8; + padding-left: 20px; +} + +.chevron { + color: var(--text-mid); + margin-right: 4px; +} + +/* ── Links ── */ +.links { + display: flex; + flex-direction: column; + gap: 4px; + padding-left: 36px; + margin-top: 4px; + margin-bottom: 12px; +} + +.link { + display: inline-flex; + align-items: center; + gap: 10px; + text-decoration: none; + padding: 3px 0; + width: fit-content; + transition: opacity 0.15s; +} + +.link:hover { opacity: 0.8; } + +.link:hover .linkLabel { + text-decoration: underline; + text-underline-offset: 3px; +} + +.linkTag { + font-size: 9px; + font-weight: 600; + letter-spacing: 0.1em; + border: 1px solid; + border-radius: 2px; + padding: 1px 5px; + min-width: 28px; + text-align: center; + opacity: 0.9; + font-family: 'IBM Plex Mono', monospace; +} + +.linkLabel { + font-size: 12px; + color: var(--text-mid); + font-family: 'IBM Plex Mono', monospace; +} + +.linkArrow { + font-size: 11px; + opacity: 0.6; + transition: opacity 0.15s, transform 0.15s; +} + +.link:hover .linkArrow { + opacity: 1; + transform: translate(2px, -2px); +} + +/* ── Authors ── */ +.authors { + margin-bottom: 8px; +} + +.authorRow { + display: flex; + flex-direction: row; + gap: 8px; + padding-left: 36px; + margin-top: 6px; + flex-wrap: wrap; +} + +/* ── Author tile ── */ +.authorTile { + display: flex; + align-items: center; + gap: 10px; + background: var(--bg3); + border: 1px solid var(--border); + border-radius: 6px; + padding: 8px 12px; + text-decoration: none; + cursor: pointer; + /* width is dynamic — grows with content */ + width: max-content; + min-width: 140px; + position: relative; + overflow: hidden; + transition: border-color 0.2s, background 0.2s, transform 0.2s; +} + +.authorTile::before { + content: ''; + position: absolute; + top: 0; left: 0; right: 0; + height: 2px; + background: var(--green); + opacity: 0; + transition: opacity 0.2s; +} + +.authorTileActive::before, +.authorTile:hover::before { + opacity: 1; +} + +.authorTileActive { + border-color: var(--green-dim); + background: rgba(57, 211, 83, 0.04); +} + +.authorTile:hover { + border-color: var(--border2); + background: #161b22; + transform: translateY(-1px); +} + +/* ── Author content ── */ +.authorAvatar { + width: 32px; + height: 32px; + border-radius: 50%; + border: 1px solid var(--border2); + flex-shrink: 0; +} + +.authorAvatarSkeleton { + width: 32px; + height: 32px; + border-radius: 50%; + background: var(--border2); + flex-shrink: 0; + animation: shimmer 1.5s ease infinite; +} + +.authorInfo { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} + +.authorName { + font-size: 12px; + font-weight: 500; + color: var(--text); + font-family: 'IBM Plex Sans', sans-serif; + white-space: nowrap; +} + +.authorLogin { + font-size: 10px; + color: var(--blue); + font-family: 'IBM Plex Mono', monospace; + white-space: nowrap; +} + +/* Bio — always reserves vertical height, width animates open */ +.authorBio { + display: block; + font-size: 10px; + color: var(--text-dim); + font-family: 'IBM Plex Sans', sans-serif; + margin-top: 2px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + /* always reserve vertical space */ + height: 14px; + /* collapsed horizontally */ + width: 0; + opacity: 0; + transition: opacity 0.25s ease, width 0.3s ease; +} + +.authorTileActive .authorBio, +.authorTile:hover .authorBio { + width: 200px; + opacity: 1; +} + +/* Placeholder for loading/no-profile/no-bio states */ +.authorBioPlaceholder { + height: 14px; + margin-top: 2px; + width: 0; /* never takes horizontal space, never expands */ +} + +.authorSkeleton { + height: 9px; + border-radius: 4px; + background: var(--border2); + animation: shimmer 1.5s ease infinite; +} + +/* ── Cursor ── */ +.cursor { + display: inline-block; + width: 8px; + height: 13px; + background: var(--green); + margin-left: 2px; + vertical-align: text-bottom; + animation: blink 1s step-end infinite; +} + +/* ── Animations ── */ +@keyframes blink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0; } +} + +@keyframes shimmer { + 0%, 100% { opacity: 0.4; } + 50% { opacity: 0.8; } +} + +@media (max-width: 600px) { + .body { padding: 20px; } + .links { padding-left: 20px; } + .authorRow { padding-left: 20px; } +} diff --git a/.github/pages/src/config.js b/.github/pages/src/config.js new file mode 100644 index 000000000..ed7a4baf9 --- /dev/null +++ b/.github/pages/src/config.js @@ -0,0 +1,38 @@ +// ─── Project Configuration ─────────────────────────────────── +// This is the ONLY file that should differ between projects. +// Everything else in the pages app is generic. +// ───────────────────────────────────────────────────────────── + +export const PROJECT_NAME = 'CustomNPC+' +export const REPO_OWNER = 'KAMKEEL' +export const REPO_NAME = 'CustomNPC-Plus' + +export const LINKS = [ + { + tag: 'GH', + label: 'github.com/KAMKEEL/CustomNPC-Plus', + href: 'https://github.com/KAMKEEL/CustomNPC-Plus', + color: '#e6edf3', + }, + { + tag: 'DC', + label: 'discord.gg/94qmjEDxkp', + href: 'https://discord.gg/94qmjEDxkp', + color: '#5865f2', + }, + { + tag: 'CF', + label: 'curseforge.com/minecraft/mc-mods/customnpc-plus', + href: 'https://www.curseforge.com/minecraft/mc-mods/customnpc-plus', + color: '#f16436', + }, + { + tag: 'MR', + label: 'modrinth.com/mod/customnpc-plus', + href: 'https://modrinth.com/mod/customnpc-plus/', + color: '#1bd96a', + }, +] + +// GitHub usernames — profiles are fetched at runtime +export const AUTHORS = ['kamkeel', 'c0508383', 'bigguy345', 'somehussar'] diff --git a/.github/pages/src/index.css b/.github/pages/src/index.css new file mode 100644 index 000000000..fef4fe128 --- /dev/null +++ b/.github/pages/src/index.css @@ -0,0 +1,50 @@ +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +:root { + --bg: #080b0f; + --bg2: #0d1117; + --bg3: #131920; + --border: #1e2936; + --border2: #253040; + --green: #39d353; + --green-dim: #1a6b2a; + --amber: #f0a030; + --amber-dim: #7a4e10; + --blue: #58a6ff; + --blue-dim: #1a3a6b; + --text: #cdd9e5; + --text-dim: #636e7b; + --text-mid: #8b949e; + --red: #f85149; +} + +html, body { + height: 100%; + background: var(--bg); + color: var(--text); + font-family: 'IBM Plex Mono', monospace; + overflow-x: hidden; +} + +/* Scanlines */ +body::after { + content: ''; + position: fixed; + inset: 0; + background: repeating-linear-gradient( + 0deg, + transparent, + transparent 2px, + rgba(0,0,0,0.025) 2px, + rgba(0,0,0,0.025) 4px + ); + pointer-events: none; + z-index: 9999; +} + +a { color: inherit; text-decoration: none; } + +::-webkit-scrollbar { width: 6px; } +::-webkit-scrollbar-track { background: var(--bg2); } +::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 3px; } +::-webkit-scrollbar-thumb:hover { background: var(--text-dim); } diff --git a/.github/pages/src/main.jsx b/.github/pages/src/main.jsx new file mode 100644 index 000000000..22bbe14e1 --- /dev/null +++ b/.github/pages/src/main.jsx @@ -0,0 +1,13 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import App from './App' +import { PROJECT_NAME } from './config' +import './index.css' + +document.title = `${PROJECT_NAME} — Javadoc Index` + +ReactDOM.createRoot(document.getElementById('root')).render( + + + +) diff --git a/.github/pages/src/useDocs.js b/.github/pages/src/useDocs.js new file mode 100644 index 000000000..1c8c5b803 --- /dev/null +++ b/.github/pages/src/useDocs.js @@ -0,0 +1,94 @@ +import { useState, useEffect } from 'react' +import { REPO_OWNER, REPO_NAME } from './config' + +const BASE_PATH = `/${REPO_NAME}` +const API_BASE = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}` + +// Cache bust on every page load — appends current timestamp to manifest URL +// so the browser never serves a stale manifest.json +async function fetchFromManifest() { + const bust = `?t=${Date.now()}` + const res = await fetch(`${BASE_PATH}/manifest.json${bust}`, { + cache: 'no-store', // tells browser not to cache this request at all + }) + if (!res.ok) throw new Error('No manifest') + return res.json() +} + +async function fetchFromGitHubAPI() { + const refRes = await fetch(`${API_BASE}/git/ref/heads/gh-pages`) + if (!refRes.ok) throw new Error('gh-pages branch not found') + const refData = await refRes.json() + const sha = refData.object.sha + + const treeRes = await fetch(`${API_BASE}/git/trees/${sha}?recursive=1`) + if (!treeRes.ok) throw new Error('Could not fetch tree') + const treeData = await treeRes.json() + + const commitsRes = await fetch(`${API_BASE}/commits?sha=gh-pages&per_page=100`) + const commits = commitsRes.ok ? await commitsRes.json() : [] + + const commitMap = {} + commits.forEach(c => { + const date = c.commit?.committer?.date || c.commit?.author?.date || '' + const hash = c.sha?.slice(0, 7) || '' + const msg = c.commit?.message || '' + const vMatch = msg.match(/releases\/([\d.]+)/) + if (vMatch) commitMap[`releases/${vMatch[1]}`] = { date, hash } + const eMatch = msg.match(/experimental\/([\w-]+)/) + if (eMatch) commitMap[`experimental/${eMatch[1]}`] = { date, hash } + }) + + const releaseDirs = new Set() + const experimentalDirs = new Set() + + treeData.tree.forEach(item => { + if (item.type !== 'tree') return + const parts = item.path.split('/') + if (parts[0] === 'releases' && parts.length === 2) releaseDirs.add(parts[1]) + if (parts[0] === 'experimental' && parts.length === 2) experimentalDirs.add(parts[1]) + }) + + // Sort releases newest first, mark first as latest + const sortedReleases = [...releaseDirs] + .sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) + + const releases = sortedReleases.map((v, i) => { + const c = commitMap[`releases/${v}`] || {} + return { + id: v, + version: v, + path: `releases/${v}`, + date: c.date, + hash: c.hash, + isLatest: i === 0, // newest version is always latest + } + }) + + const experimental = [...experimentalDirs].sort().map(b => { + const c = commitMap[`experimental/${b}`] || {} + return { id: b, branch: b, path: `experimental/${b}`, date: c.date, hash: c.hash } + }) + + return { releases, experimental, source: 'api' } +} + +export function useDocs() { + const [data, setData] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + + useEffect(() => { + fetchFromManifest() + .then(d => { setData(d); setLoading(false) }) + .catch(() => + fetchFromGitHubAPI() + .then(d => { setData(d); setLoading(false) }) + .catch(e => { setError(e.message); setLoading(false) }) + ) + }, []) + + return { data, loading, error } +} + +export { BASE_PATH, REPO_OWNER, REPO_NAME } diff --git a/.github/pages/vite.config.js b/.github/pages/vite.config.js new file mode 100644 index 000000000..1b00c454f --- /dev/null +++ b/.github/pages/vite.config.js @@ -0,0 +1,12 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { REPO_NAME } from './src/config.js' + +export default defineConfig({ + plugins: [react()], + base: `/${REPO_NAME}/`, + build: { + outDir: '../../.github/pages-dist', + emptyOutDir: true, + } +}) diff --git a/.github/scripts/doc-config.sh b/.github/scripts/doc-config.sh new file mode 100644 index 000000000..37f6a0d90 --- /dev/null +++ b/.github/scripts/doc-config.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# ----------------------------------------------- +# doc-config.sh — shared config for javadoc deploy +# +# Sourced by: +# - resolve-doc-path.sh +# - javadoc.yml (via sanity-check job) +# +# ADD WHITELISTED BRANCHES HERE AND NOWHERE ELSE. +# main is always handled automatically. +# ----------------------------------------------- + +MAIN_BRANCH_NAME="master" + +EXPERIMENTAL_WHITELIST=( + "dev" + # "new-branch" +) diff --git a/.github/scripts/generate-index.sh b/.github/scripts/generate-index.sh new file mode 100644 index 000000000..7651a800e --- /dev/null +++ b/.github/scripts/generate-index.sh @@ -0,0 +1,107 @@ +#!/bin/bash +set -e + +RELEASES=() +EXPERIMENTAL=() + +# Collect releases +if [ -d "./releases" ]; then + for dir in ./releases/*/; do + [ -d "$dir" ] || continue + name=$(basename "$dir") + RELEASES+=("$name") + done +fi + +# Collect experimental branches +if [ -d "./experimental" ]; then + for dir in ./experimental/*/; do + [ -d "$dir" ] || continue + name=$(basename "$dir") + EXPERIMENTAL+=("$name") + done +fi + +# Sort releases in reverse semver order (newest first) +if [ ${#RELEASES[@]} -gt 0 ]; then + IFS=$'\n' RELEASES=($(sort -rV <<< "${RELEASES[*]}")); unset IFS +fi + +# ── Store source commit metadata for this deploy ─────────────── +# DEPLOY_PATH, SOURCE_HASH, SOURCE_DATE are passed in as env vars from the workflow +if [ -n "$DEPLOY_PATH" ] && [ -n "$SOURCE_HASH" ]; then + mkdir -p ".doc-meta" + META_KEY="${DEPLOY_PATH//\//_}" + cat > ".doc-meta/${META_KEY}.json" << JSON +{"hash":"${SOURCE_HASH}","date":"${SOURCE_DATE}"} +JSON + echo "Stored source metadata for $DEPLOY_PATH → $SOURCE_HASH @ $SOURCE_DATE" +fi + +# ── Helper: get source commit hash + date for a path ────────── +get_commit_info() { + local path="$1" + + # If this is the path we just deployed, use the injected source commit + if [ "$path" = "$DEPLOY_PATH" ] && [ -n "$SOURCE_HASH" ]; then + echo "${SOURCE_HASH} ${SOURCE_DATE}" + return + fi + + # Try reading from stored metadata file (set by previous deploys) + local meta=".doc-meta/${path//\//_}.json" + if [ -f "$meta" ]; then + local hash date + hash=$(python3 -c "import json,sys; d=json.load(open('$meta')); print(d.get('hash',''))" 2>/dev/null || grep -o '"hash":"[^"]*"' "$meta" | cut -d'"' -f4) + date=$(python3 -c "import json,sys; d=json.load(open('$meta')); print(d.get('date',''))" 2>/dev/null || grep -o '"date":"[^"]*"' "$meta" | cut -d'"' -f4) + echo "${hash:-} ${date:-}" + return + fi + + # Last resort: gh-pages git log (hash will be wrong but better than empty) + local hash date + hash=$(git log --oneline -1 -- "$path" 2>/dev/null | awk '{print $1}') + date=$(git log --format="%cI" -1 -- "$path" 2>/dev/null) + echo "${hash:-} ${date:-}" +} + +# ── Build releases JSON ──────────────────────────────────────── +RELEASES_JSON="[" + +for i in "${!RELEASES[@]}"; do + version="${RELEASES[$i]}" + read -r HASH DATE <<< "$(get_commit_info "releases/$version")" + if [ "$i" -eq 0 ]; then + IS_LATEST="true" + else + IS_LATEST="false" + fi + RELEASES_JSON+="{\"id\":\"${version}\",\"version\":\"${version}\",\"path\":\"releases/${version}\",\"date\":\"${DATE}\",\"isLatest\":${IS_LATEST}}," +done + +RELEASES_JSON="${RELEASES_JSON%,}]" + +# ── Build experimental JSON ──────────────────────────────────── +EXPERIMENTAL_JSON="[" + +for branch in "${EXPERIMENTAL[@]}"; do + read -r HASH DATE <<< "$(get_commit_info "experimental/$branch")" + EXPERIMENTAL_JSON+="{\"id\":\"${branch}\",\"branch\":\"${branch}\",\"path\":\"experimental/${branch}\",\"hash\":\"${HASH}\",\"date\":\"${DATE}\"}," +done + +EXPERIMENTAL_JSON="${EXPERIMENTAL_JSON%,}]" + +# ── Write manifest.json ──────────────────────────────────────── +cat > manifest.json << JSON +{ + "releases": ${RELEASES_JSON}, + "experimental": ${EXPERIMENTAL_JSON}, + "generated": "$(date -u '+%Y-%m-%dT%H:%M:%SZ')", + "source": "manifest" +} +JSON + +echo "manifest.json generated:" +cat manifest.json +echo "" +echo "Done." diff --git a/.github/scripts/resolve-doc-path.sh b/.github/scripts/resolve-doc-path.sh new file mode 100644 index 000000000..92ad7ac8c --- /dev/null +++ b/.github/scripts/resolve-doc-path.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "$SCRIPT_DIR/doc-config.sh" + +BRANCH="${GITHUB_REF#refs/heads/}" +SAFE_BRANCH="${BRANCH//\//-}" + +if [ "$BRANCH" = "$MAIN_BRANCH_NAME" ]; then + # Version resolution order: + # -> check if gradle.properties has a `modVersion` tag. If it does, just grab it. + # -> check if it has the `version` tag. Grab it if it does + # -> check build.gradle for the version tag. + if [ -f "gradle.properties" ] && grep -q "^modVersion=" gradle.properties; then + VERSION=$(grep "^modVersion=" gradle.properties | cut -d'=' -f2 | tr -d '[:space:]') + elif [ -f "gradle.properties" ] && grep -q "^version=" gradle.properties; then + VERSION=$(grep "^version=" gradle.properties | cut -d'=' -f2 | tr -d '[:space:]') + elif [ -f "build.gradle" ]; then + VERSION=$(grep "^version" build.gradle | head -1 | sed "s/version\s*=\s*['\"]//;s/['\"].*//;s/\s//g") + elif [ -f "build.gradle.kts" ]; then + VERSION=$(grep "^version" build.gradle.kts | head -1 | sed "s/version\s*=\s*\"//;s/\".*//;s/\s//g") + else + echo "Could not find version. Defaulting to 'unknown'." + VERSION="unknown" + fi + + echo "Resolved version: $VERSION" + + # Only deploy to releases/ — isLatest is handled by generate-index.sh + echo "path=releases/$VERSION" >> $GITHUB_OUTPUT + echo "extra_path=" >> $GITHUB_OUTPUT + +else + MATCHED=false + for ALLOWED in "${EXPERIMENTAL_WHITELIST[@]}"; do + if [ "$BRANCH" = "$ALLOWED" ]; then + MATCHED=true + break + fi + done + + if [ "$MATCHED" = true ]; then + echo "path=experimental/$SAFE_BRANCH" >> $GITHUB_OUTPUT + echo "extra_path=" >> $GITHUB_OUTPUT + echo "Branch '$BRANCH' is whitelisted, deploying to experimental/$SAFE_BRANCH" + else + echo "path=" >> $GITHUB_OUTPUT + echo "extra_path=" >> $GITHUB_OUTPUT + echo "Branch '$BRANCH' is not whitelisted. Skipping deploy." + fi +fi diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 2d7779d62..c2fb186fe 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -24,8 +24,8 @@ jobs: with: fetch-depth: 0 - - name: Initialize CNPC+ API submodule - run: git submodule update --init --recursive src/api + - name: Initialize submodules + run: git submodule update --init --recursive - name: Checkout workflows repo uses: actions/checkout@v4 diff --git a/.github/workflows/javadoc.yml b/.github/workflows/javadoc.yml new file mode 100644 index 000000000..52954f202 --- /dev/null +++ b/.github/workflows/javadoc.yml @@ -0,0 +1,224 @@ +name: Generate and Deploy Javadoc + +on: + push: + branches: + - master + - '**' + delete: + workflow_dispatch: + inputs: + force_deploy: + description: 'Force redeploy Javadocs without a new commit' + required: false + default: 'true' + +jobs: + sanity-check: + runs-on: ubuntu-latest + outputs: + should_deploy: ${{ steps.deploy_check.outputs.should_deploy }} + steps: + - uses: actions/checkout@v4 + - name: Check for deploy tag + id: deploy_check + run: | + source .github/scripts/doc-config.sh + + BRANCH="${GITHUB_REF#refs/heads/}" + + # Always deploy on manual trigger + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + echo "should_deploy=true" >> $GITHUB_OUTPUT + echo "Reason: workflow_dispatch" + exit 0 + fi + + # Main branch: only deploy if commit message contains [deploy-docs] + if [ "$BRANCH" = "$MAIN_BRANCH_NAME" ]; then + if echo "${{ github.event.head_commit.message }}" | grep -q "\[deploy-docs\]"; then + echo "should_deploy=true" >> $GITHUB_OUTPUT + echo "Reason: master branch with [deploy-docs] tag" + else + echo "should_deploy=false" >> $GITHUB_OUTPUT + echo "Reason: master branch without [deploy-docs] tag, skipping" + fi + exit 0 + fi + + # Experimental branches: only deploy if whitelisted + for ALLOWED in "${EXPERIMENTAL_WHITELIST[@]}"; do + if [ "$BRANCH" = "$ALLOWED" ]; then + echo "should_deploy=true" >> $GITHUB_OUTPUT + echo "Reason: branch '$BRANCH' is whitelisted" + exit 0 + fi + done + + echo "should_deploy=false" >> $GITHUB_OUTPUT + echo "Reason: branch '$BRANCH' is not whitelisted, skipping" + + build-and-deploy-javadoc: + needs: sanity-check + if: needs.sanity-check.outputs.should_deploy == 'true' + runs-on: ubuntu-latest + + steps: + - name: Checkout source branch + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Initialize submodules + run: git submodule update --init --recursive + + - name: Setup JDK 8 (compile) + uses: actions/setup-java@v4 + with: + java-version: '8' + distribution: 'temurin' + + - name: Set up JDK 8 (Zulu) + uses: actions/setup-java@v4 + with: + java-version: '8' + distribution: 'zulu' + - name: Setup JDK 11 (javadoc) + uses: actions/setup-java@v4 + with: + java-version: '11' + distribution: 'temurin' + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Extract convention plugin version + id: convention + run: | + VERSION=$(grep "id 'com.gtnewhorizons.gtnhsettingsconvention'" settings.gradle settings.gradle.kts 2>/dev/null | grep -o "version '[0-9]\+\.[0-9]\+\.[0-9]\+'" | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+') + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "Detected convention version: $VERSION" + + - name: Get source commit info + id: source_commit + run: | + echo "hash=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT + echo "date=$(git log -1 --format='%cI')" >> $GITHUB_OUTPUT + + - name: Cache Gradle wrapper + uses: actions/cache@v4 + with: + path: ~/.gradle/wrapper + key: gradle-wrapper-${{ hashFiles('**/gradle-wrapper.properties') }} + + - name: Cache Gradle dependencies + uses: actions/cache@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/caches/modules-* + ~/.gradle/caches/jars-* + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', '**/gradle.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + + - name: Cache RFG + uses: actions/cache@v4 + with: + path: | + build/rfg + build/tmp/.cache/expanded + build/tmp/deobfuscateMergedJarToSrg + key: ${{ runner.os }}-rfg-convention${{ steps.convention.outputs.version }} + restore-keys: | + ${{ runner.os }}-rfg- + + - name: Cache Node modules + uses: actions/cache@v4 + with: + path: .github/pages/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('.github/pages/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- + + - name: Generate Javadoc + run: ./gradlew javadoc + + - name: Get deploy path + id: deploy_path + run: bash .github/scripts/resolve-doc-path.sh + + - name: Deploy to gh-pages + if: steps.deploy_path.outputs.path != '' + uses: peaceiris/actions-gh-pages@v4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./build/docs/javadoc + destination_dir: ${{ steps.deploy_path.outputs.path }} + keep_files: true + + # Give GitHub a moment to settle after the peaceiris push + - name: Wait for gh-pages to settle + run: sleep 10 + + - name: Checkout gh-pages + uses: actions/checkout@v4 + with: + ref: gh-pages + path: gh-pages-index + + - name: Generate manifest + run: | + cd gh-pages-index + SOURCE_HASH="${{ steps.source_commit.outputs.hash }}" \ + SOURCE_DATE="${{ steps.source_commit.outputs.date }}" \ + DEPLOY_PATH="${{ steps.deploy_path.outputs.path }}" \ + bash ../.github/scripts/generate-index.sh + + - name: Install page dependencies + run: npm ci --prefix .github/pages + + - name: Build index page + run: | + mkdir -p .github/pages/public + cp gh-pages-index/manifest.json .github/pages/public/manifest.json + npm run build --prefix .github/pages + + - name: Deploy index to gh-pages + run: | + cp -r .github/pages-dist/* gh-pages-index/ + cd gh-pages-index + git config user.name "github-actions" + git config user.email "github-actions@github.com" + git add -A + git commit -m "Regenerate index and manifest [skip ci]" || echo "Unchanged" + git push + + cleanup-on-delete: + if: github.event_name == 'delete' && github.event.ref_type == 'branch' + runs-on: ubuntu-latest + + steps: + - name: Checkout gh-pages + uses: actions/checkout@v4 + with: + ref: 'gh-pages' + + - name: Remove deleted branch docs + run: | + BRANCH="${{ github.event.ref }}" + SAFE="experimental/${BRANCH//\//-}" + if [ -d "./$SAFE" ]; then + rm -rf "./$SAFE" + META_KEY="${SAFE//\//_}" + rm -f ".doc-meta/${META_KEY}.json" + git config user.name "github-actions" + git config user.email "github-actions@github.com" + git add -A + git commit -m "Remove docs for deleted branch: $BRANCH" + git push + else + echo "No docs found for $SAFE, skipping." + fi diff --git a/.gitignore b/.gitignore index 908eae39d..5d29506b6 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,7 @@ run src/main/resources/assets/customnpcs/api df/ tmp/ +src/test +node_modules +.github/pages-dist + diff --git a/Ability_Beta_Update.md b/Ability_Beta_Update.md deleted file mode 100644 index 8733ebc8b..000000000 --- a/Ability_Beta_Update.md +++ /dev/null @@ -1,144 +0,0 @@ -# CNPC+ 1.11 Ability System Beta - -🟡 **In Testing** - - - -## Features: ⚒️ - -- **Phase-Based Execution:** - -> All abilities follow a Wind-up → Active → Completion flow. Wind-up lets players react, Active deals the effect. - - - -- **Melee Abilities:** - -> - **Slam** - Leap and AOE on impact. -> - **Heavy Hit** - Single powerful strike with bonus knockback. -> - **Cutter** - Slashing cone arc attack. -> - **Shockwave** - AOE burst radiating from the caster. - - - -- **Energy Orbs:** - -> - **Orb** - Homing energy sphere. -> - **Dual Orb** - Two simultaneous homing orbs. -> - **Orb Barrage** - Rapid volley of orbs in sequence. - - - -- **Energy Discs:** - -> - **Disc** - Spinning flat projectile with optional boomerang. -> - **Dual Disc** - Two simultaneous discs. - - - -- **Energy Beams:** - -> - **Beam** - Sustained homing beam from caster to target. -> - **Dual Beam** - Two simultaneous beams. - - - -- **Laser Shot:** - -> Instant-fire projectile with no homing. Pure aim. - - - -- **Projectile:** - -> Standard projectile using classic Minecraft physics. - - - -- **Movement Abilities:** - -> - **Charge** - Rush forward in a line, damaging everything in path. -> - **Dash** - Quick directional movement without damage. -> - **Teleport** - Instant relocation to the target. - - - -- **AOE Abilities:** - -> - **Sweeper** - Wide rotational sweep around the caster. -> - **Vortex** - Pulls entities inward while dealing damage. - - - -- **Telegraph System:** - -> Visual ground indicators during wind-up. Supports Circle, Ring, Line, Cone, and Point shapes with color customization and warning phase transitions. - - - -- **Energy Projectile Customization:** - -> Modular data system for all energy projectiles: Anchor Point, Display Colors, Homing, Combat Stats, and Lifespan. - - - -- **Ability Effects:** - -> Abilities can apply potion effects on hit: Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue. - - - -- **Ability Conditions:** - -> Condition system controlling when abilities can execute based on target state and custom predicates. - - - -- **Interruptible Wind-ups:** - -> Abilities can be interrupted by damage during wind-up, forcing a configurable Dazed recovery state. - - - -- **Movement & Rotation Locking:** - -> Lock caster movement, rotation, or both during Wind-up, Active, or both phases. - - - -- **Animation & Sound Integration:** - -> Wind-up and Active animations with optional duration sync. Custom sound events per phase. - - - -- **Player Abilities:** - -> Players can unlock abilities, select one at a time, and share a universal cooldown. - - - -- **Ability Preview:** - -> Live preview in the ability editor GUI. Test telegraphs, animations, and projectiles on a dummy NPC. - - - -- **Scripting API:** - -> Full event support: Start, Execute, Interrupt, Complete, Hit (modifiable damage/knockback), and Tick events. Start, Execute, and Hit are cancelable. - - - -- **Ability Commands:** - -> `/kam ability list`, `types`, `info`, `delete`, `reload` for managing custom abilities. - - - -**Extras** - -- Global ability presets that update everywhere when edited. -- Weighted ability selection for NPC random usage. -- Configurable min/max range per ability. -- Reusable telegraph presets shared across abilities. diff --git a/Ability_Update.md b/Ability_Update.md deleted file mode 100644 index cf160bc5f..000000000 --- a/Ability_Update.md +++ /dev/null @@ -1,199 +0,0 @@ -# ⚔️ CustomNPC+ 1.11 - Abilities ⚔️ - ---- - -The **Ability Update** introduces a full combat ability system to CNPC+! Give your NPCs powerful attacks with **visual telegraphs**, launch **energy projectiles** that home in on targets, and let players unlock abilities of their own! - ---- - -## How Abilities Work 🎯 - -Every ability follows a **phase-based execution flow** that gives combat a readable, strategic feel. - -**Phases:** -- **Wind-up** - The ability charges. Telegraphs appear, animations play, and observant players can react -- **Active** - The ability fires. Damage is dealt, projectiles launch, effects apply -- **Dazed** - Optional recovery state if the ability is interrupted during wind-up - -**Core Configuration:** -- **Cooldown** - Time before the ability can be used again -- **Targeting Mode** - Aggro Target, Self, AOE on Self, or AOE on Target -- **Range** - Configurable min and max range for activation -- **Lock Movement** - Lock the caster's movement, rotation, or both during any phase -- **Interruptible** - Allow damage to interrupt wind-up and force a dazed state -- **Weight** - Priority weighting for NPC random ability selection - -> Abilities support both **inline configuration** on individual NPCs and **global presets** that update everywhere when edited. - ---- - -## Melee Abilities 🗡️ - -Close-range attacks that hit hard and punish positioning. - -- **Slam** - Leap toward the target in an arc, dealing AOE damage on impact. Configurable radius, knockback, and leap height -- **Heavy Hit** - A single powerful melee strike with bonus knockback -- **Cutter** - A slashing arc attack in a cone. Configurable angle and reach -- **Shockwave** - An AOE burst radiating outward from the caster - -> All melee abilities support configurable **damage**, **knockback**, and **potion effects** on hit. - ---- - -## Energy Projectiles ✨ - -A brand new projectile system built from the ground up with full visual customization. - -### Orbs - -Homing energy spheres that track their target through the air. - -- **Orb** - A single homing projectile -- **Dual Orb** - Fires two orbs simultaneously -- **Orb Barrage** - Fires a volley of orbs in rapid sequence - -### Discs - -Flat spinning projectiles with optional **boomerang** behavior. - -- **Disc** - A single spinning disc with configurable radius and thickness -- **Dual Disc** - Fires two discs simultaneously - -### Beams - -Sustained energy beams that connect the caster to their target. - -- **Beam** - A homing beam with configurable width and head size. Locks the caster in place during channeling -- **Dual Beam** - Fires two beams simultaneously - -### Laser Shot - -An **instant-fire** projectile with configurable width and speed. No homing — pure aim. - -### Projectile - -A standard projectile using classic Minecraft physics for a more traditional ranged attack. - -### Energy Configuration - -Every energy projectile shares a **modular data system** for deep customization: - -- **Anchor Point** - Choose where the projectile spawns: Right Hand, Left Hand, Front, Center, Chest, or Above Head -- **Display** - Set core color, edge color, glow effect, transparency, and size -- **Homing** - Toggle homing, adjust turn rate and max tracking range -- **Combat** - Damage, knockback, vertical knockback, hit cooldown, and optional AOE splash -- **Lifespan** - Projectile speed, max age, and max travel distance - ---- - -## Movement Abilities 💨 - -Abilities that reposition the caster in combat. - -- **Charge** - Rush forward in a line, damaging all entities in the path. Configurable speed, hit width, and knockback -- **Dash** - A quick directional movement without dealing damage -- **Teleport** - Instantly relocate to the target's position - -> **Charge** locks direction during wind-up, so the telegraph accurately shows the attack path. - ---- - -## AOE Abilities 🌀 - -Area control abilities that dominate space. - -- **Sweeper** - A wide rotational sweep attack around the caster with configurable radius and rotation speed -- **Vortex** - Creates a pulling force that drags nearby entities toward the center while dealing damage - ---- - -## Telegraph System 📍 - -**Telegraphs** are visual ground indicators that warn players before an ability lands. They appear during the wind-up phase and disappear when the ability fires. - -**Shapes:** -- **Circle** - Filled circle with configurable radius -- **Ring** - Donut shape with inner and outer radius -- **Line** - Rectangle along the attack direction -- **Cone** - Fan/wedge shape with configurable angle -- **Point** - Single point indicator - -**Features:** -- **Color Customization** - Set ARGB colors for both the telegraph and its warning phase -- **Warning Phase** - Color shifts in the final ticks before the ability fires -- **Entity Tracking** - Telegraphs can follow a moving entity or stay at a fixed position -- **Smooth Interpolation** - Position updates are interpolated for clean visuals - -> Telegraphs are saved as **reusable presets** and can be shared across multiple abilities. - ---- - -## Animations & Sound 🎬 - -Abilities integrate directly with the animation and sound systems. - -- **Wind-up Animation** - Plays during the charging phase -- **Active Animation** - Plays when the ability fires -- **Animation Sync** - Optionally sync wind-up duration to match animation length exactly -- **Sound Events** - Assign custom sounds to both wind-up and active phases -- **Phase Colors** - Visual color feedback on the caster during wind-up and active - -> Many ability types include **built-in animation names** that work automatically when matching animations exist. - ---- - -## Effects & Conditions ⚡ - -### Potion Effects - -Abilities can apply **potion effects** to any entity they hit. Each effect has configurable type, duration, and amplifier. - -**Available Effects:** -Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue - -### Conditions - -Abilities support a **condition system** that controls when they can be used. Conditions are evaluated before execution and can require specific target states, ranges, or custom predicates. - ---- - -## Player Abilities 🧑 - -Players can unlock and use abilities too! - -- **Unlock System** - Players receive abilities via scripting or commands -- **Ability Selection** - Choose one ability at a time from your unlocked list -- **Universal Cooldown** - Shared cooldown across all player abilities - ---- - -## Scripting API 📜 - -Full scripting support for ability lifecycle events: - -- **StartEvent** *(Cancelable)* - Fired when wind-up begins -- **ExecuteEvent** *(Cancelable)* - Fired when the ability activates -- **InterruptEvent** - Fired when wind-up is interrupted by damage -- **CompleteEvent** - Fired when the ability finishes -- **HitEvent** *(Cancelable)* - Fired on each entity hit. Damage and knockback values can be modified -- **TickEvent** - Fired every tick with current phase and tick count - -> Scripts can cancel, modify damage, and react to every phase of ability execution. - ---- - -## Ability Preview 🔎 - -The ability editor includes a **live preview system**. Test your telegraph shapes, animations, and projectile visuals directly in the GUI on a dummy NPC — no world effects applied. - ---- - -## Ability Commands 💬 - -- `/kam ability list` - List all custom abilities -- `/kam ability types` - List all registered ability types -- `/kam ability info ` - View ability details -- `/kam ability delete ` - Delete a custom ability -- `/kam ability reload` - Reload abilities from disk - ---- diff --git a/Auction_Beta_Update.md b/Auction_Beta_Update.md deleted file mode 100644 index 8b382b4af..000000000 --- a/Auction_Beta_Update.md +++ /dev/null @@ -1,57 +0,0 @@ -# CNPC+ 1.11 Beta - Market Update - -🟡 **In Testing** - -## Features: ⚒️ - -- **Built-in Currency System:** -> Fully configurable economy currency used across all Market features. Profile persistent across character slots with Vault support for Bukkit-compatible plugins. - -- **Auction House:** -> Global player marketplace for listing items, bidding, and instant buyouts. Auctions last 24 hours by default. - -- **Auction Bidding & Snipe Protection:** -> Competitive bidding with a 5% minimum bid increment. Snipe Protection extends auctions on last-second bids. Outbid players are automatically refunded. - -- **Buyout System:** -> Instant purchase at the seller's Buyout Price. Highest bidder only pays the difference between their bid and the buyout. - -- **My Trades:** -> Single screen for managing Active Listings, Active Bids, and Pending Claims. Players can cancel listings with a 10% penalty if bids exist. - -- **Auction Notifications:** -> Real-time notifications for sales, outbids, and wins. Offline players receive a claim summary on login. - -- **Trade Slots:** -> Limited slots (default 8, max 45) shared across listings, bids, and claims. Configurable via permissions. - -- **Claim Expiration:** -> Uncollected claims expire after 20 days. - -- **Item Blacklist:** -> Block items by registry name, wildcard pattern, mod, or NBT tag. Soulbound and Profile-Slotbound items are always blocked automatically. - -- **Listing Fee & Sales Tax:** -> Configurable listing fee charged on creation and sales tax taken from successful sales. - -- **Search & Sorting:** -> Search by item name or seller. Sort by newest, ending soon, price, or most bids. - -- **Trader Stock System:** -> Limited stock with Global or Per-Player modes. Restock timers for MC Daily/Weekly, RL Daily/Weekly, or Custom intervals. - -- **Trader Currency Trades:** -> Trades can require currency on top of item costs. - -- **Auctioneer NPC Role:** -> New role that opens the Auction House on interaction. No configuration needed. - -- **Auction Commands:** -> `/kam auction open` for players. Admin commands for listing view and player activity inspection. - -**Extras** - -- Auction logging for server admins (tracks creates, bids, buyouts, sales, expirations, cancellations, claims). -- Lifetime currency tracking per player (total earned and spent). -- Configurable starting balance and max balance cap. -- Blacklist bypass permission for admins. diff --git a/Auction_Update.md b/Auction_Update.md deleted file mode 100644 index a04cc12e9..000000000 --- a/Auction_Update.md +++ /dev/null @@ -1,121 +0,0 @@ -# 🏪 CustomNPC+ 1.11 - Market Update 🏪 - ---- - -The **Market Update** brings a complete economy system to CNPC+! Create bustling marketplaces with **Traders** that have limited stock, or let players trade with each other through the brand new **Auction House**! - ---- - -## Currency System 💰 - -CNPC+ now has a **built-in currency** used across all Market features! - -- **Fully Configurable** - Name it Coins, Gold, Credits, whatever fits your world. Set a starting balance and max balance cap to shape your economy -- **Profile Persistent** - Currency carries across all your character slots -- **Vault Support** - Integrates seamlessly with Bukkit-compatible economy plugins if Vault is installed. Falls back to built-in currency otherwise -- **Lifetime Tracking** - Tracks total earned and spent per player - -> Full Scripting API support for currency operations on players. - ---- - -## Auction House 🏛️ - -A **global player marketplace** where players can list items, bid against each other, and purchase instantly! Search for items by name or seller, and sort by newest, ending soon, price, or most bids. - -### Selling - -List any item with a **Starting Price** for competitive bidding. Set an optional **Buyout Price** for players who want to skip the wait and buy immediately. Auctions last **24 hours** by default. - -> A configurable **Listing Fee** is charged when creating auctions, and a **Sales Tax** is taken from successful sales. - -### Bidding - -Compete for items by placing bids! Each bid must be at least **5%** higher than the current bid. **Snipe Protection** extends auctions when last-second bids come in, giving everyone a fair shot. If you get outbid, your currency is **automatically refunded**. - -### Buyout - -See something you need right now? Hit **Buy Now** to purchase instantly at the seller's Buyout Price. If you're currently the highest bidder on an item, you only pay the **difference** between your bid and the buyout. - -### My Trades - -One screen to manage all your auction activity: - -- **Active Listings** - Items you're currently selling -- **Active Bids** - Auctions you're competing in -- **Ready to Claim** - Won items and currency waiting for pickup - -Players can **cancel** their own listings -- items are returned as a claim. If there are active bids on the listing, a **10% cancellation penalty** is charged. - -> Claims expire after **20 days**. Make sure to collect your items and currency before they're gone! - -### Notifications - -Get notified immediately when your item sells, when you're outbid, or when you win an auction. Offline? You'll get a full **claim summary** when you log back in showing exactly what's waiting for you. - -### Trade Slots - -Every player gets a limited number of **Trade Slots** (default 8). Slots are shared across Active Listings, Active Bids, **and** Pending Claims -- so uncollected claims take up space. Pick up your claims to free slots for new listings and bids! - -> Server owners can grant players more slots via permissions up to a maximum of 45. - ---- - -## Item Blacklist 🚫 - -Server owners have full control over what items can be listed on the Auction House. - -**Block by:** -- **Item** - Specific registry names like `minecraft:diamond_sword` -- **Wildcard** - Patterns like `minecraft:diamond*` to block all diamond items -- **Mod** - Block all items from a specific mod -- **NBT Tag** - Block items containing certain NBT data - -> **Soulbound** and **Profile-Slotbound** items are always blocked automatically, regardless of blacklist settings. Bound items cannot be traded! - -Manage the blacklist in-game with `/kam auction blacklist` commands, or configure it directly in the config file. - ---- - -## Trader Enhancements 🛒 - -### Stock System - -Traders now support **limited stock** with automatic restocking! - -**Stock Modes:** -- **Global** - All players share the same stock pool -- **Per-Player** - Each player has their own purchase limits - -**Restock Timers:** -- **MC Daily / Weekly** - Restock based on Minecraft time -- **RL Daily / Weekly** - Restock based on real-life time -- **Custom** - Set your own interval in MC ticks or real-time - -Stock counts, out-of-stock status, and restock timers are all visible directly in the trade interface. - -> Admins can manually reset stock or cooldowns via the Trader GUI. - -### Currency Trades - -Trades can now require **currency on top of items**. Combine material costs with coin costs for balanced economy progression! - ---- - -## Auctioneer Role 🧑‍💼 - -New NPC role for the Auction House! Set the role on any NPC and players can access the full Auction House by interacting with them -- no extra configuration needed. The role respects the global Auction Enabled setting. - -### Auction Commands - -Players can also access the Auction House via command: - -- `/kam auction open` - Opens the Auction House GUI - -**Admin Commands:** -- `/kam auction list [page]` - View active auctions in chat -- `/kam auction view ` - View a player's auction activity - -> Server owners can enable **auction logging** to track all auction activity (creates, bids, buyouts, sales, expirations, cancellations, and claims). - ---- diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..873018f92 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,98 @@ +# CustomNPC+ 1.11 Changelog + +## Ability System +- Phase-based abilities (Wind-up, Active, Dazed) with configurable cooldowns, targeting, range, interrupts, invulnerability, and magic damage +- **Melee:** Slam, Heavy Hit, Cutter +- **Energy Projectiles:** Orb, Disc, Beam, Laser Shot with variant system, homing, hit types (Single/Pierce/Multi), size interpolation, explosions +- **Barriers:** Dome, Wall, Shield with HP, reflection, damage absorption +- **Defensive:** Guard, Counter, Dodge +- **Movement:** Charge, Dash, Teleport +- **AOE:** Shockwave, Sweeper, Vortex +- **Hazards & Traps:** Persistent zones and proximity triggers with visual presets +- **Effect:** Healing, buffs, debuffs with target filtering (Allies/Enemies/All) +- **Custom Ability:** Blank-slate type with full script hooks and toggle modes +- Burst system, chained ability combos with concurrency, telegraph system (6 shapes) +- Per-phase animations and sound events +- Ability conditions: HP Threshold, Hit Count, Has Item, Quest Completed, Has Effect +- 12-slot player ability hotbar with HUD editor +- Full scripting API for ability and energy projectile lifecycle events +- Ability Extender system for custom hooks +- Live preview in editor +- Commands: `/kam ability list|types|prebuilts|info|delete|reload|give|remove|giveChain|removeChain|player` + +## Auction House +- Global marketplace with bidding, buyout, and snipe protection +- Built-in currency system (configurable, profile-persistent, Vault support) +- Listing fees, sales tax, minimum prices +- My Trades panel with claim management (20-day expiry) +- Search/sort, notifications (online + offline summary) +- Trade slots (default 8, expandable via permissions) +- Item blacklist (by item, wildcard, mod, NBT; soulbound always blocked) +- Auctioneer NPC role +- Admin GUI and logging +- Cancelable scripting events: Create, Bid, Buyout, Cancel, Claim + +## Script Editor +- Full code editor with syntax highlighting, autocomplete, error detection, and hover tooltips +- Go to Line, Search/Replace, Go to Definition, Fullscreen +- Undo/Redo, Duplicate Line, Comment Toggle, Rename, Move Lines +- Line numbers, smooth scrolling, indent guides, brace matching, smart brackets + +## Java Scripting +- Write scripts in Java via Janino compiler with automatic hook resolution +- Per-tab language selector (mix Java and JavaScript) +- External `.java` file support + +## Client-Side Scripting +- Server-controlled client script execution with auto-sync (off by default) + +## Addon API Support +- Ship `.d.ts` type definitions for automatic script editor autocomplete +- Patch support for extending CNPC+ types, hot reload + +## Traders +- Stock system: Global or Per-Player modes with configurable restock timers +- Currency trades (items + coins) +- Client-side balance preview + +## Cloner +- Folder and subfolder organization for all categories +- Full-width directory browser, improved tabs, tag-based filtering + +## Animations +- Data store for passing data across events/frames +- Consumer-based task system +- Expanded scripting API + +## Animated Textures +- Frame-based animation for items, effect icons, ability hotbar, scripted GUIs + +## NPC API +- `IHitboxData` (width/height scaling), `ITintData` (hurt tint, persistent tints) +- Scriptable behavior: sprint, swim, doors, fire reactions, tactical chance, walking range +- `ISound` (volume, pitch, repeat, position) +- Skin overlay `getColor()`/`setColor()`, knockback API +- Six overlays in singleplayer, script error reporting to console + +## NPC Combat & Behavior +- Attack speed enforcement, passive faction protection +- Improved track speed, invalid texture fallback + +## Other Changes +- Player Dialog Events match NPC Dialog Events +- Linked Item attack speed and scripting API +- Right-click cycling on multi-option buttons +- Legacy quest import (1.6.4), fullscreen/pannable GUIs, unified menu background +- Textfield CTRL shortcuts, `java.lang.reflect` banned in scripts +- Entity packet loss fix (invisible NPCs) +- Natural spawn GUI, runtime control, and despawn improvements + +## Bug Fixes +- Script config sync, Bukkit integration +- Quest cooldown for MC/RL Custom timers, quest/dialog saving and categories +- Bard music restart on dialog open +- Spawner yaw, biome spawn persistence, NPC invisibility +- Track speed, set speed edge cases, spawn data, block waypoints, job spawner +- Hitbox scaling and collision +- Animation offsets, lookup failures, syncing, resync on teleport, registration names, double loading +- Mount movement jitter, dismount edge cases diff --git a/README.md b/README.md index 001657d95..979cd2373 100644 --- a/README.md +++ b/README.md @@ -1,95 +1,432 @@ +![CustomNPC+ Banner](images/logo_banner.png) -## 👋 Welcome to the CustomNPC+ Repository. -![](images/logo_banner.png) +# CustomNPC+ -> CustomNPC+ is a [Minecraft](https://minecraft.net/) mod that allows you to add custom NPCs to your world. It is developed for creative and storytelling players who want to make their Minecraft worlds more in-depth and unique. CustomNPC+ is only a branch version of the **1.7.10** Forge version of the original (down below) and has no plans to add or update any other version. This is not an official version of CustomNPC. +**CustomNPC+** is a Minecraft 1.7.10 Forge mod that lets you create fully customizable NPCs with advanced AI, combat abilities, quests, dialogs, scripting, an economy system, and much more. Built for creative and storytelling players who want to transform their worlds into living RPG experiences. ----------------- +> CustomNPC+ is a branch version of the original [CustomNPC](https://www.curseforge.com/minecraft/mc-mods/custom-npcs) by [Noppes](https://github.com/Noppes), developed with permission. This is not an official version of CustomNPC. - - Support Me +--- + + [![Download CustomNPC+](https://img.shields.io/badge/CustomNPC+-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://modrinth.com/mod/customnpc-plus) [![Download MPM+](https://img.shields.io/badge/MorePlayerModels+-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus) [![Download PluginMod](https://img.shields.io/badge/Plugin_Mod-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://github.com/KAMKEEL/Plugin-Mod) ----------------- +--- -### ❗ Notice -I am not the original creator of CustomNPC. The original creator is @[Noppes](https://github.com/Noppes). I have been permitted to update and develop my own branch version for 1.7.10. The original mod that is updated to the latest versions of Minecraft can be found on these links: [CurseForge](https://www.curseforge.com/minecraft/mc-mods/custom-npcs), [kodevelopment](http://www.kodevelopment.nl/minecraft/customnpcs) +## Installation -### ⬇️ Downloads +CustomNPC+ is a **replacement** for the original CustomNPC — not an add-on. Do not install both together. Simply drop CustomNPC+ into your client or server mods folder. All original CustomNPC features are preserved and expanded upon. + +> Please **backup your world** before installing. Report any bugs on the [issue tracker](https://github.com/KAMKEEL/CustomNPC-Plus/issues). + +### Downloads - **Modrinth**: [Download](https://modrinth.com/mod/customnpc-plus) - **CurseForge**: [Download](https://www.curseforge.com/minecraft/mc-mods/customnpc-plus) -### 🔹 Installation -This mod is an ***update*** to CustomNPC and not an add-on. Do not install CustomNPC with CustomNPC-Plus. CustomNPC-Plus does not remove any functional features from the original mod. It expands upon CustomNPC with original features and backported features from newer versions. Simply drag CustomNPC-Plus into any client/server mods folder to utilize. Please **backup** before using as this could still have unforeseen errors. Report any bugs if found, thank you and enjoy. +--- -### ❓ Features: -- Flying NPC (Smart Pathfinding) -- 1.8 Skin Support (64x64) (Alex/Steve64) -- Full URL64 Selector (Downloads FULL Size Images for Custom Mob Skins) -- Additional Parts: [Wings, Fins, Capes, Horns, Tail] -- Hide Body Parts [Arms, Legs, Head, Body] -- Custom Overlays -- Animation Maker -- Enhanced Cloner GUI (More Tabs, Filters, Tags) -- Markov Name Generator -- Dark Mode GUI (Link Below) -- 1.12 Scripting Features (Details below) -- Profile System (Multiple Character Slots) -- Quest Party System -- Item and Armor Attributes -- Magic System with Elemental Cycles -- Custom Effect Engine -- Scripted Blocks & Particles -- Compass Marks for Waypoints -- Custom Model Support -- Gecko & Dragon Block C Addons + -#### Scripting: -- CustomNPC+ Api: [API](https://github.com/KAMKEEL/CustomNPC-Plus-API) -- Java Doc: [kamkeel.github.io/CustomNPC-Plus](https://kamkeel.github.io/CustomNPC-Plus/) -- Scripted Items -- Player Overlays -- Script Timers -- Global Scripts -- Script Logging -- GUI Overlays -- Event Scripting -(We never remove script functionality, only add on existing functions) +> More betas with new features will continue to be released to supporters for **Early Access** to new content! -## 🔰 Skin Model Feature: -###### **Majority of these cape designs are taken from the internet with fair-usage.* -##### ❔ Please note all *local* skins in this version of CustomNPC, must match the model selected. - +--- + +## Feature Overview + +### NPC Creation & Customization + +Create NPCs with deep visual customization and lifelike behavior. + + + +- **Skin System** - 1.8 skin support (64x64), Alex & Steve64 models, full URL64 selector that downloads full-size images for custom skins +- **Body Parts** - Wings, fins, capes, horns, tails. Hide individual body parts (arms, legs, head, body) +- **Skin Overlays** - Layer additional textures on top of the base skin with color tinting and alpha control +- **Custom Models** - Support for custom model formats, plus Gecko and DBC addon model integration +- **Hitbox Scaling** - Independently scale NPC hitbox width and height +- **Tint System** - Control hurt flash color and apply persistent color tints + +--- + +### NPC AI & Behavior + +NPCs have a full AI system for combat, pathing, and interaction. + +- **Flying NPCs** - Smart pathfinding in 3D space for flying entities +- **Combat AI** - Multiple tactical behaviors: attack, ranged attack, ambush, pounce, dodge-shoot, zigzag, stalk, orbit, sprint-to-target, and leap attacks +- **Movement Types** - Standing, wandering, and moving path modes +- **Pathfinding** - Ground, flying, and water navigation +- **Door Interaction** - NPCs can break, open, or ignore doors +- **Behavior Controls** - Configurable sprinting, swimming, fire reactions, tactical chance, and walking range +- **Attack Speed** - NPCs respect attack speed timing when dealing damage +- **Faction Awareness** - NPCs respond to faction standings. Passive faction NPCs are protected from damage -#### Flying NPCs: -#### Url64: - +--- -#### DarkMode + Cloner GUI: - +### NPC Roles & Jobs -## 🔗 Want to check out my other projects? -[Plugin Mod](https://github.com/KAMKEEL/Plugin-Mod) is a mod designed to add more aesthetic items for RPG and storytelling. It is compatible with CustomNPC+ and has many items intended to be used and wielded by created NPCs. +**Roles** give NPCs interactive functions — Trader, Follower, Bank, Transporter, Postman, Companion, Mount, and Auctioneer. **Jobs** give NPCs background tasks — Bard, Healer, Guard, Item Giver, Follower, Spawner, Conversation, and Chunk Loader. -[RPG Messenger](https://github.com/KAMKEEL/RPGMessenger) is a bukkit plugin designed to allow operators to create messagable NPCs for RPG Servers. Allows a 'RPG Controller' to reply quickly as NPCs, form groupchats, and messagable parties. +--- -[CustomNPC+ Dark Mode](https://github.com/KAMKEEL/CustomNPC-Plus-Dark-Mode) is a resource pack for CustomNPC+ that alters all GUIs within the mod to a dark variant that is both clean and pleasing to look at. +### Dialog System -## Cloning / Compiling / Building +Create branching dialog trees for storytelling and player interaction. -git clone call `git submodule update --init --recursive` + -Using IntelliJ, take the following steps: -1. Run `setupDecompWorkspace` under the `forgegradle` tab. -2. Refresh Gradle. -3. Run `genIntellijRuns` under the `other` tab to set up your Minecraft runs. +- **Dialog Trees** - Multi-level branching conversations with unlimited depth +- **Dialog Options** - Player choices that affect outcomes, trigger quests, or change faction standings +- **Dialog Images** - Display images alongside dialog text +- **Dialog Colors** - Customizable text and background colors +- **Categories** - Organize dialogs into categories for large projects +- **Availability Conditions** - Show or hide dialogs based on quests, factions, items, or custom conditions +- **Script Hooks** - Full scripting support for dialog open, close, and option events -or for Eclipse, run `gradlew setupDecompWorkspace eclipse` then import the project. +--- -Mixin code will not work if you do not add `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json` to your program arguments. +### Quest System + +A complete quest framework for RPG progression. + + + +- **Quest Types** - Item collection, dialog completion, kill targets, reach locations, area kills, and fully manual (script-driven) quests +- **Quest Tracking** - On-screen HUD overlay showing active quest objectives +- **Categories** - Organize quests into categories +- **Rewards** - Configure item, XP, and currency rewards +- **Cooldowns** - Repeatable quests with MC time, real-time, or custom cooldown intervals +- **Party Quests** - Share quest objectives across party members with configurable sharing modes +- **Availability** - Control quest visibility based on completed quests, faction standing, dialogs, and more +- **Script Hooks** - Events for quest start, completion, turn-in, and custom quest objectives + +--- + +### Ability System + +A full combat ability system for both NPCs and players. + + + + +**Melee Abilities** - Slam, Heavy Hit, Cutter +**Energy Projectiles** - Orbs, Discs, Beams, Laser Shots with full visual customization, homing, and hit types +**Energy Barriers** - Domes, Walls, Shields with HP, reflection, and damage absorption +**Defensive** - Guard, Counter, Dodge with configurable damage reduction and counter-attacks +**Movement** - Charge, Dash, Teleport +**AOE** - Shockwave, Sweeper, Vortex +**Hazards & Traps** - Persistent damage zones and proximity-triggered traps with visual presets +**Support** - Ability Effect for healing, buffs, and debuffs + +**Key Features:** +- Phase-based execution (Wind-up, Active, Dazed) with visual telegraphs +- Burst system for rapid multi-fire +- Chained abilities for sequential combos +- Player ability hotbar (12 slots) with unlock system +- Full scripting API for every lifecycle event +- Live preview in the ability editor + +--- + +### Auction House & Economy + +A complete marketplace and economy system. + + + +- **Built-in Currency** - Configurable currency with starting balance, max cap, and Vault plugin integration +- **Auction House** - Global player marketplace with bidding, buyout, snipe protection, and notifications +- **Trade Slots** - Configurable per-player slot limits via permissions +- **Item Blacklist** - Block items by name, wildcard, mod, or NBT tag from being listed +- **Admin Tools** - Dedicated admin GUI for managing listings and creating server auctions +- **Scripting API** - Cancelable events for creates, bids, buyouts, cancels, and claims + +**Trader Enhancements:** +- Limited stock with automatic restocking (MC time, real-time, or custom intervals) +- Global or per-player stock modes +- Currency costs on top of item trades +- Client-side balance preview + +--- + +### Script Editor + +A full-featured code editor built right into Minecraft. + + + +- **Syntax Highlighting** - Color-coded keywords, types, variables, methods, strings, and comments +- **Autocomplete** - Smart suggestions with type awareness, static vs instance context, and auto-imports +- **Error Detection** - Real-time underlining of wrong argument types, missing methods, type mismatches, and unused imports +- **Hover Info** - Full type information, documentation, and JSDoc rendering on hover +- **Navigation** - Go to line, search & replace, go to definition, and fullscreen mode +- **Editing** - Smart undo/redo, duplicate lines, comment toggle, rename refactoring, smart bracket pairing +- **Visual** - Line numbers, smooth scrolling, indent guides, brace matching, resizable panels + +--- + +### Scripting + +Write scripts in **JavaScript** or **Java** to control every aspect of the mod. + +- **Java Scripting** - Write real Java code compiled by the Janino engine. Full support for classes, generics, lambdas, and method references +- **JavaScript** - Full Nashorn-based JavaScript with ECMAScript 5.1 globals (Math, JSON, Date, Number) +- **Client-Side Scripting** - Run scripts on the client for responsive visual experiences (server-controlled) +- **154+ Script Hooks** - Events for NPCs, players, blocks, items, quests, dialogs, factions, abilities, auction, animations, and more +- **Script Types** - NPC, Player, Global, Block, Item, Linked Item, Effect, Ability, Recipe, and Forge Event scripts +- **Scripted Blocks** - Blocks with full script hooks for click, redstone, neighbor changes, and more +- **Scripted Items** - Items with use, attack, toss, pickup, and durability hooks +- **Custom GUIs** - Build custom interfaces with buttons, text fields, scroll panels, and slots via scripting +- **GUI Overlays** - Persistent on-screen overlays with labels, lines, and textured rectangles +- **Addon API** - Mods can ship `.d.ts` type definitions for full autocomplete in the editor + +**Resources:** +- API Repository: [CustomNPC+ API](https://github.com/KAMKEEL/CustomNPC-Plus-API) +- Java Docs: [kamkeel.github.io/CustomNPC-Plus](https://kamkeel.github.io/CustomNPC-Plus/) + + + + +--- + +### Animation System + +Create custom animations for NPCs directly in-game. + +- **Animation Maker** - Visual editor for creating frame-based animations +- **Animation Parts** - Animate individual body parts with rotation, position, and scaling +- **Frame Events** - Script hooks for animation start, end, frame enter, and frame exit +- **Data Store** - Animations can store and pass data across events and frames +- **Task System** - Consumer-based callbacks for animation lifecycle +- **Built-in Animations** - Pre-made animations for abilities that work automatically +- **Multiple Registrations** - Register multiple animations under one common name +- **Animated Textures** - Frame-based animated textures for items, effects, and ability icons + + + +--- + +### Custom Effects + +Create custom status effects beyond vanilla potions. + +- **Custom Icons** - Each effect gets its own texture, with support for animated icons +- **Script Hooks** - Events for effect apply, tick, and removal +- **Ability Integration** - Abilities can apply custom effects to targets +- **Condition System** - Check if entities have specific effects for ability or availability conditions + +--- + +### Profile System + +Multiple character slots on a single account. + +- **Profile Slots** - Each slot stores separate quest progress, dialogs, factions, currency, abilities, and effects +- **Region Locking** - Lock profiles to specific areas +- **Soulbound Items** - Bind items to a specific player by UUID +- **Profile-Slotbound Items** - Bind items to a specific profile slot + +--- + +### Party System + +Group up with other players for cooperative gameplay. + +- **Party Management** - Invite, kick, leave, disband, and transfer leadership +- **Quest Sharing** - Share quest objectives across party members +- **Ability Integration** - Party members are treated as allies for AOE ability targeting +- **Script Hooks** - Events for invites, kicks, leaves, disbands, and quest completion + + + + +--- + +### Faction System + +Create factions to control NPC relationships and player reputation. + +- **Faction Points** - Players earn or lose standing with factions through quests, combat, and scripting +- **Availability Conditions** - Gate dialogs, quests, and content behind faction thresholds +- **NPC Behavior** - NPCs react to players based on faction standing (friendly, neutral, hostile) +- **Passive Factions** - Passive faction NPCs are protected from damage + +--- + +### HUD System + +Customizable on-screen elements. + +- **HUD Editor** - Drag and position HUD components to fit your screen +- **Ability Hotbar** - 12-slot bar with horizontal/vertical layout and configurable visible slots +- **Quest Tracking** - On-screen quest objective tracker +- **Compass** - Directional compass with quest and waypoint markers +- **Effect Bar** - Display active custom effects + + + +--- + +### Cloner & Organization + +Save, organize, and reuse NPCs and content. + +- **Cloner Tabs** - Save and load NPCs, items, and other content +- **Folder System** - Organize with folders and subfolders for animations, abilities, forms, auras, outlines, effects, and linked items +- **Quick Tags** - Tag-based filtering for fast searching +- **Full Screen Browser** - Wide directory view for large collections + + + +--- + +### Items & Blocks + +A large library of custom items and decorative blocks. + +**Weapons:** Battle Axe, Broadsword, Claw, Crossbow, Dagger, Staff, Glaive, Gun, Kunai, Scythe, Spear, Wand, Warhammer, Musket, and more + +**Linked Items:** Create custom items with configurable attack speed, scripted behavior, animated textures, and item versioning + +**Blocks:** Banners, barrels, beams, signs, campfires, candles, chairs, couches, crates, crystals, lanterns, mailboxes, pedestals, redstone blocks, and scripted blocks + +**Crafting:** Carpentry Bench and Anvil with custom recipe support + + + + +--- + +### Custom Models + +Support for custom NPC models beyond the default humanoid. Import Blockbench models using the **Gecko Addon** (GeckoLib integration) or use **Armorer's Workshop** skins with the AW Addon. + + + + +--- + +### Addon Compatibility + +CustomNPC+ has official addons that extend its functionality with other mods. Vault and Pixelmon are also supported natively for economy and scripting integration. + +--- + +## Official CNPC+ Addons + +### DBC Addon + +Adds full compatibility between [Dragon Block C](https://www.curseforge.com/minecraft/mc-mods/dragon-block-c) and CustomNPC+. Extends abilities with ki-based attacks, adds DBC stat integration to conditions, and enables DBC model/animation support on NPCs. + +[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/cnpc-dbc-addon) +[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/customnpc-plus-dbc-addon) +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/CustomNPC-DBC-Addon) + +### Gecko Addon + +Adds [GeckoLib](https://www.curseforge.com/minecraft/mc-mods/geckolib) support to CustomNPC+. Import Blockbench models directly into the mod and use them as custom NPC models with full animation support. + +[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/cnpc-custom-model-addon) +[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/customnpc-plus-gecko-addon) +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/CustomNPC-Gecko-Addon) + +### Armorer's Workshop Addon + +Adds compatibility between [Armorer's Workshop](https://www.curseforge.com/minecraft/mc-mods/armorers-workshop) and CustomNPC+. Use Armorer's Workshop skins and equipment on NPCs with custom rotation, scaling, and animation support. Requires UniMixins. + +[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/cnpc-armorers-workshop-addon) +[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/customnpc-plus-aw-addon) + +--- + +## Other Projects + +### MorePlayerModels+ + +An updated continuation of MorePlayerModels for 1.7.10 with backported GUIs, original parts and customizations, and permission support. Works alongside CustomNPC+. This is a replacement — do not install alongside the original MorePlayerModels. + +[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus) +[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/moreplayermodels+) +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/MorePlayerModels-Plus) + +### The Plugin Mod + +Adds aesthetic weapons, artifacts, blocks, and apples for RPG and storytelling servers. Designed to pair with CustomNPC+ — use the included swords, spears, axes, medpacks, and decorative blocks to make your NPCs and worlds more diverse. + +[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/the-plugin-mod) +[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/the-plugin-mod) +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/Plugin-Mod) + +### HexText + +Upgrades Minecraft's font renderer with full RGB hex color support, nested color spans, and animated text effects (glow, shake, wave). Works in signs, anvils, and chat. Requires UniMixins. + +[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/hex-text) +[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/hex-text) +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/HexText) + +### RPG Messenger + +A Bukkit plugin for messageable NPCs, group chats, and RPG controller tools. Allows operators to create NPCs that players can message, and lets RPG controllers reply as NPCs in real-time. + +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/RPGMessenger) + +### CustomNPC+ Dark Mode + +A resource pack that applies a clean dark theme to all CustomNPC+ GUIs. + +[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/CustomNPC-Plus-Dark-Mode) + +--- + +## Configuration + +CustomNPC+ has a modular configuration system: + +| Config | Purpose | +|--------|---------| +| **Main** | Core mod settings | +| **Client** | Client-side display and UI preferences | +| **Script** | Scripting engine settings and client script toggle | +| **Market** | Currency, auction house, trader, and economy settings | +| **Energy** | Energy projectile settings (explosion block damage, dome item blacklist) | +| **Item** | Item and gun configuration | +| **Debug** | Debug logging and diagnostics | +| **Experimental** | Experimental features toggle | + +--- + +## Building from Source + +This project uses the [GTNH Gradle Convention](https://github.com/GTNewHorizons/ExampleMod1.7.10) build system with [RetroFuturaGradle](https://github.com/GTNewHorizons/RetroFuturaGradle). + +```bash +git clone +git submodule update --init --recursive +./gradlew build +``` + +That's it. Submodules pull in the API sources, and `build` handles decompilation, compilation, and mixin embedding automatically. + +**Run the game:** +```bash +./gradlew runClient # Launch client +./gradlew runServer # Launch server +``` + +**IDE Setup (IntelliJ):** +1. Import the project as a Gradle project +2. Run `./gradlew genIntellijRuns` +3. Add program arguments: `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json` + +--- + +## Notice + +I am not the original creator of CustomNPC. The original creator is [Noppes](https://github.com/Noppes). I have been permitted to update and develop my own branch version for 1.7.10. The original mod updated to the latest Minecraft versions can be found on [CurseForge](https://www.curseforge.com/minecraft/mc-mods/custom-npcs) and [kodevelopment](http://www.kodevelopment.nl/minecraft/customnpcs). diff --git a/build.gradle b/build.gradle index 7421f7cf7..3dfbb49ae 100644 --- a/build.gradle +++ b/build.gradle @@ -3,9 +3,10 @@ plugins { id 'com.gtnewhorizons.gtnhconvention' id 'idea' + id "dts.typescript-generator" } -version = "1.11-beta1" +version = "1.11.1" group= "kamkeel.customnpc-plus" archivesBaseName = "CustomNPC-Plus" @@ -56,5 +57,57 @@ sourceSets.main.java { srcDirs += apiDir } +// ============================================================================ +// 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 { + sourceDirectories = ['src/api/java', 'src/main/java'] + outputDirectory = "src/main/resources/assets/${project.property("modId")}/api" + apiPackages = ['noppes.npcs.api', 'net.minecraft'] as Set + cleanOutputFirst = true // Clean old generated files before regenerating + patchesDirectory = "dts-patches" + implementationPackages = [ + 'noppes.npcs.scripted', + 'noppes.npcs.controllers.data', + 'noppes.npcs.entity.data', + 'noppes.npcs.quests', + 'kamkeel.npcs.controllers.data' + ] as Set +} +processResources.dependsOn generateTypeScriptDefinitions +sourcesJar.dependsOn generateTypeScriptDefinitions + + +// Javadoc configuration +javadoc { + options.encoding = 'UTF-8' + options.charSet = 'UTF-8' + options.docEncoding = 'UTF-8' + + options.tags = [ + 'hookName:a:Hook Name:' + ] + + options.stylesheetFile = file('.github/javadoc/javadoc-theme.css') + options.header = file('.github/javadoc/javadoc-header.html').text.replaceAll('\\s+', ' ').trim() + + options.addBooleanOption('-allow-script-in-comments', true) + options.footer = file('.github/javadoc/javadoc-footer.html').text.replaceAll('\\s+', ' ').trim() + + // Only document the public API, not net.minecraft stubs + include 'noppes/npcs/api/**' + + options.links( + 'https://docs.oracle.com/en/java/javase/11/docs/api/' + ) + + javadocTool = javaToolchains.javadocToolFor { + languageVersion = JavaLanguageVersion.of(11) + } +} + // Modify the existing 'build' task to depend on 'updateAPI' //tasks.apiClasses.dependsOn 'updateAPI' diff --git a/dependencies.gradle b/dependencies.gradle index 486ef7430..dce55cad2 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -35,7 +35,7 @@ */ def embedMixin = !project.hasProperty("nomixin"); dependencies { - runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.44-GTNH:dev") if (!project.hasProperty("noNashorn")) { runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946") } @@ -43,8 +43,10 @@ dependencies { // compileOnly(files("./tools/bukkit-api/spigot-api-ONLY.jar")) // compileOnly(files("./tools/bukkit-api/Vault-1.4.1.jar")) - shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar")) - annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar")) + shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.2.jar")) + annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.2.jar")) + + testImplementation("junit:junit:4.13.2") if(embedMixin){ // Normal Jar will include built in Mixins diff --git a/dts-patches/ecmascript/Array.d.ts b/dts-patches/ecmascript/Array.d.ts new file mode 100644 index 000000000..6ffd25a8c --- /dev/null +++ b/dts-patches/ecmascript/Array.d.ts @@ -0,0 +1,126 @@ +/** + * ECMAScript 5.1 - Array type for working with ordered collections of elements. + * Supports static methods like Array.isArray() and instance methods like push(), map(), filter(). + * + * ## How to Use + * + * ### Creating Arrays + * ```js + * var empty = []; // Empty array + * var nums = [1, 2, 3]; // Array with values + * var mixed = ["hello", 42, true]; // Mixed types + * var nested = [[1, 2], [3, 4]]; // Nested arrays + * ``` + * + * ### Static Methods + * ```js + * Array.isArray([1, 2, 3]); // true + * Array.isArray("hello"); // false + * Array.isArray({length: 3}); // false + * ``` + * + * ### Adding & Removing Elements + * ```js + * var arr = [1, 2, 3]; + * arr.push(4); // [1, 2, 3, 4] — add to end + * arr.pop(); // [1, 2, 3] — remove from end + * arr.unshift(0); // [0, 1, 2, 3] — add to start + * arr.shift(); // [1, 2, 3] — remove from start + * arr.splice(1, 1, 99); // [1, 99, 3] — replace at index 1 + * ``` + * + * ### Searching & Iterating + * ```js + * var arr = [10, 20, 30, 20]; + * arr.indexOf(20); // 1 (first match) + * arr.lastIndexOf(20); // 3 (last match) + * arr.forEach(function(val) { log(val); }); + * var doubled = arr.map(function(v) { return v * 2; }); // [20, 40, 60, 40] + * var big = arr.filter(function(v) { return v > 15; }); // [20, 30, 20] + * ``` + * + * ### Reducing & Testing + * ```js + * var sum = [1, 2, 3].reduce(function(acc, v) { return acc + v; }, 0); // 6 + * var allPositive = [1, 2, 3].every(function(v) { return v > 0; }); // true + * var hasNeg = [1, -2, 3].some(function(v) { return v < 0; }); // true + * ``` + * + * ### ❌ Common Mistakes + * ```js + * Array.push(1); // TypeError — push is an instance method + * var a = [3,1,2]; a.sort(); // Sorts as strings! Use compareFn for numbers + * a.sort(function(a, b) { return a - b; }); // Correct numeric sort: [1, 2, 3] + * ``` + */ +export interface Array { + /** Returns true if the given object is an array, false otherwise */ + static isArray(arg: any): boolean; + + /** The number of elements in the array */ + length: number; + + /** Combines two or more arrays and returns a new array without modifying the original */ + concat(...items: T[]): T[]; + + /** Tests whether all elements in the array pass the provided test function */ + every(callback: Java.java.util.function.Function): boolean; + + /** Creates a new array with all elements that pass the test implemented by the provided function */ + filter(callback: Java.java.util.function.Function): T[]; + + /** Executes a provided function once for each array element. Returns undefined */ + forEach(callback: Java.java.util.function.Consumer): void; + + /** Returns the first index at which an element is found, or -1 if not present */ + indexOf(searchElement: T): number; + indexOf(searchElement: T, fromIndex: number): number; + + /** Joins all elements of an array into a string separated by the given separator */ + join(separator: string): string; + + /** Returns the last index at which an element is found, or -1 if not present */ + lastIndexOf(searchElement: T): number; + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** Creates a new array with the results of calling a function on every element */ + map(callback: Java.java.util.function.Function): any[]; + + /** Removes and returns the last element from the array, modifying the original array */ + pop(): T; + + /** Adds one or more elements to the end of an array and returns the new length */ + push(...items: T[]): number; + + /** Applies a function against an accumulator and each element to reduce the array to a single value */ + reduce(callback: Java.java.util.function.BiFunction): any; + reduce(callback: Java.java.util.function.BiFunction, initialValue: any): any; + + /** Same as reduce() but processes the array from right to left */ + reduceRight(callback: Java.java.util.function.BiFunction): any; + reduceRight(callback: Java.java.util.function.BiFunction, initialValue: any): any; + + /** Reverses an array in place. The first element becomes the last, and vice versa */ + reverse(): T[]; + + /** Removes and returns the first element from the array, modifying the original array */ + shift(): T; + + /** Returns a shallow copy of a portion of an array as a new array object */ + slice(start: number, end: number): T[]; + + /** Tests whether at least one element in the array passes the test implemented by the provided function */ + some(callback: Java.java.util.function.Function): boolean; + + /** Sorts the elements of an array in place and returns the sorted array */ + sort(compareFn: Java.java.util.function.BiFunction): T[]; + + /** Changes the contents of an array by removing or replacing existing elements and/or adding new ones */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + + /** Returns a string representation of the array */ + toString(): string; + + /** Adds one or more elements to the beginning of an array and returns the new length */ + unshift(...items: T[]): number; +} diff --git a/dts-patches/ecmascript/Boolean.d.ts b/dts-patches/ecmascript/Boolean.d.ts new file mode 100644 index 000000000..50b68626e --- /dev/null +++ b/dts-patches/ecmascript/Boolean.d.ts @@ -0,0 +1,36 @@ +/** + * ECMAScript 5.1 - Boolean type for true/false values. + * Booleans are the result of comparison and logical operations. + * + * ## How to Use + * + * ### Creating Booleans + * ```js + * var yes = true; // Boolean literal + * var no = false; // Boolean literal + * var fromExpr = (5 > 3); // true (comparison result) + * ``` + * + * ### Boolean Methods + * ```js + * var b = true; + * b.toString(); // "true" + * b.valueOf(); // true (primitive value) + * ``` + * + * ### Truthy & Falsy Values + * ```js + * // These are FALSY (evaluate to false): + * // false, 0, "", null, undefined, NaN + * + * // These are TRUTHY (evaluate to true): + * // true, any non-zero number, any non-empty string, objects, arrays + * + */ +export interface Boolean { + /** Returns the string "true" or "false" */ + toString(): string; + + /** Returns the primitive boolean value */ + valueOf(): boolean; +} diff --git a/dts-patches/ecmascript/Date.d.ts b/dts-patches/ecmascript/Date.d.ts new file mode 100644 index 000000000..68f6f069c --- /dev/null +++ b/dts-patches/ecmascript/Date.d.ts @@ -0,0 +1,168 @@ +/** + * ECMAScript 5.1 - Date type for working with dates and times. + * Create with `new Date()` or use static methods like Date.now() to get current timestamp. + * + * ## How to Use + * + * ### Creating Dates + * ```js + * var now = new Date(); // Current date & time + * var epoch = new Date(0); // Jan 1, 1970 + * var specific = new Date(2024, 0, 15); // Jan 15, 2024 (months are 0-based!) + * var full = new Date(2024, 5, 15, 10, 30, 0); // Jun 15, 2024 10:30:00 + * var fromStr = new Date("2024-01-15"); // Parse from ISO string + * ``` + * + * ### Static Methods (no `new` needed) + * ```js + * var timestamp = Date.now(); // Current time in milliseconds + * var parsed = Date.parse("2024-01-15"); // Parse string to timestamp + * var utc = Date.UTC(2024, 0, 15); // UTC timestamp for Jan 15, 2024 + * ``` + * + * ### Common Mistakes + * ```js + * Date.now; // Returns the function, not the timestamp! + * Date.getMinutes(); // TypeError — instance method, not static + * new Date(2024, 1, 1); // Feb 1, not Jan 1 — months are 0-based! + * ``` + */ +export interface Date { + /** Returns the current time as the number of milliseconds since 1970-01-01 00:00:00 UTC */ + static now(): number; + + /** Parses a date string and returns the number of milliseconds since 1970-01-01 00:00:00 UTC */ + static parse(s: string): number; + + /** Returns the number of milliseconds since 1970-01-01 00:00:00 UTC for the given UTC date/time components */ + static UTC(year: number, month: number, date: number, hours: number, minutes: number, seconds: number, ms: number): number; + + /** Returns the day of the month (1-31) in local time */ + getDate(): number; + + /** Returns the day of the week (0=Sunday, 6=Saturday) in local time */ + getDay(): number; + + /** Returns the year in local time */ + getFullYear(): number; + + /** Returns the hour (0-23) in local time */ + getHours(): number; + + /** Returns the milliseconds (0-999) in local time */ + getMilliseconds(): number; + + /** Returns the minutes (0-59) in local time */ + getMinutes(): number; + + /** Returns the month (0=January, 11=December) in local time */ + getMonth(): number; + + /** Returns the seconds (0-59) in local time */ + getSeconds(): number; + + /** Returns the number of milliseconds since 1970-01-01 00:00:00 UTC */ + getTime(): number; + + /** Returns the time zone offset in minutes between local time and UTC */ + getTimezoneOffset(): number; + + /** Returns the day of the month (1-31) in UTC */ + getUTCDate(): number; + + /** Returns the day of the week (0=Sunday, 6=Saturday) in UTC */ + getUTCDay(): number; + + /** Returns the year in UTC */ + getUTCFullYear(): number; + + /** Returns the hour (0-23) in UTC */ + getUTCHours(): number; + + /** Returns the milliseconds (0-999) in UTC */ + getUTCMilliseconds(): number; + + /** Returns the minutes (0-59) in UTC */ + getUTCMinutes(): number; + + /** Returns the month (0=January, 11=December) in UTC */ + getUTCMonth(): number; + + /** Returns the seconds (0-59) in UTC */ + getUTCSeconds(): number; + + /** Sets the day of the month and returns the new timestamp */ + setDate(date: number): number; + + /** Sets the year, and optionally month and date, then returns the new timestamp */ + setFullYear(year: number, month: number, date: number): number; + + /** Sets the hour, minutes, seconds, and milliseconds, then returns the new timestamp */ + setHours(hour: number, min: number, sec: number, ms: number): number; + + /** Sets the milliseconds and returns the new timestamp */ + setMilliseconds(ms: number): number; + + /** Sets the minutes, seconds, and milliseconds, then returns the new timestamp */ + setMinutes(min: number, sec: number, ms: number): number; + + /** Sets the month, and optionally date, then returns the new timestamp */ + setMonth(month: number, date: number): number; + + /** Sets the seconds and milliseconds, then returns the new timestamp */ + setSeconds(sec: number, ms: number): number; + + /** Sets the timestamp (milliseconds since epoch) and returns it */ + setTime(time: number): number; + + /** Sets the day of the month (UTC) and returns the new timestamp */ + setUTCDate(date: number): number; + + /** Sets the year, month, and date (UTC), then returns the new timestamp */ + setUTCFullYear(year: number, month: number, date: number): number; + + /** Sets the hour, minutes, seconds, and milliseconds (UTC), then returns the new timestamp */ + setUTCHours(hour: number, min: number, sec: number, ms: number): number; + + /** Sets the milliseconds (UTC) and returns the new timestamp */ + setUTCMilliseconds(ms: number): number; + + /** Sets the minutes, seconds, and milliseconds (UTC), then returns the new timestamp */ + setUTCMinutes(min: number, sec: number, ms: number): number; + + /** Sets the month and date (UTC), then returns the new timestamp */ + setUTCMonth(month: number, date: number): number; + + /** Sets the seconds and milliseconds (UTC), then returns the new timestamp */ + setUTCSeconds(sec: number, ms: number): number; + + /** Returns a string representation of the date portion in local time (e.g., "Mon Jan 01 2024") */ + toDateString(): string; + + /** Returns the date as an ISO 8601 string (e.g., "2024-01-01T00:00:00.000Z") */ + toISOString(): string; + + /** Returns a JSON representation of the date (typically an ISO 8601 string) */ + toJSON(key: any): string; + + /** Returns a localized string for the date portion (format depends on locale) */ + toLocaleDateString(): string; + + /** Returns a localized string for the entire date and time (format depends on locale) */ + toLocaleString(): string; + + /** Returns a localized string for the time portion (format depends on locale) */ + toLocaleTimeString(): string; + + /** Returns a string representation of the date and time in local time */ + toString(): string; + + /** Returns a string representation of the time portion in local time (e.g., "00:00:00 GMT+0000") */ + toTimeString(): string; + + /** Returns a string representation of the date and time in UTC (e.g., "Mon, 01 Jan 2024 00:00:00 GMT") */ + toUTCString(): string; + + /** Returns the primitive value of the date object (milliseconds since 1970-01-01 00:00:00 UTC) */ + valueOf(): number; +} diff --git a/dts-patches/ecmascript/Error.d.ts b/dts-patches/ecmascript/Error.d.ts new file mode 100644 index 000000000..797a763e4 --- /dev/null +++ b/dts-patches/ecmascript/Error.d.ts @@ -0,0 +1,81 @@ +/** + * ECMAScript 5.1 - Error base type for runtime errors. + * Throw Error objects to indicate failure conditions in your code. + * + * ## How to Use + * + * ### Creating & Throwing Errors + * ```js + * throw new Error("Something went wrong"); + * throw new TypeError("Expected a string"); + * throw new RangeError("Value out of range"); + * ``` + * + * ### Catching Errors + * ```js + * try { + * var result = riskyOperation(); + * } catch (e) { + * log(e.name); // "Error", "TypeError", etc. + * log(e.message); // "Something went wrong" + * log(e.toString()); // "Error: Something went wrong" + * } + * ``` + * + * ### Custom Error Messages + * ```js + * function divide(a, b) { + * if (b === 0) { + * throw new Error("Cannot divide by zero"); + * } + * return a / b; + * } + * ``` + * + * ### ❌ Common Mistakes + * ```js + * throw "Something went wrong"; // Works but no .name or .message properties + * Error("oops"); // Creates error but doesn't throw it! + * throw Error("oops"); // ✅ Works (with or without `new`) + * ``` + */ +export interface Error { + /** The name of the error type (e.g., "Error", "TypeError", "RangeError") */ + name: string; + + /** A human-readable description of what went wrong */ + message: string; + + /** Returns a string representation of the error (typically "name: message") */ + toString(): string; +} + +/** + * EvalError - Thrown when eval() function is misused (rarely used in modern JavaScript) + */ +export interface EvalError extends Error {} + +/** + * RangeError - Thrown when a numeric value is out of the acceptable range (e.g., array length < 0) + */ +export interface RangeError extends Error {} + +/** + * ReferenceError - Thrown when trying to reference a variable that does not exist or is not in scope + */ +export interface ReferenceError extends Error {} + +/** + * SyntaxError - Thrown when parsing invalid syntax (usually caught during compile/parse, not runtime) + */ +export interface SyntaxError extends Error {} + +/** + * TypeError - Thrown when an operation is performed on a value of the wrong type (e.g., calling a non-function) + */ +export interface TypeError extends Error {} + +/** + * URIError - Thrown by URI encoding/decoding functions when given invalid characters or sequences + */ +export interface URIError extends Error {} diff --git a/dts-patches/ecmascript/GlobalFunctions.d.ts b/dts-patches/ecmascript/GlobalFunctions.d.ts new file mode 100644 index 000000000..4f1f7ad3d --- /dev/null +++ b/dts-patches/ecmascript/GlobalFunctions.d.ts @@ -0,0 +1,75 @@ +/** + * ECMAScript 5.1 - Global functions available in the global scope. + * These are not on any specific object - call them directly (e.g., parseInt("42")). + * + * ## How to Use + * + * ### Parsing Numbers + * ```js + * parseInt("42"); // 42 + * parseInt("42px"); // 42 (stops at non-digit) + * parseInt("0xFF", 16); // 255 (hexadecimal) + * parseInt("111", 2); // 7 (binary) + * parseFloat("3.14"); // 3.14 + * parseFloat("3.14abc"); // 3.14 (stops at invalid char) + * ``` + * + * ### Checking Special Values + * ```js + * isNaN(NaN); // true + * isNaN(42); // false + * isNaN("hello"); // true (cannot parse as number) + * isNaN("42"); // false (can parse as number) + * isFinite(42); // true + * isFinite(Infinity); // false + * isFinite(NaN); // false + * ``` + * + * ### URI Encoding/Decoding + * ```js + * encodeURI("hello world"); // "hello%20world" + * decodeURI("hello%20world"); // "hello world" + * encodeURIComponent("a=1&b=2"); // "a%3D1%26b%3D2" (encodes & and =) + * decodeURIComponent("a%3D1%26b%3D2"); // "a=1&b=2" + * ``` + * + * ### ❌ Common Mistakes + * ```js + * parseInt("08"); // Some engines treat as octal! Always specify radix + * parseInt("08", 10); // 8 ✅ — explicitly base-10 + * parseInt(""); // NaN — empty string returns NaN, not 0 + * parseFloat(""); // NaN + * isNaN(undefined); // true — coerces to NaN first + * ``` + */ +export interface GlobalFunctions { + /** Evaluates JavaScript code in a string (use with caution - slow and potential security issues) */ + static eval(x: any): any; + + /** Parses a string and returns an integer. Stops parsing at the first non-digit character */ + static parseInt(string: string): number; + + /** Parses a string and returns an integer using the specified radix (base). Stops parsing at the first non-digit character */ + static parseInt(string: string, radix: number): number; + + /** Parses a string and returns a floating-point number. Stops parsing at the first invalid character */ + static parseFloat(string: string): number; + + /** Determines whether a value is NaN (not-a-number). The value is first coerced to a number before testing */ + static isNaN(value: any): boolean; + + /** Determines whether a value is a finite number. The value is first coerced to a number. Returns false for Infinity, -Infinity, and NaN */ + static isFinite(value: any): boolean; + + /** Decodes a URI by replacing encoded sequences like %20 with their original characters */ + static decodeURI(encodedURI: string): string; + + /** Decodes URI component by replacing ALL encoded sequences including those for reserved URI characters */ + static decodeURIComponent(encodedURIComponent: string): string; + + /** Encodes a URI by replacing special characters with %HH sequences (but preserves reserved characters like / : ?) */ + static encodeURI(uri: string): string; + + /** Encodes URI component by replacing ALL special characters including reserved ones with %HH sequences */ + static encodeURIComponent(uriComponent: string): string; +} diff --git a/dts-patches/ecmascript/JSON.d.ts b/dts-patches/ecmascript/JSON.d.ts new file mode 100644 index 000000000..1934e532e --- /dev/null +++ b/dts-patches/ecmascript/JSON.d.ts @@ -0,0 +1,100 @@ +/** + * ECMAScript 5.1 - JSON built-in object for parsing and serializing JSON data. + * + * ## How to Use + * + * JSON is a **static object** — use its methods directly, never with `new`. + * + * ### Parsing JSON Strings to Objects + * ```js + * var obj = JSON.parse('{"name": "Steve", "level": 5}'); + * log(obj.name); // "Steve" + * log(obj.level); // 5 + * + * var arr = JSON.parse('[1, 2, 3]'); + * log(arr[0]); // 1 + * ``` + * + * ### Converting Objects to JSON Strings + * ```js + * var data = { name: "Steve", hp: 100 }; + * var json = JSON.stringify(data); // '{"name":"Steve","hp":100}' + * + * // Pretty-printed with 2-space indent: + * var pretty = JSON.stringify(data, null, 2); + * // '{ + * // "name": "Steve", + * // "hp": 100 + * // }' + * ``` + * + * ### Storing & Loading Data + * ```js + * // Save to NPC stored data: + * var inventory = { sword: 1, potion: 5 }; + * npc.getStoredData().put("inv", JSON.stringify(inventory)); + * + * // Load from NPC stored data: + * var raw = npc.getStoredData().get("inv"); + * var loaded = JSON.parse(raw); + * log(loaded.potion); // 5 + * ``` + * + * ### ❌ Common Mistakes + * ```js + * new JSON(); // TypeError — JSON is not a constructor + * JSON.parse('{name: "Steve"}'); // SyntaxError — keys must be quoted + * JSON.parse("{'name': 'Steve'}"); // SyntaxError — must use double quotes + * JSON.parse('{"name": "Steve"}'); // ✅ Correct — double-quoted keys & values + * ``` + */ +export interface JSON { + /** + * Parses a JSON string and returns the parsed value (object, array, string, number, boolean, or null). + * @param text - A valid JSON string to parse + * @returns The parsed JavaScript value + */ + static parse(text: string): any; + + /** + * Parses a JSON string with a reviver function that transforms each parsed key-value pair. + * @param text - A valid JSON string to parse + * @param reviver - Function called for each key-value pair; receives the key and parsed value, returns the transformed value + * @returns The parsed JavaScript value after applying the reviver + */ + static parse(text: string, reviver: Java.java.util.function.BiFunction): any; + + /** + * Converts a JavaScript value to a JSON string. + * @param value - The value to serialize (object, array, string, number, boolean, or null) + * @returns A JSON-formatted string representation of the value + */ + static stringify(value: any): string; + + /** + * Converts a JavaScript value to a JSON string, using a replacer function to filter or transform properties. + * @param value - The value to serialize + * @param replacer - Function called for each key-value pair; receives the key and value, returns the value to include (or undefined to omit) + * @param space - Optional indentation: a number of spaces (up to 10), or a string prefix per level + * @returns A JSON-formatted string representation of the value + */ + static stringify(value: any, replacer: Java.java.util.function.BiFunction, space?: any): string; + + /** + * Converts a JavaScript value to a JSON string, including only the specified properties. + * @param value - The value to serialize + * @param replacer - Array of property names to include in the output + * @param space - Optional indentation: a number of spaces (up to 10), or a string prefix per level + * @returns A JSON-formatted string representation of the value + */ + static stringify(value: any, replacer: string[], space?: any): string; + + /** + * Converts a JavaScript value to a JSON string with optional pretty-printing. + * @param value - The value to serialize + * @param replacer - Pass null to include all properties + * @param space - Indentation: a number of spaces (up to 10), or a string prefix per level + * @returns A JSON-formatted string representation of the value + */ + static stringify(value: any, replacer: null, space: any): string; +} diff --git a/dts-patches/ecmascript/Math.d.ts b/dts-patches/ecmascript/Math.d.ts new file mode 100644 index 000000000..30f7e2889 --- /dev/null +++ b/dts-patches/ecmascript/Math.d.ts @@ -0,0 +1,128 @@ +/** + * ECMAScript 5.1 - Math built-in object providing mathematical constants and functions. + * All methods are static and called as Math.methodName(). No constructor. + * + * ## How to Use + * + * Math is a **static object** — use its methods directly, never with `new`. + * + * ### Basic Math Operations + * ```js + * var rounded = Math.floor(3.7); // 3 + * var ceiling = Math.ceil(3.2); // 4 + * var nearest = Math.round(3.5); // 4 + * var absolute = Math.abs(-42); // 42 + * ``` + * + * ### Powers, Roots & Logarithms + * ```js + * var squared = Math.pow(2, 3); // 8 + * var root = Math.sqrt(16); // 4 + * var natural = Math.log(Math.E); // 1 + * ``` + * + * ### Random Numbers + * ```js + * var rand = Math.random(); // 0.0 to 0.999... + * // Random integer between 1 and 10: + * var dice = Math.floor(Math.random() * 10) + 1; + * ``` + * + * ### Finding Min/Max + * ```js + * var biggest = Math.max(5, 10, 3); // 10 + * var smallest = Math.min(5, 10, 3); // 3 + * ``` + * + * ### Trigonometry + * ```js + * var sine = Math.sin(Math.PI / 2); // 1 + * var cosine = Math.cos(0); // 1 + * var angle = Math.atan2(1, 1); // 0.785... (PI/4) + * ``` + * + * ### ❌ Common Mistakes + * ```js + * new Math() // TypeError — Math is not a constructor + * Math() // TypeError — Math is not a function + * ``` + */ +export interface Math { + /** Euler's number (~2.718), the base of natural logarithms */ + static readonly E: number; + + /** Natural logarithm of 2 (~0.693) */ + static readonly LN2: number; + + /** Natural logarithm of 10 (~2.303) */ + static readonly LN10: number; + + /** Base-2 logarithm of e (~1.443) */ + static readonly LOG2E: number; + + /** Base-10 logarithm of e (~0.434) */ + static readonly LOG10E: number; + + /** Ratio of a circle's circumference to its diameter (~3.14159) */ + static readonly PI: number; + + /** Square root of 0.5 (~0.707) */ + static readonly SQRT1_2: number; + + /** Square root of 2 (~1.414) */ + static readonly SQRT2: number; + + /** Returns the absolute value of a number */ + static abs(x: number): number; + + /** Returns the arccosine (in radians) of a number */ + static acos(x: number): number; + + /** Returns the arcsine (in radians) of a number */ + static asin(x: number): number; + + /** Returns the arctangent (in radians) of a number */ + static atan(x: number): number; + + /** Returns the arctangent of two numbers (y/x), with proper quadrant handling */ + static atan2(y: number, x: number): number; + + /** Returns the smallest integer greater than or equal to a number */ + static ceil(x: number): number; + + /** Returns the cosine (in radians) of a number */ + static cos(x: number): number; + + /** Returns e raised to the power of a number */ + static exp(x: number): number; + + /** Returns the largest integer less than or equal to a number */ + static floor(x: number): number; + + /** Returns the natural logarithm (base e) of a number */ + static log(x: number): number; + + /** Returns the largest of zero or more numbers */ + static max(...values: number[]): number; + + /** Returns the smallest of zero or more numbers */ + static min(...values: number[]): number; + + /** Returns base raised to the power of exponent */ + static pow(x: number, y: number): number; + + /** Returns a random number between 0 (inclusive) and 1 (exclusive) */ + static random(): number; + + /** Returns the value of a number rounded to the nearest integer */ + static round(x: number): number; + + /** Returns the sine (in radians) of a number */ + static sin(x: number): number; + + /** Returns the square root of a number */ + static sqrt(x: number): number; + + /** Returns the tangent (in radians) of a number */ + static tan(x: number): number; +} diff --git a/dts-patches/ecmascript/Number.d.ts b/dts-patches/ecmascript/Number.d.ts new file mode 100644 index 000000000..10f57f816 --- /dev/null +++ b/dts-patches/ecmascript/Number.d.ts @@ -0,0 +1,74 @@ +/** + * ECMAScript 5.1 - Number type for working with numeric values and constants. + * Access static constants like Number.MAX_VALUE or format numbers with instance methods. + * + * ## How to Use + * + * ### Number Constants + * ```js + * Number.MAX_VALUE; // ~1.79e+308 (largest representable number) + * Number.MIN_VALUE; // ~5e-324 (smallest positive number) + * Number.NaN; // NaN + * Number.POSITIVE_INFINITY; // Infinity + * Number.NEGATIVE_INFINITY; // -Infinity + * ``` + * + * ### Formatting Numbers + * ```js + * var n = 3.14159; + * n.toFixed(2); // "3.14" (fixed decimal places) + * n.toFixed(0); // "3" + * n.toPrecision(4); // "3.142" (significant digits) + * n.toExponential(2); // "3.14e+0" (scientific notation) + * ``` + * + * ### Converting to String + * ```js + * var n = 255; + * n.toString(); // "255" (base 10, default) + * n.toString(16); // "ff" (hexadecimal) + * n.toString(2); // "11111111" (binary) + * n.toString(8); // "377" (octal) + * ``` + * + * ### ❌ Common Mistakes + * ```js + * Number.toFixed(2); // TypeError — instance method, not static + * (3).toFixed(2); // "3.00" ✅ — wrap literal in parentheses + * 3.toFixed(2); // SyntaxError — parser reads 3. as float + * ``` + */ +export interface Number { + /** The largest representable number (~1.79e+308) */ + static readonly MAX_VALUE: number; + + /** The smallest representable positive number (~5e-324) */ + static readonly MIN_VALUE: number; + + /** Represents "Not a Number" (NaN) - the result of undefined or invalid arithmetic operations */ + static readonly NaN: number; + + /** Represents negative infinity, the result of overflow or division by zero */ + static readonly NEGATIVE_INFINITY: number; + + /** Represents positive infinity, the result of overflow or division by zero */ + static readonly POSITIVE_INFINITY: number; + + /** Formats the number using exponential notation with optional fractional digits */ + toExponential(fractionDigits: number): string; + + /** Formats the number as a fixed-point string with the specified number of fractional digits (0-20) */ + toFixed(fractionDigits: number): string; + + /** Returns a localized string representation of the number (format depends on locale) */ + toLocaleString(): string; + + /** Formats the number as a string with the specified number of significant digits (1-21) */ + toPrecision(precision: number): string; + + /** Converts the number to a string in the specified radix (base 2-36, default 10) */ + toString(radix: number): string; + + /** Returns the primitive numeric value of this Number object */ + valueOf(): number; +} diff --git a/dts-patches/ecmascript/Object.d.ts b/dts-patches/ecmascript/Object.d.ts new file mode 100644 index 000000000..3b103139c --- /dev/null +++ b/dts-patches/ecmascript/Object.d.ts @@ -0,0 +1,105 @@ +/** + * ECMAScript 5.1 - Object type, the base type for all JavaScript objects. + * Use static methods like Object.keys() and Object.create() to manipulate object structure. + * + * ## How to Use + * + * ### Creating Objects + * ```js + * var obj = {}; // Empty object literal + * var person = { name: "Steve", age: 20 }; // Object with properties + * var child = Object.create(person); // Create with prototype + * ``` + * + * ### Inspecting Objects + * ```js + * var obj = { a: 1, b: 2, c: 3 }; + * Object.keys(obj); // ["a", "b", "c"] + * Object.getOwnPropertyNames(obj); // ["a", "b", "c"] (includes non-enumerable) + * obj.hasOwnProperty("a"); // true + * obj.hasOwnProperty("toString"); // false (inherited, not own) + * ``` + * + * ### Freezing & Sealing + * ```js + * var config = { debug: false }; + * Object.freeze(config); // Cannot modify, add, or delete properties + * config.debug = true; // Silently fails (or throws in strict mode) + * Object.isFrozen(config); // true + * + * var settings = { volume: 50 }; + * Object.seal(settings); // Can modify values, but cannot add/delete + * settings.volume = 75; // ✅ Works + * settings.newProp = true; // Silently fails + * ``` + * + * ### Property Descriptors + * ```js + * var obj = {}; + * Object.defineProperty(obj, "id", { + * value: 42, + * writable: false, // Cannot be changed + * enumerable: true // Shows up in for-in / Object.keys + * }); + * ``` + * + * ### ❌ Common Mistakes + * ```js + * Object.keys(); // TypeError — needs an argument + * obj.keys(); // TypeError — keys is a static method + * Object.hasOwnProperty("a"); // Wrong — instance method on the object + * ``` + */ +export interface Object { + /** Creates a new object with the specified prototype and optional property descriptors */ + static create(proto: any, propertiesObject: any): any; + + /** Defines or modifies multiple properties on an object and returns the modified object */ + static defineProperties(obj: any, props: any): any; + + /** Defines a new property on an object or modifies an existing property and returns the object */ + static defineProperty(obj: any, prop: string, descriptor: any): any; + + /** Prevents all modifications to an object (cannot add, modify, or delete properties) */ + static freeze(obj: any): any; + + /** Returns a property descriptor for a named property on an object, or undefined if not found */ + static getOwnPropertyDescriptor(obj: any, prop: string): any; + + /** Returns an array of all property names (both enumerable and non-enumerable) on an object */ + static getOwnPropertyNames(obj: any): string[]; + + /** Returns the prototype object of the specified object */ + static getPrototypeOf(obj: any): any; + + /** Determines whether an object is extensible (can have new properties added to it) */ + static isExtensible(obj: any): boolean; + + /** Determines whether an object has been frozen (is immutable) */ + static isFrozen(obj: any): boolean; + + /** Determines whether an object is sealed (cannot add or delete properties) */ + static isSealed(obj: any): boolean; + + /** Returns an array of all enumerable property names on an object */ + static keys(obj: any): string[]; + + /** Prevents new properties from being added to an object but allows modification of existing ones */ + static preventExtensions(obj: any): any; + + /** Prevents all modifications to an object except for reading and writing property values */ + static seal(obj: any): any; + + /** Determines whether an object has a property with the specified name (direct property, not inherited) */ + hasOwnProperty(prop: string): boolean; + + /** Determines whether an object is in the prototype chain of another object */ + isPrototypeOf(obj: any): boolean; + + /** Determines whether an object property is enumerable (would be included in a for-in loop) */ + propertyIsEnumerable(prop: string): boolean; + + /** Returns a localized string representation of the object (format depends on locale) */ + toLocaleString(): string; + +} diff --git a/dts-patches/ecmascript/RegExp.d.ts b/dts-patches/ecmascript/RegExp.d.ts new file mode 100644 index 000000000..a048f429d --- /dev/null +++ b/dts-patches/ecmascript/RegExp.d.ts @@ -0,0 +1,94 @@ +/** + * ECMAScript 5.1 - RegExp type for pattern matching and string manipulation. + * Create with the RegExp constructor or literal syntax: /pattern/flags + * + * ## How to Use + * + * ### Creating Regular Expressions + * ```js + * // Method 1: Regex literal (preferred) + * var re = /hello/; + * var reFlags = /hello/gi; // g=global, i=ignore case, m=multiline + * + * // Method 2: Constructor (useful for dynamic patterns) + * var re2 = new RegExp("hello"); + * var re3 = new RegExp("hello", "gi"); + * var dynamic = new RegExp(playerName); // Build pattern from variable + * ``` + * + * ### Testing for Matches + * ```js + * /\d+/.test("abc123"); // true — contains digits + * /^\d+$/.test("abc123"); // false — not ALL digits + * /^\d+$/.test("12345"); // true — all digits + * /hello/i.test("Hello World"); // true — case insensitive + * ``` + * + * ### Extracting Matches + * ```js + * var match = /\d+/.exec("abc123def"); // ["123"] + * var noMatch = /\d+/.exec("no digits"); // null + * + * // With capturing groups + * var result = /(\w+)@(\w+)/.exec("user@domain"); + * // result[0] = "user@domain" (full match) + * // result[1] = "user" (first group) + * // result[2] = "domain" (second group) + * ``` + * + * ### Using with String Methods + * ```js + * "abc123".match(/\d+/); // ["123"] + * "abc123".search(/\d/); // 3 (index of first digit) + * "abc123".replace(/\d+/, "NUM"); // "abcNUMdef" + * "a,b,,c".split(/,+/); // ["a", "b", "c"] + * ``` + * + * ### RegExp Properties + * ```js + * var re = /hello/gi; + * re.source; // "hello" + * re.global; // true + * re.ignoreCase; // true + * re.multiline; // false + * re.lastIndex; // 0 (changes with global exec/test) + * ``` + * + * ### ❌ Common Mistakes + * ```js + * RegExp.test("string"); // TypeError — test is an INSTANCE method! + * new RegExp.test("string"); // TypeError — incorrect syntax + * // ✅ CORRECT: + * /pattern/.test("string"); // Use on a regex instance + * new RegExp("pattern").test("string"); // Or create instance first + * + * // Double-escape backslashes in constructor strings: + * new RegExp("\d+"); // Wrong — \d becomes just d + * new RegExp("\\d+"); // ✅ Correct — \\d becomes \d + * ``` + */ +export interface RegExp { + /** The pattern string that was used to create this regular expression */ + source: string; + + /** True if the 'g' (global) flag is set, affecting match behavior in exec() and test() */ + global: boolean; + + /** True if the 'i' (ignore case) flag is set, making pattern matching case-insensitive */ + ignoreCase: boolean; + + /** True if the 'm' (multiline) flag is set, affecting ^ and $ anchor behavior */ + multiline: boolean; + + /** The index at which to start searching in the string (used with 'g' flag in exec() loops) */ + lastIndex: number; + + /** Searches the string for a match and returns an array of matches or null if no match found */ + exec(string: string): any[]; + + /** Tests whether the pattern matches the string, returning true or false */ + test(string: string): boolean; + + /** Returns a string representation of the regular expression (e.g., "/pattern/flags") */ + toString(): string; +} diff --git a/dts-patches/ecmascript/String.d.ts b/dts-patches/ecmascript/String.d.ts new file mode 100644 index 000000000..8a48033e2 --- /dev/null +++ b/dts-patches/ecmascript/String.d.ts @@ -0,0 +1,82 @@ +/** + * ECMAScript 5.1 - String type for working with text. Strings are immutable sequences of characters. + * Use String.fromCharCode() to create a string from character codes. + * + * ## How to Use + * + * ### Creating Strings + * ```js + * var greeting = "Hello, world!"; // String literal (double quotes) + * var name = 'Steve'; // String literal (single quotes) + * var fromCode = String.fromCharCode(65); // "A" (from char code) + * ``` + * + * ### Searching & Checking + * ```js + * var str = "Hello, world!"; + * str.indexOf("world"); // 7 + * str.indexOf("missing"); // -1 (not found) + * str.lastIndexOf("l"); // 10 + * str.search(/world/); // 7 (regex search) + * str.charAt(0); // "H" + * str.charCodeAt(0); // 72 + * str.length; // 13 + * ``` + * + * ### Extracting & Transforming + * ```js + * var str = "Hello, world!"; + * str.slice(7, 12); // "world" + * str.substring(0, 5); // "Hello" + * str.toUpperCase(); // "HELLO, WORLD!" + * str.toLowerCase(); // "hello, world!" + * str.trim(); // Removes leading/trailing whitespace + * str.replace("world", "NPC"); // "Hello, NPC!" + * str.replace(/l/g, "L"); // "HeLLo, worLd!" (regex with global flag) + * ``` + * + * ### Splitting & Joining + * ```js + * "a,b,c".split(","); // ["a", "b", "c"] + * "hello".split(""); // ["h", "e", "l", "l", "o"] + * ["a", "b", "c"].join("-"); // "a-b-c" (Array.join, but related) + * "one two three".split(" ", 2); // ["one", "two"] (limit results) + * ``` + * + * ### Pattern Matching + * ```js + * "abc123".match(/\d+/); // ["123"] + * "no numbers".match(/\d+/); // null + * "hello".concat(" ", "world"); // "hello world" + * ``` + * + * ### ❌ Common Mistakes + * ```js + * str.replace("l", "L"); // Only replaces FIRST "l" — use /l/g for all + * String.charAt(0); // TypeError — instance method, not static + * "abc"[0]; // May not work in all engines — use charAt() + * ``` + */ +export interface String { + /** The number of characters in the string */ + length: number; + + /** Creates a string from one or more Unicode character codes (e.g., String.fromCharCode(65, 66, 67) returns "ABC") */ + static fromCharCode(...codes: number[]): string; + + /** Returns the Unicode code point (0–65535) of the character at the specified index. Unlike Java's charAt() + cast, this returns the numeric code directly. */ + charCodeAt(pos: number): number; + + /** Tests the string against a regular expression and returns an array of matches, or null if no match found */ + match(regexp: any): any[]; + + /** + * Replaces a pattern (string or RegExp object) with a replacement string. + * Unlike Java's replace/replaceAll which only accept String/CharSequence, + * this accepts a RegExp object as the first argument. + */ + replace(searchValue: any, replaceValue: any): string; + + /** Returns the index of the first character that matches a regular expression, or -1 if not found */ + search(regexp: any): number; +} diff --git a/gradle-plugins b/gradle-plugins index f1c82c10c..19dc9a836 160000 --- a/gradle-plugins +++ b/gradle-plugins @@ -1 +1 @@ -Subproject commit f1c82c10c8c92eaaf55044cf931da5e1c7a2668f +Subproject commit 19dc9a836148062fa744b9a9ca87391f84274b44 diff --git a/images/Animation Maker.png b/images/Animation Maker.png deleted file mode 100644 index 2fa6f2bef..000000000 Binary files a/images/Animation Maker.png and /dev/null differ diff --git a/images/AnimationMaker.gif b/images/AnimationMaker.gif new file mode 100644 index 000000000..dcd917fca Binary files /dev/null and b/images/AnimationMaker.gif differ diff --git a/images/Auction.png b/images/Auction.png new file mode 100644 index 000000000..c7794860c Binary files /dev/null and b/images/Auction.png differ diff --git a/images/ClonerGUI-DarkMode.png b/images/ClonerGUI-DarkMode.png deleted file mode 100644 index 946f9dd8e..000000000 Binary files a/images/ClonerGUI-DarkMode.png and /dev/null differ diff --git a/images/ClonerTabs.png b/images/ClonerTabs.png new file mode 100644 index 000000000..f833ab6cd Binary files /dev/null and b/images/ClonerTabs.png differ diff --git a/images/Dialog.png b/images/Dialog.png new file mode 100644 index 000000000..6671e96bb Binary files /dev/null and b/images/Dialog.png differ diff --git a/images/GUI.png b/images/GUI.png deleted file mode 100644 index c75a95abf..000000000 Binary files a/images/GUI.png and /dev/null differ diff --git a/images/GUIRevamp.png b/images/GUIRevamp.png deleted file mode 100644 index c944da6ac..000000000 Binary files a/images/GUIRevamp.png and /dev/null differ diff --git a/images/CustomModel1.png b/images/GeckoAddon1.png similarity index 100% rename from images/CustomModel1.png rename to images/GeckoAddon1.png diff --git a/images/CustomModel2.png b/images/GeckoAddon2.png similarity index 100% rename from images/CustomModel2.png rename to images/GeckoAddon2.png diff --git a/images/HudSystem.png b/images/HudSystem.png new file mode 100644 index 000000000..cb6c063b1 Binary files /dev/null and b/images/HudSystem.png differ diff --git a/images/NewTextures2.png b/images/JappaTextures.png similarity index 100% rename from images/NewTextures2.png rename to images/JappaTextures.png diff --git a/images/NPCAbilities.gif b/images/NPCAbilities.gif new file mode 100644 index 000000000..fa13b8630 Binary files /dev/null and b/images/NPCAbilities.gif differ diff --git a/images/NPCEditor.gif b/images/NPCEditor.gif new file mode 100644 index 000000000..b6a24fbe4 Binary files /dev/null and b/images/NPCEditor.gif differ diff --git a/images/Party System.png b/images/PartySystem.png similarity index 100% rename from images/Party System.png rename to images/PartySystem.png diff --git a/images/PlayerAbilities.gif b/images/PlayerAbilities.gif new file mode 100644 index 000000000..819b2e870 Binary files /dev/null and b/images/PlayerAbilities.gif differ diff --git a/images/Marks.png b/images/QuestMarks.png similarity index 100% rename from images/Marks.png rename to images/QuestMarks.png diff --git a/images/ScriptEditor.gif b/images/ScriptEditor.gif new file mode 100644 index 000000000..bd3d365a9 Binary files /dev/null and b/images/ScriptEditor.gif differ diff --git a/images/Url64Example.gif b/images/Url64Example.gif deleted file mode 100644 index c2e7ffec2..000000000 Binary files a/images/Url64Example.gif and /dev/null differ diff --git a/images/New Textures.png b/images/VariousWeapons.png similarity index 100% rename from images/New Textures.png rename to images/VariousWeapons.png diff --git a/images/guiAnimation.gif b/images/guiAnimation.gif deleted file mode 100644 index 65f7e3fdb..000000000 Binary files a/images/guiAnimation.gif and /dev/null differ diff --git a/images/showcase.gif b/images/showcase.gif deleted file mode 100644 index 0d7272146..000000000 Binary files a/images/showcase.gif and /dev/null differ diff --git a/images/skinAnimation.gif b/images/skinAnimation.gif deleted file mode 100644 index 132adf09b..000000000 Binary files a/images/skinAnimation.gif and /dev/null differ diff --git a/settings.gradle b/settings.gradle index ec9681d97..e58786789 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,6 +1,14 @@ - pluginManagement { +// resolutionStrategy { +// eachPlugin { +// if(requested.id.toString() == "dts.typescript-generator") { +// useModule("com.github.bigguy345:dts-gradle-plugin:95b8ab4") +// } +// } +// } +// repositories { + maven { url "https://jitpack.io"} maven { // RetroFuturaGradle name "GTNH Maven" @@ -19,3 +27,6 @@ pluginManagement { plugins { id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.27' } + +// Include the local gradle-plugins composite build so plugin is resolved locally +includeBuild 'gradle-plugins' \ No newline at end of file diff --git a/src/api b/src/api index fd4c77d01..e7f363727 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit fd4c77d015add1f6f3012a1681561b2774f2f997 +Subproject commit e7f363727e8fea0823d3377fec757dcbd1a467d8 diff --git a/src/main/java/foxz/command/CmdDialog.java b/src/main/java/foxz/command/CmdDialog.java index 2bb2d1da3..74ec807fc 100644 --- a/src/main/java/foxz/command/CmdDialog.java +++ b/src/main/java/foxz/command/CmdDialog.java @@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand; import foxz.commandhelper.permissions.OpOnly; import foxz.commandhelper.permissions.ParamCheck; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.command.CommandBase; import net.minecraft.entity.player.EntityPlayer; import noppes.npcs.NoppesUtilServer; @@ -90,7 +91,7 @@ public class CmdDialog extends ChMcLogger { ) public boolean reload(String args[]) { new DialogController().load(); - SyncController.syncAllDialogs(); + SyncController.syncAll(SyncType.DIALOG_CATEGORY); return true; } diff --git a/src/main/java/foxz/command/CmdNpc.java b/src/main/java/foxz/command/CmdNpc.java index 5bcbded53..c09b82310 100644 --- a/src/main/java/foxz/command/CmdNpc.java +++ b/src/main/java/foxz/command/CmdNpc.java @@ -142,7 +142,7 @@ public class CmdNpc extends ChMcLogger { EntityCustomNpc npc = new EntityCustomNpc(pw); if (args.length > 0) npc.display.name = args[0]; - npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch); + npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0); npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)}; pw.spawnEntityInWorld(npc); npc.setHealth(npc.getMaxHealth()); diff --git a/src/main/java/foxz/command/CmdQuest.java b/src/main/java/foxz/command/CmdQuest.java index 5f7a7f1f4..95e4b75f0 100644 --- a/src/main/java/foxz/command/CmdQuest.java +++ b/src/main/java/foxz/command/CmdQuest.java @@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand; import foxz.commandhelper.permissions.OpOnly; import foxz.commandhelper.permissions.ParamCheck; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.network.packets.data.AchievementPacket; import kamkeel.npcs.network.packets.data.ChatAlertPacket; import net.minecraft.entity.player.EntityPlayerMP; @@ -170,7 +171,7 @@ public class CmdQuest extends ChMcLogger { ) public boolean reload(String args[]) { new QuestController().load(); - SyncController.syncAllQuests(); + SyncController.syncAll(SyncType.QUEST_CATEGORY); return true; } } diff --git a/src/main/java/kamkeel/npcs/addon/DBCAddon.java b/src/main/java/kamkeel/npcs/addon/DBCAddon.java index ff290e9d2..08c493a3c 100644 --- a/src/main/java/kamkeel/npcs/addon/DBCAddon.java +++ b/src/main/java/kamkeel/npcs/addon/DBCAddon.java @@ -37,6 +37,15 @@ public class DBCAddon { public void doDBCDamage(EntityNPCInterface npc, float attackStrength, Entity receiver) { } + /** + * Returns the pre-calculated DBC attack damage of the current attacker, + * or the vanilla damage if DBC damage was not calculated. + * Used by Counter (PERCENT mode) to base counter damage on the full DBC attack, not vanilla base. + */ + public float getAttackerDBCDamage(float vanillaDamage) { + return vanillaDamage; + } + public boolean isKO(EntityNPCInterface npc, EntityPlayer player) { return false; } diff --git a/src/main/java/kamkeel/npcs/client/command/CommandCNPCDebugger.java b/src/main/java/kamkeel/npcs/client/command/CommandCNPCDebugger.java new file mode 100644 index 000000000..42e18ed6c --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/command/CommandCNPCDebugger.java @@ -0,0 +1,42 @@ +package kamkeel.npcs.client.command; + +import kamkeel.npcs.util.CNPCDebug; +import net.minecraft.command.CommandBase; +import net.minecraft.command.ICommandSender; +import net.minecraft.util.ChatComponentText; + +/** + * Client-only command to toggle debug logging. + * Registered via ClientCommandHandler so it runs entirely on the client + * without sending a packet to the server. + */ +public class CommandCNPCDebugger extends CommandBase { + + @Override + public String getCommandName() { + return "cnpcdebugger"; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return "/cnpcdebugger - Toggle client debug logging for a type (e.g. energy)"; + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (args.length == 0) { + sender.addChatMessage(new ChatComponentText("\u00A7cUsage: /cnpcdebugger ")); + return; + } + + String type = args[0].toLowerCase(); + boolean newState = CNPCDebug.toggleClient(type); + String stateText = newState ? "\u00A7aENABLED" : "\u00A7cDISABLED"; + sender.addChatMessage(new ChatComponentText("\u00A77[CNPC+] \u00A7eClient debug '" + type + "' " + stateText)); + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/EnergyChargePreviewRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/EnergyChargePreviewRenderer.java new file mode 100644 index 000000000..66bf4869b --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/EnergyChargePreviewRenderer.java @@ -0,0 +1,38 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.client.event.RenderWorldLastEvent; + +/** + * Renders packet-driven charging previews through RenderManager. + */ +public class EnergyChargePreviewRenderer { + + @SubscribeEvent + public void onRenderWorldLast(RenderWorldLastEvent event) { + if (EnergyChargePreviewManager.ClientInstance == null || !EnergyChargePreviewManager.ClientInstance.hasPreviews()) { + return; + } + + Minecraft mc = Minecraft.getMinecraft(); + EntityPlayer player = mc.thePlayer; + if (player == null) return; + + float partialTicks = event.partialTicks; + + for (EntityEnergyProjectile entity : EnergyChargePreviewManager.ClientInstance.getPreviews()) { + if (entity == null || entity.isDead) continue; + + double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - RenderManager.renderPosX; + double y = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - RenderManager.renderPosY; + double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - RenderManager.renderPosZ; + + RenderManager.instance.renderEntityWithPosYaw(entity, x, y, z, entity.rotationYaw, partialTicks); + } + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java deleted file mode 100644 index 96e8e7b08..000000000 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java +++ /dev/null @@ -1,259 +0,0 @@ -package kamkeel.npcs.client.renderer; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -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 org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -/** - * Base renderer for ability projectiles. - * Provides common GL state setup and rendering utilities. - * - * Design inspired by LouisXIV's energy rendering system. - */ -@SideOnly(Side.CLIENT) -public abstract class RenderAbilityProjectile extends Render { - - protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png"); - - public RenderAbilityProjectile() { - this.shadowSize = 0.0f; - } - - /** - * Setup GL state for translucent, self-illuminated rendering. - * Forces full brightness so world lighting does not affect projectiles. - */ - protected void setupRenderState() { - GL11.glPushMatrix(); - 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); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_TEXTURE_2D); - - // Force full brightness - prevents world lighting from darkening projectiles - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f); - } - - /** - * Restore GL state after rendering. - */ - protected void restoreRenderState() { - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } - - /** - * Extract RGB components from color int. - */ - protected float[] extractRGB(int color) { - float r = ((color >> 16) & 0xFF) / 255.0f; - float g = ((color >> 8) & 0xFF) / 255.0f; - float b = (color & 0xFF) / 255.0f; - return new float[]{r, g, b}; - } - - /** - * Render a cube centered at origin with given color and alpha. - */ - protected void renderCube(int color, float alpha, float halfSize) { - float[] rgb = extractRGB(color); - float r = rgb[0], g = rgb[1], b = rgb[2]; - - Tessellator tess = Tessellator.instance; - - // Front face (z+) - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(0, 0, 1); - tess.addVertex(-halfSize, -halfSize, halfSize); - tess.addVertex(halfSize, -halfSize, halfSize); - tess.addVertex(halfSize, halfSize, halfSize); - tess.addVertex(-halfSize, halfSize, halfSize); - tess.draw(); - - // Back face (z-) - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(0, 0, -1); - tess.addVertex(halfSize, -halfSize, -halfSize); - tess.addVertex(-halfSize, -halfSize, -halfSize); - tess.addVertex(-halfSize, halfSize, -halfSize); - tess.addVertex(halfSize, halfSize, -halfSize); - tess.draw(); - - // Top face (y+) - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(0, 1, 0); - tess.addVertex(-halfSize, halfSize, halfSize); - tess.addVertex(halfSize, halfSize, halfSize); - tess.addVertex(halfSize, halfSize, -halfSize); - tess.addVertex(-halfSize, halfSize, -halfSize); - tess.draw(); - - // Bottom face (y-) - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(0, -1, 0); - tess.addVertex(-halfSize, -halfSize, -halfSize); - tess.addVertex(halfSize, -halfSize, -halfSize); - tess.addVertex(halfSize, -halfSize, halfSize); - tess.addVertex(-halfSize, -halfSize, halfSize); - tess.draw(); - - // Right face (x+) - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(1, 0, 0); - tess.addVertex(halfSize, -halfSize, halfSize); - tess.addVertex(halfSize, -halfSize, -halfSize); - tess.addVertex(halfSize, halfSize, -halfSize); - tess.addVertex(halfSize, halfSize, halfSize); - tess.draw(); - - // Left face (x-) - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(-1, 0, 0); - tess.addVertex(-halfSize, -halfSize, -halfSize); - tess.addVertex(-halfSize, -halfSize, halfSize); - tess.addVertex(-halfSize, halfSize, halfSize); - tess.addVertex(-halfSize, halfSize, -halfSize); - tess.draw(); - } - - /** - * Render a flat disc (cylinder with very small height) centered at origin. - * The disc lies flat on the XZ plane. - */ - protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) { - float[] rgb = extractRGB(color); - float r = rgb[0], g = rgb[1], b = rgb[2]; - - Tessellator tess = Tessellator.instance; - float halfThick = thickness * 0.5f; - - // Top face - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(0, 1, 0); - for (int i = 0; i < segments; i++) { - float angle1 = (float) (2 * Math.PI * i / segments); - float angle2 = (float) (2 * Math.PI * (i + 1) / segments); - float x1 = (float) Math.cos(angle1) * radius; - float z1 = (float) Math.sin(angle1) * radius; - float x2 = (float) Math.cos(angle2) * radius; - float z2 = (float) Math.sin(angle2) * radius; - - tess.addVertex(0, halfThick, 0); - tess.addVertex(x1, halfThick, z1); - tess.addVertex(x2, halfThick, z2); - tess.addVertex(0, halfThick, 0); - } - tess.draw(); - - // Bottom face - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.setNormal(0, -1, 0); - for (int i = 0; i < segments; i++) { - float angle1 = (float) (2 * Math.PI * i / segments); - float angle2 = (float) (2 * Math.PI * (i + 1) / segments); - float x1 = (float) Math.cos(angle1) * radius; - float z1 = (float) Math.sin(angle1) * radius; - float x2 = (float) Math.cos(angle2) * radius; - float z2 = (float) Math.sin(angle2) * radius; - - tess.addVertex(0, -halfThick, 0); - tess.addVertex(x2, -halfThick, z2); - tess.addVertex(x1, -halfThick, z1); - tess.addVertex(0, -halfThick, 0); - } - tess.draw(); - - // Edge - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - for (int i = 0; i < segments; i++) { - float angle1 = (float) (2 * Math.PI * i / segments); - float angle2 = (float) (2 * Math.PI * (i + 1) / segments); - float x1 = (float) Math.cos(angle1) * radius; - float z1 = (float) Math.sin(angle1) * radius; - float x2 = (float) Math.cos(angle2) * radius; - float z2 = (float) Math.sin(angle2) * radius; - - // Normal pointing outward - float nx = (float) Math.cos((angle1 + angle2) * 0.5); - float nz = (float) Math.sin((angle1 + angle2) * 0.5); - tess.setNormal(nx, 0, nz); - - tess.addVertex(x1, -halfThick, z1); - tess.addVertex(x2, -halfThick, z2); - tess.addVertex(x2, halfThick, z2); - tess.addVertex(x1, halfThick, z1); - } - tess.draw(); - } - - /** - * Render a line segment as a quad billboard facing the camera. - */ - protected void renderLineSegment(double x1, double y1, double z1, - double x2, double y2, double z2, - float width, int color, float alpha) { - float[] rgb = extractRGB(color); - float r = rgb[0], g = rgb[1], b = rgb[2]; - - // Calculate direction - double dx = x2 - x1; - double dy = y2 - y1; - double dz = z2 - z1; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len < 0.001) return; - - // Perpendicular vectors for billboard - double perpX, perpY, perpZ; - if (Math.abs(dy) < 0.9) { - // Cross with up vector - perpX = -dz; - perpY = 0; - perpZ = dx; - } else { - // Cross with right vector - perpX = 0; - perpY = dz; - perpZ = -dy; - } - double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ); - if (perpLen > 0) { - perpX = perpX / perpLen * width * 0.5; - perpY = perpY / perpLen * width * 0.5; - perpZ = perpZ / perpLen * width * 0.5; - } - - Tessellator tess = Tessellator.instance; - tess.startDrawingQuads(); - tess.setColorRGBA_F(r, g, b, alpha); - tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ); - tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ); - tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ); - tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ); - tess.draw(); - } - - @Override - protected ResourceLocation getEntityTexture(Entity entity) { - return WHITE_TEXTURE; - } -} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java new file mode 100644 index 000000000..980293c17 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java @@ -0,0 +1,410 @@ +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.EntityEnergyAbility; +import kamkeel.npcs.entity.EntityEnergyProjectile; +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.entity.player.EntityPlayer; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.config.ConfigClient; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +/** + * Base renderer for ability projectiles. + * Provides common GL state setup and rendering utilities. + *

+ * Design inspired by LouisXIV's energy rendering system. + */ +@SideOnly(Side.CLIENT) +public abstract class RenderEnergy extends Render { + + protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png"); + protected static final int HIDE_INITIAL_ACTIVE_TICKS = 1; + + public RenderEnergy() { + this.shadowSize = 0.0f; + } + + /** + * Hide the first active tick to avoid the visible spawn-frame pause at fire time. + * Charging previews are never hidden. + */ + protected boolean shouldSkipInitialActiveRender(Entity entity) { + if (!(entity instanceof EntityEnergyAbility)) return false; + EntityEnergyAbility ability = (EntityEnergyAbility) entity; + return !ability.isPreviewMode() && !ability.isCharging() && ability.ticksExisted <= HIDE_INITIAL_ACTIVE_TICKS; + } + + /** + * Setup GL state for translucent, self-illuminated rendering. + * Forces full brightness so world lighting does not affect projectiles. + */ + protected void setupRenderState() { + GL11.glPushMatrix(); + 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); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_TEXTURE_2D); + + // Force full brightness - prevents world lighting from darkening projectiles + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f); + } + + /** + * Restore GL state after rendering. + */ + protected void restoreRenderState() { + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + + /** + * Extract RGB components from color int. + */ + protected float[] extractRGB(int color) { + float r = ((color >> 16) & 0xFF) / 255.0f; + float g = ((color >> 8) & 0xFF) / 255.0f; + float b = (color & 0xFF) / 255.0f; + return new float[]{r, g, b}; + } + + /** + * Render a cube centered at origin with given color and alpha. + */ + protected void renderCube(int color, float alpha, float halfSize) { + Tessellator tess = Tessellator.instance; + float r = ((color >> 16) & 0xFF) / 255.0f; + float g = ((color >> 8) & 0xFF) / 255.0f; + float b = (color & 0xFF) / 255.0f; + + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + addCubeVertices(tess, 0, 0, 0, halfSize); + tess.draw(); + } + + // ==================== BATCHED CUBE RENDERING ==================== + + /** + * Begin a batched cube draw call. All cubes added via {@link #addBatchedCube} + * will be drawn in a single tessellator pass when {@link #endCubeBatch} is called. + */ + protected void beginCubeBatch() { + Tessellator.instance.startDrawingQuads(); + } + + /** + * Add a cube to the current batch at the given position with per-cube color/alpha. + * Must be called between {@link #beginCubeBatch} and {@link #endCubeBatch}. + */ + protected void addBatchedCube(float px, float py, float pz, float halfSize, + float r, float g, float b, float alpha) { + Tessellator tess = Tessellator.instance; + tess.setColorRGBA_F(r, g, b, alpha); + addCubeVertices(tess, px, py, pz, halfSize); + } + + /** + * End the batched cube draw call, flushing all queued cubes in one draw. + */ + protected void endCubeBatch() { + Tessellator.instance.draw(); + } + + /** + * Add the 24 vertices (6 faces) of a cube centered at (px,py,pz) to the tessellator. + * Color must be set before calling. Used by both single and batched cube rendering. + */ + private static void addCubeVertices(Tessellator tess, float px, float py, float pz, float h) { + float x0 = px - h, x1 = px + h; + float y0 = py - h, y1 = py + h; + float z0 = pz - h, z1 = pz + h; + + // Front (z+) + tess.setNormal(0, 0, 1); + tess.addVertex(x0, y0, z1); + tess.addVertex(x1, y0, z1); + tess.addVertex(x1, y1, z1); + tess.addVertex(x0, y1, z1); + + // Back (z-) + tess.setNormal(0, 0, -1); + tess.addVertex(x1, y0, z0); + tess.addVertex(x0, y0, z0); + tess.addVertex(x0, y1, z0); + tess.addVertex(x1, y1, z0); + + // Top (y+) + tess.setNormal(0, 1, 0); + tess.addVertex(x0, y1, z1); + tess.addVertex(x1, y1, z1); + tess.addVertex(x1, y1, z0); + tess.addVertex(x0, y1, z0); + + // Bottom (y-) + tess.setNormal(0, -1, 0); + tess.addVertex(x0, y0, z0); + tess.addVertex(x1, y0, z0); + tess.addVertex(x1, y0, z1); + tess.addVertex(x0, y0, z1); + + // Right (x+) + tess.setNormal(1, 0, 0); + tess.addVertex(x1, y0, z1); + tess.addVertex(x1, y0, z0); + tess.addVertex(x1, y1, z0); + tess.addVertex(x1, y1, z1); + + // Left (x-) + tess.setNormal(-1, 0, 0); + tess.addVertex(x0, y0, z0); + tess.addVertex(x0, y0, z1); + tess.addVertex(x0, y1, z1); + tess.addVertex(x0, y1, z0); + } + + /** + * Render a flat disc (cylinder with very small height) centered at origin. + * The disc lies flat on the XZ plane. + */ + protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + + Tessellator tess = Tessellator.instance; + float halfThick = thickness * 0.5f; + + // Top face + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, 1, 0); + for (int i = 0; i < segments; i++) { + float angle1 = (float) (2 * Math.PI * i / segments); + float angle2 = (float) (2 * Math.PI * (i + 1) / segments); + float x1 = (float) Math.cos(angle1) * radius; + float z1 = (float) Math.sin(angle1) * radius; + float x2 = (float) Math.cos(angle2) * radius; + float z2 = (float) Math.sin(angle2) * radius; + + tess.addVertex(0, halfThick, 0); + tess.addVertex(x1, halfThick, z1); + tess.addVertex(x2, halfThick, z2); + tess.addVertex(0, halfThick, 0); + } + tess.draw(); + + // Bottom face + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, -1, 0); + for (int i = 0; i < segments; i++) { + float angle1 = (float) (2 * Math.PI * i / segments); + float angle2 = (float) (2 * Math.PI * (i + 1) / segments); + float x1 = (float) Math.cos(angle1) * radius; + float z1 = (float) Math.sin(angle1) * radius; + float x2 = (float) Math.cos(angle2) * radius; + float z2 = (float) Math.sin(angle2) * radius; + + tess.addVertex(0, -halfThick, 0); + tess.addVertex(x2, -halfThick, z2); + tess.addVertex(x1, -halfThick, z1); + tess.addVertex(0, -halfThick, 0); + } + tess.draw(); + + // Edge + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + for (int i = 0; i < segments; i++) { + float angle1 = (float) (2 * Math.PI * i / segments); + float angle2 = (float) (2 * Math.PI * (i + 1) / segments); + float x1 = (float) Math.cos(angle1) * radius; + float z1 = (float) Math.sin(angle1) * radius; + float x2 = (float) Math.cos(angle2) * radius; + float z2 = (float) Math.sin(angle2) * radius; + + // Normal pointing outward + float nx = (float) Math.cos((angle1 + angle2) * 0.5); + float nz = (float) Math.sin((angle1 + angle2) * 0.5); + tess.setNormal(nx, 0, nz); + + tess.addVertex(x1, -halfThick, z1); + tess.addVertex(x2, -halfThick, z2); + tess.addVertex(x2, halfThick, z2); + tess.addVertex(x1, halfThick, z1); + } + tess.draw(); + } + + /** + * Render a line segment as a quad billboard facing the camera. + */ + protected void renderLineSegment(double x1, double y1, double z1, + double x2, double y2, double z2, + float width, int color, float alpha) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + + // Calculate direction + double dx = x2 - x1; + double dy = y2 - y1; + double dz = z2 - z1; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len < 0.001) return; + + // Perpendicular vectors for billboard + double perpX, perpY, perpZ; + if (Math.abs(dy) < 0.9) { + // Cross with up vector + perpX = -dz; + perpY = 0; + perpZ = dx; + } else { + // Cross with right vector + perpX = 0; + perpY = dz; + perpZ = -dy; + } + double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ); + if (perpLen > 0) { + perpX = perpX / perpLen * width * 0.5; + perpY = perpY / perpLen * width * 0.5; + perpZ = perpZ / perpLen * width * 0.5; + } + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ); + tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ); + tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ); + tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ); + tess.draw(); + } + + // ==================== SHARED LIGHTNING ==================== + + /** + * Get or create the lightning state for an energy entity. + * Uses the lightningState field on EntityEnergyAbility (stored as Object + * to avoid client class loading on server). + */ + protected AttachedLightningRenderer.LightningState getLightningState(EntityEnergyAbility entity) { + if (entity.lightningState == null) { + entity.lightningState = new AttachedLightningRenderer.LightningState(); + } + return (AttachedLightningRenderer.LightningState) entity.lightningState; + } + + /** + * Render attached lightning arcs around an energy entity. + * + * @param entity the energy entity + * @param innerScale multiplier for inner radius (e.g. 0.3f for projectiles, 0.95f for dome) + * @param baseSize the entity's current render size/scale + */ + protected void renderAttachedLightning(EntityEnergyAbility entity, float innerScale, float baseSize) { + AttachedLightningRenderer.LightningState state = getLightningState(entity); + + float density = entity.getLightningDensity(); + float innerRadius = innerScale * baseSize; + float radius = innerRadius + entity.getLightningRadius() * baseSize; + int outerColor = entity.getOuterColor(); + int innerColor = entity.getInnerColor(); + int fadeTime = entity.getLightningFadeTime(); + + // Barrier impact spark: briefly force brighter white crackles at the contact point. + if (entity instanceof EntityEnergyProjectile) { + int sparkTicks = ((EntityEnergyProjectile) entity).getBarrierSparkTicks(); + if (sparkTicks > 0) { + density = Math.max(density, 4.0f + sparkTicks * 0.6f); + radius = Math.max(radius, innerRadius + Math.max(0.35f, baseSize * 0.65f)); + outerColor = 0xF0F6FF; + innerColor = 0xFFFFFF; + fadeTime = Math.max(fadeTime, 6); + } + } + + state.update(density, radius, outerColor, innerColor, fadeTime); + state.render(); + } + + // ==================== PROXIMITY ALPHA ==================== + + /** + * Calculate a proximity-based alpha multiplier for owner's energy projectiles. + * Returns a factor between ProximityAlphaMin and 1.0 based on: + * - Distance from camera (close = faded, far = full) + * - Entity age (young = faded, old = full; ignored while charging) + *

+ * Only applies to the owning player's client. Non-owners always get 1.0. + * + * @param entity the energy projectile entity + * @param x camera-relative X (from doRender) + * @param y camera-relative Y (from doRender) + * @param z camera-relative Z (from doRender) + * @return alpha multiplier between ProximityAlphaMin and 1.0 + */ + protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z) { + return getProximityAlphaFactor(entity, x, y, z, false); + } + + /** + * Overload that allows forcing proximity-only fade (no age fade-out). + * Used for attached beams and lasers that stay connected to the owner. + * + * @param alwaysUseProximity if true, age factor is ignored (proximity fade never expires) + */ + protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z, boolean alwaysUseProximity) { + float minAlpha = ConfigClient.ProximityAlphaMin; + if (minAlpha >= 1.0f) return 1.0f; + + // Only apply to the owner's client + EntityPlayer player = Minecraft.getMinecraft().thePlayer; + if (player == null || entity.getOwnerEntityId() != player.getEntityId()) { + return 1.0f; + } + + // Distance factor: ramp from minAlpha at 0 to 1.0 at maxDist + float maxDist = ConfigClient.ProximityAlphaDistance; + float dist = (float) Math.sqrt(x * x + y * y + z * z); + float distFactor = Math.min(1.0f, dist / maxDist); + + // Age factor: ramp from 0 to 1.0 over ageTicks + // Charging, attached beams/lasers, and alwaysUseProximity skip age fade + float ageFactor; + if (entity.isCharging() || alwaysUseProximity) { + ageFactor = 0.0f; // Always apply full proximity fade + } else { + int ageTicks = ConfigClient.ProximityAlphaAgeTicks; + if (ageTicks <= 0) { + ageFactor = 1.0f; // Age fade disabled + } else { + ageFactor = Math.min(1.0f, (float) entity.ticksExisted / ageTicks); + } + } + + // Combined: take the max of both factors (either being far OR being old restores alpha) + float combinedFactor = Math.max(distFactor, ageFactor); + + // Lerp between minAlpha and 1.0 + return minAlpha + (1.0f - minAlpha) * combinedFactor; + } + + @Override + protected ResourceLocation getEntityTexture(Entity entity) { + return WHITE_TEXTURE; + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java new file mode 100644 index 000000000..846c167ea --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java @@ -0,0 +1,23 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityEnergyBarrier; + +/** + * Intermediate renderer base for energy barrier entities (Dome, Panel). + * Provides shared hit flash alpha computation. + */ +@SideOnly(Side.CLIENT) +public abstract class RenderEnergyBarrier extends RenderEnergy { + + /** + * Compute the alpha boost from a hit flash effect. + * Flash value decays from 4 to 0, producing alpha from 0.3 to 0. + */ + protected float computeFlashAlpha(EntityEnergyBarrier barrier) { + byte flash = barrier.getHitFlash(); + if (flash <= 0) return 0.0f; + return flash / 4.0f * 0.3f; + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java similarity index 85% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java index 4912e4b72..decd15ef8 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java @@ -2,9 +2,9 @@ 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.EntityAbilityBeam; import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.util.Vec3; import org.lwjgl.opengl.GL11; @@ -15,26 +15,32 @@ import java.util.List; /** * Renders the AbilityBeam entity with a head, tail orb, and curving trail. * The trail shows the path the head has traveled using laser-style rectangular segments. - * + *

* IMPORTANT: Trail points are stored RELATIVE to the origin position. * We render by translating to the origin first, then drawing all points relative to that. - * + *

* Trail segments now share vertices at connection points to prevent gaps during curves. - * + *

* Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public class RenderAbilityBeam extends RenderAbilityProjectile { +public class RenderEnergyBeam extends RenderEnergy { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + if (shouldSkipInitialActiveRender(entity)) { + return; + } EntityAbilityBeam beam = (EntityAbilityBeam) entity; setupRenderState(); + // Proximity alpha fade for owner (attached beams always use proximity, never age out) + float proximityAlpha = getProximityAlphaFactor(beam, x, y, z, beam.isAttachedToOwner()); + // Handle charging state (windup phase) - render only growing orb if (beam.isCharging()) { - renderChargingOrb(beam, x, y, z, partialTicks); + renderChargingOrb(beam, x, y, z, partialTicks, proximityAlpha); restoreRenderState(); return; } @@ -46,24 +52,25 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { return; } - // Get interpolated head offset + // Get interpolated head offset (for head/trail rendering relative to origin) double headOffsetX = beam.getInterpolatedHeadOffsetX(partialTicks); double headOffsetY = beam.getInterpolatedHeadOffsetY(partialTicks); double headOffsetZ = beam.getInterpolatedHeadOffsetZ(partialTicks); - // The render system passes x,y,z as the position to render the entity at - // Entity position = origin + headOffset (in world coords) - // So origin render position = x,y,z - headOffset - double renderOriginX = x - headOffsetX; - double renderOriginY = y - headOffsetY; - double renderOriginZ = z - headOffsetZ; + // Compute render origin directly from the world origin and camera position. + // We can't derive it from MC's x,y,z because syncPositionStateToCurrent() snaps + // lastTickPos = posX on every sync packet, killing MC's position interpolation. + // The headOffset interpolation then mismatches, causing the origin to wobble. + double renderOriginX = beam.getOriginX() - RenderManager.renderPosX; + double renderOriginY = beam.getOriginY() - RenderManager.renderPosY; + double renderOriginZ = beam.getOriginZ() - RenderManager.renderPosZ; - // Get beam properties - float beamWidth = beam.getBeamWidth(); - float headSize = beam.getHeadSize(); + // Get beam properties (lerp-smoothed for smooth size transitions) + float beamWidth = beam.getInterpolatedBeamWidth(partialTicks); + float headSize = beam.getInterpolatedHeadSize(partialTicks); int innerColor = beam.getInnerColor(); int outerColor = beam.getOuterColor(); - float outerAlpha = beam.getOuterColorAlpha(); + float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha; // Render everything relative to origin position GL11.glPushMatrix(); @@ -72,21 +79,24 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Calculate head distance from origin (for overlap check) double headDistFromOrigin = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ); - // Render tail orb at origin (0,0,0) - only in anchored mode - // Don't render if head is too close to origin (would cause overlap/extra orb appearance) - if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) { - renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha); + float innerAlpha = beam.getInnerAlpha() * proximityAlpha; + + // Render trail segments first (with fading for non-anchored) + if (beam.hasFadingTrail()) { + renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha); + } else { + renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha); } - // Render trail segments with smooth connections (with fading for non-anchored) - if (beam.hasFadingTrail()) { - renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth()); - } else { - renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth()); + // Render tail orb at origin (0,0,0) AFTER trail so it draws on top + // Don't render if head is too close to origin (would cause overlap/extra orb appearance) + // Use target headSize (not lerped) so the threshold isn't inflated by lerp lag + if (beam.shouldRenderTailOrb() && headDistFromOrigin > beam.getHeadSize() * 0.5) { + renderTailOrb(beam.getHeadSize() * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, innerAlpha); } // Render head at interpolated offset position - renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, partialTicks); + renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks); GL11.glPopMatrix(); @@ -97,8 +107,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { * Render the charging orb during windup phase. * Grows from 0 to headSize based on charge progress. */ - private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks) { - float headSize = beam.getHeadSize(); + private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks, float proximityAlpha) { + float headSize = beam.getInterpolatedHeadSize(partialTicks); float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks); float size = headSize * chargeProgress; @@ -117,7 +127,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Render lightning during charging if enabled if (beam.hasLightningEffect()) { - renderAttachedLightning(beam, scale); + renderAttachedLightning(beam, 0.6f * 0.5f, scale); } GL11.glPushMatrix(); @@ -129,7 +139,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Render outer glow only if enabled if (beam.isOuterColorEnabled()) { float outerScale = innerScale + beam.getOuterColorWidth(); - float outerAlpha = beam.getOuterColorAlpha(); + float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha; GL11.glDepthMask(false); GL11.glPushMatrix(); GL11.glScalef(outerScale, outerScale, outerScale); @@ -140,7 +150,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Render inner core GL11.glScalef(innerScale, innerScale, innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -150,7 +160,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { * Render the tail orb at the origin (where the beam emanates from). * This orb does not rotate - it's a stable anchor point. */ - private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha) { + private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha, float innerAlpha) { GL11.glPushMatrix(); // Already at origin (0,0,0) @@ -172,7 +182,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Render inner core (solid) GL11.glPushMatrix(); GL11.glScalef(size * innerScale, size * innerScale, size * innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, innerAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -183,7 +193,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { * Uses averaged perpendicular vectors at connection points to prevent gaps. */ private void renderSmoothTrail(List trail, float width, int innerColor, int outerColor, - boolean outerColorEnabled, float outerColorWidth) { + boolean outerColorEnabled, float outerColorWidth, float innerAlpha) { if (trail.size() < 2) return; int trailSize = trail.size(); @@ -206,7 +216,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { } // Render inner core trail - renderTrailTube(trail, perpFrames, innerWidth, innerColor, 0.9f, false); + renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false); } /** @@ -214,7 +224,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { * Older trail points fade out based on their age. */ private void renderFadingTrail(EntityAbilityBeam beam, List trail, float width, int innerColor, int outerColor, - boolean outerColorEnabled, float outerColorWidth) { + boolean outerColorEnabled, float outerColorWidth, float innerAlpha) { if (trail.size() < 2) return; List ages = beam.getTrailPointAges(); @@ -236,14 +246,14 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { } // Render inner core trail with fading - renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, 0.9f); + renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, innerAlpha); } /** * Render trail tube with age-based fading. */ private void renderFadingTrailTube(List trail, List perpFrames, List ages, - int fadeTime, float width, int color, float baseAlpha) { + int fadeTime, float width, int color, float baseAlpha) { float[] rgb = extractRGB(color); float r = rgb[0], g = rgb[1], b = rgb[2]; float halfWidth = width * 0.5f; @@ -261,8 +271,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Calculate alpha based on age (older = more faded) float age1 = i < ages.size() ? ages.get(i) : 0; float age2 = (i + 1) < ages.size() ? ages.get(i + 1) : 0; - float fade1 = 1.0f - Math.min(1.0f, age1 / fadeTime); - float fade2 = 1.0f - Math.min(1.0f, age2 / fadeTime); + float fade1 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age1 / fadeTime)) : 0.0f; + float fade2 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age2 / fadeTime)) : 0.0f; float alpha1 = baseAlpha * fade1; float alpha2 = baseAlpha * fade2; @@ -393,13 +403,17 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { dy /= len; dz /= len; } else { - dx = 0; dy = 0; dz = 1; + dx = 0; + dy = 0; + dz = 1; } // Calculate perpendicular vectors using consistent up reference double upX = 0, upY = 1, upZ = 0; if (Math.abs(dy) > 0.9) { - upX = 1; upY = 0; upZ = 0; + upX = 1; + upY = 0; + upZ = 0; } // Cross product for horizontal perpendicular @@ -418,8 +432,12 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { double vertY = dz * horzX - dx * horzZ; double vertZ = dx * horzY - dy * horzX; - frame[0] = horzX; frame[1] = horzY; frame[2] = horzZ; - frame[3] = vertX; frame[4] = vertY; frame[5] = vertZ; + frame[0] = horzX; + frame[1] = horzY; + frame[2] = horzZ; + frame[3] = vertX; + frame[4] = vertY; + frame[5] = vertZ; frames.add(frame); } @@ -430,7 +448,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { * Render the trail as a continuous tube using pre-computed perpendicular frames. */ private void renderTrailTube(List trail, List perpFrames, - float width, int color, float baseAlpha, boolean fadeFromStart) { + float width, int color, float baseAlpha, boolean fadeFromStart) { float[] rgb = extractRGB(color); float r = rgb[0], g = rgb[1], b = rgb[2]; float halfWidth = width * 0.5f; @@ -534,7 +552,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { * Coordinates are relative to origin. */ private void renderHead(EntityAbilityBeam beam, double x, double y, double z, - float size, int innerColor, int outerColor, float outerAlpha, float partialTicks) { + float size, int innerColor, int outerColor, float outerAlpha, float innerAlpha, float partialTicks) { GL11.glPushMatrix(); GL11.glTranslated(x, y, z); @@ -545,7 +563,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Render lightning BEFORE rotation so it crackles in all directions (only on head) if (beam.hasLightningEffect()) { - renderAttachedLightning(beam, scale); + renderAttachedLightning(beam, 0.6f * 0.5f, scale); } // Rotation @@ -573,37 +591,10 @@ public class RenderAbilityBeam extends RenderAbilityProjectile { // Render inner core GL11.glScalef(innerScale, innerScale, innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, innerAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); } - /** - * Render fading lightning arcs attached to the beam head (in local space). - */ - private void renderAttachedLightning(EntityAbilityBeam beam, float headScale) { - AttachedLightningRenderer.LightningState state = getLightningState(beam); - - float density = beam.getLightningDensity(); - // Lightning radius extends outward from inner surface (innerScale = 0.6) - float innerRadius = 0.6f * headScale * 0.5f; - float radius = innerRadius + beam.getLightningRadius() * headScale; - int outerColor = beam.getOuterColor(); - int innerColor = beam.getInnerColor(); - int fadeTime = beam.getLightningFadeTime(); - - state.update(density, radius, outerColor, innerColor, fadeTime); - state.render(); - } - - /** - * Get or create the lightning state for an entity. - */ - private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityBeam beam) { - if (beam.lightningState == null) { - beam.lightningState = new AttachedLightningRenderer.LightningState(); - } - return (AttachedLightningRenderer.LightningState) beam.lightningState; - } } diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java similarity index 76% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java index 8cb8cdaad..93b90023e 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java @@ -2,22 +2,26 @@ 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.EntityAbilityDisc; import net.minecraft.entity.Entity; +import net.minecraft.util.Vec3; +import noppes.npcs.util.MathUtil; import org.lwjgl.opengl.GL11; /** * Renders the AbilityDisc entity as a flat spinning square. * Rotates only on Y axis (flat spin like a saw blade). - * + *

* Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public class RenderAbilityDisc extends RenderAbilityProjectile { +public class RenderEnergyDisc extends RenderEnergy { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + if (shouldSkipInitialActiveRender(entity)) { + return; + } EntityAbilityDisc disc = (EntityAbilityDisc) entity; setupRenderState(); @@ -27,8 +31,8 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { // Get interpolated values float size = disc.getInterpolatedSize(partialTicks); - float radius = disc.getDiscRadius() * size; - float thickness = disc.getDiscThickness() * size; + float radius = disc.getInterpolatedDiscRadius(partialTicks) * size; + float thickness = disc.getInterpolatedDiscThickness(partialTicks) * size; // Subtle pulsing effect float pulseTime = entity.ticksExisted + partialTicks; @@ -37,7 +41,7 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { // Render lightning BEFORE rotation so it crackles in all directions if (disc.hasLightningEffect()) { - renderAttachedLightning(disc, radius * scale); + renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale); } GL11.glPushMatrix(); @@ -52,23 +56,41 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); } + double motionX = entity.motionX; + double motionY = entity.motionY; + double motionZ = entity.motionZ; + double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ; + + // Only apply motion-based facing when speed is meaningful. + // Near-zero motion makes atan2 unstable, producing jittery angles. + if (speedSq > 0.0001) { + Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ); + float motionYaw = MathUtil.getYaw(motionVec); + float motionPitch = MathUtil.getPitch(motionVec); + GL11.glRotatef(motionYaw, 0, 1, 0); + GL11.glRotatef(motionPitch, 1, 0, 0); + } + // Apply Y-axis rotation for spin GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f); // Inner scale defines the core size float innerScale = 0.6f; + // Proximity alpha fade for owner + float proximityAlpha = getProximityAlphaFactor(disc, x, y, z); + // Render outer square (translucent) - only if enabled // outerColorWidth is an additive offset from inner size if (disc.isOuterColorEnabled()) { float outerScale = innerScale + disc.getOuterColorWidth(); GL11.glDepthMask(false); - renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha(), radius * outerScale, thickness); + renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha() * proximityAlpha, radius * outerScale, thickness); GL11.glDepthMask(true); } // Render inner square (solid) - renderFlatSquare(disc.getInnerColor(), 1.0f, radius * innerScale, thickness * 1.2f); + renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -76,34 +98,6 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { restoreRenderState(); } - /** - * Render fading lightning arcs attached to the disc (in local space). - */ - private void renderAttachedLightning(EntityAbilityDisc disc, float discSize) { - AttachedLightningRenderer.LightningState state = getLightningState(disc); - - float density = disc.getLightningDensity(); - // Lightning radius extends outward from inner surface (innerScale = 0.6) - float innerRadius = 0.6f * discSize * 0.5f; - float radius = innerRadius + disc.getLightningRadius() * discSize; - int outerColor = disc.getOuterColor(); - int innerColor = disc.getInnerColor(); - int fadeTime = disc.getLightningFadeTime(); - - state.update(density, radius, outerColor, innerColor, fadeTime); - state.render(); - } - - /** - * Get or create the lightning state for an entity. - */ - private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityDisc disc) { - if (disc.lightningState == null) { - disc.lightningState = new AttachedLightningRenderer.LightningState(); - } - return (AttachedLightningRenderer.LightningState) disc.lightningState; - } - /** * Render a flat square (thin cube) centered at origin. * The square lies flat on the XZ plane with thin Y height. diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java new file mode 100644 index 000000000..34465635c --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java @@ -0,0 +1,111 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityEnergyDome; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import org.lwjgl.opengl.GL11; + +/** + * Renders the Dome entity as a translucent sphere. + * Inner layer solid, outer layer translucent glow. + */ +@SideOnly(Side.CLIENT) +public class RenderEnergyDome extends RenderEnergyBarrier { + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + if (shouldSkipInitialActiveRender(entity)) { + return; + } + EntityEnergyDome dome = (EntityEnergyDome) entity; + float radius = dome.getDomeRadius(); + float healthPercent = dome.getHealthPercent(); + + setupRenderState(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Lightning BEFORE any rotation (uniform spread) + if (dome.hasLightningEffect()) { + renderAttachedLightning(dome, 0.95f, radius); + } + + // Hit flash effect + float flashAlpha = computeFlashAlpha(dome); + + float innerScale = 1.0f; + + // Render outer dome (translucent glow) + if (dome.isOuterColorEnabled()) { + float outerScale = 1.0f + dome.getOuterColorWidth() * 0.1f; + float outerAlpha = dome.getOuterColorAlpha() * healthPercent; + GL11.glDepthMask(false); + renderSphere(dome.getOuterColor(), outerAlpha + (dome.getOuterColorAlpha() > 0 ? flashAlpha : 0), radius * outerScale, 8); + } + + GL11.glDepthMask(true); + // Render inner dome (depth write enabled so inner sphere properly occludes) + renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8); + GL11.glPopMatrix(); + + restoreRenderState(); + } + + /** + * Render a sphere made of quad panels. + * Uses latitude/longitude segments to form a full sphere. + */ + private void renderSphere(int color, float alpha, float radius, int segments) { + float[] rgb = extractRGB(color); + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + tess.setColorRGBA_F(rgb[0], rgb[1], rgb[2], alpha); + + for (int lat = 0; lat < segments; lat++) { + float theta1 = (float) (Math.PI * lat / segments - Math.PI * 0.5); + float theta2 = (float) (Math.PI * (lat + 1) / segments - Math.PI * 0.5); + + float y1 = (float) Math.sin(theta1) * radius; + float y2 = (float) Math.sin(theta2) * radius; + float r1 = (float) Math.cos(theta1) * radius; + float r2 = (float) Math.cos(theta2) * radius; + + for (int lon = 0; lon < segments; lon++) { + float phi1 = (float) (2 * Math.PI * lon / segments); + float phi2 = (float) (2 * Math.PI * (lon + 1) / segments); + + float x1 = (float) Math.cos(phi1) * r1; + float z1 = (float) Math.sin(phi1) * r1; + float x2 = (float) Math.cos(phi2) * r1; + float z2 = (float) Math.sin(phi2) * r1; + float x3 = (float) Math.cos(phi2) * r2; + float z3 = (float) Math.sin(phi2) * r2; + float x4 = (float) Math.cos(phi1) * r2; + float z4 = (float) Math.sin(phi1) * r2; + + float nx = (x1 + x2 + x3 + x4) * 0.25f; + float ny = (y1 + y1 + y2 + y2) * 0.25f; + float nz = (z1 + z2 + z3 + z4) * 0.25f; + float nLen = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); + if (nLen > 0) { + nx /= nLen; + ny /= nLen; + nz /= nLen; + } + + tess.setNormal(nx, ny, nz); + tess.addVertex(x1, y1, z1); + tess.addVertex(x2, y1, z2); + tess.addVertex(x3, y2, z3); + tess.addVertex(x4, y2, z4); + } + } + + tess.draw(); + } + +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java new file mode 100644 index 000000000..bb1f94cab --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java @@ -0,0 +1,211 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityEnergyExplosion; +import net.minecraft.entity.Entity; +import noppes.npcs.config.ConfigClient; +import org.lwjgl.opengl.GL11; + +/** + * Voxel-style renderer for {@link EntityEnergyExplosion}. + * Draws expanding cubic shells with a short fade-out. + * Uses batched cube rendering for performance — all cubes of each layer + * are drawn in a single tessellator pass instead of per-cube draw calls. + */ +@SideOnly(Side.CLIENT) +public class RenderEnergyExplosion extends RenderEnergy { + + private static final float MAX_OUTER_ALPHA = 0.85f; + private static final float MAX_INNER_ALPHA = 1.0f; + private static final float MAX_SMOKE_CUBE_ALPHA = 0.55f; + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + if (shouldSkipInitialActiveRender(entity)) return; + if (!(entity instanceof EntityEnergyExplosion)) return; + if (ConfigClient.LowResExplosion) return; + EntityEnergyExplosion explosion = (EntityEnergyExplosion) entity; + + setupRenderState(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + float radius = explosion.getInterpolatedRadius(partialTicks); + float life = explosion.getLifeProgress(partialTicks); + if (radius > 0.01f && life < 1.0f) { + renderVoxelBurst(explosion, radius, life); + if (explosion.hasLightningEffect()) { + renderAttachedLightning(explosion, 0.55f, Math.max(0.7f, radius * 0.45f)); + } + } + + GL11.glPopMatrix(); + restoreRenderState(); + } + + private void renderVoxelBurst(EntityEnergyExplosion explosion, float radius, float life) { + int outerColor = explosion.getOuterColor(); + int innerColor = explosion.getInnerColor(); + boolean hasOuter = explosion.isOuterColorEnabled(); + + float fade = 1.0f - life; + float outerAlpha = Math.min(MAX_OUTER_ALPHA, (0.25f + fade * 0.75f) * explosion.getOuterColorAlpha()); + float innerAlpha = Math.min(MAX_INNER_ALPHA, (0.30f + fade * 0.80f) * explosion.getInnerAlpha()); + + int steps = Math.max(2, Math.min(6, (int) Math.ceil(radius * 0.65f) + 1)); + float cell = radius / steps; + float cubeHalf = Math.max(0.04f, cell * 0.22f * (0.90f - life * 0.25f)); + float outerScale = hasOuter ? 1.0f + explosion.getOuterColorWidth() * 0.35f : 1.0f; + long seed = explosion.getRenderSeed(); + + // Pre-extract RGB for batched rendering + float outerR = ((outerColor >> 16) & 0xFF) / 255.0f; + float outerG = ((outerColor >> 8) & 0xFF) / 255.0f; + float outerB = (outerColor & 0xFF) / 255.0f; + float innerR = ((innerColor >> 16) & 0xFF) / 255.0f; + float innerG = ((innerColor >> 8) & 0xFF) / 255.0f; + float innerB = (innerColor & 0xFF) / 255.0f; + + GL11.glDepthMask(false); + + // Smoke layer — single batched pass + renderSmokeVoxelShell(radius, life, seed); + + // Outer color layer — single batched pass + if (hasOuter) { + float outerHalf = cubeHalf * outerScale; + float oa = outerAlpha * fade; + beginCubeBatch(); + for (int ix = -steps; ix <= steps; ix++) { + for (int iy = -steps; iy <= steps; iy++) { + for (int iz = -steps; iz <= steps; iz++) { + int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz))); + if (edge != steps) continue; + if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue; + + float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f; + float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f; + float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f; + addBatchedCube(px, py, pz, outerHalf, outerR, outerG, outerB, oa); + } + } + } + endCubeBatch(); + } + + // Inner color layer — single batched pass + { + float innerHalf = cubeHalf * 0.9f; + float ia = innerAlpha * fade; + beginCubeBatch(); + for (int ix = -steps; ix <= steps; ix++) { + for (int iy = -steps; iy <= steps; iy++) { + for (int iz = -steps; iz <= steps; iz++) { + int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz))); + if (edge != steps) continue; + if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue; + + float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f; + float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f; + float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f; + addBatchedCube(px, py, pz, innerHalf, innerR, innerG, innerB, ia); + } + } + } + endCubeBatch(); + } + + renderCoreFlash(innerColor, innerAlpha, radius, cubeHalf, life); + GL11.glDepthMask(true); + } + + /** + * Adds large translucent white/gray cubes to fake a smoky volumetric expansion. + * All smoke cubes are batched into a single draw call. + */ + private void renderSmokeVoxelShell(float radius, float life, long seed) { + int smokeSteps = Math.max(2, Math.min(5, (int) Math.ceil(radius * 0.5f) + 1)); + float smokeCell = radius / smokeSteps * 1.2f; + float smokeJitter = smokeCell * 0.28f; + float smokeCubeHalf = Math.max(0.07f, smokeCell * 0.24f * (0.95f - life * 0.25f)); + float smokeAlpha = Math.min(MAX_SMOKE_CUBE_ALPHA, (0.15f + (1.0f - life) * 0.55f)); + + // White = 1,1,1 Gray (0xDCDCDC) = 0.863,0.863,0.863 + beginCubeBatch(); + for (int ix = -smokeSteps; ix <= smokeSteps; ix++) { + for (int iy = -smokeSteps; iy <= smokeSteps; iy++) { + for (int iz = -smokeSteps; iz <= smokeSteps; iz++) { + int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz))); + if (edge < smokeSteps - 1) continue; + + int h = hash(ix * 5, iy * 7, iz * 11, seed ^ 0x4f1bbcdcL); + if ((h & 3) != 0) continue; + if (life > 0.72f && ((h >>> 5) & 7) > 2) continue; + + float px = ix * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 1) * smokeJitter; + float py = iy * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 2) * smokeJitter; + float pz = iz * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 3) * smokeJitter; + + boolean isWhite = ((h >>> 9) & 1) == 0; + float gray = isWhite ? 1.0f : 0.863f; + float alpha = smokeAlpha * (0.78f + (((h >>> 10) & 15) / 15.0f) * 0.22f); + addBatchedCube(px, py, pz, smokeCubeHalf, gray, gray, gray, alpha); + } + } + } + endCubeBatch(); + } + + /** + * White-hot core flash pass for the initial frames. + */ + private void renderCoreFlash(int innerColor, float innerAlpha, float radius, float cubeHalf, float life) { + float flash = saturate((0.60f - life) / 0.60f); + if (flash <= 0.0f) return; + + float coreHalf = Math.max(cubeHalf, radius * 0.07f) * (1.0f + flash * 0.55f); + float whiteAlpha = Math.min(1.0f, 0.25f + flash * 0.95f); + float innerFlashAlpha = Math.min(1.0f, innerAlpha * (0.45f + flash * 0.95f)); + + renderCube(0xFFFFFF, whiteAlpha, coreHalf * 1.45f); + renderCube(innerColor, innerFlashAlpha, coreHalf * 0.82f); + } + + private float saturate(float value) { + if (value < 0.0f) return 0.0f; + if (value > 1.0f) return 1.0f; + return value; + } + + private boolean shouldRenderVoxel(int ix, int iy, int iz, int steps, long seed, float life) { + int h = hash(ix, iy, iz, seed); + + int keepMask = steps >= 5 ? 3 : 1; + if ((h & keepMask) != 0) return false; + + if (life > 0.55f) { + int decay = (h >>> 3) & 7; + if (decay > 2) return false; + } + + return true; + } + + private float jitter(int ix, int iy, int iz, long seed, int channel) { + int h = hash(ix + channel * 17, iy - channel * 31, iz + channel * 47, seed); + return (((h >>> 8) & 1023) / 1023.0f) - 0.5f; + } + + private int hash(int x, int y, int z, long seed) { + long h = seed; + h ^= (long) x * 73428767L; + h ^= (long) y * 912931L; + h ^= (long) z * 19349663L; + h ^= (h >>> 33); + h *= 0xff51afd7ed558ccdL; + h ^= (h >>> 33); + return (int) h; + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java similarity index 72% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java index e70e5c6ba..8b0c79b65 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java @@ -3,19 +3,23 @@ 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.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityLaser; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; +import java.util.HashMap; +import java.util.Map; + /** * Renders the AbilityLaser entity as a rectangular beam with clear inner/outer colors. - * + *

* Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public class RenderAbilityLaser extends RenderAbilityProjectile { +public class RenderEnergyLaser extends RenderEnergy { + + private final Map tipLightningStates = new HashMap<>(); @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { @@ -23,21 +27,24 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { setupRenderState(); + // Proximity alpha fade for owner (lasers are always attached, never age out) + float proximityAlpha = getProximityAlphaFactor(laser, x, y, z, true); + if (laser.isCharging()) { - renderChargingOrb(laser, x, y, z, partialTicks); + renderChargingOrb(laser, x, y, z, partialTicks, proximityAlpha); restoreRenderState(); return; } - // Get laser parameters - double startX = laser.getStartX(); - double startY = laser.getStartY(); - double startZ = laser.getStartZ(); - double endX = laser.getEndX(); - double endY = laser.getEndY(); - double endZ = laser.getEndZ(); - float width = laser.getLaserWidth(); - float alpha = laser.getLingerAlpha(); + // Get interpolated laser positions for smooth rendering between ticks + double startX = laser.getInterpolatedStartX(partialTicks); + double startY = laser.getInterpolatedStartY(partialTicks); + double startZ = laser.getInterpolatedStartZ(partialTicks); + double endX = laser.getInterpolatedEndX(partialTicks); + double endY = laser.getInterpolatedEndY(partialTicks); + double endZ = laser.getInterpolatedEndZ(partialTicks); + float width = laser.getInterpolatedLaserWidth(partialTicks); + float alpha = 1.0f; // Calculate render offset (entity position is used as reference) double offsetX = x - laser.posX; @@ -70,7 +77,9 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { // Calculate perpendicular vectors (one horizontal, one vertical relative to beam) double upX = 0, upY = 1, upZ = 0; if (Math.abs(dy) > 0.9) { - upX = 1; upY = 0; upZ = 0; + upX = 1; + upY = 0; + upZ = 0; } // Cross product for horizontal perpendicular @@ -89,6 +98,25 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { double vertY = dz * horzX - dx * horzZ; double vertZ = dx * horzY - dy * horzX; + // Rotate perpendicular vectors around beam axis (Rodrigues' rotation) + float rotationSpeed = laser.getRotationSpeed(); + if (rotationSpeed != 0.0f) { + double angle = (laser.ticksExisted + partialTicks) * rotationSpeed * Math.PI / 180.0; + double cosA = Math.cos(angle); + double sinA = Math.sin(angle); + + double rHorzX = horzX * cosA + vertX * sinA; + double rHorzY = horzY * cosA + vertY * sinA; + double rHorzZ = horzZ * cosA + vertZ * sinA; + + double rVertX = -horzX * sinA + vertX * cosA; + double rVertY = -horzY * sinA + vertY * cosA; + double rVertZ = -horzZ * sinA + vertZ * cosA; + + horzX = rHorzX; horzY = rHorzY; horzZ = rHorzZ; + vertX = rVertX; vertY = rVertY; vertZ = rVertZ; + } + // Inner scale defines the core width float innerScale = 0.6f; float innerWidth = width * innerScale; @@ -99,36 +127,36 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { float outerWidth = innerWidth + laser.getOuterColorWidth() * width; GL11.glDepthMask(false); renderBeamRectangle(renderStartX, renderStartY, renderStartZ, - renderEndX, renderEndY, renderEndZ, - horzX, horzY, horzZ, vertX, vertY, vertZ, - outerWidth, laser.getOuterColor(), alpha * 0.4f); + renderEndX, renderEndY, renderEndZ, + horzX, horzY, horzZ, vertX, vertY, vertZ, + outerWidth, laser.getOuterColor(), alpha * 0.4f * proximityAlpha); // Render middle layer (halfway between inner and outer) float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f; renderBeamRectangle(renderStartX, renderStartY, renderStartZ, - renderEndX, renderEndY, renderEndZ, - horzX, horzY, horzZ, vertX, vertY, vertZ, - midWidth, laser.getOuterColor(), alpha * 0.7f); + renderEndX, renderEndY, renderEndZ, + horzX, horzY, horzZ, vertX, vertY, vertZ, + midWidth, laser.getOuterColor(), alpha * 0.7f * proximityAlpha); GL11.glDepthMask(true); } // Render inner core (solid) renderBeamRectangle(renderStartX, renderStartY, renderStartZ, - renderEndX, renderEndY, renderEndZ, - horzX, horzY, horzZ, vertX, vertY, vertZ, - innerWidth, laser.getInnerColor(), alpha); + renderEndX, renderEndY, renderEndZ, + horzX, horzY, horzZ, vertX, vertY, vertZ, + innerWidth, laser.getInnerColor(), alpha * laser.getInnerAlpha() * proximityAlpha); // Render lightning along the laser beam if (laser.hasLightningEffect() && laser.getCurrentLength() > 0.1f) { renderLaserLightning(laser, renderStartX, renderStartY, renderStartZ, - renderEndX, renderEndY, renderEndZ, width); + renderEndX, renderEndY, renderEndZ, width); } restoreRenderState(); } - private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks) { - float headSize = laser.getLaserWidth() * 1.5f; + private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) { + float headSize = laser.getInterpolatedLaserWidth(partialTicks) * 0.5f; float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks); float size = headSize * chargeProgress; @@ -147,7 +175,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { // Render lightning during charging if enabled if (laser.hasLightningEffect()) { - renderAttachedLightning(laser, scale); + renderAttachedLightning(laser, 0.6f * 0.5f, scale); } GL11.glPushMatrix(); @@ -159,7 +187,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { // Render outer glow only if enabled if (laser.isOuterColorEnabled()) { float outerScale = innerScale + laser.getOuterColorWidth(); - float outerAlpha = laser.getOuterColorAlpha(); + float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha; GL11.glDepthMask(false); GL11.glPushMatrix(); GL11.glScalef(outerScale, outerScale, outerScale); @@ -170,7 +198,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { // Render inner core GL11.glScalef(innerScale, innerScale, innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -180,8 +208,8 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { * Render lightning effects along the laser beam at multiple points. */ private void renderLaserLightning(EntityAbilityLaser laser, - double startX, double startY, double startZ, - double endX, double endY, double endZ, float width) { + double startX, double startY, double startZ, + double endX, double endY, double endZ, float width) { AttachedLightningRenderer.LightningState state = getLightningState(laser); float density = laser.getLightningDensity(); @@ -215,50 +243,28 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { } - private void renderAttachedLightning(EntityAbilityLaser laser, float headScale) { - AttachedLightningRenderer.LightningState state = getLightningState(laser); - - float density = laser.getLightningDensity(); - // Lightning radius extends outward from inner surface (innerScale = 0.6) - float innerRadius = 0.6f * headScale * 0.5f; - float radius = innerRadius + laser.getLightningRadius() * headScale; - int outerColor = laser.getOuterColor(); - int innerColor = laser.getInnerColor(); - int fadeTime = laser.getLightningFadeTime(); - - state.update(density, radius, outerColor, innerColor, fadeTime); - state.render(); - } - - /** - * Get or create the main lightning state for the laser. - */ - private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityLaser laser) { - if (laser.lightningState == null) { - laser.lightningState = new AttachedLightningRenderer.LightningState(); - } - return (AttachedLightningRenderer.LightningState) laser.lightningState; - } - /** * Get or create the tip lightning state for the laser. - * Stored as a secondary object in lightningState2. + * Persisted per entity ID so arcs accumulate and fade properly across frames. */ private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) { - // Use a simple approach - store in a transient field - // Since lightningState is already used, we'll create a new state each time - // This works because we're updating and rendering immediately - return new AttachedLightningRenderer.LightningState(); + int id = laser.getEntityId(); + AttachedLightningRenderer.LightningState state = tipLightningStates.get(id); + if (state == null) { + state = new AttachedLightningRenderer.LightningState(); + tipLightningStates.put(id, state); + } + return state; } /** * Render a beam as a 3D rectangular prism (box along a line). */ private void renderBeamRectangle(double x1, double y1, double z1, - double x2, double y2, double z2, - double horzX, double horzY, double horzZ, - double vertX, double vertY, double vertZ, - float width, int color, float alpha) { + double x2, double y2, double z2, + double horzX, double horzY, double horzZ, + double vertX, double vertY, double vertZ, + float width, int color, float alpha) { float[] rgb = extractRGB(color); float r = rgb[0], g = rgb[1], b = rgb[2]; diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java similarity index 58% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java index 048b3642f..5efe83222 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java @@ -2,9 +2,10 @@ 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.EntityAbilityOrb; import net.minecraft.entity.Entity; +import net.minecraft.util.Vec3; +import noppes.npcs.util.MathUtil; import org.lwjgl.opengl.GL11; /** @@ -12,7 +13,7 @@ import org.lwjgl.opengl.GL11; * Minecraft-style blocky appearance using Tessellator. */ @SideOnly(Side.CLIENT) -public class RenderAbilityOrb extends RenderAbilityProjectile { +public class RenderEnergyOrb extends RenderEnergy { private static final int LIGHTNING_FADE_TICKS = 6; @@ -20,6 +21,10 @@ public class RenderAbilityOrb extends RenderAbilityProjectile { public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { EntityAbilityOrb orb = (EntityAbilityOrb) entity; + if (shouldSkipInitialActiveRender(entity)) { + return; + } + setupRenderState(); GL11.glPushMatrix(); @@ -35,7 +40,22 @@ public class RenderAbilityOrb extends RenderAbilityProjectile { // Render lightning BEFORE rotation so it crackles in all directions if (orb.hasLightningEffect()) { - renderAttachedLightning(orb, scale); + renderAttachedLightning(orb, 0.6f * 0.5f, scale); + } + + double motionX = entity.motionX; + double motionY = entity.motionY; + double motionZ = entity.motionZ; + double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ; + + // Only apply motion-based facing when speed is meaningful. + // Near-zero motion makes atan2 unstable, producing jittery angles. + if (speedSq > 0.0001) { + Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ); + float motionYaw = MathUtil.getYaw(motionVec); + float motionPitch = MathUtil.getPitch(motionVec); + GL11.glRotatef(motionYaw, 0, 1, 0); + GL11.glRotatef(motionPitch, 1, 0, 0); } // Use entity's interpolated rotation for smooth spinning @@ -49,6 +69,9 @@ public class RenderAbilityOrb extends RenderAbilityProjectile { // Inner scale defines the core size float innerScale = 0.6f; + // Proximity alpha fade for owner + float proximityAlpha = getProximityAlphaFactor(orb, x, y, z); + // Render outer cube (translucent) - only if enabled // outerColorWidth is an additive offset from inner size if (orb.isOuterColorEnabled()) { @@ -56,14 +79,14 @@ public class RenderAbilityOrb extends RenderAbilityProjectile { GL11.glDepthMask(false); GL11.glPushMatrix(); GL11.glScalef(outerScale, outerScale, outerScale); - renderCube(orb.getOuterColor(), orb.getOuterColorAlpha(), 0.5f); + renderCube(orb.getOuterColor(), orb.getOuterColorAlpha() * proximityAlpha, 0.5f); GL11.glPopMatrix(); GL11.glDepthMask(true); } // Render inner cube (solid) GL11.glScalef(innerScale, innerScale, innerScale); - renderCube(orb.getInnerColor(), 1.0f, 0.5f); + renderCube(orb.getInnerColor(), orb.getInnerAlpha() * proximityAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -71,36 +94,4 @@ public class RenderAbilityOrb extends RenderAbilityProjectile { restoreRenderState(); } - /** - * Render fading lightning arcs attached to the orb (in local space). - * Arcs persist for a few ticks and fade out, while staying attached to the orb. - */ - private void renderAttachedLightning(EntityAbilityOrb orb, float orbScale) { - // Get or create the lightning state for this entity - AttachedLightningRenderer.LightningState state = getLightningState(orb); - - float density = orb.getLightningDensity(); - // Lightning radius extends outward from inner surface (innerScale = 0.6) - float innerRadius = 0.6f * orbScale * 0.5f; // Half size of inner cube - float radius = innerRadius + orb.getLightningRadius() * orbScale; - int outerColor = orb.getOuterColor(); - int innerColor = orb.getInnerColor(); - int fadeTime = orb.getLightningFadeTime(); - - // Update: age existing arcs, spawn new ones based on density - state.update(density, radius, outerColor, innerColor, fadeTime); - - // Render all active arcs in local space (they move with the orb) - state.render(); - } - - /** - * Get or create the lightning state for an entity. - */ - private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityOrb orb) { - if (orb.lightningState == null) { - orb.lightningState = new AttachedLightningRenderer.LightningState(); - } - return (AttachedLightningRenderer.LightningState) orb.lightningState; - } } diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java new file mode 100644 index 000000000..5cb9a7abc --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java @@ -0,0 +1,143 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityEnergyPanel; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import org.lwjgl.opengl.GL11; + +/** + * Renders the Energy Panel entity as a flat translucent rectangle. + * Used by both Energy Wall and Energy Shield abilities. + * Voxel-blocky style with inner/outer layers. + */ +@SideOnly(Side.CLIENT) +public class RenderEnergyPanel extends RenderEnergyBarrier { + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + if (shouldSkipInitialActiveRender(entity)) { + return; + } + EntityEnergyPanel panel = (EntityEnergyPanel) entity; + + float width = panel.getPanelData().panelWidth; + float height = panel.getPanelData().panelHeight; + float healthPercent = panel.getHealthPercent(); + + // Interpolate panel yaw for smooth rotation between ticks + float prevYaw = panel.getPrevPanelYaw(); + float currentYaw = panel.getPanelYaw(); + float yawDelta = currentYaw - prevYaw; + // Wrap angle delta to -180..180 for shortest rotation path + while (yawDelta > 180.0f) yawDelta -= 360.0f; + while (yawDelta < -180.0f) yawDelta += 360.0f; + float renderYaw = prevYaw + yawDelta * partialTicks; + + setupRenderState(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Lightning BEFORE rotation for uniform spread (like Orb pattern) + if (panel.hasLightningEffect()) { + renderAttachedLightning(panel, 0.9f, Math.max(width, height) * 0.5f); + } + + // Rotate panel to face the correct direction (interpolated) + GL11.glRotatef(-renderYaw, 0.0f, 1.0f, 0.0f); + + // Hit flash + float flashAlpha = computeFlashAlpha(panel); + + // Subtle pulsing + float pulseTime = entity.ticksExisted + partialTicks; + float pulse = (float) Math.sin(pulseTime * 0.08f) * 0.02f; + float scale = 1.0f + pulse; + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + float innerScale = 1.0f; + float panelThickness = 0.1f; + + // Render outer panel (translucent glow) + if (panel.isOuterColorEnabled()) { + float outerScale = 1.0f + panel.getOuterColorWidth() * 0.15f; + float outerAlpha = panel.getOuterColorAlpha() * healthPercent; + GL11.glDepthMask(false); + renderPanel(panel.getOuterColor(), outerAlpha + (panel.getOuterColorAlpha() > 0 ? flashAlpha : 0), + width * 0.5f * outerScale, height * 0.5f * outerScale, panelThickness * 1.5f); + GL11.glDepthMask(true); + } + + // Render inner panel (uses configurable innerAlpha for semi-transparency) + renderPanel(panel.getInnerColor(), panel.getInnerAlpha(), + width * 0.5f * innerScale, height * 0.5f * innerScale, panelThickness); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + + restoreRenderState(); + } + + /** + * Render a flat panel (thin box) centered at origin. + * Panel faces along the Z axis (width on X, height on Y). + * All 6 faces batched into a single draw call. + */ + private void renderPanel(int color, float alpha, float halfWidth, float halfHeight, float halfThickness) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + + // Front face (z+) + tess.setNormal(0, 0, 1); + tess.addVertex(-halfWidth, -halfHeight, halfThickness); + tess.addVertex(halfWidth, -halfHeight, halfThickness); + tess.addVertex(halfWidth, halfHeight, halfThickness); + tess.addVertex(-halfWidth, halfHeight, halfThickness); + + // Back face (z-) + tess.setNormal(0, 0, -1); + tess.addVertex(halfWidth, -halfHeight, -halfThickness); + tess.addVertex(-halfWidth, -halfHeight, -halfThickness); + tess.addVertex(-halfWidth, halfHeight, -halfThickness); + tess.addVertex(halfWidth, halfHeight, -halfThickness); + + // Top edge (y+) + tess.setNormal(0, 1, 0); + tess.addVertex(-halfWidth, halfHeight, halfThickness); + tess.addVertex(halfWidth, halfHeight, halfThickness); + tess.addVertex(halfWidth, halfHeight, -halfThickness); + tess.addVertex(-halfWidth, halfHeight, -halfThickness); + + // Bottom edge (y-) + tess.setNormal(0, -1, 0); + tess.addVertex(-halfWidth, -halfHeight, -halfThickness); + tess.addVertex(halfWidth, -halfHeight, -halfThickness); + tess.addVertex(halfWidth, -halfHeight, halfThickness); + tess.addVertex(-halfWidth, -halfHeight, halfThickness); + + // Right edge (x+) + tess.setNormal(1, 0, 0); + tess.addVertex(halfWidth, -halfHeight, halfThickness); + tess.addVertex(halfWidth, -halfHeight, -halfThickness); + tess.addVertex(halfWidth, halfHeight, -halfThickness); + tess.addVertex(halfWidth, halfHeight, halfThickness); + + // Left edge (x-) + tess.setNormal(-1, 0, 0); + tess.addVertex(-halfWidth, -halfHeight, -halfThickness); + tess.addVertex(-halfWidth, -halfHeight, halfThickness); + tess.addVertex(-halfWidth, halfHeight, halfThickness); + tess.addVertex(-halfWidth, halfHeight, -halfThickness); + + tess.draw(); + } + +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java new file mode 100644 index 000000000..589818905 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java @@ -0,0 +1,131 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityEnergySlicer; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import org.lwjgl.opengl.GL11; + +/** + * Renders the Energy Slicer entity as a thin wide blade. + * Oriented perpendicular to travel direction. + * Inner solid core with outer translucent glow. + */ +@SideOnly(Side.CLIENT) +public class RenderEnergySlicer extends RenderEnergy { + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + if (shouldSkipInitialActiveRender(entity)) { + return; + } + EntityEnergySlicer slicer = (EntityEnergySlicer) entity; + + float width = slicer.getSliceWidth(); + float thickness = slicer.getSliceThickness(); + + // During charging, width/thickness grow from 0.01 to target via updateCharging(). + // Use current dimensions directly - no separate sizeRatio needed. + if (width <= 0.01f) return; + + setupRenderState(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Lightning BEFORE rotation for uniform spread (like Orb pattern) + if (slicer.hasLightningEffect()) { + renderAttachedLightning(slicer, 0.7f, width * 0.5f); + } + + // Orient perpendicular to travel direction + float travelYaw = slicer.getTravelYaw(); + float travelPitch = slicer.getTravelPitch(); + GL11.glRotatef(travelYaw, 0.0f, 1.0f, 0.0f); + GL11.glRotatef(travelPitch, 1.0f, 0.0f, 0.0f); + + float innerScale = 0.7f; + + // Proximity alpha fade for owner + float proximityAlpha = getProximityAlphaFactor(slicer, x, y, z); + + // Render outer blade (translucent glow) + if (slicer.isOuterColorEnabled()) { + float outerScale = 1.0f + slicer.getOuterColorWidth() * 0.2f; + GL11.glDepthMask(false); + renderBlade(slicer.getOuterColor(), slicer.getOuterColorAlpha() * proximityAlpha, + width * 0.5f * outerScale, thickness * 2.0f, 0.05f); + GL11.glDepthMask(true); + } + + // Render inner blade (solid core) + renderBlade(slicer.getInnerColor(), slicer.getInnerAlpha() * proximityAlpha, + width * 0.5f * innerScale, thickness, 0.03f); + + GL11.glPopMatrix(); + + restoreRenderState(); + } + + /** + * Render a thin wide blade shape. + * The blade extends along X (width), thin on Y (thickness), and very thin on Z (depth). + * All 6 faces batched into a single draw call. + */ + private void renderBlade(int color, float alpha, float halfWidth, float halfHeight, float halfDepth) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + + // Front face (z+) + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, 0, 1); + tess.addVertex(-halfWidth, -halfHeight, halfDepth); + tess.addVertex(halfWidth, -halfHeight, halfDepth); + tess.addVertex(halfWidth, halfHeight, halfDepth); + tess.addVertex(-halfWidth, halfHeight, halfDepth); + + // Back face (z-) + tess.setNormal(0, 0, -1); + tess.addVertex(halfWidth, -halfHeight, -halfDepth); + tess.addVertex(-halfWidth, -halfHeight, -halfDepth); + tess.addVertex(-halfWidth, halfHeight, -halfDepth); + tess.addVertex(halfWidth, halfHeight, -halfDepth); + + // Top edge (y+) + tess.setColorRGBA_F(r, g, b, alpha * 0.8f); + tess.setNormal(0, 1, 0); + tess.addVertex(-halfWidth, halfHeight, halfDepth); + tess.addVertex(halfWidth, halfHeight, halfDepth); + tess.addVertex(halfWidth, halfHeight, -halfDepth); + tess.addVertex(-halfWidth, halfHeight, -halfDepth); + + // Bottom edge (y-) + tess.setNormal(0, -1, 0); + tess.addVertex(-halfWidth, -halfHeight, -halfDepth); + tess.addVertex(halfWidth, -halfHeight, -halfDepth); + tess.addVertex(halfWidth, -halfHeight, halfDepth); + tess.addVertex(-halfWidth, -halfHeight, halfDepth); + + // Right edge (x+) + tess.setColorRGBA_F(r, g, b, alpha * 0.6f); + tess.setNormal(1, 0, 0); + tess.addVertex(halfWidth, -halfHeight, halfDepth); + tess.addVertex(halfWidth, -halfHeight, -halfDepth); + tess.addVertex(halfWidth, halfHeight, -halfDepth); + tess.addVertex(halfWidth, halfHeight, halfDepth); + + // Left edge (x-) + tess.setNormal(-1, 0, 0); + tess.addVertex(-halfWidth, -halfHeight, -halfDepth); + tess.addVertex(-halfWidth, -halfHeight, halfDepth); + tess.addVertex(-halfWidth, halfHeight, halfDepth); + tess.addVertex(-halfWidth, halfHeight, -halfDepth); + + tess.draw(); + } + +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java similarity index 59% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java index 10705d762..01ec9b429 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergySweeper; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; @@ -15,16 +15,17 @@ import org.lwjgl.opengl.GL11; * Uses similar rendering style to the Beam trail for visual consistency. */ @SideOnly(Side.CLIENT) -public class RenderAbilitySweeper extends Render { +public class RenderSweeper extends Render { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { - EntityAbilitySweeper sweeper = (EntityAbilitySweeper) entity; + EntityEnergySweeper sweeper = (EntityEnergySweeper) entity; setupRenderState(); float beamLength = sweeper.getBeamLength(); float beamWidth = sweeper.getBeamWidth(); + float beamHeight = sweeper.getBeamHeight(); int innerColor = sweeper.getInnerColor(); int outerColor = sweeper.getOuterColor(); boolean outerColorEnabled = sweeper.isOuterColorEnabled(); @@ -38,7 +39,7 @@ public class RenderAbilitySweeper extends Render { GL11.glRotatef(-angle, 0, 1, 0); // Negative for correct direction // Render the beam extending in the +Z direction (like beam trail segments) - renderBeam(beamLength, beamWidth, innerColor, outerColor, outerColorEnabled, outerColorWidth); + renderBeam(beamLength, beamWidth, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth); GL11.glPopMatrix(); @@ -70,8 +71,10 @@ public class RenderAbilitySweeper extends Render { /** * Render beam using the same style as the Beam entity trail. * Three layers: outer glow, middle, inner core. + * outerColorWidth is an additive offset from inner width (consistent with other renderers). + * Width and height control the rectangular cross-section independently. */ - private void renderBeam(float length, float width, int innerColor, int outerColor, + private void renderBeam(float length, float width, float height, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth) { // Extract colors float outerR = ((outerColor >> 16) & 0xFF) / 255.0f; @@ -82,30 +85,40 @@ public class RenderAbilitySweeper extends Render { float innerG = ((innerColor >> 8) & 0xFF) / 255.0f; float innerB = (innerColor & 0xFF) / 255.0f; + // Inner scale defines the core size (consistent with other renderers) + float innerScale = 0.6f; + float innerWidth = width * innerScale; + float innerHeight = height * innerScale; + // Render from origin (0,0,0) to (0,0,length) in local coords // After rotation this extends in the correct world direction - // Outer glow (wider, translucent) - like beam trail - only if enabled + // Outer glow (wider, translucent) - only if enabled + // outerColorWidth is additive offset from inner size if (outerColorEnabled) { + float outerWidth = innerWidth + outerColorWidth * width; + float outerHeight = innerHeight + outerColorWidth * height; GL11.glDepthMask(false); - renderBeamSegment(0, 0, 0, 0, 0, length, width * outerColorWidth, outerR, outerG, outerB, 0.3f); + renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f); GL11.glDepthMask(true); - // Middle layer - renderBeamSegment(0, 0, 0, 0, 0, length, width * 1.3f, outerR, outerG, outerB, 0.6f); + // Middle layer (halfway between inner and outer) + float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f; + float midHeight = innerHeight + (outerHeight - innerHeight) * 0.5f; + renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, midHeight, outerR, outerG, outerB, 0.6f); } - // Inner core (solid) - like beam trail inner - renderBeamSegment(0, 0, 0, 0, 0, length, width * 0.6f, innerR, innerG, innerB, 1.0f); + // Inner core (solid) + renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f); } /** - * Render a beam segment as a 3D rectangular prism. - * Uses the same approach as RenderAbilityBeam.renderBeamRectangle. + * Render a beam segment as a 3D rectangular prism with independent width and height. + * Uses the same approach as RenderEnergyBeam.renderBeamRectangle. */ private void renderBeamSegment(double x1, double y1, double z1, - double x2, double y2, double z2, - float width, float r, float g, float b, float a) { + double x2, double y2, double z2, + float width, float height, float r, float g, float b, float a) { // Calculate direction double dx = x2 - x1; double dy = y2 - y1; @@ -121,7 +134,9 @@ public class RenderAbilitySweeper extends Render { // Calculate perpendicular vectors double upX = 0, upY = 1, upZ = 0; if (Math.abs(dy) > 0.9) { - upX = 1; upY = 0; upZ = 0; + upX = 1; + upY = 0; + upZ = 0; } // Cross product for horizontal perpendicular @@ -141,39 +156,40 @@ public class RenderAbilitySweeper extends Render { double vertZ = dx * horzY - dy * horzX; float halfWidth = width * 0.5f; + float halfHeight = height * 0.5f; - // Calculate 8 corners of the box - double s1x = x1 - horzX * halfWidth - vertX * halfWidth; - double s1y = y1 - horzY * halfWidth - vertY * halfWidth; - double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth; + // Calculate 8 corners of the box (horz scaled by halfWidth, vert scaled by halfHeight) + double s1x = x1 - horzX * halfWidth - vertX * halfHeight; + double s1y = y1 - horzY * halfWidth - vertY * halfHeight; + double s1z = z1 - horzZ * halfWidth - vertZ * halfHeight; - double s2x = x1 + horzX * halfWidth - vertX * halfWidth; - double s2y = y1 + horzY * halfWidth - vertY * halfWidth; - double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth; + double s2x = x1 + horzX * halfWidth - vertX * halfHeight; + double s2y = y1 + horzY * halfWidth - vertY * halfHeight; + double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight; - double s3x = x1 + horzX * halfWidth + vertX * halfWidth; - double s3y = y1 + horzY * halfWidth + vertY * halfWidth; - double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth; + double s3x = x1 + horzX * halfWidth + vertX * halfHeight; + double s3y = y1 + horzY * halfWidth + vertY * halfHeight; + double s3z = z1 + horzZ * halfWidth + vertZ * halfHeight; - double s4x = x1 - horzX * halfWidth + vertX * halfWidth; - double s4y = y1 - horzY * halfWidth + vertY * halfWidth; - double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth; + double s4x = x1 - horzX * halfWidth + vertX * halfHeight; + double s4y = y1 - horzY * halfWidth + vertY * halfHeight; + double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight; - double e1x = x2 - horzX * halfWidth - vertX * halfWidth; - double e1y = y2 - horzY * halfWidth - vertY * halfWidth; - double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth; + double e1x = x2 - horzX * halfWidth - vertX * halfHeight; + double e1y = y2 - horzY * halfWidth - vertY * halfHeight; + double e1z = z2 - horzZ * halfWidth - vertZ * halfHeight; - double e2x = x2 + horzX * halfWidth - vertX * halfWidth; - double e2y = y2 + horzY * halfWidth - vertY * halfWidth; - double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth; + double e2x = x2 + horzX * halfWidth - vertX * halfHeight; + double e2y = y2 + horzY * halfWidth - vertY * halfHeight; + double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight; - double e3x = x2 + horzX * halfWidth + vertX * halfWidth; - double e3y = y2 + horzY * halfWidth + vertY * halfWidth; - double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth; + double e3x = x2 + horzX * halfWidth + vertX * halfHeight; + double e3y = y2 + horzY * halfWidth + vertY * halfHeight; + double e3z = z2 + horzZ * halfWidth + vertZ * halfHeight; - double e4x = x2 - horzX * halfWidth + vertX * halfWidth; - double e4y = y2 - horzY * halfWidth + vertY * halfWidth; - double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth; + double e4x = x2 - horzX * halfWidth + vertX * halfHeight; + double e4y = y2 - horzY * halfWidth + vertY * halfHeight; + double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight; Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java new file mode 100644 index 000000000..1d3d92d85 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java @@ -0,0 +1,797 @@ +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 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.CustomFX; +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 RenderZone 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.max(0, 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.max(0, 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.max(0, 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..dc653e73f 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java @@ -105,11 +105,14 @@ public class TelegraphRenderer { renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha); break; case CONE: - renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha); + renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha); break; case POINT: renderPoint(red, green, blue, alpha); break; + case SQUARE: + renderSquare(telegraph.getRadius(), red, green, blue, alpha); + break; default: break; } @@ -204,42 +207,98 @@ public class TelegraphRenderer { tessellator.draw(); } - private void renderCone(float length, float angle, float r, float g, float b, float a) { + private void renderCone(float length, float angle, float innerRadius, float r, float g, float b, float a) { float halfAngleRad = (float) Math.toRadians(angle / 2); Tessellator tessellator = Tessellator.instance; - tessellator.startDrawing(GL11.GL_TRIANGLE_FAN); - tessellator.setColorRGBA_F(r, g, b, a); - // Origin point - tessellator.addVertex(0, 0, 0); + if (innerRadius <= 0) { + // Standard cone: triangle fan from origin + tessellator.startDrawing(GL11.GL_TRIANGLE_FAN); + tessellator.setColorRGBA_F(r, g, b, a); - // Arc points - for (int i = 0; i <= CONE_SEGMENTS; i++) { - float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; - double x = Math.sin(segmentAngle) * length; - double z = Math.cos(segmentAngle) * length; - tessellator.addVertex(x, 0, z); + tessellator.addVertex(0, 0, 0); + + for (int i = 0; i <= CONE_SEGMENTS; i++) { + float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; + double x = Math.sin(segmentAngle) * length; + double z = Math.cos(segmentAngle) * length; + tessellator.addVertex(x, 0, z); + } + + tessellator.draw(); + + // Border + tessellator.startDrawing(GL11.GL_LINE_STRIP); + tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2)); + + tessellator.addVertex(0, 0.01, 0); + + for (int i = 0; i <= CONE_SEGMENTS; i++) { + float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; + double x = Math.sin(segmentAngle) * length; + double z = Math.cos(segmentAngle) * length; + tessellator.addVertex(x, 0.01, z); + } + + tessellator.addVertex(0, 0.01, 0); + + tessellator.draw(); + } else { + // Truncated cone: strip between inner and outer arcs + tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP); + tessellator.setColorRGBA_F(r, g, b, a); + + for (int i = 0; i <= CONE_SEGMENTS; i++) { + float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; + double sinA = Math.sin(segmentAngle); + double cosA = Math.cos(segmentAngle); + + tessellator.addVertex(sinA * length, 0, cosA * length); + tessellator.addVertex(sinA * innerRadius, 0, cosA * innerRadius); + } + + tessellator.draw(); + + // Border: outer arc + float borderAlpha = Math.min(1.0f, a * 2); + tessellator.startDrawing(GL11.GL_LINE_STRIP); + tessellator.setColorRGBA_F(r, g, b, borderAlpha); + + for (int i = 0; i <= CONE_SEGMENTS; i++) { + float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; + tessellator.addVertex(Math.sin(segmentAngle) * length, 0.01, Math.cos(segmentAngle) * length); + } + + tessellator.draw(); + + // Border: inner arc + tessellator.startDrawing(GL11.GL_LINE_STRIP); + tessellator.setColorRGBA_F(r, g, b, borderAlpha); + + for (int i = 0; i <= CONE_SEGMENTS; i++) { + float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; + tessellator.addVertex(Math.sin(segmentAngle) * innerRadius, 0.01, Math.cos(segmentAngle) * innerRadius); + } + + tessellator.draw(); + + // Border: side edges connecting inner and outer arcs + tessellator.startDrawing(GL11.GL_LINES); + tessellator.setColorRGBA_F(r, g, b, borderAlpha); + + double sinStart = Math.sin(-halfAngleRad); + double cosStart = Math.cos(-halfAngleRad); + tessellator.addVertex(sinStart * innerRadius, 0.01, cosStart * innerRadius); + tessellator.addVertex(sinStart * length, 0.01, cosStart * length); + + double sinEnd = Math.sin(halfAngleRad); + double cosEnd = Math.cos(halfAngleRad); + tessellator.addVertex(sinEnd * innerRadius, 0.01, cosEnd * innerRadius); + tessellator.addVertex(sinEnd * length, 0.01, cosEnd * length); + + tessellator.draw(); } - - tessellator.draw(); - - // Draw border - tessellator.startDrawing(GL11.GL_LINE_STRIP); - tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2)); - - tessellator.addVertex(0, 0.01, 0); - - for (int i = 0; i <= CONE_SEGMENTS; i++) { - float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS; - double x = Math.sin(segmentAngle) * length; - double z = Math.cos(segmentAngle) * length; - tessellator.addVertex(x, 0.01, z); - } - - tessellator.addVertex(0, 0.01, 0); - - tessellator.draw(); } private void renderPoint(float r, float g, float b, float a) { @@ -258,6 +317,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 ==================== /** @@ -272,8 +355,8 @@ public class TelegraphRenderer { * @param partialTicks Partial ticks for interpolation */ public void renderTelegraphInGUI(TelegraphInstance instance, - double centerX, double centerY, double centerZ, - float scale, float partialTicks) { + double centerX, double centerY, double centerZ, + float scale, float partialTicks) { if (instance == null) return; Telegraph telegraph = instance.getTelegraph(); @@ -317,11 +400,14 @@ public class TelegraphRenderer { renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha); break; case CONE: - renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha); + renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha); break; 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 d68c4037b..4debb90d6 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -3,7 +3,6 @@ package kamkeel.npcs.client.renderer.lightning; import net.minecraft.client.renderer.Tessellator; import org.lwjgl.opengl.GL11; -import java.awt.Color; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -37,6 +36,7 @@ public class AttachedLightningRenderer { public float getAlphaMultiplier() { // Fade out over lifetime + if (maxAge <= 0) return 0.0f; return 1.0f - ((float) age / (float) maxAge); } @@ -85,6 +85,28 @@ 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. @@ -143,8 +165,8 @@ public class AttachedLightningRenderer { * Generate a jagged lightning path between two points. */ private static List generateLightningPath(double x1, double y1, double z1, - double x2, double y2, double z2, - int segments, float displacement) { + double x2, double y2, double z2, + int segments, float displacement) { List points = new ArrayList<>(); points.add(new double[]{x1, y1, z1}); @@ -186,10 +208,9 @@ public class AttachedLightningRenderer { private static void renderBoltPath(Tessellator tess, List points, int color, float width, float alpha) { if (alpha <= 0.01f) return; - Color c = new Color(color); - int r = c.getRed(); - int g = c.getGreen(); - int b = c.getBlue(); + int r = (color >> 16) & 0xFF; + int g = (color >> 8) & 0xFF; + int b = color & 0xFF; int a = Math.min(255, Math.max(0, (int) (alpha * 255))); for (int i = 0; i < points.size() - 1; i++) { @@ -231,6 +252,17 @@ 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) ==================== /** diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java index 6cf6e7d3a..beea63fd3 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java @@ -56,7 +56,7 @@ public class LightningBolt { this.numSegments0 = 1; this.length = end.copy().subtract(start).mag(); - this.particleMaxAge = FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2; + this.particleMaxAge = Math.max(1, FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2); this.particleAge = -(int) (length * speed); segments.add(new Segment(start, end)); @@ -243,7 +243,7 @@ public class LightningBolt { public Segment(Vec3d start, Vec3d end) { this(new BoltPoint(start, new Vec3d(0, 0, 0)), - new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0); + new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0); } public void calcDiff() { diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java index 1951666e4..d3f9aeedd 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java @@ -5,7 +5,6 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.client.renderer.lightning.LightningBolt.Segment; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ActiveRenderInfo; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.entity.Entity; @@ -19,7 +18,7 @@ import java.awt.Color; /** * Handles rendering of lightning bolts in the world. * Adapted from Botania's LightningHandler by Vazkii/ChickenBones. - * + *

* Register this handler with: MinecraftForge.EVENT_BUS.register(new LightningHandler()); */ @SideOnly(Side.CLIENT) @@ -168,13 +167,13 @@ public class LightningHandler { /** * Spawn a lightning bolt between two points. * - * @param world The world - * @param start Start position - * @param end End position + * @param world The world + * @param start Start position + * @param end End position * @param ticksPerMeter Speed of bolt expansion - * @param seed Random seed for consistent appearance - * @param colorOuter Outer glow color (ARGB) - * @param colorInner Inner core color (ARGB) + * @param seed Random seed for consistent appearance + * @param colorOuter Outer glow color (ARGB) + * @param colorInner Inner core color (ARGB) */ public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) { LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, seed, colorOuter, colorInner); diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java index 004274fc3..982a975b3 100644 --- a/src/main/java/kamkeel/npcs/command/AbilityCommand.java +++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java @@ -1,12 +1,14 @@ package kamkeel.npcs.command; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityController; -import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.enums.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.PlayerAbilityData; import noppes.npcs.controllers.data.PlayerData; import java.util.ArrayList; @@ -33,20 +35,19 @@ public class AbilityCommand extends CommandKamkeelBase { desc = "List all custom abilities" ) public void list(ICommandSender sender, String[] args) { - Set uuids = AbilityController.Instance.getCustomAbilityIds(); - if (uuids.isEmpty()) { + Set names = AbilityController.Instance.getCustomAbilityNames(); + if (names.isEmpty()) { sendResult(sender, "No custom abilities found."); return; } - sendResult(sender, "Custom Abilities (" + uuids.size() + "):"); - for (String uuid : uuids) { - Ability ability = AbilityController.Instance.getCustomAbility(uuid); + sendResult(sender, "Custom Abilities (" + names.size() + "):"); + for (String name : names) { + Ability ability = AbilityController.Instance.getCustomAbility(name); if (ability != null) { - String name = ability.getName() != null ? ability.getName() : uuid; - sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ") [" + uuid + "]"); + sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")"); } else { - sendResult(sender, " - \u00A7b" + uuid); + sendResult(sender, " - \u00A7b" + name); } } } @@ -78,27 +79,27 @@ public class AbilityCommand extends CommandKamkeelBase { ) public void reload(ICommandSender sender, String[] args) { AbilityController.Instance.load(); - sendResult(sender, "Abilities reloaded from disk."); + sendResult(sender, "Abilities and chained abilities reloaded from disk."); } @SubCommand( - desc = "Delete a custom ability by UUID", - usage = "" + desc = "Delete a custom ability by name", + usage = "" ) public void delete(ICommandSender sender, String[] args) { if (args.length < 1) { - sendError(sender, "Usage: /kam ability delete "); + sendError(sender, "Usage: /kam ability delete "); return; } - String uuid = args[0]; - if (!AbilityController.Instance.hasCustomAbility(uuid)) { - sendError(sender, "No custom ability with UUID: " + uuid); + String name = joinArgs(args, 0); + if (!AbilityController.Instance.hasCustomAbilityName(name)) { + sendError(sender, "No custom ability with name: " + name); return; } - AbilityController.Instance.deleteCustomAbility(uuid); - sendResult(sender, "Deleted ability: \u00A7b" + uuid); + AbilityController.Instance.deleteCustomAbility(name); + sendResult(sender, "Deleted ability: \u00A7b" + name); } @SubCommand( @@ -111,14 +112,15 @@ public class AbilityCommand extends CommandKamkeelBase { return; } - String key = args[0]; + String key = joinArgs(args, 0); Ability ability = AbilityController.Instance.resolveAbility(key); if (ability == null) { sendError(sender, "No ability found for: " + key); return; } - sendResult(sender, "Ability: \u00A7b" + ability.getName()); + sendResult(sender, "Ability: \u00A7b" + ability.getDisplayName()); + sendResult(sender, " Name: \u00A77" + ability.getName()); sendResult(sender, " Type: \u00A7d" + ability.getTypeId()); sendResult(sender, " Cooldown: \u00A7e" + ability.getCooldownTicks() + " ticks"); sendResult(sender, " Wind Up: \u00A7e" + ability.getWindUpTicks() + " ticks"); @@ -163,26 +165,24 @@ public class AbilityCommand extends CommandKamkeelBase { } @SubCommand( - desc = "Unlock an ability for a player", + desc = "Give an ability to a player", usage = " " ) - public void unlock(ICommandSender sender, String[] args) { + public void give(ICommandSender sender, String[] args) { if (args.length < 2) { - sendError(sender, "Usage: /kam ability unlock "); + sendError(sender, "Usage: /kam ability give "); 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); @@ -192,17 +192,15 @@ public class AbilityCommand extends CommandKamkeelBase { // 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 + canonicalKey = abilityKey; } - String displayName = ability.getName() != null ? ability.getName() : canonicalKey; + String displayName = ability.getDisplayName(); - // 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); @@ -210,39 +208,36 @@ public class AbilityCommand extends CommandKamkeelBase { } data.abilityData.unlockAbility(canonicalKey); - sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName); + sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName); } @SubCommand( - desc = "Lock (revoke) an ability from a player", + desc = "Remove an ability from a player", usage = " " ) - public void lock(ICommandSender sender, String[] args) { + public void remove(ICommandSender sender, String[] args) { if (args.length < 2) { - sendError(sender, "Usage: /kam ability lock "); + sendError(sender, "Usage: /kam ability remove "); 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; + if (ability == null) { + sendError(sender, "Ability not found: " + abilityKey); + return; } + String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey; + String displayName = ability.getDisplayName(); - // Get player data and lock PlayerData data = PlayerDataController.Instance.getPlayerData(player); if (!data.abilityData.hasUnlockedAbility(canonicalKey)) { sendError(sender, "Player doesn't have ability: " + displayName); @@ -250,7 +245,98 @@ public class AbilityCommand extends CommandKamkeelBase { } data.abilityData.lockAbility(canonicalKey); - sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName); + sendResult(sender, "Removed ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName); + } + + @SubCommand( + desc = "Give a chained ability to a player", + usage = " " + ) + public void giveChain(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability giveChain "); + return; + } + + String playerName = args[0]; + String chainKey = joinArgs(args, 1); + + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey); + if (chain == null) { + sendError(sender, "Chained ability not found: " + chainKey); + return; + } + + if (!chain.getAllowedBy().allowsPlayer()) { + sendError(sender, "Chained ability '\u00A7b" + chain.getDisplayName() + "\u00A7c' is NPC-only and cannot be given to players."); + return; + } + + String chainId = chain.getId(); + if (chainId == null || chainId.isEmpty()) { + sendError(sender, "Chained ability has no ID: " + chain.getDisplayName()); + return; + } + + // Store by UUID: chain: + String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId; + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data.abilityData.hasUnlockedAbility(storageKey)) { + sendError(sender, "Player already has chained ability: " + chain.getDisplayName()); + return; + } + + data.abilityData.unlockAbility(storageKey); + sendResult(sender, "Gave chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' to player \u00A7a" + playerName); + } + + @SubCommand( + desc = "Remove a chained ability from a player", + usage = " " + ) + public void removeChain(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability removeChain "); + return; + } + + String playerName = args[0]; + String chainKey = joinArgs(args, 1); + + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey); + if (chain == null) { + sendError(sender, "Chained ability not found: " + chainKey); + return; + } + + String chainId = chain.getId(); + if (chainId == null || chainId.isEmpty()) { + sendError(sender, "Chained ability has no ID: " + chain.getDisplayName()); + return; + } + + // Storage uses UUID: chain: + String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId; + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (!data.abilityData.hasUnlockedAbility(storageKey)) { + sendError(sender, "Player doesn't have chained ability: " + chain.getDisplayName()); + return; + } + + data.abilityData.lockAbility(storageKey); + sendResult(sender, "Removed chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' from player \u00A7a" + playerName); } @SubCommand( @@ -284,14 +370,23 @@ public class AbilityCommand extends CommandKamkeelBase { 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 + "]"); + + if (key.startsWith(PlayerAbilityData.CHAIN_PREFIX)) { + // Chained ability + String chainName = key.substring(PlayerAbilityData.CHAIN_PREFIX.length()); + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainName); + String display = chain != null ? chain.getDisplayName() : chainName; + sendResult(sender, prefix + "\u00A7d[Chain] \u00A7b" + display); } else { - sendResult(sender, prefix + "\u00A7b" + displayName); + // Regular ability + Ability ability = AbilityController.Instance.resolveAbility(key); + String displayName = ability != null ? ability.getDisplayName() : key; + if (!displayName.equals(key)) { + sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]"); + } else { + sendResult(sender, prefix + "\u00A7b" + displayName); + } } } } @@ -306,13 +401,34 @@ public class AbilityCommand extends CommandKamkeelBase { } /** - * Get list of player-usable ability keys (for tab completion). - * Uses registry keys for built-in abilities (no spaces) and UUIDs for custom. - * Used by CommandKamkeel for usage token. + * Get list of player-usable ability names (for tab completion). + * Resolves UUIDs to names so tab completion shows human-readable names. + * Used by CommandKamkeel for {@code } usage token. */ public static List getPlayerAbilityNames() { - List keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys()); - Collections.sort(keys); - return keys; + Set keys = AbilityController.Instance.getPlayerAbilityKeys(); + List names = new ArrayList<>(); + for (String key : keys) { + Ability a = AbilityController.Instance.resolveAbility(key); + names.add(a != null ? a.getName() : key); + } + Collections.sort(names); + return names; + } + + /** + * Get list of player-usable chained ability names (for tab completion). + * Used by CommandKamkeel for {@code } usage token. + */ + public static List getPlayerChainNames() { + List names = new ArrayList<>(); + for (String chainName : AbilityController.Instance.getChainedAbilityNamesSet()) { + ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName); + if (chain != null && chain.getAllowedBy().allowsPlayer()) { + names.add(chainName); + } + } + Collections.sort(names); + return names; } } diff --git a/src/main/java/kamkeel/npcs/command/AuctionCommand.java b/src/main/java/kamkeel/npcs/command/AuctionCommand.java index 87d7e4385..a56dce671 100644 --- a/src/main/java/kamkeel/npcs/command/AuctionCommand.java +++ b/src/main/java/kamkeel/npcs/command/AuctionCommand.java @@ -20,6 +20,7 @@ import static kamkeel.npcs.util.ColorUtil.sendMessage; import static kamkeel.npcs.util.ColorUtil.sendResult; public class AuctionCommand extends CommandKamkeelBase { + private static final int COMMAND_PAGE_SIZE = 10; public AuctionCommand() { super(); @@ -62,9 +63,10 @@ public class AuctionCommand extends CommandKamkeelBase { } } - List listings = controller.getActiveListings(null, page - 1, 10); + page = Math.max(1, page); + List listings = controller.getActiveListings(null, page - 1, COMMAND_PAGE_SIZE); int total = controller.getTotalActiveListings(null); - int totalPages = Math.max(1, (int) Math.ceil((double) total / 10)); + int totalPages = Math.max(1, (int) Math.ceil((double) total / COMMAND_PAGE_SIZE)); if (listings.isEmpty()) { sendMessage(sender, "\u00A77No active auctions found"); @@ -98,6 +100,10 @@ public class AuctionCommand extends CommandKamkeelBase { return; } + if (args.length < 1) { + throw new CommandException("Usage: /auction view "); + } + String playername = args[0]; List dataList = PlayerDataController.Instance.getPlayersData(sender, playername); diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java index 91356c825..f87068968 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames; +import static kamkeel.npcs.command.AbilityCommand.getPlayerChainNames; import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames; public class CommandKamkeel extends CommandBase { @@ -51,6 +52,7 @@ public class CommandKamkeel extends CommandBase { registerCommand(new AuctionCommand()); if (ConfigMain.AttributesEnabled) registerCommand(new AttributeCommand()); + registerCommand(new DebugCommand()); } public void registerCommand(CommandKamkeelBase command) { @@ -134,10 +136,13 @@ public class CommandKamkeel extends CommandBase { List keys = new ArrayList<>(RequirementCheckerRegistry.getAllKeys()); return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); } else if (usage.equals("")) { - List keys = getSortedEffectNames(); + List keys = stripColorCodes(getSortedEffectNames()); return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); } else if (usage.equals("")) { - List keys = getPlayerAbilityNames(); + List keys = stripColorCodes(getPlayerAbilityNames()); + return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); + } else if (usage.equals("")) { + List keys = stripColorCodes(getPlayerChainNames()); return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); } } @@ -145,6 +150,14 @@ public class CommandKamkeel extends CommandBase { return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length)); } + private static List stripColorCodes(List list) { + List result = new ArrayList<>(list.size()); + for (String s : list) { + result.add(s.replaceAll("\u00A7[0-9a-fk-or]", "")); + } + return result; + } + public CommandKamkeelBase getCommand(String[] args) { if (args.length == 0) return null; diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java b/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java index df4d34998..c6ffe7ec1 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java @@ -11,7 +11,13 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; public abstract class CommandKamkeelBase extends CommandBase { public Map subcommands = new HashMap(); diff --git a/src/main/java/kamkeel/npcs/command/DebugCommand.java b/src/main/java/kamkeel/npcs/command/DebugCommand.java new file mode 100644 index 000000000..1cb497a93 --- /dev/null +++ b/src/main/java/kamkeel/npcs/command/DebugCommand.java @@ -0,0 +1,41 @@ +package kamkeel.npcs.command; + +import kamkeel.npcs.util.CNPCDebug; +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; + +import static kamkeel.npcs.util.ColorUtil.sendResult; + +public class DebugCommand extends CommandKamkeelBase { + + @Override + public String getCommandName() { + return "debug"; + } + + @Override + public String getDescription() { + return "Toggle debug logging types"; + } + + @Override + public String getUsage() { + return ""; + } + + @Override + public boolean runSubCommands() { + return false; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) throws CommandException { + if (args.length == 0) { + throw new CommandException("Usage: /kam debug (e.g. energy)"); + } + + String type = args[0].toLowerCase(); + boolean newState = CNPCDebug.toggleServer(type); + sendResult(sender, "Server debug '" + type + "' " + (newState ? "\u00A7aENABLED" : "\u00A7cDISABLED")); + } +} diff --git a/src/main/java/kamkeel/npcs/command/DialogCommand.java b/src/main/java/kamkeel/npcs/command/DialogCommand.java index 2392859a4..d9df94c13 100644 --- a/src/main/java/kamkeel/npcs/command/DialogCommand.java +++ b/src/main/java/kamkeel/npcs/command/DialogCommand.java @@ -1,6 +1,7 @@ package kamkeel.npcs.command; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -93,7 +94,7 @@ public class DialogCommand extends CommandKamkeelBase { ) public void reload(ICommandSender sender, String args[]) { new DialogController().load(); - SyncController.syncAllDialogs(); + SyncController.syncAll(SyncType.DIALOG_CATEGORY); sendResult(sender, "Dialogs Reloaded"); } diff --git a/src/main/java/kamkeel/npcs/command/EffectCommand.java b/src/main/java/kamkeel/npcs/command/EffectCommand.java index 8a6a2e669..3d7cdbec8 100644 --- a/src/main/java/kamkeel/npcs/command/EffectCommand.java +++ b/src/main/java/kamkeel/npcs/command/EffectCommand.java @@ -308,6 +308,7 @@ public class EffectCommand extends CommandKamkeelBase { // Helper method to find effects by name. private List findEffectsByName(String name) { + String strippedName = stripColorCodes(name); List matches = new ArrayList<>(); CustomEffectController controller = CustomEffectController.getInstance(); for (Map.Entry> entry : controller.indexMapper.entrySet()) { @@ -317,11 +318,12 @@ public class EffectCommand extends CommandKamkeelBase { for (Map.Entry effectEntry : effects.entrySet()) { int id = effectEntry.getKey(); CustomEffect effect = effectEntry.getValue(); - if (effect.getName().equalsIgnoreCase(name)) { + String effectName = stripColorCodes(effect.getName()); + if (effectName.equalsIgnoreCase(strippedName)) { List exact = new ArrayList<>(); exact.add(new EffectEntry(idx, id, effect)); return exact; - } else if (effect.getName().toLowerCase().contains(name.toLowerCase())) { + } else if (effectName.toLowerCase().contains(strippedName.toLowerCase())) { matches.add(new EffectEntry(idx, id, effect)); } } @@ -329,6 +331,10 @@ public class EffectCommand extends CommandKamkeelBase { return matches; } + private static String stripColorCodes(String s) { + return s.replaceAll("\u00A7[0-9a-fk-or]", ""); + } + public static List getSortedEffectNames() { List entries = new ArrayList<>(); CustomEffectController controller = CustomEffectController.getInstance(); diff --git a/src/main/java/kamkeel/npcs/command/NpcCommand.java b/src/main/java/kamkeel/npcs/command/NpcCommand.java index 556976ed0..74a125e19 100644 --- a/src/main/java/kamkeel/npcs/command/NpcCommand.java +++ b/src/main/java/kamkeel/npcs/command/NpcCommand.java @@ -200,7 +200,7 @@ public class NpcCommand extends CommandKamkeelBase { EntityCustomNpc npc = new EntityCustomNpc(pw); if (args.length > 0) npc.display.name = args[0]; - npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch); + npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0); npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)}; pw.spawnEntityInWorld(npc); npc.setHealth(npc.getMaxHealth()); diff --git a/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java b/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java index f33d3626b..27eb0efb8 100644 --- a/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java +++ b/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java @@ -99,7 +99,9 @@ public class QuestCategoryCommand extends CommandKamkeelBase { playerdata.questData.finishedQuests.put(quest.id, completeTime); } - if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) + if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime); ; diff --git a/src/main/java/kamkeel/npcs/command/QuestCommand.java b/src/main/java/kamkeel/npcs/command/QuestCommand.java index 0a6cb5edf..7cfd6ebe4 100644 --- a/src/main/java/kamkeel/npcs/command/QuestCommand.java +++ b/src/main/java/kamkeel/npcs/command/QuestCommand.java @@ -2,6 +2,7 @@ package kamkeel.npcs.command; import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.network.packets.data.AchievementPacket; import kamkeel.npcs.network.packets.data.ChatAlertPacket; import net.minecraft.command.CommandException; @@ -115,7 +116,9 @@ public class QuestCommand extends CommandKamkeelBase { playerdata.questData.finishedQuests.put(quest.id, completeTime); } - if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) + if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime); playerdata.save(); @@ -391,7 +394,7 @@ public class QuestCommand extends CommandKamkeelBase { ) public void reload(ICommandSender sender, String args[]) { new QuestController().load(); - SyncController.syncAllQuests(); + SyncController.syncAll(SyncType.QUEST_CATEGORY); sendResult(sender, "Quests Reloaded"); } } diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java new file mode 100644 index 000000000..66c057929 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -0,0 +1,1532 @@ +package kamkeel.npcs.controllers; + +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionItem; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.extender.IAbilityExtender; +import kamkeel.npcs.controllers.data.ability.gui.IAbilityFieldProvider; +import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider; +import kamkeel.npcs.controllers.data.ability.CustomAbility; +import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; +import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDash; +import kamkeel.npcs.controllers.data.ability.type.AbilityCounter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDodge; +import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; +import kamkeel.npcs.controllers.data.ability.type.AbilityHazard; +import kamkeel.npcs.controllers.data.ability.type.AbilityEffect; +import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit; +import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave; +import kamkeel.npcs.controllers.data.ability.type.AbilitySlam; +import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport; +import kamkeel.npcs.controllers.data.ability.type.AbilityTrap; +import kamkeel.npcs.controllers.data.ability.type.AbilityVortex; +import kamkeel.npcs.network.enums.SyncType; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityBeam; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityDisc; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityDome; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityLaser; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityOrb; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityShield; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilitySweeper; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityWall; +import net.minecraftforge.common.util.Constants; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import net.minecraft.entity.EntityLivingBase; +import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcs; +import noppes.npcs.LogWriter; +import noppes.npcs.api.ability.IChainedAbility; +import noppes.npcs.api.handler.IAbilityHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.CategoryManager; +import noppes.npcs.controllers.TagController; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.util.NBTJsonUtil; +import kamkeel.npcs.util.FileNameHelper; + +import java.io.File; +import java.util.*; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public class AbilityController implements IAbilityHandler { + + public static AbilityController Instance = new AbilityController(); + + // ── Core Registries ────────────────────────────────────────────────────── + private final Map> abilityTypes = new LinkedHashMap<>(); + private final Map builtAbilities = new LinkedHashMap<>(); + private final Map customAbilities = new LinkedHashMap<>(); // name → Ability + private final Map customAbilitiesById = new LinkedHashMap<>(); // UUID → Ability + + // ── Script Handlers ──────────────────────────────────────────────────── + public final HashMap abilityScriptHandlers = new HashMap<>(); + public final HashMap chainedAbilityScriptHandlers = new HashMap<>(); + + // ── Extension Points ───────────────────────────────────────────────────── + private final Map> externalVariants = new LinkedHashMap<>(); + private final List fieldProviders = new ArrayList<>(); + private final List chainedFieldProviders = new ArrayList<>(); + private final List extenders = new ArrayList<>(); + private final Map> conditionTypes = new HashMap<>(); + private final List> flightCheckers = new ArrayList<>(); + private final List> activationCheckers = new ArrayList<>(); + + // ── Chained Abilities ────────────────────────────────────────────────── + private final Map chainedAbilities = new LinkedHashMap<>(); // name → ChainedAbility + private final Map chainedAbilitiesById = new LinkedHashMap<>(); // UUID → ChainedAbility + private int chainedAbilityRevision = 0; + + // ── Category Managers ───────────────────────────────────────────────── + public final CategoryManager customAbilityCategories = new CategoryManager(); + public final CategoryManager chainedAbilityCategories = new CategoryManager(); + private final Map customAbilityCatMap = new HashMap<>(); // abilityName → catId + private final Map chainedAbilityCatMap = new HashMap<>(); // chainName → catId + + // ── Effect Action Registry ────────────────────────────────────────────── + private final Map effectActions = new LinkedHashMap<>(); + + // ── Derived State ──────────────────────────────────────────────────────── + private final Set builtInTypeIds = new HashSet<>(); + + public AbilityController() { + registerBuiltinTypes(); + registerBuiltinConditionTypes(); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // TYPE REGISTRATION + // ═══════════════════════════════════════════════════════════════════════════ + + public void registerType(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; + } + + String typeId = nbt.getString("typeId"); + Supplier factory = abilityTypes.get(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown ability type: " + typeId); + return null; + } + + Ability ability = factory.get(); + ability.readNBT(nbt); + return ability; + } + + private void registerBuiltinTypes() { + registerType(CustomAbility::new); + + registerType(AbilitySlam::new); + registerType(AbilityCharge::new); + + registerType(AbilityHeavyHit::new); + registerType(AbilityCutter::new); + + registerType(AbilitySweeper::new); + registerType(AbilityOrb::new); + registerType(AbilityDisc::new); + registerType(AbilityLaser::new); + registerType(AbilityBeam::new); + + registerType(AbilityDash::new); + registerType(AbilityTeleport::new); + + registerType(AbilityVortex::new); + registerType(AbilityShockwave::new); + + registerType(AbilityGuard::new); + registerType(AbilityCounter::new); + registerType(AbilityDodge::new); + registerType(AbilityEffect::new); + + registerType(AbilityHazard::new); + registerType(AbilityTrap::new); + + registerType(AbilityDome::new); + registerType(AbilityWall::new); + registerType(AbilityShield::new); + } + + private void registerBuiltinConditionTypes() { + registerCondition(ConditionHPThreshold::new); + registerCondition(ConditionHitCount::new); + registerCondition(ConditionItem::new); + registerCondition(ConditionQuestCompleted::new); + registerCondition(ConditionHasEffect::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.getDisplayName().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(); + customAbilitiesById.clear(); + abilityScriptHandlers.clear(); + customAbilityCatMap.clear(); + + File dir = getDir(); + customAbilityCategories.loadCategories(dir, "chained"); + + // Load from root directory (Uncategorized) + loadAbilitiesFromDir(dir, CategoryManager.UNCATEGORIZED_ID); + + // Load from category subdirectories + for (Map.Entry entry : customAbilityCategories.getCategories().entrySet()) { + File catDir = new File(dir, entry.getValue().title); + loadAbilitiesFromDir(catDir, entry.getKey()); + } + + customAbilityRevision++; + LogWriter.info("Loaded " + customAbilities.size() + " custom abilities"); + + loadChainedAbilities(); + } + + private void loadAbilitiesFromDir(File dir, int catId) { + File[] files = dir.exists() ? dir.listFiles() : null; + if (files == null) return; + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) continue; + try { + String filename = file.getName(); + String fileKey = filename.substring(0, filename.length() - 5); + + NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); + Ability ability = fromNBT(nbt); + if (ability == null) continue; + + String name = FileNameHelper.sanitizeName(fileKey, "Ability"); + name = makeUniqueNameForLoad(customAbilities, dir, file, name, fileKey); + + boolean dirty = false; + if (!name.equals(fileKey)) { + File renamedFile = new File(dir, name + ".json"); + if (file.renameTo(renamedFile)) { + file = renamedFile; + dirty = true; + } + } + + ability.setName(name); + + String uuid = ability.getId(); + if (uuid == null || uuid.isEmpty()) { + uuid = UUID.randomUUID().toString(); + ability.setId(uuid); + dirty = true; + } + + if (dirty) { + NBTJsonUtil.SaveFile(file, ability.writeNBT(true)); + } + + customAbilities.put(name, ability); + customAbilitiesById.put(uuid, ability); + if (catId > CategoryManager.UNCATEGORIZED_ID) { + customAbilityCatMap.put(name, catId); + } + } catch (Exception e) { + LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e); + } + } + } + + private boolean nameFileExists(File dir, String name, File ignoredFile) { + File existing = new File(dir, name + ".json"); + if (!existing.exists()) return false; + return ignoredFile == null || !existing.getAbsolutePath().equals(ignoredFile.getAbsolutePath()); + } + + private String makeUniqueNameForLoad(Map loadedMap, File dir, File currentFile, String baseName, String selfKey) { + String candidate = baseName; + while ((loadedMap.containsKey(candidate) && !candidate.equals(selfKey)) + || nameFileExists(dir, candidate, currentFile)) { + candidate = candidate + "_"; + } + return candidate; + } + + private String makeUniqueNameForMap(Map map, String baseName, String selfName) { + String candidate = baseName; + while (map.containsKey(candidate) && (selfName == null || !candidate.equals(selfName))) { + candidate = candidate + "_"; + } + return candidate; + } + + public boolean saveCustomAbility(Ability ability) { + if (ability == null) return false; + if (ability.isBuiltIn()) return false; + + String name = FileNameHelper.sanitizeName(ability.getName(), "Ability"); + ability.setName(name); + + String uuid = ability.getId(); + boolean isNew = (uuid == null || uuid.isEmpty()); + int catId = CategoryManager.UNCATEGORIZED_ID; + + if (isNew) { + // Generate UUID for new ability + uuid = UUID.randomUUID().toString(); + ability.setId(uuid); + + // Ensure unique name + name = makeUniqueNameForMap(customAbilities, name, null); + ability.setName(name); + } else { + // Existing ability — check for rename via UUID lookup + Ability existing = customAbilitiesById.get(uuid); + if (existing != null) { + String oldName = existing.getName(); + catId = customAbilityCatMap.getOrDefault(oldName, CategoryManager.UNCATEGORIZED_ID); + name = makeUniqueNameForMap(customAbilities, name, oldName); + ability.setName(name); + + if (!oldName.equals(name)) { + // Delete old file and remove old map entry + File oldDir = getCustomAbilityDir(oldName); + File oldFile = new File(oldDir, oldName + ".json"); + if (oldFile.exists()) { + oldFile.delete(); + } + customAbilities.remove(oldName); + // Update catMap key + customAbilityCatMap.remove(oldName); + if (catId > CategoryManager.UNCATEGORIZED_ID) { + customAbilityCatMap.put(name, catId); + } + } + } else { + name = makeUniqueNameForMap(customAbilities, name, null); + ability.setName(name); + } + } + + TagController.validateTagUUIDs(ability.getTagUUIDs()); + + File dir = getCustomAbilityDir(name); + File fileNew = new File(dir, name + ".json_new"); + File fileCurrent = new File(dir, name + ".json"); + + try { + NBTTagCompound nbt = ability.writeNBT(true); + + NBTJsonUtil.SaveFile(fileNew, nbt); + + if (fileCurrent.exists()) { + fileCurrent.delete(); + } + fileNew.renameTo(fileCurrent); + if (fileNew.exists()) { + fileNew.delete(); + } + + customAbilities.put(name, ability); + customAbilitiesById.put(uuid, ability); + customAbilityRevision++; + LogWriter.script("Saved custom ability: " + name + " [" + uuid + "]"); + SyncController.syncAll(SyncType.CUSTOM_ABILITY); + return true; + } catch (Exception e) { + LogWriter.error("Error saving custom ability: " + name, e); + return false; + } + } + + public Ability cloneCustomAbility(String originalName) { + Ability original = customAbilities.get(originalName); + if (original == null || original.isBuiltIn()) return null; + + int originalCatId = customAbilityCatMap.getOrDefault(originalName, CategoryManager.UNCATEGORIZED_ID); + + NBTTagCompound nbt = original.writeNBT(true); + nbt.setString("id", UUID.randomUUID().toString()); + + Ability clone = fromNBT(nbt); + if (clone == null) return null; + + String name = clone.getName(); + while (customAbilities.containsKey(name)) name += "_"; + clone.setName(name); + + saveCustomAbility(clone); + + if (originalCatId > CategoryManager.UNCATEGORIZED_ID) { + customAbilityCatMap.put(clone.getName(), originalCatId); + } + + return clone; + } + + public boolean deleteCustomAbility(String name) { + if (name == null || name.isEmpty()) return false; + + Ability removed = customAbilities.remove(name); + if (removed == null) { + String sanitized = FileNameHelper.sanitizeTextInput(name); + if (!sanitized.equals(name)) { + removed = customAbilities.remove(sanitized); + if (removed != null) { + name = sanitized; + } + } + } + if (removed == null) return false; + + // Also remove from UUID index and script handler + String uuid = removed.getId(); + if (uuid != null && !uuid.isEmpty()) { + customAbilitiesById.remove(uuid); + abilityScriptHandlers.remove(uuid); + } + + File dir = getCustomAbilityDir(name); + File file = new File(dir, name + ".json"); + if (file.exists()) { + file.delete(); + } + customAbilityCatMap.remove(name); + + // Clean up online players' unlocked ability lists + if (PlayerDataController.Instance != null) { + List snapshot = new ArrayList<>(PlayerDataController.Instance.getAllPlayerData()); + for (PlayerData pData : snapshot) { + if (pData.abilityData != null) { + boolean changed = false; + if (uuid != null && !uuid.isEmpty() && pData.abilityData.hasUnlockedAbility(uuid)) { + pData.abilityData.lockAbility(uuid); + changed = true; + } + if (pData.abilityData.hasUnlockedAbility(name)) { + pData.abilityData.lockAbility(name); + changed = true; + } + + // An active toggle holds the resolved Ability directly and keeps ticking it, + // so drop it without firing onToggle against an unregistered ability. + if (uuid != null && !uuid.isEmpty()) { + pData.abilityData.setToggleEntryDirect(uuid, 0); + } + pData.abilityData.setToggleEntryDirect(name, 0); + + if (pData.hotbarData != null) { + pData.hotbarData.validateSlots(); + } + + if (changed) { + pData.save(); + } + + if (pData.player instanceof EntityPlayerMP) { + PlayerAbilitySyncHelper.syncAbilities((EntityPlayerMP) pData.player); + } + } + } + } + + customAbilityRevision++; + LogWriter.script("Deleted custom ability: " + name); + SyncController.syncAll(SyncType.CUSTOM_ABILITY); + return true; + } + + public Ability getCustomAbility(String name) { + Ability ability = customAbilities.get(name); + if (ability != null) return ability; + String sanitized = FileNameHelper.sanitizeTextInput(name); + if (!sanitized.equals(name)) { + return customAbilities.get(sanitized); + } + return null; + } + + public Set getCustomAbilityNames() { + return new LinkedHashSet<>(customAbilities.keySet()); + } + + public Map getCustomAbilities() { + return customAbilities; + } + + public synchronized void setCustomAbilities(Map synced) { + customAbilities.clear(); + customAbilitiesById.clear(); + customAbilities.putAll(synced); + for (Ability ability : synced.values()) { + String uuid = ability.getId(); + if (uuid != null && !uuid.isEmpty()) { + customAbilitiesById.put(uuid, ability); + } + } + customAbilityRevision++; + } + + public int getCustomAbilityRevision() { + return customAbilityRevision; + } + + private File getDir() { + File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities"); + if (!dir.exists()) { + dir.mkdirs(); + } + return dir; + } + + private File getCustomAbilityDir(String name) { + int catId = customAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID); + return customAbilityCategories.getCategoryDir(catId); + } + + private File getChainedAbilityDir(String name) { + int catId = chainedAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID); + return chainedAbilityCategories.getCategoryDir(catId); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CUSTOM ABILITY CATEGORY HELPERS + // ═══════════════════════════════════════════════════════════════════════════ + + public Map getCustomAbilityCategoryScrollData() { + return customAbilityCategories.getCategoryScrollData(); + } + + public Map getCustomAbilityItemsByCategoryScrollData(int catId) { + Map map = new HashMap<>(); + for (Map.Entry entry : customAbilities.entrySet()) { + int assignedCat = customAbilityCatMap.getOrDefault(entry.getKey(), CategoryManager.UNCATEGORIZED_ID); + if (assignedCat == catId) { + map.put(entry.getKey(), entry.getValue().getAllowedBy().ordinal()); + } + } + return map; + } + + public HashMap> getCustomAbilityTagMapForCategory(int catId) { + HashMap> tagMap = new HashMap<>(); + for (Map.Entry entry : customAbilities.entrySet()) { + int assignedCat = customAbilityCatMap.getOrDefault(entry.getKey(), CategoryManager.UNCATEGORIZED_ID); + if (assignedCat == catId && !entry.getValue().getTagUUIDs().isEmpty()) { + tagMap.put(entry.getKey(), entry.getValue().getTagUUIDs()); + } + } + return tagMap; + } + + public void moveCustomAbilityToCategory(String name, int destCatId) { + Ability ability = customAbilities.get(name); + if (ability == null) return; + + int oldCatId = customAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID); + if (oldCatId == destCatId) return; + + File oldDir = customAbilityCategories.getCategoryDir(oldCatId); + File newDir = customAbilityCategories.getCategoryDir(destCatId); + if (!newDir.exists()) newDir.mkdirs(); + + File oldFile = new File(oldDir, name + ".json"); + File newFile = new File(newDir, name + ".json"); + if (oldFile.exists()) oldFile.renameTo(newFile); + + if (destCatId == CategoryManager.UNCATEGORIZED_ID) { + customAbilityCatMap.remove(name); + } else { + customAbilityCatMap.put(name, destCatId); + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CHAINED ABILITY CATEGORY HELPERS + // ═══════════════════════════════════════════════════════════════════════════ + + public Map getChainedAbilityCategoryScrollData() { + return chainedAbilityCategories.getCategoryScrollData(); + } + + public Map getChainedAbilityItemsByCategoryScrollData(int catId) { + Map map = new HashMap<>(); + for (Map.Entry entry : chainedAbilities.entrySet()) { + int assignedCat = chainedAbilityCatMap.getOrDefault(entry.getKey(), CategoryManager.UNCATEGORIZED_ID); + if (assignedCat == catId) { + map.put(entry.getKey(), entry.getValue().getAllowedBy().ordinal()); + } + } + return map; + } + + public void moveChainedAbilityToCategory(String name, int destCatId) { + ChainedAbility chain = chainedAbilities.get(name); + if (chain == null) return; + + int oldCatId = chainedAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID); + if (oldCatId == destCatId) return; + + File oldDir = chainedAbilityCategories.getCategoryDir(oldCatId); + File newDir = chainedAbilityCategories.getCategoryDir(destCatId); + if (!newDir.exists()) newDir.mkdirs(); + + File oldFile = new File(oldDir, name + ".json"); + File newFile = new File(newDir, name + ".json"); + if (oldFile.exists()) oldFile.renameTo(newFile); + + if (destCatId == CategoryManager.UNCATEGORIZED_ID) { + chainedAbilityCatMap.remove(name); + } else { + chainedAbilityCatMap.put(name, destCatId); + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CHAINED ABILITIES + // ═══════════════════════════════════════════════════════════════════════════ + + private void loadChainedAbilities() { + chainedAbilities.clear(); + chainedAbilitiesById.clear(); + chainedAbilityScriptHandlers.clear(); + chainedAbilityCatMap.clear(); + + File dir = getChainedDir(); + chainedAbilityCategories.loadCategories(dir); + + // Load from root directory (Uncategorized) + loadChainedFromDir(dir, CategoryManager.UNCATEGORIZED_ID); + + // Load from category subdirectories + for (Map.Entry entry : chainedAbilityCategories.getCategories().entrySet()) { + File catDir = new File(dir, entry.getValue().title); + loadChainedFromDir(catDir, entry.getKey()); + } + + chainedAbilityRevision++; + LogWriter.info("Loaded " + chainedAbilities.size() + " chained abilities"); + } + + private void loadChainedFromDir(File dir, int catId) { + File[] files = dir.exists() ? dir.listFiles() : null; + if (files == null) return; + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) continue; + try { + String filename = file.getName(); + String fileKey = filename.substring(0, filename.length() - 5); + + NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); + ChainedAbility chain = new ChainedAbility(); + chain.readNBT(nbt); + + String name = FileNameHelper.sanitizeName(fileKey, "Chain"); + name = makeUniqueNameForLoad(chainedAbilities, dir, file, name, fileKey); + + boolean dirty = false; + if (!name.equals(fileKey)) { + File renamedFile = new File(dir, name + ".json"); + if (file.renameTo(renamedFile)) { + file = renamedFile; + dirty = true; + } + } + + chain.setName(name); + + String uuid = chain.getId(); + if (uuid == null || uuid.isEmpty()) { + uuid = UUID.randomUUID().toString(); + chain.setId(uuid); + dirty = true; + } + + if (dirty) { + NBTJsonUtil.SaveFile(file, chain.writeNBT(true)); + } + + chainedAbilities.put(name, chain); + chainedAbilitiesById.put(uuid, chain); + if (catId > CategoryManager.UNCATEGORIZED_ID) { + chainedAbilityCatMap.put(name, catId); + } + } catch (Exception e) { + LogWriter.error("Error loading chained ability: " + file.getAbsolutePath(), e); + } + } + } + + public boolean saveChainedAbility(ChainedAbility chain) { + if (chain == null) return false; + + String name = FileNameHelper.sanitizeName(chain.getName(), "Chain"); + chain.setName(name); + + String uuid = chain.getId(); + boolean isNew = (uuid == null || uuid.isEmpty()); + + if (isNew) { + uuid = UUID.randomUUID().toString(); + chain.setId(uuid); + + name = makeUniqueNameForMap(chainedAbilities, name, null); + chain.setName(name); + } else { + ChainedAbility existing = chainedAbilitiesById.get(uuid); + if (existing != null) { + String oldName = existing.getName(); + int catId = chainedAbilityCatMap.getOrDefault(oldName, CategoryManager.UNCATEGORIZED_ID); + name = makeUniqueNameForMap(chainedAbilities, name, oldName); + chain.setName(name); + + if (!oldName.equals(name)) { + File oldDir = getChainedAbilityDir(oldName); + File oldFile = new File(oldDir, oldName + ".json"); + if (oldFile.exists()) { + oldFile.delete(); + } + chainedAbilities.remove(oldName); + chainedAbilityCatMap.remove(oldName); + if (catId > CategoryManager.UNCATEGORIZED_ID) { + chainedAbilityCatMap.put(name, catId); + } + } + } else { + name = makeUniqueNameForMap(chainedAbilities, name, null); + chain.setName(name); + } + } + + File dir = getChainedAbilityDir(name); + File fileNew = new File(dir, name + ".json_new"); + File fileCurrent = new File(dir, name + ".json"); + + try { + NBTTagCompound nbt = chain.writeNBT(true); + + NBTJsonUtil.SaveFile(fileNew, nbt); + + if (fileCurrent.exists()) { + fileCurrent.delete(); + } + fileNew.renameTo(fileCurrent); + if (fileNew.exists()) { + fileNew.delete(); + } + + chainedAbilities.put(name, chain); + chainedAbilitiesById.put(uuid, chain); + chainedAbilityRevision++; + LogWriter.script("Saved chained ability: " + name + " [" + uuid + "]"); + SyncController.syncAll(SyncType.CHAINED_ABILITY); + return true; + } catch (Exception e) { + LogWriter.error("Error saving chained ability: " + name, e); + return false; + } + } + + public ChainedAbility cloneChainedAbility(String originalName) { + ChainedAbility original = chainedAbilities.get(originalName); + if (original == null) return null; + + int originalCatId = chainedAbilityCatMap.getOrDefault(originalName, CategoryManager.UNCATEGORIZED_ID); + + NBTTagCompound nbt = original.writeNBT(true); + nbt.setString("Id", UUID.randomUUID().toString()); + + ChainedAbility clone = new ChainedAbility(); + clone.readNBT(nbt); + + String name = clone.getName(); + while (chainedAbilities.containsKey(name)) name += "_"; + clone.setName(name); + + saveChainedAbility(clone); + + if (originalCatId > CategoryManager.UNCATEGORIZED_ID) { + chainedAbilityCatMap.put(clone.getName(), originalCatId); + } + + return clone; + } + + public boolean deleteChainedAbility(String name) { + if (name == null || name.isEmpty()) return false; + + ChainedAbility removed = chainedAbilities.remove(name); + if (removed == null) { + String sanitized = FileNameHelper.sanitizeTextInput(name); + if (!sanitized.equals(name)) { + removed = chainedAbilities.remove(sanitized); + if (removed != null) { + name = sanitized; + } + } + } + if (removed == null) return false; + + String uuid = removed.getId(); + if (uuid != null && !uuid.isEmpty()) { + chainedAbilitiesById.remove(uuid); + chainedAbilityScriptHandlers.remove(uuid); + } + + File dir = getChainedAbilityDir(name); + File file = new File(dir, name + ".json"); + if (file.exists()) { + file.delete(); + } + chainedAbilityCatMap.remove(name); + + // Clean up online players' unlocked ability lists (chain keys use "chain:" prefix) + if (PlayerDataController.Instance != null) { + List snapshot = new ArrayList<>(PlayerDataController.Instance.getAllPlayerData()); + for (PlayerData pData : snapshot) { + if (pData.abilityData != null) { + String chainKey = "chain:" + (uuid != null && !uuid.isEmpty() ? uuid : name); + if (pData.abilityData.hasUnlockedAbility(chainKey)) { + pData.abilityData.lockAbility(chainKey); + } + String chainNameKey = "chain:" + name; + if (!chainNameKey.equals(chainKey) && pData.abilityData.hasUnlockedAbility(chainNameKey)) { + pData.abilityData.lockAbility(chainNameKey); + } + } + } + } + + chainedAbilityRevision++; + LogWriter.script("Deleted chained ability: " + name); + SyncController.syncAll(SyncType.CHAINED_ABILITY); + return true; + } + + public ChainedAbility resolveChainedAbility(String key) { + if (key == null || key.isEmpty()) return null; + + ChainedAbility byId = chainedAbilitiesById.get(key); + if (byId != null) return byId.deepCopy(); + + ChainedAbility chain = chainedAbilities.get(key); + if (chain != null) return chain.deepCopy(); + + for (Map.Entry entry : chainedAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue().deepCopy(); + } + } + + String sanitizedKey = FileNameHelper.sanitizeTextInput(key); + if (!sanitizedKey.equals(key)) { + ChainedAbility sanitized = chainedAbilities.get(sanitizedKey); + if (sanitized != null) return sanitized.deepCopy(); + } + + return null; + } + + /** + * Resolve a chained ability by key and return the live (non-copied) reference. + * For validation/permission checks only — do NOT expose or modify the returned chain. + * Uses the same lookup chain as {@link #resolveChainedAbility(String)}. + */ + public ChainedAbility peekChainedAbility(String key) { + if (key == null || key.isEmpty()) return null; + + ChainedAbility byId = chainedAbilitiesById.get(key); + if (byId != null) return byId; + + ChainedAbility chain = chainedAbilities.get(key); + if (chain != null) return chain; + + for (Map.Entry entry : chainedAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue(); + } + } + + String sanitizedKey = FileNameHelper.sanitizeTextInput(key); + if (!sanitizedKey.equals(key)) { + ChainedAbility sanitized = chainedAbilities.get(sanitizedKey); + if (sanitized != null) return sanitized; + } + + return null; + } + + public boolean canResolveChainedAbility(String key) { + if (key == null || key.isEmpty()) return false; + if (chainedAbilitiesById.containsKey(key)) return true; + if (chainedAbilities.containsKey(key)) return true; + for (String name : chainedAbilities.keySet()) { + if (name.equalsIgnoreCase(key)) return true; + } + String sanitizedKey = FileNameHelper.sanitizeTextInput(key); + if (!sanitizedKey.equals(key) && chainedAbilities.containsKey(sanitizedKey)) return true; + return false; + } + + @Override + public ChainedAbility getChainedAbility(String name) { + ChainedAbility chain = chainedAbilities.get(name); + if (chain == null) { + String sanitized = FileNameHelper.sanitizeTextInput(name); + if (!sanitized.equals(name)) { + chain = chainedAbilities.get(sanitized); + } + } + return chain != null ? chain.deepCopy() : null; + } + + public ChainedAbility getChainedAbilityByUUID(String uuid) { + return chainedAbilitiesById.get(uuid); + } + + public Set getChainedAbilityNamesSet() { + return new LinkedHashSet<>(chainedAbilities.keySet()); + } + + public Map getChainedAbilities() { + return chainedAbilities; + } + + @Override + public String[] getChainedAbilityNames() { + return chainedAbilities.keySet().toArray(new String[0]); + } + + @Override + public boolean hasChainedAbilityName(String name) { + if (chainedAbilities.containsKey(name)) return true; + String sanitized = FileNameHelper.sanitizeTextInput(name); + return !sanitized.equals(name) && chainedAbilities.containsKey(sanitized); + } + + @Override + public boolean deleteChainedAbilityByName(String name) { + return deleteChainedAbility(name); + } + + @Override + public boolean saveChainedAbility(IChainedAbility chain) { + if (chain instanceof ChainedAbility) { + return saveChainedAbility((ChainedAbility) chain); + } + return false; + } + + public int getChainedAbilityRevision() { + return chainedAbilityRevision; + } + + public synchronized void setChainedAbilities(Map synced) { + chainedAbilities.clear(); + chainedAbilitiesById.clear(); + chainedAbilities.putAll(synced); + for (ChainedAbility chain : synced.values()) { + String uuid = chain.getId(); + if (uuid != null && !uuid.isEmpty()) { + chainedAbilitiesById.put(uuid, chain); + } + } + chainedAbilityRevision++; + } + + private File getChainedDir() { + File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities" + File.separator + "chained"); + if (!dir.exists()) { + dir.mkdirs(); + } + return dir; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // RESOLUTION + // ═══════════════════════════════════════════════════════════════════════════ + + public Ability resolveAbility(String key) { + if (key == null || key.isEmpty()) return null; + + // Custom: UUID lookup (most common for persistent references) + Ability byUuid = customAbilitiesById.get(key); + if (byUuid != null) return byUuid.deepCopy(); + + // Built-in: exact key + Ability builtIn = builtAbilities.get(key); + if (builtIn != null) return builtIn.deepCopy(); + + // Built-in: case-insensitive key + String lowerKey = key.toLowerCase(); + for (Map.Entry entry : builtAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(lowerKey)) { + return entry.getValue().deepCopy(); + } + } + + // Built-in: by ID (case-insensitive) + for (Ability ability : builtAbilities.values()) { + if (key.equalsIgnoreCase(ability.getId())) { + return ability.deepCopy(); + } + } + + // Custom: exact name + Ability custom = customAbilities.get(key); + if (custom != null) return custom.deepCopy(); + + // Custom: case-insensitive name + for (Map.Entry entry : customAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue().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); + } + } + // Custom abilities keyed by UUID (stable references) + for (Ability ability : customAbilities.values()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + 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); + } + } + } + // Custom abilities keyed by UUID (stable references) + for (Ability ability : customAbilities.values()) { + if (ability.getAllowedBy().allowsPlayer()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + } + return keys; + } + + public boolean hasAbility(String key) { + return builtAbilities.containsKey(key) || customAbilities.containsKey(key) + || customAbilitiesById.containsKey(key); + } + + public Ability getCustomAbilityByUUID(String uuid) { + return customAbilitiesById.get(uuid); + } + + public Ability getCustomAbilityByName(String name) { + return customAbilities.get(name); + } + + /** + * Resolve an ability by key and return the live (non-copied) reference. + * For validation/permission checks only — do NOT expose or modify the returned ability. + * Uses the same lookup chain as {@link #resolveAbility(String)}. + */ + public Ability peekAbility(String key) { + if (key == null || key.isEmpty()) return null; + + // Custom: UUID lookup + Ability byUuid = customAbilitiesById.get(key); + if (byUuid != null) return byUuid; + + // Built-in: exact key + Ability builtIn = builtAbilities.get(key); + if (builtIn != null) return builtIn; + + // Built-in: case-insensitive key + for (Map.Entry entry : builtAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue(); + } + } + + // Built-in: by ID (case-insensitive) + for (Ability ability : builtAbilities.values()) { + if (key.equalsIgnoreCase(ability.getId())) return ability; + } + + // Custom: exact name + Ability custom = customAbilities.get(key); + if (custom != null) return custom; + + // Custom: case-insensitive name + for (Map.Entry entry : customAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue(); + } + } + + return null; + } + + /** + * 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; + + // Custom: UUID lookup + if (customAbilitiesById.containsKey(key)) return true; + + // Built-in: exact key + if (builtAbilities.containsKey(key)) return true; + + // Built-in: by ID + for (Ability ability : builtAbilities.values()) { + if (key.equals(ability.getId())) return true; + } + + // Custom: exact name + if (customAbilities.containsKey(key)) return true; + + return false; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // UNIFIED ACTION RESOLUTION + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Resolve any action key to an IAbilityAction. + * Checks abilities first, then chained abilities. + */ + public IAbilityAction resolveAction(String key) { + if (key == null || key.isEmpty()) return null; + + Ability ability = resolveAbility(key); + if (ability != null) return ability; + + return resolveChainedAbility(key); + } + + /** + * Check if a key can be resolved as any action (ability or chain). + */ + public boolean canResolveAction(String key) { + if (canResolveAbility(key)) return true; + return canResolveChainedAbility(key); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // 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 registerChainedFieldProvider(IChainedAbilityFieldProvider provider) { + chainedFieldProviders.add(provider); + } + + public List getChainedFieldProviders() { + return chainedFieldProviders; + } + + public void registerExtender(IAbilityExtender extender) { + extenders.add(extender); + } + + public List getExtenders() { + return extenders; + } + + public void registerCondition(Supplier conditionFactory) { + AbilityCondition temp = conditionFactory.get(); + String typeId = temp.getTypeId(); + if (conditionTypes.containsKey(typeId)) { + LogWriter.info("AbilityController: Overwriting Condition type: " + typeId); + } + conditionTypes.put(typeId, conditionFactory); + } + + public Supplier getConditionType(String key) { + return conditionTypes.get(key); + } + + public String[] getConditionTypes() { + return conditionTypes.keySet().toArray(new String[0]); + } + + public List getConditionNamespaces() { + LinkedHashSet seen = new LinkedHashSet<>(); + for (String typeId : conditionTypes.keySet()) { + String[] parts = typeId.split("\\.", 3); + if (parts.length >= 2) { + seen.add(parts[1]); + } + } + return new ArrayList<>(seen); + } + + public String[] getConditionTypesByNamespace(String namespace) { + String prefix = "condition." + namespace + "."; + List result = new ArrayList<>(); + for (String typeId : conditionTypes.keySet()) { + if (typeId.startsWith(prefix)) { + result.add(typeId); + } + } + return result.toArray(new String[0]); + } + + 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; + } + + public void registerActivationChecker(Predicate checker) { + activationCheckers.add(checker); + } + + public boolean canPlayerActivate(EntityPlayer player) { + for (Predicate checker : activationCheckers) { + if (!checker.test(player)) return false; + } + return true; + } + + /** + * 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, + float damageMultiplier) { + for (IAbilityExtender ext : extenders) { + if (ext.onAbilityDamage(ability, caster, target, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ, damageMultiplier)) { + return true; + } + } + return false; + } + + /** + * Fire modifyProjectileDamage on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { + float damage = baseDamage; + for (IAbilityExtender ext : extenders) { + damage = ext.modifyProjectileDamage(ability, caster, damage); + } + return damage; + } + + /** + * Fire modifyBarrierHealth on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) { + float health = baseHealth; + for (IAbilityExtender ext : extenders) { + health = ext.modifyBarrierHealth(ability, caster, health); + } + return health; + } + + /** + * Fire modifyBarrierMeleeDamage on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) { + float damage = baseDamage; + for (IAbilityExtender ext : extenders) { + damage = ext.modifyBarrierMeleeDamage(barrier, attacker, damage); + } + return damage; + } + + /** + * Fire onAbilityHeal on all extenders. Chain of responsibility — first true wins. + */ + public boolean fireOnAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) { + for (IAbilityExtender ext : extenders) { + if (ext.onAbilityHeal(ability, caster, target, healAmount)) { + return true; + } + } + return false; + } + + public Boolean fireCheckConditions(AbilityCondition condition, EntityLivingBase caster, EntityLivingBase target) { + for (IAbilityExtender ext : extenders) { + Boolean result = ext.onCheckCondition(condition, caster, target); + if (result != null) { + return result; + } + } + + return null; + } + + public Boolean fireCheckConditionsForPlayer(AbilityCondition condition, EntityLivingBase player) { + for (IAbilityExtender ext : extenders) { + Boolean result = ext.onCheckConditionForPlayer(condition, player); + if (result != null) { + return result; + } + } + return null; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // IAbilityHandler + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public String[] getTypes() { + return abilityTypes.keySet().toArray(new String[0]); + } + + public boolean isBuiltInType(String typeId) { + return builtInTypeIds.contains(typeId); + } + + public boolean isConcurrentCapableType(String typeId) { + Supplier factory = abilityTypes.get(typeId); + if (factory == null) return false; + return factory.get().isConcurrentCapable(); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // EFFECT ACTION REGISTRY + // ═══════════════════════════════════════════════════════════════════════════ + + public void registerEffectAction(IEffectAction action) { + if (action == null || action.getId() == null) return; + effectActions.put(action.getId(), action); + } + + public IEffectAction getEffectAction(String id) { + return effectActions.get(id); + } + + public String[] getEffectActionIds() { + return effectActions.keySet().toArray(new String[0]); + } + + public java.util.Collection getEffectActions() { + return effectActions.values(); + } + + public boolean hasEffectActions() { + return !effectActions.isEmpty(); + } + + @Override + public boolean hasType(String typeId) { + return abilityTypes.containsKey(typeId); + } + + public boolean isAllowedByPlayer(String typeId) { + if (abilityTypes.containsKey(typeId)) { + Ability temp = abilityTypes.get(typeId).get(); + return temp.getAllowedBy().allowsPlayer(); + } + + return false; + } + + public boolean isAllowedByNPC(String typeId) { + if (abilityTypes.containsKey(typeId)) { + Ability temp = abilityTypes.get(typeId).get(); + return temp.getAllowedBy().allowsNpc(); + } + + return false; + } + + public boolean isAllowedByBoth(String typeId) { + if (abilityTypes.containsKey(typeId)) { + Ability temp = abilityTypes.get(typeId).get(); + return temp.getAllowedBy() == UserType.BOTH; + } + + return false; + } + + @Override + public String[] getAbilityNameArray() { + return builtAbilities.keySet().toArray(new String[0]); + } + + @Override + public boolean hasAbilityName(String name) { + return builtAbilities.containsKey(name); + } + + @Override + public String[] getCustomAbilityNameArray() { + return customAbilities.keySet().toArray(new String[0]); + } + + @Override + public boolean hasCustomAbilityName(String name) { + if (customAbilities.containsKey(name)) return true; + String sanitized = FileNameHelper.sanitizeTextInput(name); + return !sanitized.equals(name) && customAbilities.containsKey(sanitized); + } + + @Override + public boolean deleteCustomAbilityByName(String name) { + return deleteCustomAbility(name); + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/EnergyController.java b/src/main/java/kamkeel/npcs/controllers/EnergyController.java new file mode 100644 index 000000000..5b6bc123a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/EnergyController.java @@ -0,0 +1,209 @@ +package kamkeel.npcs.controllers; + +import kamkeel.npcs.controllers.data.energy.IEnergyExtender; +import kamkeel.npcs.entity.*; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import noppes.npcs.api.IEnergyHandler; +import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.*; +import noppes.npcs.api.entity.IEnergyExplosion; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.scripted.entity.ScriptEnergyExplosion; + +import java.util.ArrayList; +import java.util.List; + +/** + * Central controller for script-created energy entities and handler registration. + * Provides factory methods for creating all energy entity types and routes + * damage through registered handlers when entities have customDamageData + * but no sourceAbility. + */ +public class EnergyController implements IEnergyHandler { + + public static EnergyController Instance = new EnergyController(); + + private final List extenders = new ArrayList<>(); + + // ═══════════════════════════════════════════════════════════════════ + // HANDLER REGISTRATION + // ═══════════════════════════════════════════════════════════════════ + + public void registerExtender(IEnergyExtender handler) { + extenders.add(handler); + } + + public List getExtenders() { + return extenders; + } + + // ═══════════════════════════════════════════════════════════════════ + // DAMAGE ROUTING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Fire onEnergyDamage on all handlers. Chain of responsibility — first true wins. + */ + public boolean fireOnEnergyDamage(Entity energyEntity, EntityLivingBase owner, + EntityLivingBase target, float damage, + float knockback, float knockbackUp, + double kbDirX, double kbDirZ, + float damageMultiplier, + NBTTagCompound damageData) { + for (IEnergyExtender handler : extenders) { + if (handler.onEnergyDamage(energyEntity, owner, target, damage, + knockback, knockbackUp, kbDirX, kbDirZ, damageMultiplier, damageData)) { + return true; + } + } + return false; + } + + /** + * Fire modifyEnergyDamage on all handlers. Cumulative — each handler's output feeds the next. + */ + public float fireModifyEnergyDamage(Entity energyEntity, EntityLivingBase owner, + float baseDamage, NBTTagCompound damageData) { + float damage = baseDamage; + for (IEnergyExtender handler : extenders) { + damage = handler.modifyEnergyDamage(energyEntity, owner, damage, damageData); + } + return damage; + } + + // ═══════════════════════════════════════════════════════════════════ + // INTERNAL FACTORY METHODS (MC types) + // ═══════════════════════════════════════════════════════════════════ + + public EntityAbilityOrb createOrbInternal(World world, Entity 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.getEntityId()); + entity.setProjectileSize(size); + return entity; + } + + public EntityAbilityBeam createBeamInternal(World world, Entity 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.getEntityId()); + entity.setBeamWidth(beamWidth); + entity.setHeadSize(headSize); + return entity; + } + + public EntityAbilityDisc createDiscInternal(World world, Entity 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.getEntityId()); + entity.setDiscRadius(radius); + entity.setDiscThickness(thickness); + return entity; + } + + public EntityAbilityLaser createLaserInternal(World world, Entity 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.getEntityId()); + entity.setLaserWidth(laserWidth); + return entity; + } + + public EntityAbilityZone createHazardInternal(World world, Entity owner, double x, double y, double z) { + EntityAbilityZone entity = new EntityAbilityZone(world); + entity.initAsHazard(owner, x, y, z); + return entity; + } + + public EntityAbilityZone createTrapInternal(World world, Entity owner, double x, double y, double z) { + EntityAbilityZone entity = new EntityAbilityZone(world); + entity.initAsTrap(owner, x, y, z); + return entity; + } + + public EntityEnergySweeper createSweeperInternal(World world, Entity owner, double x, double y, double z) { + EntityEnergySweeper entity = new EntityEnergySweeper(world); + entity.setPosition(x, y, z); + entity.setOwnerEntityId(owner.getEntityId()); + return entity; + } + + public EntityEnergyPanel createPanelInternal(World world, Entity owner, double x, double y, double z) { + EntityEnergyPanel entity = new EntityEnergyPanel(world); + entity.setPosition(x, y, z); + entity.setOwnerEntityId(owner.getEntityId()); + return entity; + } + + public EntityEnergyExplosion createExplosionInternal(World world, Entity owner, double x, double y, double z, float radius) { + return new EntityEnergyExplosion(world, owner, x, y, z, radius); + } + + // ═══════════════════════════════════════════════════════════════════ + // IEnergyHandler (Script API methods) + // ═══════════════════════════════════════════════════════════════════ + + @Override + public IEnergyOrb createOrb(IWorld world, IEntity owner, double x, double y, double z, float size) { + EntityAbilityOrb entity = createOrbInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, size); + return (IEnergyOrb) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyBeam createBeam(IWorld world, IEntity owner, double x, double y, double z, float beamWidth, float headSize) { + EntityAbilityBeam entity = createBeamInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, beamWidth, headSize); + return (IEnergyBeam) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyDisc createDisc(IWorld world, IEntity owner, double x, double y, double z, float radius, float thickness) { + EntityAbilityDisc entity = createDiscInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius, thickness); + return (IEnergyDisc) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyLaser createLaser(IWorld world, IEntity owner, double x, double y, double z, float laserWidth) { + EntityAbilityLaser entity = createLaserInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, laserWidth); + return (IEnergyLaser) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyZone createHazard(IWorld world, IEntity owner, double x, double y, double z) { + EntityAbilityZone entity = createHazardInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z); + return (IEnergyZone) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyZone createTrap(IWorld world, IEntity owner, double x, double y, double z) { + EntityAbilityZone entity = createTrapInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z); + return (IEnergyZone) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergySweeper createSweeper(IWorld world, IEntity owner, double x, double y, double z) { + EntityEnergySweeper entity = createSweeperInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z); + return (IEnergySweeper) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyPanel createPanel(IWorld world, IEntity owner, double x, double y, double z) { + EntityEnergyPanel entity = createPanelInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z); + return (IEnergyPanel) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyExplosion createExplosion(IWorld world, IEntity owner, double x, double y, double z, float radius) { + EntityEnergyExplosion entity = createExplosionInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius); + return new ScriptEnergyExplosion<>(entity); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/ProfileController.java b/src/main/java/kamkeel/npcs/controllers/ProfileController.java index 103da1309..c4be7322e 100644 --- a/src/main/java/kamkeel/npcs/controllers/ProfileController.java +++ b/src/main/java/kamkeel/npcs/controllers/ProfileController.java @@ -7,7 +7,9 @@ import kamkeel.npcs.controllers.data.profile.Profile; import kamkeel.npcs.controllers.data.profile.ProfileInfoEntry; import kamkeel.npcs.controllers.data.profile.ProfileOperation; import kamkeel.npcs.controllers.data.profile.Slot; +import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; @@ -453,6 +455,9 @@ public class ProfileController implements IProfileHandler { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(profile.player); verifySlotQuests(profile.player); save(profile.player, profile); + if (profile.player instanceof EntityPlayerMP) { + ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) profile.player); + } IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player); EventHooks.onProfileCreate(handler, scriptPlayer, profile, newSlotId, true); @@ -523,6 +528,10 @@ public class ProfileController implements IProfileHandler { // overwrite the destination slot with stale data. saveSlotData(profile.player, profile, prevSlot); loadSlotData(profile.player, profile, newSlotId); + syncSharedQuestsToPlayer(profile.player); + if (profile.player instanceof EntityPlayerMP) { + ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) profile.player); + } EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true); } else { @@ -832,15 +841,6 @@ public class ProfileController implements IProfileHandler { else compound = (NBTTagCompound) compound.copy(); playerData.setNBT(compound); - - // Trade data is shared across all profile slots - copy from player's live data - PlayerData liveData = PlayerData.get(player); - if (liveData != null) { - NBTTagCompound tradeCompound = new NBTTagCompound(); - liveData.tradeData.writeToNBT(tradeCompound); - playerData.tradeData.readFromNBT(tradeCompound); - } - return playerData; } @@ -869,6 +869,9 @@ public class ProfileController implements IProfileHandler { } } + // Update the profile cache + profile.sharedQuestTimestamps = universalFinished; + // Push the universal shared completion times into every slot. for (ISlot slot : profile.getSlots().values()) { IPlayerData data = getSlotPlayerData(player, slot.getId()); @@ -881,22 +884,33 @@ public class ProfileController implements IProfileHandler { } } + public void syncSharedQuestsToPlayer(EntityPlayer player) { + Profile profile = getProfile(player); + if (profile == null || profile.sharedQuestTimestamps.isEmpty()) { + return; + } + PlayerQuestData questData = PlayerData.get(player).questData; + for (Map.Entry entry : profile.sharedQuestTimestamps.entrySet()) { + Long existing = questData.finishedQuests.get(entry.getKey()); + if (existing == null || entry.getValue() > existing) { + questData.finishedQuests.put(entry.getKey(), entry.getValue()); + } + } + } + public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) { Profile profile = getProfile(player); if (profile == null) { return; } - for (ISlot slot : profile.getSlots().values()) { - IPlayerData playerData = getSlotPlayerData(player, slot.getId()); - if (playerData != null) { - PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData(); - Long existing = questData.finishedQuests.get(questId); - if (existing == null || completeTime > existing) { - questData.finishedQuests.put(questId, completeTime); - } - playerData.save(); - } + + Long existing = profile.sharedQuestTimestamps.get(questId); + if (existing == null || completeTime > existing) { + profile.sharedQuestTimestamps.put(questId, completeTime); } save(player, profile); + if (player instanceof EntityPlayerMP) { + ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) player); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/SyncController.java b/src/main/java/kamkeel/npcs/controllers/SyncController.java index b6010ad86..56dc377f9 100644 --- a/src/main/java/kamkeel/npcs/controllers/SyncController.java +++ b/src/main/java/kamkeel/npcs/controllers/SyncController.java @@ -5,854 +5,339 @@ import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import kamkeel.npcs.addon.DBCAddon; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.controllers.sync.SyncRegistry; +import kamkeel.npcs.controllers.sync.handlers.*; import kamkeel.npcs.network.LargeAbstractPacket; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSyncAction; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.network.packets.data.LoginPacket; -import kamkeel.npcs.network.packets.data.large.SyncEffectPacket; +import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket; import kamkeel.npcs.network.packets.data.large.SyncPacket; import kamkeel.npcs.network.packets.request.party.PartyInfoPacket; import kamkeel.npcs.util.ByteBufUtils; -import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; +import noppes.npcs.LogWriter; import noppes.npcs.client.ClientCacheHandler; -import noppes.npcs.controllers.CustomEffectController; -import noppes.npcs.controllers.DialogController; -import noppes.npcs.controllers.FactionController; -import noppes.npcs.controllers.MagicController; -import noppes.npcs.controllers.QuestController; -import noppes.npcs.controllers.RecipeController; -import noppes.npcs.controllers.data.CustomEffect; -import noppes.npcs.controllers.data.Dialog; -import noppes.npcs.controllers.data.DialogCategory; -import noppes.npcs.controllers.data.EffectKey; -import noppes.npcs.controllers.data.Faction; -import noppes.npcs.controllers.data.Magic; -import noppes.npcs.controllers.data.MagicCycle; +import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.controllers.data.PlayerData; -import noppes.npcs.controllers.data.PlayerEffect; -import noppes.npcs.controllers.data.Quest; -import noppes.npcs.controllers.data.QuestCategory; -import noppes.npcs.controllers.data.RecipeAnvil; -import noppes.npcs.controllers.data.RecipeCarpentry; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityController; -import java.io.IOException; -import java.util.EnumMap; -import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; +/** + * Central sync backend for CNPC+. + * + *

This controller manages two distinct sync lanes:

+ *
    + *
  • Global cached registry families — registered via {@link SyncRegistry} + * with concrete {@link SyncHandler} implementations. These families use + * cached serialized payloads, revision-based delta sync on reconnect, + * and chunked delivery. All family-specific RELOAD/UPDATE/REMOVE logic + * lives in the handler implementations, not here.
  • + *
  • Direct per-player sync helpers — for transient per-player state + * like effects, ability hotbars, and cooldowns. These bypass the cached + * registry system and are sent as direct packets. Owned by + * {@link PlayerEffectSyncHelper} and {@link PlayerAbilitySyncHelper}.
  • + *
+ * + *

This class retains ownership of:

+ *
    + *
  • Cache entry storage and lazy rebuild ({@link SyncCacheEntry})
  • + *
  • Cached payload byte[] + precomputed chunks ({@link CachedSyncPayload})
  • + *
  • Per-player revision tracking ({@link PlayerSyncState})
  • + *
  • Login handshake and post-login packet sequencing
  • + *
  • Generic sync dispatch helpers (syncAll, syncUpdate, syncRemove)
  • + *
+ */ public class SyncController { - public static boolean DEBUG_SYNC_LOGGING = false; + /** Cached serialized reload payloads and revision state for each global sync family. */ + private static final Map cacheEntries = new LinkedHashMap<>(); - private static final EnumMap cacheEntries = new EnumMap<>(EnumSyncType.class); + /** Last known synced revision map for each connected player. */ private static final ConcurrentHashMap playerSyncState = new ConcurrentHashMap<>(); + /** Stable identity token for the current dedicated-server process, used by the revision handshake. */ + private static final String SERVER_IDENTITY_KEY = UUID.randomUUID().toString(); - private static void debug(String message, Object... args) { - if (DEBUG_SYNC_LOGGING) { - System.out.println("[SyncController] " + String.format(message, args)); - } + // ═══════════════════════════════════════════════════════════════════════ + // Lifecycle — handler registration and cache initialization + // ═══════════════════════════════════════════════════════════════════════ + + /** + * Registers all core CNPC+ sync handlers in deterministic order. + * Called on server start. The registration order determines login + * sync ordering via {@link SyncRegistry#getLoginTypes()}. + * + *

Handler registration order matches the original hard-coded + * LOGIN_SYNC_TYPES array for behavioral parity.

+ */ + public static void register() { + SyncRegistry.register(SyncType.FACTION, new FactionSyncHandler()); + SyncRegistry.register(SyncType.DIALOG, new DialogSyncHandler()); + SyncRegistry.register(SyncType.DIALOG_CATEGORY, new DialogCategorySyncHandler()); + SyncRegistry.register(SyncType.QUEST, new QuestSyncHandler()); + SyncRegistry.register(SyncType.QUEST_CATEGORY, new QuestCategorySyncHandler()); + SyncRegistry.register(SyncType.PLAYERDATA, new PlayerDataSyncHandler()); + SyncRegistry.register(SyncType.WORKBENCH_RECIPES, new WorkbenchRecipeSyncHandler()); + SyncRegistry.register(SyncType.CARPENTRY_RECIPES, new CarpentryRecipeSyncHandler()); + SyncRegistry.register(SyncType.ANVIL_RECIPES, new AnvilRecipeSyncHandler()); + SyncRegistry.register(SyncType.CUSTOM_EFFECTS, new CustomEffectSyncHandler()); + SyncRegistry.register(SyncType.MAGIC, new MagicSyncHandler()); + SyncRegistry.register(SyncType.MAGIC_CYCLE, new MagicCycleSyncHandler()); + SyncRegistry.register(SyncType.CUSTOM_ABILITY, new CustomAbilitySyncHandler()); + SyncRegistry.register(SyncType.CHAINED_ABILITY, new ChainedAbilitySyncHandler()); } - - private static final EnumSyncType[] LOGIN_SYNC_TYPES = new EnumSyncType[]{ - EnumSyncType.FACTION, - EnumSyncType.DIALOG_CATEGORY, - EnumSyncType.QUEST_CATEGORY, - EnumSyncType.WORKBENCH_RECIPES, - EnumSyncType.CARPENTRY_RECIPES, - EnumSyncType.ANVIL_RECIPES, - EnumSyncType.CUSTOM_EFFECTS, - EnumSyncType.MAGIC, - EnumSyncType.MAGIC_CYCLE, - EnumSyncType.CUSTOM_ABILITY - }; - + public static void load() { cacheEntries.clear(); playerSyncState.clear(); - registerCache(EnumSyncType.FACTION, SyncController::factionsNBT); - registerCache(EnumSyncType.DIALOG_CATEGORY, SyncController::dialogCategoriesNBT); - registerCache(EnumSyncType.QUEST_CATEGORY, SyncController::questCategoriesNBT); - registerCache(EnumSyncType.WORKBENCH_RECIPES, SyncController::workbenchNBT); - registerCache(EnumSyncType.CARPENTRY_RECIPES, SyncController::carpentryNBT); - registerCache(EnumSyncType.ANVIL_RECIPES, SyncController::anvilNBT); - registerCache(EnumSyncType.CUSTOM_EFFECTS, SyncController::customEffectsNBT); - registerCache(EnumSyncType.MAGIC, SyncController::magicsNBT); - registerCache(EnumSyncType.MAGIC_CYCLE, SyncController::magicCyclesNBT); - registerCache(EnumSyncType.CUSTOM_ABILITY, SyncController::customAbilitiesNBT); + // Register caches for all cached (login-sync) types + // The cache supplier delegates to the handler's serializeAll() + for (SyncType type : SyncRegistry.getLoginTypes()) { + SyncHandler handler = SyncRegistry.getHandler(type); + if (handler != null) + registerCache(type, handler::serializeAll); + } } - public static void syncPlayer(EntityPlayerMP player) { - SyncController.syncPlayerInternal(player, true); + + // ═══════════════════════════════════════════════════════════════════════ + // Other Login syncers + // ═══════════════════════════════════════════════════════════════════════ + + public static void beginLogin(EntityPlayerMP player) { + playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); + PacketHandler.Instance.sendToPlayer(new LoginPacket(getServerCacheKey(), getServerRevisionSnapshot()), player); } - private static void syncPlayerInternal(EntityPlayerMP player, boolean includePostPackets) { + private static void sendPostLoginPackets(EntityPlayerMP player) { + DBCAddon.instance.syncPlayer(player); + PlayerDataSyncHandler.syncPlayerData(player, false); + PartyInfoPacket.sendPartyData(player); + ProfileSharedQuestPacket.sendToPlayer(player); + + // Sync skin overlays after full handshake to ensure the client is ready. + // Overlays are not part of getSyncNBTFull(), and packets sent during + // PlayerLoggedInEvent can arrive before the client entity exists. + PlayerData data = PlayerData.get(player); + if (data != null) data.skinOverlays.updateClient(); + } + + // ═══════════════════════════════════════════════════════════════════════ + // MAIN PIPELINE — completion of login handshake and full catalog sync + // ═══════════════════════════════════════════════════════════════════════ + + /** + * Runs the cached-family sync pass for one player using the currently tracked + * revision state. Used after the login handshake and by server-side callers + * that need to refresh a player's global cached sync families. + */ + public static void dispatchSyncForAllTypes(EntityPlayerMP player) { PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); - for (EnumSyncType type : LOGIN_SYNC_TYPES) { + // Registry-driven login iteration: iterate only cached types + for (SyncType type : SyncRegistry.getLoginTypes()) { SyncCacheEntry entry = cacheEntries.get(type); - if (entry == null) { - continue; - } + if (entry == null) continue; int currentRevision = entry.getRevisionValue(); int lastRevision = state.getRevision(type); - if (lastRevision == currentRevision) { - continue; - } - + if (lastRevision == currentRevision) continue; + CachedSyncPayload payload = entry.getPayload(type); - if (payload == null) { - continue; - } + if (payload == null) continue; if (lastRevision != payload.getRevision()) { - debug("Sending %s data to %s", type, player.getCommandSenderName()); PacketHandler.Instance.sendToPlayer(new SyncPacket(type, payload), player); state.updateRevision(type, payload.getRevision()); } } - if (includePostPackets) { - sendPostLoginPackets(player); - } - } - - public static void beginLogin(EntityPlayerMP player) { - playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); - PacketHandler.Instance.sendToPlayer( - new LoginPacket(getServerCacheKey(), getServerRevisionSnapshot()), - player - ); - } - - public static void handleClientRevisionReport( - EntityPlayerMP player, - String serverKey, - String previousServerKey, - Map clientRevisions - ) { - String currentServerKey = getServerCacheKey(); - PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); - - if (!currentServerKey.equals(serverKey)) { - state.reset(); - syncPlayer(player); - return; - } - - if (!currentServerKey.isEmpty()) { - if (previousServerKey == null || !currentServerKey.equals(previousServerKey)) { - state.reset(); - syncPlayer(player); - return; - } - } - - if (clientRevisions == null || clientRevisions.isEmpty()) { - debug( - "Client %s reported no cached revisions; forcing full sync", - player.getCommandSenderName() - ); - state.reset(); - } else { - state.applyHandshake(clientRevisions); - } - - syncPlayer(player); - } - - private static void sendPostLoginPackets(EntityPlayerMP player) { - DBCAddon.instance.syncPlayer(player); - syncPlayerData(player, false); - PartyInfoPacket.sendPartyData(player); - } - - private static EnumMap getServerRevisionSnapshot() { - EnumMap snapshot = new EnumMap<>(EnumSyncType.class); - for (EnumSyncType type : LOGIN_SYNC_TYPES) { - SyncCacheEntry entry = cacheEntries.get(type); - if (entry != null) { - snapshot.put(type, entry.getRevisionValue()); - } - } - return snapshot; - } - - private static final String SERVER_IDENTITY_KEY = UUID.randomUUID().toString(); - - private static String getServerCacheKey() { - MinecraftServer server = MinecraftServer.getServer(); - if (server == null) { - return ""; - } - - if (!server.isDedicatedServer()) { - return ""; - } - - return SERVER_IDENTITY_KEY; - } - - public static int getCurrentRevision(EnumSyncType type) { - SyncCacheEntry entry = cacheEntries.get(type); - return entry == null ? -1 : entry.getRevisionValue(); - } - - public static NBTTagCompound workbenchNBT() { - RecipeController controller = RecipeController.Instance; - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (RecipeCarpentry recipe : controller.globalRecipes.values()) { - list.appendTag(recipe.writeNBT(false)); - } - compound.setTag("recipes", list); - return compound; - } - - public static NBTTagCompound carpentryNBT() { - RecipeController controller = RecipeController.Instance; - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (RecipeCarpentry recipe : controller.carpentryRecipes.values()) { - list.appendTag(recipe.writeNBT(false)); - } - compound.setTag("recipes", list); - return compound; - } - - public static NBTTagCompound anvilNBT() { - RecipeController controller = RecipeController.Instance; - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (RecipeAnvil recipe : controller.anvilRecipes.values()) { - list.appendTag(recipe.writeNBT(false)); - } - compound.setTag("recipes", list); - return compound; - } - - public static NBTTagCompound factionsNBT() { - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (Faction faction : FactionController.getInstance().factions.values()) { - NBTTagCompound factioNBT = new NBTTagCompound(); - faction.writeNBT(factioNBT); - list.appendTag(factioNBT); - } - compound.setTag("Factions", list); - return compound; - } - - public static NBTTagCompound dialogCategoriesNBT() { - NBTTagCompound compound = new NBTTagCompound(); - NBTTagList categoryList = new NBTTagList(); - for (DialogCategory category : DialogController.Instance.categories.values()) { - NBTTagCompound questCompound = new NBTTagCompound(); - NBTTagList dialogList = new NBTTagList(); - for (int dialogID : category.dialogs.keySet()) { - Dialog quest = category.dialogs.get(dialogID); - dialogList.appendTag(quest.writeToNBT(new NBTTagCompound())); - } - questCompound.setTag("Data", dialogList); - questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound())); - categoryList.appendTag(questCompound); - } - compound.setTag("DialogCategories", categoryList); - return compound; - } - - public static NBTTagCompound questCategoriesNBT() { - NBTTagCompound compound = new NBTTagCompound(); - NBTTagList categoryList = new NBTTagList(); - for (QuestCategory category : QuestController.Instance.categories.values()) { - NBTTagCompound questCompound = new NBTTagCompound(); - ; - NBTTagList questList = new NBTTagList(); - for (int questID : category.quests.keySet()) { - Quest quest = category.quests.get(questID); - questList.appendTag(quest.writeToNBT(new NBTTagCompound())); - } - questCompound.setTag("Data", questList); - questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound())); - categoryList.appendTag(questCompound); - } - compound.setTag("QuestCategories", categoryList); - return compound; - } - - public static NBTTagCompound customEffectsNBT() { - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (CustomEffect effect : CustomEffectController.getInstance().getCustomEffects().values()) { - list.appendTag(effect.writeToNBT(false)); - } - compound.setTag("Data", list); - return compound; - } - - public static NBTTagCompound magicsNBT() { - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (Magic magic : MagicController.getInstance().magics.values()) { - NBTTagCompound magicCompound = new NBTTagCompound(); - magic.writeNBT(magicCompound); - list.appendTag(magicCompound); - } - compound.setTag("Data", list); - return compound; - } - - public static NBTTagCompound magicCyclesNBT() { - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (MagicCycle cycle : MagicController.getInstance().cycles.values()) { - NBTTagCompound cycleCompound = new NBTTagCompound(); - cycle.writeNBT(cycleCompound); - list.appendTag(cycleCompound); - } - compound.setTag("Data", list); - return compound; - } - - public static NBTTagCompound customAbilitiesNBT() { - NBTTagList list = new NBTTagList(); - NBTTagCompound compound = new NBTTagCompound(); - for (Map.Entry entry : AbilityController.Instance.getCustomAbilities().entrySet()) { - NBTTagCompound abilityNBT = entry.getValue().writeNBT(); - abilityNBT.setString("CustomAbilityId", entry.getKey()); - list.appendTag(abilityNBT); - } - compound.setTag("Data", list); - return compound; - } - - public static void syncAllCustomAbilities() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.CUSTOM_ABILITY); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CUSTOM_ABILITY, payload)); - updateAllPlayerRevisions(EnumSyncType.CUSTOM_ABILITY, payload.getRevision()); - } - - public static void syncPlayerData(EntityPlayerMP player, boolean update) { - PlayerData data = PlayerData.get(player); - if (data != null) { - if (update) { - PacketHandler.Instance.sendToPlayer(new SyncPacket( - EnumSyncType.PLAYERDATA, - EnumSyncAction.UPDATE, - -1, - data.getSyncNBT()) - , player); - } else { - PacketHandler.Instance.sendToPlayer(new SyncPacket( - EnumSyncType.PLAYERDATA, - EnumSyncAction.RELOAD, - -1, - data.getSyncNBTFull()), player); - } - } - } - - public static void syncRemove(EnumSyncType enumSyncType, int id) { - Map revisions = invalidateCaches(enumSyncType); - int revision = revisions.getOrDefault(enumSyncType, getCurrentRevision(enumSyncType)); - PacketHandler.Instance.sendToAll(new SyncPacket( - enumSyncType, - EnumSyncAction.REMOVE, - id, - revision, - new NBTTagCompound() - )); - updateAllPlayerRevisions(revisions); - } - - public static void syncAllDialogs() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.DIALOG_CATEGORY); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.DIALOG_CATEGORY, payload)); - updateAllPlayerRevisions(EnumSyncType.DIALOG_CATEGORY, payload.getRevision()); - } - - public static void syncAllQuests() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.QUEST_CATEGORY); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.QUEST_CATEGORY, payload)); - updateAllPlayerRevisions(EnumSyncType.QUEST_CATEGORY, payload.getRevision()); - } - - public static void syncAllWorkbenchRecipes() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.WORKBENCH_RECIPES); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.WORKBENCH_RECIPES, payload)); - updateAllPlayerRevisions(EnumSyncType.WORKBENCH_RECIPES, payload.getRevision()); - } - - public static void syncAllCarpentryRecipes() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.CARPENTRY_RECIPES); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CARPENTRY_RECIPES, payload)); - updateAllPlayerRevisions(EnumSyncType.CARPENTRY_RECIPES, payload.getRevision()); - } - - public static void syncAllAnvilRecipes() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.ANVIL_RECIPES); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.ANVIL_RECIPES, payload)); - updateAllPlayerRevisions(EnumSyncType.ANVIL_RECIPES, payload.getRevision()); - } - - public static void syncAllCustomEffects() { - CachedSyncPayload payload = rebuildNow(EnumSyncType.CUSTOM_EFFECTS); - if (payload == null) { - return; - } - PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CUSTOM_EFFECTS, payload)); - updateAllPlayerRevisions(EnumSyncType.CUSTOM_EFFECTS, payload.getRevision()); - } - - @SideOnly(Side.CLIENT) - public static void clientSync(EnumSyncType enumSyncType, int revision, NBTTagCompound fullCompound) { - switch (enumSyncType) { - case FACTION: { - NBTTagList list = fullCompound.getTagList("Factions", 10); - for (int i = 0; i < list.tagCount(); i++) { - Faction faction = new Faction(); - faction.readNBT(list.getCompoundTagAt(i)); - FactionController.getInstance().factionsSync.put(faction.id, faction); - } - FactionController.getInstance().factions = FactionController.getInstance().factionsSync; - FactionController.getInstance().factionsSync = new HashMap(); - break; - } - case DIALOG_CATEGORY: { - if (!fullCompound.hasNoTags()) { - NBTTagList categories = fullCompound.getTagList("DialogCategories", 10); - for (int j = 0; j < fullCompound.getTagList("DialogCategories", 10).tagCount(); j++) { - NBTTagCompound categoryCompound = categories.getCompoundTagAt(j); - if (categoryCompound.hasNoTags()) - continue; - - DialogCategory category = new DialogCategory(); - category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); - NBTTagList dialogList = categoryCompound.getTagList("Data", 10); - if (DialogController.Instance.categoriesSync.containsKey(category.id)) { - category = DialogController.Instance.categoriesSync.get(category.id); - category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); - } - for (int i = 0; i < dialogList.tagCount(); i++) { - Dialog dialog = new Dialog(); - dialog.readNBT(dialogList.getCompoundTagAt(i)); - dialog.category = category; - category.dialogs.put(dialog.id, dialog); - } - DialogController.Instance.categoriesSync.put(category.id, category); - } - } - - HashMap dialogs = new HashMap(); - for (DialogCategory category : DialogController.Instance.categoriesSync.values()) { - for (Dialog dialog : category.dialogs.values()) { - dialogs.put(dialog.id, dialog); - } - } - - DialogController.Instance.categories = DialogController.Instance.categoriesSync; - DialogController.Instance.dialogs = dialogs; - DialogController.Instance.categoriesSync = new HashMap(); - break; - } - case QUEST_CATEGORY: { - if (!fullCompound.hasNoTags()) { - NBTTagList categories = fullCompound.getTagList("QuestCategories", 10); - for (int j = 0; j < fullCompound.getTagList("QuestCategories", 10).tagCount(); j++) { - NBTTagCompound categoryCompound = categories.getCompoundTagAt(j); - if (categoryCompound.hasNoTags()) - continue; - - QuestCategory category = new QuestCategory(); - category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); - NBTTagList questList = categoryCompound.getTagList("Data", 10); - if (QuestController.Instance.categoriesSync.containsKey(category.id)) { - category = QuestController.Instance.categoriesSync.get(category.id); - category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); - } - for (int i = 0; i < questList.tagCount(); i++) { - Quest quest = new Quest(); - quest.readNBT(questList.getCompoundTagAt(i)); - quest.category = category; - category.quests.put(quest.id, quest); - } - QuestController.Instance.categoriesSync.put(category.id, category); - } - } - - HashMap quests = new HashMap(); - for (QuestCategory category : QuestController.Instance.categoriesSync.values()) { - for (Quest quest : category.quests.values()) { - quests.put(quest.id, quest); - } - } - - QuestController.Instance.categories = QuestController.Instance.categoriesSync; - QuestController.Instance.quests = quests; - QuestController.Instance.categoriesSync = new HashMap(); - break; - } - case PLAYERDATA: { - ClientCacheHandler.playerData.setSyncNBTFull(fullCompound); - break; - } - case MAGIC: { - NBTTagList list = fullCompound.getTagList("Data", 10); - MagicController mc = MagicController.getInstance(); - mc.magicSync.clear(); - for (int i = 0; i < list.tagCount(); i++) { - Magic magic = new Magic(); - magic.readNBT(list.getCompoundTagAt(i)); - mc.magicSync.put(magic.id, magic); - } - - mc.magics.clear(); - mc.magics.putAll(mc.magicSync); - mc.magicSync.clear(); - break; - } - case MAGIC_CYCLE: { - NBTTagList list = fullCompound.getTagList("Data", 10); - MagicController mc = MagicController.getInstance(); - mc.cyclesSync.clear(); - for (int i = 0; i < list.tagCount(); i++) { - MagicCycle cycle = new MagicCycle(); - cycle.readNBT(list.getCompoundTagAt(i)); - mc.cyclesSync.put(cycle.id, cycle); - } - - mc.cycles.clear(); - mc.cycles.putAll(mc.cyclesSync); - mc.cyclesSync.clear(); - break; - } - case WORKBENCH_RECIPES: { - NBTTagList list = fullCompound.getTagList("recipes", 10); - if (list == null) - return; - - for (int i = 0; i < list.tagCount(); i++) { - NBTTagCompound recipeCompound = list.getCompoundTagAt(i); - RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound); - recipe.readNBT(recipeCompound); - RecipeController.syncRecipes.put(recipe.id, recipe); - } - - RecipeController.reloadGlobalRecipes(RecipeController.syncRecipes); - RecipeController.syncRecipes = new HashMap(); - break; - } - case CARPENTRY_RECIPES: { - NBTTagList list = fullCompound.getTagList("recipes", 10); - if (list == null) - return; - - for (int i = 0; i < list.tagCount(); i++) { - NBTTagCompound recipeCompound = list.getCompoundTagAt(i); - RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound); - recipe.readNBT(recipeCompound); - RecipeController.syncRecipes.put(recipe.id, recipe); - } - - RecipeController.Instance.carpentryRecipes = RecipeController.syncRecipes; - RecipeController.syncRecipes = new HashMap(); - break; - } - case ANVIL_RECIPES: { - NBTTagList list = fullCompound.getTagList("recipes", 10); - if (list == null) - return; - - for (int i = 0; i < list.tagCount(); i++) { - RecipeAnvil recipe = new RecipeAnvil(); - recipe.readNBT(list.getCompoundTagAt(i)); - RecipeController.syncAnvilRecipes.put(recipe.id, recipe); - } - - RecipeController.Instance.anvilRecipes = RecipeController.syncAnvilRecipes; - RecipeController.syncAnvilRecipes = new HashMap(); - break; - } - case CUSTOM_EFFECTS: { - NBTTagList list = fullCompound.getTagList("Data", 10); - CustomEffectController ce = CustomEffectController.getInstance(); - ce.customEffectsSync.clear(); - for (int i = 0; i < list.tagCount(); i++) { - CustomEffect effect = new CustomEffect(); - effect.readFromNBT(list.getCompoundTagAt(i)); - ClientCacheHandler.getImageData(effect.icon); - ce.customEffectsSync.put(effect.id, effect); - } - - ce.getCustomEffects().clear(); - ce.getCustomEffects().putAll(ce.customEffectsSync); - ce.customEffectsSync.clear(); - break; - } - case CUSTOM_ABILITY: { - NBTTagList list = fullCompound.getTagList("Data", 10); - LinkedHashMap sync = new LinkedHashMap<>(); - for (int i = 0; i < list.tagCount(); i++) { - NBTTagCompound nbt = list.getCompoundTagAt(i); - String uuid = nbt.getString("CustomAbilityId"); - Ability ability = AbilityController.Instance.fromNBT(nbt); - if (ability != null) { - ability.setId(uuid); - sync.put(uuid, ability); - } - } - AbilityController.Instance.setCustomAbilities(sync); - break; - } - } - - ClientCacheHandler.updateClientRevision(enumSyncType, revision); + sendPostLoginPackets(player); } /** - * Update Related Tasks + * Completes the server-side revision handshake that follows {@link LoginPacket}. + * + * The client reports which cached revisions it believes are still valid for the + * current server identity. If the reported server identity is stale or missing, + * we reset the stored state and force a full cached resync. Otherwise we seed the + * player's tracked revisions from the client report and only send outdated families. */ - @SideOnly(Side.CLIENT) - public static void clientUpdate(EnumSyncType enumSyncType, int category_id, int revision, NBTTagCompound compound) { - switch (enumSyncType) { - case FACTION: { - Faction faction = new Faction(); - faction.readNBT(compound); - FactionController.getInstance().factions.put(faction.id, faction); - break; - } - case DIALOG: { - DialogCategory category = DialogController.Instance.categories.get(category_id); - Dialog dialog = new Dialog(); - dialog.category = category; - dialog.readNBT(compound); - DialogController.Instance.dialogs.put(dialog.id, dialog); - category.dialogs.put(dialog.id, dialog); - break; - } - case QUEST: { - QuestCategory category = QuestController.Instance.categories.get(category_id); - Quest quest = new Quest(); - quest.category = category; - quest.readNBT(compound); - QuestController.Instance.quests.put(quest.id, quest); - category.quests.put(quest.id, quest); - break; - } - case QUEST_CATEGORY: { - QuestCategory category = new QuestCategory(); - category.readSmallNBT(compound.getCompoundTag("CatNBT")); - NBTTagList list = compound.getTagList("Data", 10); - if (QuestController.Instance.categoriesSync.containsKey(category.id)) { - category = QuestController.Instance.categoriesSync.get(category.id); - category.readSmallNBT(compound.getCompoundTag("CatNBT")); - } - for (int i = 0; i < list.tagCount(); i++) { - Quest quest = new Quest(); - quest.readNBT(list.getCompoundTagAt(i)); - quest.category = category; - category.quests.put(quest.id, quest); - } - QuestController.Instance.categories.put(category.id, category); - break; - } - case DIALOG_CATEGORY: { - DialogCategory category = new DialogCategory(); - category.readSmallNBT(compound.getCompoundTag("CatNBT")); - NBTTagList list = compound.getTagList("Data", 10); - if (DialogController.Instance.categoriesSync.containsKey(category.id)) { - category = DialogController.Instance.categoriesSync.get(category.id); - category.readSmallNBT(compound.getCompoundTag("CatNBT")); - } - for (int i = 0; i < list.tagCount(); i++) { - Dialog dialog = new Dialog(); - dialog.readNBT(list.getCompoundTagAt(i)); - dialog.category = category; - category.dialogs.put(dialog.id, dialog); - } - DialogController.Instance.categories.put(category.id, category); - break; - } - case MAGIC_CYCLE: { - MagicCycle cycle = new MagicCycle(); - cycle.readNBT(compound); - MagicController.getInstance().cycles.put(cycle.id, cycle); - break; - } - case MAGIC: { - Magic magic = new Magic(); - magic.readNBT(compound); - MagicController.getInstance().magics.put(magic.id, magic); - break; - } - case PLAYERDATA: { - ClientCacheHandler.playerData.setSyncNBT(compound); - break; - } - case CUSTOM_EFFECTS: { - CustomEffect effect = new CustomEffect(); - effect.readFromNBT(compound); - ClientCacheHandler.getImageData(effect.icon); + public static void completeLoginRevisionHandshake(EntityPlayerMP player, String serverKey, String previousServerKey, + Map clientRevisions) { + String currentServerKey = getServerCacheKey(); + PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); - CustomEffectController.Instance.getCustomEffects().put(effect.id, effect); - break; - } - } + boolean serverIdentityMismatch = !currentServerKey.equals(serverKey); + boolean previousServerMismatch = !currentServerKey.isEmpty() && (previousServerKey == null || !currentServerKey.equals( + previousServerKey)); + boolean canReuseClientRevisions = clientRevisions != null && !clientRevisions.isEmpty(); - ClientCacheHandler.updateClientRevision(enumSyncType, revision); + // Any server identity mismatch means the client's cached revision map is unsafe to reuse. + if (serverIdentityMismatch || previousServerMismatch || !canReuseClientRevisions) + state.reset(); + else // The client and server agree on identity, so seed the stored state from the report. + state.applyHandshake(clientRevisions); + + dispatchSyncForAllTypes(player); } - public static void syncUpdate(EnumSyncType type, int cat, NBTTagCompound compound) { - Map revisions = invalidateCaches(type); - int revision = revisions.getOrDefault(type, getCurrentRevision(type)); - PacketHandler.Instance.sendToAll(new SyncPacket( - type, - EnumSyncAction.UPDATE, - cat, - revision, - compound - )); + + // ═══════════════════════════════════════════════════════════════════════ + // Generic dispatcher — called from outside SyncController + // ═══════════════════════════════════════════════════════════════════════ + + /** + * Generic full-broadcast helper. Rebuilds the cache for the given type + * and sends to all connected players. + */ + public static void syncAll(SyncType type) { + CachedSyncPayload payload = rebuildCache(type); + if (payload == null) return; + + PacketHandler.Instance.sendToAll(new SyncPacket(type, payload)); + updateAllPlayerRevisions(type, payload.getRevision()); + } + + // ═══════════════════════════════════════════════════════════════════════ + // Player data sync + // ═══════════════════════════════════════════════════════════════════════ + + public static void syncPlayerData(SyncType type, NBTTagCompound compound, boolean fullData, EntityPlayerMP player) { + Map revisions = invalidateCaches(type); + int revision = getRequestedInvalidationRevision(type, revisions); + PacketHandler.Instance.sendToPlayer( + new SyncPacket(type, EnumSyncAction.UPDATE, fullData ? 1 : 0, null, revision, compound), player); + updateAllPlayerRevisions(revisions); + } + + // ═══════════════════════════════════════════════════════════════════════ + // Server-side dispatchers — registry-driven + // ═══════════════════════════════════════════════════════════════════════ + public static void syncUpdate(SyncType type, NBTTagCompound compound) { + Map revisions = invalidateCaches(type); + int revision = getRequestedInvalidationRevision(type, revisions); + PacketHandler.Instance.sendToAll(new SyncPacket(type, EnumSyncAction.UPDATE, -1, null, revision, compound)); + updateAllPlayerRevisions(revisions); + } + + public static void syncUpdate(SyncType type, String key, NBTTagCompound compound) { + Map revisions = invalidateCaches(type); + int revision = getRequestedInvalidationRevision(type, revisions); + PacketHandler.Instance.sendToAll(new SyncPacket(type, EnumSyncAction.UPDATE, -1, key, revision, compound)); + updateAllPlayerRevisions(revisions); + } + + public static void syncUpdate(SyncType type, int cat, NBTTagCompound compound) { + Map revisions = invalidateCaches(type); + int revision = getRequestedInvalidationRevision(type, revisions); + PacketHandler.Instance.sendToAll(new SyncPacket(type, EnumSyncAction.UPDATE, cat, null, revision, compound)); + updateAllPlayerRevisions(revisions); + } + + public static void syncRemove(SyncType syncType, String key) { + Map revisions = invalidateCaches(syncType); + int revision = getRequestedInvalidationRevision(syncType, revisions); + PacketHandler.Instance.sendToAll(new SyncPacket(syncType, EnumSyncAction.REMOVE, -1, key, revision, null)); + updateAllPlayerRevisions(revisions); + } + + public static void syncRemove(SyncType syncType, int id) { + Map revisions = invalidateCaches(syncType); + int revision = getRequestedInvalidationRevision(syncType, revisions); + PacketHandler.Instance.sendToAll(new SyncPacket(syncType, EnumSyncAction.REMOVE, id, null, revision, null)); updateAllPlayerRevisions(revisions); } - public static NBTTagCompound updateQuestCat(QuestCategory questCategory) { - NBTTagCompound questCompound = new NBTTagCompound(); - NBTTagList questList = new NBTTagList(); - for (int questID : questCategory.quests.keySet()) { - Quest quest = questCategory.quests.get(questID); - questList.appendTag(quest.writeToNBT(new NBTTagCompound())); - } - questCompound.setTag("Data", questList); - questCompound.setTag("CatNBT", questCategory.writeSmallNBT(new NBTTagCompound())); - return questCompound; - } + // ═══════════════════════════════════════════════════════════════════════ + // Client-side handlers — registry-driven handler delegation + // ═══════════════════════════════════════════════════════════════════════ - public static NBTTagCompound updateDialogCat(DialogCategory dialogCategory) { - NBTTagCompound dialogCompound = new NBTTagCompound(); - NBTTagList dialogList = new NBTTagList(); - for (int questID : dialogCategory.dialogs.keySet()) { - Dialog dialog = dialogCategory.dialogs.get(questID); - dialogList.appendTag(dialog.writeToNBT(new NBTTagCompound())); + @SideOnly(Side.CLIENT) + public static void clientHandleAll(SyncType syncType, int revision, NBTTagCompound fullCompound) { + SyncHandler handler = SyncRegistry.getHandler(syncType); + if (handler == null) return; + try { + handler.clientHandleReload(fullCompound); + } catch (Exception e) { + LogWriter.error("[SyncController] Failed to handle RELOAD for sync type " + syncType, e); } - dialogCompound.setTag("Data", dialogList); - dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound())); - return dialogCompound; + ClientCacheHandler.updateClientRevision(syncType, revision); + } @SideOnly(Side.CLIENT) - public static void clientSyncRemove(EnumSyncType enumSyncType, int id, int revision) { - switch (enumSyncType) { - case FACTION: - FactionController.getInstance().factions.remove(id); - break; - case DIALOG: - Dialog dialog = DialogController.Instance.dialogs.remove(id); - if (dialog != null) { - dialog.category.dialogs.remove(id); - } - break; - case DIALOG_CATEGORY: - DialogCategory dialogCategory = DialogController.Instance.categories.remove(id); - if (dialogCategory != null) { - DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet()); - } - break; - case QUEST: - Quest quest = QuestController.Instance.quests.remove(id); - if (quest != null) { - quest.category.quests.remove(id); - } - break; - case QUEST_CATEGORY: - QuestCategory questCategory = QuestController.Instance.categories.remove(id); - if (questCategory != null) { - QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet()); - } - break; - case MAGIC: - for (MagicCycle cycle : MagicController.getInstance().cycles.values()) { - cycle.associations.remove(id); - } - MagicController.getInstance().cycles.remove(id); - break; - case MAGIC_CYCLE: - MagicController.getInstance().cycles.remove(id); - break; - case CUSTOM_EFFECTS: - CustomEffectController.Instance.getCustomEffects().remove(id); - break; + public static void clientHandleUpdate(SyncType syncType, int id, String key, int revision, NBTTagCompound compound) { + SyncHandler handler = SyncRegistry.getHandler(syncType); + if (handler == null) return; + try { + handler.clientHandleUpdate(compound); + handler.clientHandleUpdate(compound, id); + handler.clientHandleUpdate(compound, key); + } catch (Exception e) { + LogWriter.error("[SyncController] Failed to handle UPDATE for sync type " + syncType, e); } - - ClientCacheHandler.updateClientRevision(enumSyncType, revision); - } - - public static void syncEffects(EntityPlayerMP playerMP) { - ConcurrentHashMap playerEffects = CustomEffectController.getInstance().getPlayerEffects(playerMP); - PlayerData playerData = PlayerData.get(playerMP); - playerData.effectData.setEffects(playerEffects); - - NBTTagCompound compound = playerData.getPlayerEffects(); - PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP); + + ClientCacheHandler.updateClientRevision(syncType, revision); + + // New GUI data handling approach + IGuiData.notifyUpdate(compound, key, id); } @SideOnly(Side.CLIENT) - public static void clientSyncEffects(NBTTagCompound compound) { - PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer); - if (playerData != null) { - playerData.setPlayerEffects(compound); + public static void clientHandleRemove(SyncType syncType, int id, String key, int revision) { + SyncHandler handler = SyncRegistry.getHandler(syncType); + if (handler == null) return; + try { + handler.clientHandleRemove(id); + handler.clientHandleRemove(key); + } catch (Exception e) { + LogWriter.error("[SyncController] Failed to handle REMOVE for sync type " + syncType, e); } + + ClientCacheHandler.updateClientRevision(syncType, revision); + + // New GUI data handling approach + IGuiData.notifyRemove(key, id); } - private static void registerCache(EnumSyncType type, Supplier supplier) { - cacheEntries.put(type, new SyncCacheEntry(type, supplier)); + // ═══════════════════════════════════════════════════════════════════════ + // Cache and revision internals + // ═══════════════════════════════════════════════════════════════════════ + + private static void registerCache(SyncType type, Supplier supplier) { + cacheEntries.put(type, new SyncCacheEntry(supplier)); } - private static CachedSyncPayload rebuildNow(EnumSyncType type) { + private static CachedSyncPayload rebuildCache(SyncType type) { SyncCacheEntry entry = cacheEntries.get(type); - if (entry == null) { - return null; - } + if (entry == null) return null; + entry.invalidate(); return entry.getPayload(type); } - public static Map invalidateCaches(EnumSyncType type) { - EnumSet targets = getInvalidationTargets(type); - EnumMap revisions = new EnumMap<>(EnumSyncType.class); - for (EnumSyncType target : targets) { + /** + * Registry-driven invalidation: delegates to handler-owned + * invalidation targets via {@link SyncRegistry#getInvalidationTargets}. + */ + private static Map invalidateCaches(SyncType type) { + Set targets = SyncRegistry.getInvalidationTargets(type); + Map revisions = new LinkedHashMap<>(); + for (SyncType target : targets) { SyncCacheEntry entry = cacheEntries.get(target); if (entry != null) { int newRevision = entry.invalidate(); @@ -862,55 +347,55 @@ public class SyncController { return revisions; } - private static EnumSet getInvalidationTargets(EnumSyncType type) { - switch (type) { - case DIALOG: - case DIALOG_CATEGORY: - return EnumSet.of(EnumSyncType.DIALOG_CATEGORY); - case QUEST: - case QUEST_CATEGORY: - return EnumSet.of(EnumSyncType.QUEST_CATEGORY); - case FACTION: - return EnumSet.of(EnumSyncType.FACTION); - case MAGIC: - return EnumSet.of(EnumSyncType.MAGIC); - case MAGIC_CYCLE: - return EnumSet.of(EnumSyncType.MAGIC_CYCLE); - case WORKBENCH_RECIPES: - return EnumSet.of(EnumSyncType.WORKBENCH_RECIPES); - case CARPENTRY_RECIPES: - return EnumSet.of(EnumSyncType.CARPENTRY_RECIPES); - case ANVIL_RECIPES: - return EnumSet.of(EnumSyncType.ANVIL_RECIPES); - case CUSTOM_EFFECTS: - return EnumSet.of(EnumSyncType.CUSTOM_EFFECTS); - case CUSTOM_ABILITY: - return EnumSet.of(EnumSyncType.CUSTOM_ABILITY); - default: - return EnumSet.noneOf(EnumSyncType.class); - } + private static int getRequestedInvalidationRevision(SyncType type, Map revisions) { + Integer revision = revisions.get(type); + return revision != null ? revision : getCurrentServerRevision(type); } - private static void updateAllPlayerRevisions(EnumSyncType type, int revision) { - if (revision < 0) { - return; + public static int getCurrentServerRevision(SyncType type) { + SyncCacheEntry entry = cacheEntries.get(type); + return entry == null ? -1 : entry.getRevisionValue(); + } + + private static Map getServerRevisionSnapshot() { + // Registry-driven: iterate login types from registry + Map snapshot = new LinkedHashMap<>(); + for (SyncType type : SyncRegistry.getLoginTypes()) { + SyncCacheEntry entry = cacheEntries.get(type); + if (entry != null) + snapshot.put(type, entry.getRevisionValue()); } - for (PlayerSyncState state : playerSyncState.values()) { + return snapshot; + } + + private static void updateAllPlayerRevisions(SyncType type, int revision) { + if (revision < 0) return; + + for (PlayerSyncState state : playerSyncState.values()) state.updateRevision(type, revision); + } + + private static void updateAllPlayerRevisions(Map revisions) { + if (revisions.isEmpty()) return; + + for (PlayerSyncState state : playerSyncState.values()) { + for (Map.Entry entry : revisions.entrySet()) + state.updateRevision(entry.getKey(), entry.getValue()); } } - private static void updateAllPlayerRevisions(Map revisions) { - if (revisions.isEmpty()) { - return; - } - for (PlayerSyncState state : playerSyncState.values()) { - for (Map.Entry entry : revisions.entrySet()) { - state.updateRevision(entry.getKey(), entry.getValue()); - } - } + private static String getServerCacheKey() { + MinecraftServer server = MinecraftServer.getServer(); + if (server == null || !server.isDedicatedServer()) return ""; + + return SERVER_IDENTITY_KEY; } + + // ═══════════════════════════════════════════════════════════════════════ + // Inner classes — cache payload and player revision state + // ═══════════════════════════════════════════════════════════════════════ + public static final class CachedSyncPayload { private final int revision; private final byte[] payload; @@ -941,20 +426,19 @@ public class SyncController { private int revision = 0; private boolean dirty = true; - private SyncCacheEntry(EnumSyncType type, Supplier supplier) { + private SyncCacheEntry(Supplier supplier) { this.supplier = supplier; } - private synchronized CachedSyncPayload getPayload(EnumSyncType requestedType) { - if (!dirty && payload != null) { - return payload; - } + private synchronized CachedSyncPayload getPayload(SyncType requestedType) { + if (!dirty && payload != null) return payload; int payloadRevision = revision; - NBTTagCompound data = supplier.get(); ByteBuf buffer = Unpooled.buffer(); byte[] bytes; try { + NBTTagCompound data = supplier.get(); + buffer.writeInt(requestedType.ordinal()); buffer.writeInt(EnumSyncAction.RELOAD.ordinal()); buffer.writeInt(-1); @@ -963,8 +447,9 @@ public class SyncController { bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); - } catch (IOException e) { - throw new RuntimeException("Failed to serialize sync payload for " + requestedType, e); + } catch (Exception e) { + LogWriter.error("Failed to serialize sync payload for " + requestedType, e); + return null; } finally { buffer.release(); } @@ -975,6 +460,23 @@ public class SyncController { return payload; } + private static byte[][] splitIntoChunks(byte[] payload) { + int totalSize = payload.length; + int chunkCount = (totalSize + LargeAbstractPacket.CHUNK_SIZE - 1) / LargeAbstractPacket.CHUNK_SIZE; + if (chunkCount <= 0) + chunkCount = 1; + + byte[][] chunks = new byte[chunkCount][]; + for (int i = 0; i < chunkCount; i++) { + int offset = i * LargeAbstractPacket.CHUNK_SIZE; + int length = Math.min(LargeAbstractPacket.CHUNK_SIZE, totalSize - offset); + byte[] chunk = new byte[length]; + System.arraycopy(payload, offset, chunk, 0, length); + chunks[i] = chunk; + } + return chunks; + } + private synchronized int invalidate() { dirty = true; payload = null; @@ -991,50 +493,30 @@ public class SyncController { payload = null; revision = 0; } - - private static byte[][] splitIntoChunks(byte[] payload) { - int totalSize = payload.length; - int chunkCount = (totalSize + LargeAbstractPacket.CHUNK_SIZE - 1) / LargeAbstractPacket.CHUNK_SIZE; - if (chunkCount <= 0) { - chunkCount = 1; - } - byte[][] chunks = new byte[chunkCount][]; - for (int i = 0; i < chunkCount; i++) { - int offset = i * LargeAbstractPacket.CHUNK_SIZE; - int length = Math.min(LargeAbstractPacket.CHUNK_SIZE, totalSize - offset); - byte[] chunk = new byte[length]; - System.arraycopy(payload, offset, chunk, 0, length); - chunks[i] = chunk; - } - return chunks; - } } private static final class PlayerSyncState { - private final EnumMap revisions = new EnumMap<>(EnumSyncType.class); + private final Map revisions = new HashMap<>(); private PlayerSyncState(UUID ignored) { } - private synchronized int getRevision(EnumSyncType type) { + private synchronized int getRevision(SyncType type) { Integer value = revisions.get(type); return value == null ? -1 : value; } - private synchronized void updateRevision(EnumSyncType type, int revision) { + private synchronized void updateRevision(SyncType type, int revision) { revisions.put(type, revision); } - private synchronized void applyHandshake(Map incoming) { - if (incoming == null || incoming.isEmpty()) { - return; - } + private synchronized void applyHandshake(Map incoming) { + if (incoming == null || incoming.isEmpty()) return; revisions.putAll(incoming); } private synchronized void reset() { revisions.clear(); } - } } diff --git a/src/main/java/kamkeel/npcs/controllers/SyncControllerOld.java b/src/main/java/kamkeel/npcs/controllers/SyncControllerOld.java new file mode 100644 index 000000000..05f37e8e9 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/SyncControllerOld.java @@ -0,0 +1,1058 @@ +//package kamkeel.npcs.controllers; +// +//import cpw.mods.fml.relauncher.Side; +//import cpw.mods.fml.relauncher.SideOnly; +//import io.netty.buffer.ByteBuf; +//import io.netty.buffer.Unpooled; +//import kamkeel.npcs.addon.DBCAddon; +//import kamkeel.npcs.controllers.data.ability.Ability; +//import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +//import kamkeel.npcs.network.LargeAbstractPacket; +//import kamkeel.npcs.network.PacketHandler; +//import kamkeel.npcs.network.enums.EnumSyncAction; +//import kamkeel.npcs.network.enums.SyncType; +//import kamkeel.npcs.network.packets.data.LoginPacket; +//import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket; +//import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; +//import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +//import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; +//import kamkeel.npcs.network.packets.data.large.SyncEffectPacket; +//import kamkeel.npcs.network.packets.data.large.SyncPacket; +//import kamkeel.npcs.network.packets.request.party.PartyInfoPacket; +//import kamkeel.npcs.util.ByteBufUtils; +//import net.minecraft.client.Minecraft; +//import net.minecraft.entity.player.EntityPlayerMP; +//import net.minecraft.nbt.NBTTagCompound; +//import net.minecraft.nbt.NBTTagList; +//import net.minecraft.server.MinecraftServer; +//import noppes.npcs.client.ClientCacheHandler; +//import noppes.npcs.controllers.*; +//import noppes.npcs.controllers.data.*; +// +//import java.io.IOException; +//import java.util.*; +//import java.util.concurrent.ConcurrentHashMap; +//import java.util.function.Supplier; +// +//public class SyncControllerOld { +// +// public static boolean DEBUG_SYNC_LOGGING = false; +// +// private static final Map cacheEntries = new LinkedHashMap<>(); +// private static final ConcurrentHashMap playerSyncState = new ConcurrentHashMap<>(); +// +// +// private static void debug(String message, Object... args) { +// if (DEBUG_SYNC_LOGGING) { +// System.out.println("[SyncController] " + String.format(message, args)); +// } +// } +// +// private static final SyncType[] LOGIN_SYNC_TYPES = new SyncType[]{ +// SyncType.FACTION, +// SyncType.DIALOG_CATEGORY, +// SyncType.QUEST_CATEGORY, +// SyncType.WORKBENCH_RECIPES, +// SyncType.CARPENTRY_RECIPES, +// SyncType.ANVIL_RECIPES, +// SyncType.CUSTOM_EFFECTS, +// SyncType.MAGIC, +// SyncType.MAGIC_CYCLE, +// SyncType.CUSTOM_ABILITY, +// SyncType.CHAINED_ABILITY +// }; +// +// public static void load() { +// cacheEntries.clear(); +// playerSyncState.clear(); +// +// registerCache(SyncType.FACTION, SyncControllerOld::factionsNBT); +// registerCache(SyncType.DIALOG_CATEGORY, SyncControllerOld::dialogCategoriesNBT); +// registerCache(SyncType.QUEST_CATEGORY, SyncControllerOld::questCategoriesNBT); +// registerCache(SyncType.WORKBENCH_RECIPES, SyncControllerOld::workbenchNBT); +// registerCache(SyncType.CARPENTRY_RECIPES, SyncControllerOld::carpentryNBT); +// registerCache(SyncType.ANVIL_RECIPES, SyncControllerOld::anvilNBT); +// registerCache(SyncType.CUSTOM_EFFECTS, SyncControllerOld::customEffectsNBT); +// registerCache(SyncType.MAGIC, SyncControllerOld::magicsNBT); +// registerCache(SyncType.MAGIC_CYCLE, SyncControllerOld::magicCyclesNBT); +// registerCache(SyncType.CUSTOM_ABILITY, SyncControllerOld::customAbilitiesNBT); +// registerCache(SyncType.CHAINED_ABILITY, SyncControllerOld::chainedAbilitiesNBT); +// } +// +// public static void syncPlayer(EntityPlayerMP player) { +// SyncControllerOld.syncPlayerInternal(player, true); +// } +// +// private static void syncPlayerInternal(EntityPlayerMP player, boolean includePostPackets) { +// PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); +// +// for (SyncType type : LOGIN_SYNC_TYPES) { +// SyncCacheEntry entry = cacheEntries.get(type); +// if (entry == null) { +// continue; +// } +// +// int currentRevision = entry.getRevisionValue(); +// int lastRevision = state.getRevision(type); +// if (lastRevision == currentRevision) { +// continue; +// } +// +// CachedSyncPayload payload = entry.getPayload(type); +// if (payload == null) { +// continue; +// } +// +// if (lastRevision != payload.getRevision()) { +// debug("Sending %s data to %s", type, player.getCommandSenderName()); +// PacketHandler.Instance.sendToPlayer(new SyncPacket(type, payload), player); +// state.updateRevision(type, payload.getRevision()); +// } +// } +// +// if (includePostPackets) { +// sendPostLoginPackets(player); +// } +// } +// +// public static void beginLogin(EntityPlayerMP player) { +// playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); +// PacketHandler.Instance.sendToPlayer( +// new LoginPacket(getServerCacheKey(), getServerRevisionSnapshot()), +// player +// ); +// } +// +// public static void handleClientRevisionReport( +// EntityPlayerMP player, +// String serverKey, +// String previousServerKey, +// Map clientRevisions +// ) { +// String currentServerKey = getServerCacheKey(); +// PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new); +// +// if (!currentServerKey.equals(serverKey)) { +// state.reset(); +// syncPlayer(player); +// return; +// } +// +// if (!currentServerKey.isEmpty()) { +// if (previousServerKey == null || !currentServerKey.equals(previousServerKey)) { +// state.reset(); +// syncPlayer(player); +// return; +// } +// } +// +// if (clientRevisions == null || clientRevisions.isEmpty()) { +// debug( +// "Client %s reported no cached revisions; forcing full sync", +// player.getCommandSenderName() +// ); +// state.reset(); +// } else { +// state.applyHandshake(clientRevisions); +// } +// +// syncPlayer(player); +// } +// +// private static void sendPostLoginPackets(EntityPlayerMP player) { +// DBCAddon.instance.syncPlayer(player); +// syncPlayerData(player, false); +// PartyInfoPacket.sendPartyData(player); +// ProfileSharedQuestPacket.sendToPlayer(player); +// +// // Sync skin overlays after full handshake to ensure the client is ready. +// // Overlays are not part of getSyncNBTFull(), and packets sent during +// // PlayerLoggedInEvent can arrive before the client entity exists. +// PlayerData data = PlayerData.get(player); +// if (data != null) { +// data.skinOverlays.updateClient(); +// } +// } +// +// private static Map getServerRevisionSnapshot() { +// Map snapshot = new LinkedHashMap<>(); +// for (SyncType type : LOGIN_SYNC_TYPES) { +// SyncCacheEntry entry = cacheEntries.get(type); +// if (entry != null) { +// snapshot.put(type, entry.getRevisionValue()); +// } +// } +// return snapshot; +// } +// +// private static final String SERVER_IDENTITY_KEY = UUID.randomUUID().toString(); +// +// private static String getServerCacheKey() { +// MinecraftServer server = MinecraftServer.getServer(); +// if (server == null) { +// return ""; +// } +// +// if (!server.isDedicatedServer()) { +// return ""; +// } +// +// return SERVER_IDENTITY_KEY; +// } +// +// public static int getCurrentRevision(SyncType type) { +// SyncCacheEntry entry = cacheEntries.get(type); +// return entry == null ? -1 : entry.getRevisionValue(); +// } +// +// public static NBTTagCompound workbenchNBT() { +// RecipeController controller = RecipeController.Instance; +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (RecipeCarpentry recipe : controller.globalRecipes.values()) { +// list.appendTag(recipe.writeNBT(false)); +// } +// compound.setTag("recipes", list); +// return compound; +// } +// +// public static NBTTagCompound carpentryNBT() { +// RecipeController controller = RecipeController.Instance; +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (RecipeCarpentry recipe : controller.carpentryRecipes.values()) { +// list.appendTag(recipe.writeNBT(false)); +// } +// compound.setTag("recipes", list); +// return compound; +// } +// +// public static NBTTagCompound anvilNBT() { +// RecipeController controller = RecipeController.Instance; +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (RecipeAnvil recipe : controller.anvilRecipes.values()) { +// list.appendTag(recipe.writeNBT(false)); +// } +// compound.setTag("recipes", list); +// return compound; +// } +// +// public static NBTTagCompound factionsNBT() { +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (Faction faction : FactionController.getInstance().factions.values()) { +// NBTTagCompound factioNBT = new NBTTagCompound(); +// faction.writeNBT(factioNBT); +// list.appendTag(factioNBT); +// } +// compound.setTag("Factions", list); +// return compound; +// } +// +// public static NBTTagCompound dialogCategoriesNBT() { +// NBTTagCompound compound = new NBTTagCompound(); +// NBTTagList categoryList = new NBTTagList(); +// for (DialogCategory category : DialogController.Instance.categories.values()) { +// NBTTagCompound questCompound = new NBTTagCompound(); +// NBTTagList dialogList = new NBTTagList(); +// for (int dialogID : category.dialogs.keySet()) { +// Dialog quest = category.dialogs.get(dialogID); +// dialogList.appendTag(quest.writeToNBT(new NBTTagCompound())); +// } +// questCompound.setTag("Data", dialogList); +// questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound())); +// categoryList.appendTag(questCompound); +// } +// compound.setTag("DialogCategories", categoryList); +// return compound; +// } +// +// public static NBTTagCompound questCategoriesNBT() { +// NBTTagCompound compound = new NBTTagCompound(); +// NBTTagList categoryList = new NBTTagList(); +// for (QuestCategory category : QuestController.Instance.categories.values()) { +// NBTTagCompound questCompound = new NBTTagCompound(); +// ; +// NBTTagList questList = new NBTTagList(); +// for (int questID : category.quests.keySet()) { +// Quest quest = category.quests.get(questID); +// questList.appendTag(quest.writeToNBT(new NBTTagCompound())); +// } +// questCompound.setTag("Data", questList); +// questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound())); +// categoryList.appendTag(questCompound); +// } +// compound.setTag("QuestCategories", categoryList); +// return compound; +// } +// +// public static NBTTagCompound customEffectsNBT() { +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (CustomEffect effect : CustomEffectController.getInstance().getCustomEffects().values()) { +// list.appendTag(effect.writeToNBT(false)); +// } +// compound.setTag("Data", list); +// return compound; +// } +// +// public static NBTTagCompound magicsNBT() { +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (Magic magic : MagicController.getInstance().magics.values()) { +// NBTTagCompound magicCompound = new NBTTagCompound(); +// magic.writeNBT(magicCompound); +// list.appendTag(magicCompound); +// } +// compound.setTag("Data", list); +// return compound; +// } +// +// public static NBTTagCompound magicCyclesNBT() { +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (MagicCycle cycle : MagicController.getInstance().cycles.values()) { +// NBTTagCompound cycleCompound = new NBTTagCompound(); +// cycle.writeNBT(cycleCompound); +// list.appendTag(cycleCompound); +// } +// compound.setTag("Data", list); +// return compound; +// } +// +// public static NBTTagCompound customAbilitiesNBT() { +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (Map.Entry entry : AbilityController.Instance.getCustomAbilities().entrySet()) { +// NBTTagCompound abilityNBT = entry.getValue().writeNBT(false); +// abilityNBT.setString("CustomAbilityId", entry.getKey()); +// list.appendTag(abilityNBT); +// } +// compound.setTag("Data", list); +// return compound; +// } +// +// public static void syncAllCustomAbilities() { +// CachedSyncPayload payload = rebuildNow(SyncType.CUSTOM_ABILITY); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CUSTOM_ABILITY, payload)); +// updateAllPlayerRevisions(SyncType.CUSTOM_ABILITY, payload.getRevision()); +// } +// +// public static NBTTagCompound chainedAbilitiesNBT() { +// NBTTagList list = new NBTTagList(); +// NBTTagCompound compound = new NBTTagCompound(); +// for (Map.Entry entry : AbilityController.Instance.getChainedAbilities().entrySet()) { +// NBTTagCompound chainNBT = entry.getValue().writeNBT(false); +// chainNBT.setString("ChainedAbilityId", entry.getKey()); +// list.appendTag(chainNBT); +// } +// compound.setTag("Data", list); +// return compound; +// } +// +// public static void syncAllChainedAbilities() { +// CachedSyncPayload payload = rebuildNow(SyncType.CHAINED_ABILITY); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CHAINED_ABILITY, payload)); +// updateAllPlayerRevisions(SyncType.CHAINED_ABILITY, payload.getRevision()); +// } +// +// public static void syncPlayerData(EntityPlayerMP player, boolean update) { +// PlayerData data = PlayerData.get(player); +// if (data != null) { +// if (update) { +// PacketHandler.Instance.sendToPlayer(new SyncPacket( +// SyncType.PLAYERDATA, +// EnumSyncAction.UPDATE, +// -1, +// data.getSyncNBT()) +// , player); +// } else { +// PacketHandler.Instance.sendToPlayer(new SyncPacket( +// SyncType.PLAYERDATA, +// EnumSyncAction.RELOAD, +// -1, +// data.getSyncNBTFull()), player); +// } +// } +// } +// +// public static void syncRemove(SyncType syncType, int id) { +// Map revisions = invalidateCaches(syncType); +// int revision = revisions.getOrDefault(syncType, getCurrentRevision(syncType)); +// PacketHandler.Instance.sendToAll(new SyncPacket( +// syncType, +// EnumSyncAction.REMOVE, +// id, +// revision, +// new NBTTagCompound() +// )); +// updateAllPlayerRevisions(revisions); +// } +// +// public static void syncAllDialogs() { +// CachedSyncPayload payload = rebuildNow(SyncType.DIALOG_CATEGORY); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.DIALOG_CATEGORY, payload)); +// updateAllPlayerRevisions(SyncType.DIALOG_CATEGORY, payload.getRevision()); +// } +// +// public static void syncAllQuests() { +// CachedSyncPayload payload = rebuildNow(SyncType.QUEST_CATEGORY); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.QUEST_CATEGORY, payload)); +// updateAllPlayerRevisions(SyncType.QUEST_CATEGORY, payload.getRevision()); +// } +// +// public static void syncAllWorkbenchRecipes() { +// CachedSyncPayload payload = rebuildNow(SyncType.WORKBENCH_RECIPES); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.WORKBENCH_RECIPES, payload)); +// updateAllPlayerRevisions(SyncType.WORKBENCH_RECIPES, payload.getRevision()); +// } +// +// public static void syncAllCarpentryRecipes() { +// CachedSyncPayload payload = rebuildNow(SyncType.CARPENTRY_RECIPES); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CARPENTRY_RECIPES, payload)); +// updateAllPlayerRevisions(SyncType.CARPENTRY_RECIPES, payload.getRevision()); +// } +// +// public static void syncAllAnvilRecipes() { +// CachedSyncPayload payload = rebuildNow(SyncType.ANVIL_RECIPES); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.ANVIL_RECIPES, payload)); +// updateAllPlayerRevisions(SyncType.ANVIL_RECIPES, payload.getRevision()); +// } +// +// public static void syncAllCustomEffects() { +// CachedSyncPayload payload = rebuildNow(SyncType.CUSTOM_EFFECTS); +// if (payload == null) { +// return; +// } +// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CUSTOM_EFFECTS, payload)); +// updateAllPlayerRevisions(SyncType.CUSTOM_EFFECTS, payload.getRevision()); +// } +// +// @SideOnly(Side.CLIENT) +// public static void clientSync(SyncType syncType, int revision, NBTTagCompound fullCompound) { +// if (syncType == SyncType.FACTION) { +// NBTTagList list = fullCompound.getTagList("Factions", 10); +// for (int i = 0; i < list.tagCount(); i++) { +// Faction faction = new Faction(); +// faction.readNBT(list.getCompoundTagAt(i)); +// FactionController.getInstance().factionsSync.put(faction.id, faction); +// } +// FactionController.getInstance().factions = FactionController.getInstance().factionsSync; +// FactionController.getInstance().factionsSync = new HashMap(); +// } else if (syncType == SyncType.DIALOG_CATEGORY) { +// if (!fullCompound.hasNoTags()) { +// NBTTagList categories = fullCompound.getTagList("DialogCategories", 10); +// for (int j = 0; j < fullCompound.getTagList("DialogCategories", 10).tagCount(); j++) { +// NBTTagCompound categoryCompound = categories.getCompoundTagAt(j); +// if (categoryCompound.hasNoTags()) +// continue; +// +// DialogCategory category = new DialogCategory(); +// category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); +// NBTTagList dialogList = categoryCompound.getTagList("Data", 10); +// if (DialogController.Instance.categoriesSync.containsKey(category.id)) { +// category = DialogController.Instance.categoriesSync.get(category.id); +// category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); +// } +// for (int i = 0; i < dialogList.tagCount(); i++) { +// Dialog dialog = new Dialog(); +// dialog.readNBT(dialogList.getCompoundTagAt(i)); +// dialog.category = category; +// category.dialogs.put(dialog.id, dialog); +// } +// DialogController.Instance.categoriesSync.put(category.id, category); +// } +// } +// +// HashMap dialogs = new HashMap(); +// for (DialogCategory category : DialogController.Instance.categoriesSync.values()) { +// for (Dialog dialog : category.dialogs.values()) { +// dialogs.put(dialog.id, dialog); +// } +// } +// +// DialogController.Instance.categories = DialogController.Instance.categoriesSync; +// DialogController.Instance.dialogs = dialogs; +// DialogController.Instance.categoriesSync = new HashMap(); +// } else if (syncType == SyncType.QUEST_CATEGORY) { +// if (!fullCompound.hasNoTags()) { +// NBTTagList categories = fullCompound.getTagList("QuestCategories", 10); +// for (int j = 0; j < fullCompound.getTagList("QuestCategories", 10).tagCount(); j++) { +// NBTTagCompound categoryCompound = categories.getCompoundTagAt(j); +// if (categoryCompound.hasNoTags()) +// continue; +// +// QuestCategory category = new QuestCategory(); +// category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); +// NBTTagList questList = categoryCompound.getTagList("Data", 10); +// if (QuestController.Instance.categoriesSync.containsKey(category.id)) { +// category = QuestController.Instance.categoriesSync.get(category.id); +// category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); +// } +// for (int i = 0; i < questList.tagCount(); i++) { +// Quest quest = new Quest(); +// quest.readNBT(questList.getCompoundTagAt(i)); +// quest.category = category; +// category.quests.put(quest.id, quest); +// } +// QuestController.Instance.categoriesSync.put(category.id, category); +// } +// } +// +// HashMap quests = new HashMap(); +// for (QuestCategory category : QuestController.Instance.categoriesSync.values()) { +// for (Quest quest : category.quests.values()) { +// quests.put(quest.id, quest); +// } +// } +// +// QuestController.Instance.categories = QuestController.Instance.categoriesSync; +// QuestController.Instance.quests = quests; +// QuestController.Instance.categoriesSync = new HashMap(); +// } else if (syncType == SyncType.PLAYERDATA) { +// ClientCacheHandler.playerData.setSyncNBTFull(fullCompound); +// } else if (syncType == SyncType.MAGIC) { +// NBTTagList list = fullCompound.getTagList("Data", 10); +// MagicController mc = MagicController.getInstance(); +// mc.magicSync.clear(); +// for (int i = 0; i < list.tagCount(); i++) { +// Magic magic = new Magic(); +// magic.readNBT(list.getCompoundTagAt(i)); +// mc.magicSync.put(magic.id, magic); +// } +// +// mc.magics.clear(); +// mc.magics.putAll(mc.magicSync); +// mc.magicSync.clear(); +// } else if (syncType == SyncType.MAGIC_CYCLE) { +// NBTTagList list = fullCompound.getTagList("Data", 10); +// MagicController mc = MagicController.getInstance(); +// mc.cyclesSync.clear(); +// for (int i = 0; i < list.tagCount(); i++) { +// MagicCycle cycle = new MagicCycle(); +// cycle.readNBT(list.getCompoundTagAt(i)); +// mc.cyclesSync.put(cycle.id, cycle); +// } +// +// mc.cycles.clear(); +// mc.cycles.putAll(mc.cyclesSync); +// mc.cyclesSync.clear(); +// } else if (syncType == SyncType.WORKBENCH_RECIPES) { +// NBTTagList list = fullCompound.getTagList("recipes", 10); +// if (list == null) +// return; +// +// for (int i = 0; i < list.tagCount(); i++) { +// NBTTagCompound recipeCompound = list.getCompoundTagAt(i); +// RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound); +// recipe.readNBT(recipeCompound); +// RecipeController.syncRecipes.put(recipe.id, recipe); +// } +// +// RecipeController.reloadGlobalRecipes(RecipeController.syncRecipes); +// RecipeController.syncRecipes = new HashMap(); +// } else if (syncType == SyncType.CARPENTRY_RECIPES) { +// NBTTagList list = fullCompound.getTagList("recipes", 10); +// if (list == null) +// return; +// +// for (int i = 0; i < list.tagCount(); i++) { +// NBTTagCompound recipeCompound = list.getCompoundTagAt(i); +// RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound); +// recipe.readNBT(recipeCompound); +// RecipeController.syncRecipes.put(recipe.id, recipe); +// } +// +// RecipeController.Instance.carpentryRecipes = RecipeController.syncRecipes; +// RecipeController.syncRecipes = new HashMap(); +// } else if (syncType == SyncType.ANVIL_RECIPES) { +// NBTTagList list = fullCompound.getTagList("recipes", 10); +// if (list == null) +// return; +// +// for (int i = 0; i < list.tagCount(); i++) { +// RecipeAnvil recipe = new RecipeAnvil(); +// recipe.readNBT(list.getCompoundTagAt(i)); +// RecipeController.syncAnvilRecipes.put(recipe.id, recipe); +// } +// +// RecipeController.Instance.anvilRecipes = RecipeController.syncAnvilRecipes; +// RecipeController.syncAnvilRecipes = new HashMap(); +// } else if (syncType == SyncType.CUSTOM_EFFECTS) { +// NBTTagList list = fullCompound.getTagList("Data", 10); +// CustomEffectController ce = CustomEffectController.getInstance(); +// ce.customEffectsSync.clear(); +// for (int i = 0; i < list.tagCount(); i++) { +// CustomEffect effect = new CustomEffect(); +// effect.readFromNBT(list.getCompoundTagAt(i)); +// ClientCacheHandler.getImageData(effect.icon); +// ce.customEffectsSync.put(effect.id, effect); +// } +// +// ce.getCustomEffects().clear(); +// ce.getCustomEffects().putAll(ce.customEffectsSync); +// ce.customEffectsSync.clear(); +// } else if (syncType == SyncType.CUSTOM_ABILITY) { +// NBTTagList list = fullCompound.getTagList("Data", 10); +// LinkedHashMap sync = new LinkedHashMap<>(); +// for (int i = 0; i < list.tagCount(); i++) { +// NBTTagCompound nbt = list.getCompoundTagAt(i); +// String name = nbt.getString("CustomAbilityId"); +// Ability ability = AbilityController.Instance.fromNBT(nbt); +// if (ability != null) { +// ability.setName(name); +// sync.put(name, ability); +// } +// } +// AbilityController.Instance.setCustomAbilities(sync); +// } else if (syncType == SyncType.CHAINED_ABILITY) { +// NBTTagList list = fullCompound.getTagList("Data", 10); +// LinkedHashMap sync = new LinkedHashMap<>(); +// for (int i = 0; i < list.tagCount(); i++) { +// NBTTagCompound nbt = list.getCompoundTagAt(i); +// String id = nbt.getString("ChainedAbilityId"); +// ChainedAbility chain = new ChainedAbility(); +// chain.readNBT(nbt); +// chain.setName(id); +// sync.put(id, chain); +// } +// AbilityController.Instance.setChainedAbilities(sync); +// } +// +// ClientCacheHandler.updateClientRevision(syncType, revision); +// } +// +// @SideOnly(Side.CLIENT) +// public static void clientUpdate(SyncType syncType, int category_id, int revision, NBTTagCompound compound) { +// if (syncType == SyncType.FACTION) { +// Faction faction = new Faction(); +// faction.readNBT(compound); +// FactionController.getInstance().factions.put(faction.id, faction); +// } else if (syncType == SyncType.DIALOG) { +// DialogCategory category = DialogController.Instance.categories.get(category_id); +// Dialog dialog = new Dialog(); +// dialog.category = category; +// dialog.readNBT(compound); +// DialogController.Instance.dialogs.put(dialog.id, dialog); +// category.dialogs.put(dialog.id, dialog); +// } else if (syncType == SyncType.QUEST) { +// QuestCategory category = QuestController.Instance.categories.get(category_id); +// Quest quest = new Quest(); +// quest.category = category; +// quest.readNBT(compound); +// QuestController.Instance.quests.put(quest.id, quest); +// category.quests.put(quest.id, quest); +// } else if (syncType == SyncType.QUEST_CATEGORY) { +// QuestCategory category = new QuestCategory(); +// category.readSmallNBT(compound.getCompoundTag("CatNBT")); +// NBTTagList list = compound.getTagList("Data", 10); +// if (QuestController.Instance.categoriesSync.containsKey(category.id)) { +// category = QuestController.Instance.categoriesSync.get(category.id); +// category.readSmallNBT(compound.getCompoundTag("CatNBT")); +// } +// for (int i = 0; i < list.tagCount(); i++) { +// Quest quest = new Quest(); +// quest.readNBT(list.getCompoundTagAt(i)); +// quest.category = category; +// category.quests.put(quest.id, quest); +// } +// QuestController.Instance.categories.put(category.id, category); +// } else if (syncType == SyncType.DIALOG_CATEGORY) { +// DialogCategory category = new DialogCategory(); +// category.readSmallNBT(compound.getCompoundTag("CatNBT")); +// NBTTagList list = compound.getTagList("Data", 10); +// if (DialogController.Instance.categoriesSync.containsKey(category.id)) { +// category = DialogController.Instance.categoriesSync.get(category.id); +// category.readSmallNBT(compound.getCompoundTag("CatNBT")); +// } +// for (int i = 0; i < list.tagCount(); i++) { +// Dialog dialog = new Dialog(); +// dialog.readNBT(list.getCompoundTagAt(i)); +// dialog.category = category; +// category.dialogs.put(dialog.id, dialog); +// } +// DialogController.Instance.categories.put(category.id, category); +// } else if (syncType == SyncType.MAGIC_CYCLE) { +// MagicCycle cycle = new MagicCycle(); +// cycle.readNBT(compound); +// MagicController.getInstance().cycles.put(cycle.id, cycle); +// } else if (syncType == SyncType.MAGIC) { +// Magic magic = new Magic(); +// magic.readNBT(compound); +// MagicController.getInstance().magics.put(magic.id, magic); +// } else if (syncType == SyncType.PLAYERDATA) { +// ClientCacheHandler.playerData.setSyncNBT(compound); +// } else if (syncType == SyncType.CUSTOM_EFFECTS) { +// CustomEffect effect = new CustomEffect(); +// effect.readFromNBT(compound); +// ClientCacheHandler.getImageData(effect.icon); +// +// CustomEffectController.Instance.getCustomEffects().put(effect.id, effect); +// } +// +// ClientCacheHandler.updateClientRevision(syncType, revision); +// } +// +// public static void syncUpdate(SyncType type, int cat, NBTTagCompound compound) { +// Map revisions = invalidateCaches(type); +// int revision = revisions.getOrDefault(type, getCurrentRevision(type)); +// PacketHandler.Instance.sendToAll(new SyncPacket( +// type, +// EnumSyncAction.UPDATE, +// cat, +// revision, +// compound +// )); +// updateAllPlayerRevisions(revisions); +// } +// +// +// public static NBTTagCompound updateQuestCat(QuestCategory questCategory) { +// NBTTagCompound questCompound = new NBTTagCompound(); +// NBTTagList questList = new NBTTagList(); +// for (int questID : questCategory.quests.keySet()) { +// Quest quest = questCategory.quests.get(questID); +// questList.appendTag(quest.writeToNBT(new NBTTagCompound())); +// } +// questCompound.setTag("Data", questList); +// questCompound.setTag("CatNBT", questCategory.writeSmallNBT(new NBTTagCompound())); +// return questCompound; +// } +// +// public static NBTTagCompound updateDialogCat(DialogCategory dialogCategory) { +// NBTTagCompound dialogCompound = new NBTTagCompound(); +// NBTTagList dialogList = new NBTTagList(); +// for (int questID : dialogCategory.dialogs.keySet()) { +// Dialog dialog = dialogCategory.dialogs.get(questID); +// dialogList.appendTag(dialog.writeToNBT(new NBTTagCompound())); +// } +// dialogCompound.setTag("Data", dialogList); +// dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound())); +// return dialogCompound; +// } +// +// @SideOnly(Side.CLIENT) +// public static void clientSyncRemove(SyncType syncType, int id, int revision) { +// if (syncType == SyncType.FACTION) { +// FactionController.getInstance().factions.remove(id); +// } else if (syncType == SyncType.DIALOG) { +// Dialog dialog = DialogController.Instance.dialogs.remove(id); +// if (dialog != null) { +// dialog.category.dialogs.remove(id); +// } +// } else if (syncType == SyncType.DIALOG_CATEGORY) { +// DialogCategory dialogCategory = DialogController.Instance.categories.remove(id); +// if (dialogCategory != null) { +// DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet()); +// } +// } else if (syncType == SyncType.QUEST) { +// Quest quest = QuestController.Instance.quests.remove(id); +// if (quest != null) { +// quest.category.quests.remove(id); +// } +// } else if (syncType == SyncType.QUEST_CATEGORY) { +// QuestCategory questCategory = QuestController.Instance.categories.remove(id); +// if (questCategory != null) { +// QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet()); +// } +// } else if (syncType == SyncType.MAGIC) { +// for (MagicCycle cycle : MagicController.getInstance().cycles.values()) { +// cycle.associations.remove(id); +// } +// MagicController.getInstance().cycles.remove(id); +// } else if (syncType == SyncType.MAGIC_CYCLE) { +// MagicController.getInstance().cycles.remove(id); +// } else if (syncType == SyncType.CUSTOM_EFFECTS) { +// CustomEffectController.Instance.getCustomEffects().remove(id); +// } +// +// ClientCacheHandler.updateClientRevision(syncType, revision); +// } +// +// public static void syncEffects(EntityPlayerMP playerMP) { +// ConcurrentHashMap playerEffects = CustomEffectController.getInstance().getPlayerEffects(playerMP); +// PlayerData playerData = PlayerData.get(playerMP); +// playerData.effectData.setEffects(playerEffects); +// +// NBTTagCompound compound = playerData.getPlayerEffects(); +// PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP); +// } +// +// /** +// * Full sync of all player ability state to the client: unlocked abilities, +// * selection, toggles, hotbar layout, and cooldowns. +// * Used for entity reconstruction and other full-refresh scenarios. +// */ +// public static void syncAbilities(EntityPlayerMP playerMP) { +// PlayerData playerData = PlayerData.get(playerMP); +// if (playerData == null) return; +// +// PlayerAbilitySyncPacket.sendToPlayer(playerMP); +// AbilityHotbarSyncPacket.sendToPlayer(playerMP); +// AbilityCooldownSyncPacket.sendToPlayer(playerMP); +// } +// +// /** +// * Lightweight sync of cooldown state only (global + per-ability). +// * Called periodically (every 10 ticks) to keep the client's cooldown +// * display accurate. Cooldowns are transient and not part of NBT sync. +// */ +// public static void syncAbilityCooldowns(EntityPlayerMP playerMP) { +// PlayerData playerData = PlayerData.get(playerMP); +// if (playerData == null) return; +// +// AbilityCooldownSyncPacket.sendToPlayer(playerMP); +// } +// +// @SideOnly(Side.CLIENT) +// public static void clientSyncEffects(NBTTagCompound compound) { +// PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer); +// if (playerData != null) { +// playerData.setPlayerEffects(compound); +// } +// } +// +// private static void registerCache(SyncType type, Supplier supplier) { +// cacheEntries.put(type, new SyncCacheEntry(supplier)); +// } +// +// private static CachedSyncPayload rebuildNow(SyncType type) { +// SyncCacheEntry entry = cacheEntries.get(type); +// if (entry == null) { +// return null; +// } +// entry.invalidate(); +// return entry.getPayload(type); +// } +// +// public static Map invalidateCaches(SyncType type) { +// Set targets = getInvalidationTargets(type); +// Map revisions = new LinkedHashMap<>(); +// for (SyncType target : targets) { +// SyncCacheEntry entry = cacheEntries.get(target); +// if (entry != null) { +// int newRevision = entry.invalidate(); +// revisions.put(target, newRevision); +// } +// } +// return revisions; +// } +// +// private static Set getInvalidationTargets(SyncType type) { +// if (type == SyncType.DIALOG || type == SyncType.DIALOG_CATEGORY) { +// Set set = new HashSet<>(); +// set.add(SyncType.DIALOG_CATEGORY); +// return set; +// } else if (type == SyncType.QUEST || type == SyncType.QUEST_CATEGORY) { +// Set set = new HashSet<>(); +// set.add(SyncType.QUEST_CATEGORY); +// return set; +// } else if (type == SyncType.FACTION) { +// Set set = new HashSet<>(); +// set.add(SyncType.FACTION); +// return set; +// } else if (type == SyncType.MAGIC) { +// Set set = new HashSet<>(); +// set.add(SyncType.MAGIC); +// return set; +// } else if (type == SyncType.MAGIC_CYCLE) { +// Set set = new HashSet<>(); +// set.add(SyncType.MAGIC_CYCLE); +// return set; +// } else if (type == SyncType.WORKBENCH_RECIPES) { +// Set set = new HashSet<>(); +// set.add(SyncType.WORKBENCH_RECIPES); +// return set; +// } else if (type == SyncType.CARPENTRY_RECIPES) { +// Set set = new HashSet<>(); +// set.add(SyncType.CARPENTRY_RECIPES); +// return set; +// } else if (type == SyncType.ANVIL_RECIPES) { +// Set set = new HashSet<>(); +// set.add(SyncType.ANVIL_RECIPES); +// return set; +// } else if (type == SyncType.CUSTOM_EFFECTS) { +// Set set = new HashSet<>(); +// set.add(SyncType.CUSTOM_EFFECTS); +// return set; +// } else if (type == SyncType.CUSTOM_ABILITY) { +// Set set = new HashSet<>(); +// set.add(SyncType.CUSTOM_ABILITY); +// return set; +// } else if (type == SyncType.CHAINED_ABILITY) { +// Set set = new HashSet<>(); +// set.add(SyncType.CHAINED_ABILITY); +// return set; +// } +// return Collections.emptySet(); +// } +// +// private static void updateAllPlayerRevisions(SyncType type, int revision) { +// if (revision < 0) { +// return; +// } +// for (PlayerSyncState state : playerSyncState.values()) { +// state.updateRevision(type, revision); +// } +// } +// +// private static void updateAllPlayerRevisions(Map revisions) { +// if (revisions.isEmpty()) { +// return; +// } +// for (PlayerSyncState state : playerSyncState.values()) { +// for (Map.Entry entry : revisions.entrySet()) { +// state.updateRevision(entry.getKey(), entry.getValue()); +// } +// } +// } +// +// public static final class CachedSyncPayload { +// private final int revision; +// private final byte[] payload; +// private final byte[][] chunks; +// +// private CachedSyncPayload(int revision, byte[] payload, byte[][] chunks) { +// this.revision = revision; +// this.payload = payload; +// this.chunks = chunks; +// } +// +// public int getRevision() { +// return revision; +// } +// +// public byte[] getPayload() { +// return payload; +// } +// +// public byte[][] getChunks() { +// return chunks; +// } +// } +// +// private static final class SyncCacheEntry { +// private final Supplier supplier; +// private volatile CachedSyncPayload payload; +// private int revision = 0; +// private boolean dirty = true; +// +// private SyncCacheEntry(Supplier supplier) { +// this.supplier = supplier; +// } +// +// private synchronized CachedSyncPayload getPayload(SyncType requestedType) { +// if (!dirty && payload != null) { +// return payload; +// } +// +// int payloadRevision = revision; +// NBTTagCompound data = supplier.get(); +// ByteBuf buffer = Unpooled.buffer(); +// byte[] bytes; +// try { +// buffer.writeInt(requestedType.ordinal()); +// buffer.writeInt(EnumSyncAction.RELOAD.ordinal()); +// buffer.writeInt(-1); +// buffer.writeInt(payloadRevision); +// ByteBufUtils.writeBigNBT(buffer, data); +// +// bytes = new byte[buffer.readableBytes()]; +// buffer.readBytes(bytes); +// } catch (IOException e) { +// throw new RuntimeException("Failed to serialize sync payload for " + requestedType, e); +// } finally { +// buffer.release(); +// } +// +// byte[][] chunks = splitIntoChunks(bytes); +// payload = new CachedSyncPayload(payloadRevision, bytes, chunks); +// dirty = false; +// return payload; +// } +// +// private synchronized int invalidate() { +// dirty = true; +// payload = null; +// revision++; +// return revision; +// } +// +// private synchronized int getRevisionValue() { +// return revision; +// } +// +// private synchronized void reset() { +// dirty = true; +// payload = null; +// revision = 0; +// } +// +// private static byte[][] splitIntoChunks(byte[] payload) { +// int totalSize = payload.length; +// int chunkCount = (totalSize + LargeAbstractPacket.CHUNK_SIZE - 1) / LargeAbstractPacket.CHUNK_SIZE; +// if (chunkCount <= 0) { +// chunkCount = 1; +// } +// byte[][] chunks = new byte[chunkCount][]; +// for (int i = 0; i < chunkCount; i++) { +// int offset = i * LargeAbstractPacket.CHUNK_SIZE; +// int length = Math.min(LargeAbstractPacket.CHUNK_SIZE, totalSize - offset); +// byte[] chunk = new byte[length]; +// System.arraycopy(payload, offset, chunk, 0, length); +// chunks[i] = chunk; +// } +// return chunks; +// } +// } +// +// private static final class PlayerSyncState { +// private final Map revisions = new HashMap<>(); +// +// private PlayerSyncState(UUID ignored) { +// } +// +// private synchronized int getRevision(SyncType type) { +// Integer value = revisions.get(type); +// return value == null ? -1 : value; +// } +// +// private synchronized void updateRevision(SyncType type, int revision) { +// revisions.put(type, revision); +// } +// +// private synchronized void applyHandshake(Map incoming) { +// if (incoming == null || incoming.isEmpty()) { +// return; +// } +// revisions.putAll(incoming); +// } +// +// private synchronized void reset() { +// revisions.clear(); +// } +// +// } +//} diff --git a/src/main/java/kamkeel/npcs/controllers/TelegraphController.java b/src/main/java/kamkeel/npcs/controllers/TelegraphController.java index 5449245a6..7956f4ff6 100644 --- a/src/main/java/kamkeel/npcs/controllers/TelegraphController.java +++ b/src/main/java/kamkeel/npcs/controllers/TelegraphController.java @@ -308,6 +308,11 @@ public class TelegraphController implements ITelegraphHandler { return new ScriptTelegraph(Telegraph.cone(length, angle)); } + @Override + public ITelegraph createSquare(float radius) { + return new ScriptTelegraph(Telegraph.square(radius)); + } + @Override public ITelegraph createPoint() { return new ScriptTelegraph(Telegraph.point()); @@ -332,6 +337,9 @@ public class TelegraphController implements ITelegraphHandler { case CONE: telegraph = Telegraph.cone(5.0f, 45.0f); break; + case SQUARE: + telegraph = Telegraph.square(3.0f); + break; case POINT: telegraph = Telegraph.point(); break; 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 b95879c3b..d944f7535 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -2,55 +2,89 @@ package kamkeel.npcs.controllers.data.ability; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.AbilityIconData; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.enums.InvulnerableMode; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.preview.PreviewEntityHandler; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.gui.IAbilityFieldProvider; +import kamkeel.npcs.controllers.data.ability.enums.RotationMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; 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.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.util.AttributeAttackUtil; +import kamkeel.npcs.util.FileNameHelper; import net.minecraft.block.Block; +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.nbt.NBTTagString; +import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.StatCollector; +import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.DataAbilities; import noppes.npcs.NpcDamageSource; +import noppes.npcs.config.ConfigMain; import noppes.npcs.api.INbt; import noppes.npcs.api.ability.IAbility; import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; +import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.IScriptUnit; +import noppes.npcs.controllers.TagController; import noppes.npcs.controllers.data.Animation; -import net.minecraft.entity.player.EntityPlayer; import noppes.npcs.controllers.data.Frame; +import noppes.npcs.controllers.data.AbilityScript; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.api.entity.IPlayer; -import noppes.npcs.controllers.ScriptController; -import noppes.npcs.controllers.data.PlayerDataScript; +import noppes.npcs.EventHooks; import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.controllers.MagicController; +import noppes.npcs.controllers.data.Magic; +import noppes.npcs.controllers.data.MagicData; +import noppes.npcs.controllers.data.MagicEntry; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.client.gui.advanced.SubGuiAbilityMagic; import noppes.npcs.scripted.event.AbilityEvent; -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.HashSet; import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Predicate; -import net.minecraft.entity.Entity; - -public abstract class Ability implements IAbility { +public abstract class Ability implements IAbility, IAbilityAction { // ═══════════════════════════════════════════════════════════════════ // CONFIGURATION (saved to NBT) // ═══════════════════════════════════════════════════════════════════ - protected String id; - protected String name; - protected String typeId; // e.g., "ability.cnpc.slam" (also used as lang key) + protected String id = ""; // UUID for custom, registry key for built-in + protected String name = ""; // Unique file key / identifier + protected String displayName = ""; // Cosmetic name (falls back to name when empty) + protected String typeId = ""; // e.g., "ability.cnpc.slam" (also used as lang key) // Selection protected int weight = 10; protected boolean enabled = true; - protected List conditions = new ArrayList<>(); + protected List conditions = new ArrayList<>(); // Targeting protected TargetingMode targetingMode = TargetingMode.AGGRO_TARGET; @@ -65,11 +99,14 @@ public abstract class Ability implements IAbility { // Interruption protected boolean interruptible = true; + protected InvulnerableMode invulnerableMode = InvulnerableMode.NONE; + protected boolean ignoreIFrames = false; // Feedback - protected LockMovementType lockMovement = LockMovementType.WINDUP; + protected LockMode lockMovement = LockMode.WINDUP; protected RotationMode rotationMode = RotationMode.FREE; - protected LockMovementType rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; + protected LockMode rotationPhase = LockMode.WINDUP_AND_ACTIVE; + protected float trackSpeed = 0; // 0 = instant tracking. Linear tracking speed in blocks/second. protected int windUpColor = 0x80FF4400; // Telegraph color during wind up protected int activeColor = 0xC0FF0000; // Telegraph warning/active color @@ -80,10 +117,12 @@ public abstract class Ability implements IAbility { // Animations (global animation IDs, -1 = none) protected int windUpAnimationId = -1; // Animation to play during wind up (user animations) protected int activeAnimationId = -1; // Animation to play during active phase (user animations) + protected int dazedAnimationId = -1; // Animation to play during dazed phase (user animations) // Built-in animation names (empty = none, takes priority over IDs if set) protected String windUpAnimationName = ""; // Built-in animation name for wind up protected String activeAnimationName = ""; // Built-in animation name for active phase + protected String dazedAnimationName = "Ability_Generic_Dazed"; // Built-in animation name for dazed phase // Telegraph configuration protected boolean showTelegraph = true; @@ -93,14 +132,108 @@ public abstract class Ability implements IAbility { // Custom data for external mods protected NBTTagCompound customData = new NBTTagCompound(); + // Tags + protected HashSet tagUUIDs = new HashSet<>(); + + // Magic data — defines magic types and damage splits for this ability + protected MagicData magicData = new MagicData(); + // User type restriction protected UserType allowedBy = UserType.BOTH; // Cooldown override protected boolean ignoreCooldown = false; + // Per-ability cooldown: if true, this ability has its own independent cooldown + // instead of sharing the global cooldown with other abilities + protected boolean perAbilityCooldown = false; + + // Free on Cast: if true, ability enters cooldown immediately after entities are spawned, + // allowing the caster to use other abilities while summoned entities remain active + protected boolean freeOnCast = false; + + // ═══════════════════════════════════════════════════════════════════ + // BUILT-IN (set in constructor via configureAsBuiltIn, NOT persisted) + // ═══════════════════════════════════════════════════════════════════ + + protected transient boolean builtIn = false; + protected transient String registryKey; + + // Default icon layers (set in subclass constructors, NOT persisted) + protected transient DefaultIconLayer[] defaultIconLayers = null; + protected transient int defaultIconWidth = 48; + protected transient int defaultIconHeight = 48; + + /** + * Optional player requirement predicate. When set, the ability is only visible + * and usable by players for whom this predicate returns true. + * Evaluated on-demand (no polling). Null means no requirement (always available). + *

+ * This is transient — set programmatically by addons, not saved to NBT. + */ + protected transient Predicate playerRequirement; + + /** + * A single layer of a default ability icon. Each layer has a texture, + * an optional dynamic color source, and optional per-state texture variants. + */ + public static class DefaultIconLayer { + public final String texture; + public final String[] stateTextures; + public final java.util.function.IntSupplier colorSource; + + public DefaultIconLayer(String texture, String[] stateTextures, java.util.function.IntSupplier colorSource) { + this.texture = texture; + this.stateTextures = stateTextures; + this.colorSource = colorSource; + } + + public DefaultIconLayer(String texture, java.util.function.IntSupplier colorSource) { + this(texture, null, colorSource); + } + + /** Layer with no color tinting (renders as white). */ + public DefaultIconLayer(String texture) { + this(texture, null, null); + } + + /** Resolve texture for a given toggle state. Falls back to base texture. */ + public String getTextureForState(int state) { + if (state > 0 && stateTextures != null && state - 1 < stateTextures.length) { + return stateTextures[state - 1]; + } + return texture; + } + + public int getColor() { + return colorSource != null ? colorSource.getAsInt() : 0xFFFFFF; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // TOGGLE CONFIGURATION (saved to NBT for custom abilities) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Number of toggle states. 0 = not toggleable, 1 = binary on/off, 2+ = multi-state cycling. + * Cycling order: Off(0) -> State 1 -> State 2 -> ... -> State N -> Off(0) + */ + protected int toggleStates = 0; + + /** + * Whether the toggled-ON state ticks each game tick (e.g., Kaioken drains ki per tick) + */ + protected boolean hasActiveToggle = false; + + /** + * Optional display labels for each toggle state (1-indexed). + * Used in ability wheel/hotbar to show current state name. + * Null means no labels. Array length should match toggleStates. + */ + protected String[] toggleStateLabels; + // Configurable potion effects - protected List effects = new ArrayList<>(); + protected List effects = new ArrayList<>(); // Burst protected boolean burstEnabled = false; @@ -117,12 +250,16 @@ 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<>(); + // Per-instance script (isolated per execution, not saved to NBT) + protected transient AbilityScript instanceScript; + protected transient float damageMultiplier = 1.0f; // Ability-internal damage scaling (e.g., Slam height) + // ═══════════════════════════════════════════════════════════════════ // PREVIEW STATE (client-side only, not saved) // ═══════════════════════════════════════════════════════════════════ @@ -130,19 +267,28 @@ public abstract class Ability implements IAbility { 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 @@ -168,6 +314,35 @@ public abstract class Ability implements IAbility { return true; } + /** + * Returns true if this ability type uses magic data. + * By default, any ability that deals damage also has magic. + * Override in subclasses like Barrier that need magic but don't deal direct damage. + */ + public boolean hasMagic() { + return hasDamage(); + } + + // ── Display methods for inventory preview ────────────────────── + + /** Base damage for preview display. Override in damaging types. */ + public float getDisplayDamage() { return 0; } + + /** True if getDisplayDamage() is damage-per-second (e.g., Hazard). */ + public boolean isDisplayDamageDPS() { return false; } + + /** Base barrier health for preview display. Override in barrier types. */ + public float getDisplayBarrierHealth() { return 0; } + + /** True if this ability reflects projectiles. */ + public boolean isDisplayReflect() { return false; } + + /** Reflection strength percentage (0-100). */ + public float getDisplayReflectStrength() { return 0; } + + /** True if this ability absorbs projectiles. */ + public boolean isDisplayAbsorbing() { return false; } + /** * Override to provide variant templates for this ability type. * When a user creates this ability type, they will be shown a selection dialog @@ -193,36 +368,82 @@ public abstract class Ability implements IAbility { return false; } + /** + * Whether this ability can run concurrently alongside the primary ability in a chain. + * Override to return true for passive/effect abilities that don't need exclusive animations. + * Concurrent abilities skip animations entirely and run their tick/execute logic independently. + */ + public boolean isConcurrentCapable() { + return false; + } + + /** + * Whether this ability type supports the Free on Cast option. + * Override to return true for abilities that spawn persistent entities (projectiles, barriers, zones, sweeper). + */ + public boolean allowFreeOnCast() { + return false; + } + + /** + * Detach all spawned entities (let them live independently) without killing them. + * Called during signalCompletion() when freeOnCast is enabled. + * Override in subclasses to null entity references without calling setDead(). + */ + public void detach() { + } + + // ═══════════════════════════════════════════════════════════════════ + // TOGGLE CALLBACKS (optional overrides for toggleable abilities) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Called whenever the toggle state changes (activation, deactivation, or mid-cycling). + * Override to apply/remove effects based on state transitions. + * + * @param caster The entity + * @param oldState Previous state (0 = was off) + * @param newState New state (0 = now off, 1+ = active state) + */ + public void onToggle(EntityLivingBase caster, int oldState, int newState) { + } + + /** + * Called every tick while this toggle is active (only if hasActiveToggle is true). + * Override for per-tick effects (e.g., ki drain for Kaioken). + * + * @param state Current toggle state (1-based) + * @return true to keep the toggle active, false to auto-deactivate + */ + public boolean onToggleTick(EntityLivingBase caster, int tickCount, int state) { + return true; + } + /** * 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) {} + + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) {} + + public void onComplete(EntityLivingBase caster, EntityLivingBase target) {} + /** - * Called when burst re-fires without replay animations (burstReplayAnimations=false). - * Entity-spawning abilities should override to spawn and fire entities in one step, - * since onWindUpTick was not called (windup was skipped). - * Default: does nothing (ability goes directly to onExecute with existing state). + * Called when the ability enters BURST_DELAY between burst iterations. + * Override in subclasses to reset transient state that should not carry + * across burst repetitions (e.g., movement direction, hit entity lists). + *

+ * Unlike {@link #cleanup()}, this does NOT kill spawned entities (they may + * still be in flight for overlap mode). */ - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - // Override in entity-spawning abilities (Orb, Beam, Disc, LaserShot) - } - - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - } - - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - } - - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) { - } + public void resetForBurst() {} /** * Apply damage to an entity with ability hit event support. @@ -241,24 +462,6 @@ public abstract class Ability implements IAbility { return applyAbilityDamageInternal(caster, hitEntity, damage, knockback, 0.0f, dx, dz); } - /** - * Apply damage to an entity with ability hit event support and vertical knockback. - * Fires the abilityHit script event, allowing scripts to modify or cancel the damage. - * - * @param caster The entity executing the ability (NPC or Player) - * @param hitEntity The entity being hit - * @param damage The damage amount - * @param knockback The horizontal knockback - * @param knockbackUp The vertical knockback - * @return true if damage was applied (not cancelled), false if cancelled - */ - protected boolean applyAbilityDamage(EntityLivingBase caster, EntityLivingBase hitEntity, - float damage, float knockback, float knockbackUp) { - double dx = hitEntity.posX - caster.posX; - double dz = hitEntity.posZ - caster.posZ; - return applyAbilityDamageInternal(caster, hitEntity, damage, knockback, knockbackUp, dx, dz); - } - /** * Apply damage to an entity with ability hit event support and custom knockback direction. * Fires the abilityHit script event, allowing scripts to modify or cancel the damage. @@ -277,6 +480,28 @@ public abstract class Ability implements IAbility { return applyAbilityDamageInternal(caster, hitEntity, damage, knockback, 0.0f, knockbackDirX, knockbackDirZ); } + /** + * Clears hurt resistance before damage and returns the previous value so it can be restored later. + */ + public static int clearHurtResistanceIfNeeded(EntityLivingBase target, boolean ignoreIFrames) { + if (!ignoreIFrames || target == null) { + return -1; + } + int previous = target.hurtResistantTime; + target.hurtResistantTime = 0; + return previous; + } + + /** + * Restores hurt resistance after damage when {@link #clearHurtResistanceIfNeeded} was used. + */ + public static void restoreHurtResistanceIfNeeded(EntityLivingBase target, boolean ignoreIFrames, int previous) { + if (!ignoreIFrames || target == null || previous < 0) { + return; + } + target.hurtResistantTime = previous; + } + /** * Internal unified damage application method. * All public damage methods delegate to this. @@ -285,64 +510,61 @@ public abstract class Ability implements IAbility { private boolean applyAbilityDamageInternal(EntityLivingBase caster, EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp, double knockbackDirX, double knockbackDirZ) { - // Fire hit event for NPC casters (NPC event system) - if (caster instanceof EntityNPCInterface) { - EntityNPCInterface npc = (EntityNPCInterface) caster; - DataAbilities dataAbilities = npc.abilities; - AbilityEvent.HitEvent event = dataAbilities.fireHitEvent( - this, currentTarget, hitEntity, damage, knockback, knockbackUp); - - if (event == null) { - return false; // Cancelled - } - - damage = event.getDamage(); - knockback = event.getKnockback(); - knockbackUp = event.getKnockbackUp(); + // Fire hit event (unified — works for both NPC and Player casters) + AbilityEvent.HitEvent hitEvent = new AbilityEvent.HitEvent( + caster, this, currentTarget, hitEntity, damage, knockback, knockbackUp); + if (EventHooks.onAbilityHit(this, hitEvent)) { + return false; // Cancelled } - // Fire hit event for Player casters (Player event system) - else if (caster instanceof EntityPlayer && ScriptController.Instance != null) { - EntityPlayer player = (EntityPlayer) caster; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler != null) { - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.HitEvent event = new PlayerAbilityEvent.HitEvent( - iPlayer, this, currentTarget, hitEntity, damage, knockback, knockbackUp); + damage = hitEvent.getDamage(); + knockback = hitEvent.getKnockback(); + knockbackUp = hitEvent.getKnockbackUp(); - if (noppes.npcs.EventHooks.onPlayerAbilityHit(handler, event)) { - return false; // Cancelled - } - - damage = event.getDamage(); - knockback = event.getKnockback(); - knockbackUp = event.getKnockbackUp(); - } - } + // Save velocity before damage to cancel vanilla knockback when ability knockback is zero + double prevMotionX = hitEntity.motionX; + double prevMotionY = hitEntity.motionY; + double prevMotionZ = hitEntity.motionZ; // 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); - } - if (!handled) { - // Default damage path - if (caster instanceof EntityNPCInterface) { - hitEntity.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), damage); - } else if (caster instanceof EntityPlayer) { - hitEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) caster), damage); - } else { - hitEntity.attackEntityFrom(DamageSource.causeMobDamage(caster), damage); + int previousHurtResistantTime = clearHurtResistanceIfNeeded(hitEntity, ignoreIFrames); + try { + // Check for ability extenders (e.g., DBC Addon damage routing) + boolean handled = AbilityController.Instance.fireOnAbilityDamage( + this, caster, hitEntity, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ, 1.0f); + if (!handled) { + float finalDamage = damage; + + // Apply magic pipeline for player and NPC casters + MagicData resolved = resolveMagicData(caster); + if (resolved != null && !resolved.isEmpty()) { + finalDamage = AttributeAttackUtil.calculateAbilityDamage( + caster, hitEntity, damage, resolved); + } + + // Default damage path + if (caster instanceof EntityNPCInterface) { + hitEntity.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), finalDamage); + } else if (caster instanceof EntityPlayer) { + hitEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) caster), finalDamage); + } else { + hitEntity.attackEntityFrom(DamageSource.causeMobDamage(caster), finalDamage); + } } + } finally { + restoreHurtResistanceIfNeeded(hitEntity, ignoreIFrames, previousHurtResistantTime); } } - // Apply knockback if any + // Apply knockback if any, otherwise restore velocity to cancel vanilla knockback if (knockback > 0 || knockbackUp > 0) { applyKnockback(hitEntity, knockbackDirX, knockbackDirZ, knockback, knockbackUp); + } else { + hitEntity.motionX = prevMotionX; + hitEntity.motionY = prevMotionY; + hitEntity.motionZ = prevMotionZ; + hitEntity.velocityChanged = true; } return true; @@ -371,7 +593,7 @@ public abstract class Ability implements IAbility { if (entity == null || effects.isEmpty()) { return; } - for (AbilityEffect effect : effects) { + for (AbilityPotionEffect effect : effects) { effect.apply(entity); } } @@ -392,6 +614,18 @@ public abstract class Ability implements IAbility { return 45.0f; } + public float getTelegraphInnerRadius() { + return 0.0f; + } + + /** + * Override to return true if the ability type manages its own telegraph GUI controls. + * When true, the base class will skip adding the default telegraph section. + */ + public boolean hasOwnTelegraphControls() { + return false; + } + /** * Returns true if the caster is a player (not an NPC). * Use this instead of checking {@code target != null} to make NPC/Player @@ -404,6 +638,16 @@ public abstract class Ability implements IAbility { 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. @@ -430,14 +674,6 @@ public abstract class Ability implements IAbility { return null; } - /** - * Returns true if the telegraph type for this ability is locked and cannot be changed. - * Telegraph type is inherent to how the ability works (e.g., Charge uses LINE, Slam uses CIRCLE). - */ - public boolean isTelegraphTypeLocked() { - return true; - } - /** * Add field definitions for this ability's GUI. * Override in subclasses to add type-specific fields. The list already contains @@ -466,6 +702,11 @@ public abstract class Ability implements IAbility { // ── General tab ────────────────────────────────────────────── defs.add(FieldDef.stringField("gui.name", this::getName, this::setName) .tab("General")); + defs.add(FieldDef.stringField("gui.displayName", this::getRawDisplayName, this::setDisplayName) + .tab("General")); + defs.add(FieldDef.labelField("ability.validFor", () -> + "\u00A7e" + StatCollector.translateToLocal("ability.userType." + getAllowedBy().name())) + .tab("General")); defs.add(FieldDef.row( FieldDef.intField("ability.weight", this::getWeight, this::setWeight).range(1, 1000), FieldDef.boolField("gui.enabled", this::isEnabled, this::setEnabled) @@ -484,43 +725,81 @@ public abstract class Ability implements IAbility { FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) .hover("ability.hover.sync") ).tab("General").visibleWhen(() -> hasWindUpAnimation() && isSyncWindupWithAnimation())); - defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks) - .tab("General").range(0, 10000)); + defs.add(FieldDef.row( + FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks).range(0, 10000), + FieldDef.boolField("ability.perAbilityCooldown", this::isPerAbilityCooldown, this::setPerAbilityCooldown) + ).tab("General")); + if (allowFreeOnCast()) { + defs.add(FieldDef.boolField("ability.freeOnCast", this::isFreeOnCast, this::setFreeOnCast) + .tab("General").hover("ability.hover.freeOnCast")); + } defs.add(FieldDef.section("ability.section.movement").tab("General")); - defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), + defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMode.getDisplayKeys(), () -> this.getLockMovement().getDisplayKey(), v -> { - for (LockMovementType t : LockMovementType.values()) { - if (t.getDisplayKey().equals(v)) { this.setLockMovement(t); break; } + for (LockMode t : LockMode.values()) { + if (t.getDisplayKey().equals(v)) { + this.setLockMovement(t); + break; + } } }) - .hover("ability.hover.lockMovement") - .tab("General")); + .hover("ability.hover.lockMovement") + .tab("General")); defs.add(FieldDef.row( FieldDef.stringEnumField("ability.rotationMode", RotationMode.getDisplayKeys(), - () -> this.getRotationMode().getDisplayKey(), - v -> { - for (RotationMode m : RotationMode.values()) { - if (m.getDisplayKey().equals(v)) { this.setRotationMode(m); break; } - } - }) + () -> this.getRotationMode().getDisplayKey(), + v -> { + for (RotationMode m : RotationMode.values()) { + if (m.getDisplayKey().equals(v)) { + this.setRotationMode(m); + break; + } + } + }) .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; } - } - }) + () -> this.getRotationPhase().getDisplayKey(), + v -> { + for (LockMode t : LockMode.values()) { + if (t.getDisplayKey().equals(v)) { + this.setRotationPhase(t); + break; + } + } + }) .hover("ability.hover.rotationPhase") .visibleWhen(() -> this.rotationMode != RotationMode.FREE) ).tab("General")); + defs.add(FieldDef.floatField("ability.trackSpeed", this::getTrackSpeed, this::setTrackSpeed) + .range(0.0f, 12.0f) + .hover("ability.hover.trackSpeed") + .visibleWhen(() -> this.rotationMode == RotationMode.TRACK) + .tab("General")); defs.add(FieldDef.row( FieldDef.boolField("ability.interruptible", this::isInterruptible, this::setInterruptible) - .hover("ability.hover.interruptible"), + .hover("ability.hover.interruptible") + .enabledWhen(() -> !invulnerableMode.invulnerableDuringWindup()), FieldDef.intField("ability.dazedTicks", this::getDazedTicks, this::setDazedTicks) - .range(0, 1000).visibleWhen(this::isInterruptible) + .range(0, 1000) + .visibleWhen(() -> isInterruptible() && !invulnerableMode.invulnerableDuringWindup()) ).tab("General")); + defs.add(FieldDef.stringEnumField("ability.invulnerable", InvulnerableMode.getDisplayKeys(), + () -> this.getInvulnerableMode().getDisplayKey(), + v -> { + for (InvulnerableMode mode : InvulnerableMode.values()) { + if (mode.getDisplayKey().equals(v)) { + this.setInvulnerableMode(mode); + break; + } + } + }) + .hover("ability.hover.invulnerable") + .tab("General")); + defs.add(FieldDef.boolField("ability.ignoreIFrames", this::isIgnoreIFrames, this::setIgnoreIFrames) + .hover("ability.hover.ignoreIFrames") + .visibleWhen(this::hasDamage) + .tab("General")); // ── Burst section ──────────────────────────────────────────── if (allowBurst()) { @@ -541,6 +820,29 @@ public abstract class Ability implements IAbility { } } + // ── Magic section ──────────────────────────────────────────── + if (hasMagic()) { + defs.add(FieldDef.section("ability.section.magic").tab("General")); + + defs.add(FieldDef.labelField("ability.magic.note", () -> { + if (magicData.isEmpty()) { + return StatCollector.translateToLocal("ability.magic.usesCaster"); + } + StringBuilder sb = new StringBuilder(); + for (Map.Entry entry : magicData.getMagics().entrySet()) { + Magic magic = MagicController.getInstance().getMagic(entry.getKey()); + if (magic != null) { + if (sb.length() > 0) sb.append(", "); + sb.append(magic.getDisplayName()).append(": ") + .append(Math.round(entry.getValue().split * 100)).append("%"); + } + } + return sb.toString(); + }).tab("General")); + + defs.add(SubGuiAbilityMagic.createMagicField(magicData)); + } + // ── Target tab ─────────────────────────────────────────────── defs.add(FieldDef.row( FieldDef.intField("ability.minRange", () -> (int) getMinRange(), v -> setMinRange(v)).range(0, 100), @@ -554,15 +856,17 @@ public abstract class Ability implements IAbility { allowedKeys[i] = allowed[i].name(); } defs.add(FieldDef.stringEnumField("ability.targetingMode", allowedKeys, - () -> this.getTargetingMode().name(), - v -> { - try { this.setTargetingMode(TargetingMode.valueOf(v)); } - catch (Exception ignored) {} - }) + () -> this.getTargetingMode().name(), + v -> { + try { + this.setTargetingMode(TargetingMode.valueOf(v)); + } catch (Exception ignored) { + } + }) .tab("Target").hover("ability.hover.targeting")); } else { defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, - this::getTargetingMode, this::setTargetingMode) + this::getTargetingMode, this::setTargetingMode) .tab("Target").hover("ability.hover.targeting")); } } @@ -575,16 +879,20 @@ public abstract class Ability implements IAbility { .tab("Effects")); defs.add(FieldDef.section("ability.section.animations").tab("Effects")); defs.add(FieldDef.animSubGui("ability.windUpAnimation", - this::getWindUpAnimationId, this::setWindUpAnimationId, - this::getWindUpAnimationName, this::setWindUpAnimationName) + this::getWindUpAnimationId, this::setWindUpAnimationId, + this::getWindUpAnimationName, this::setWindUpAnimationName) .tab("Effects")); defs.add(FieldDef.animSubGui("ability.activeAnimation", - this::getActiveAnimationId, this::setActiveAnimationId, - this::getActiveAnimationName, this::setActiveAnimationName) + this::getActiveAnimationId, this::setActiveAnimationId, + this::getActiveAnimationName, this::setActiveAnimationName) + .tab("Effects")); + defs.add(FieldDef.animSubGui("ability.dazedAnimation", + this::getDazedAnimationId, this::setDazedAnimationId, + this::getDazedAnimationName, this::setDazedAnimationName) .tab("Effects")); TelegraphType tType = getTelegraphType(); - if (tType != null && tType != TelegraphType.NONE) { + if (tType != null && tType != TelegraphType.NONE && !hasOwnTelegraphControls()) { defs.add(FieldDef.section("ability.section.telegraph").tab("Effects") .hover("telegraph." + tType.name().toLowerCase())); defs.add(FieldDef.boolField("ability.showTelegraph", this::isShowTelegraph, this::setShowTelegraph) @@ -605,6 +913,37 @@ public abstract class Ability implements IAbility { } } + // ── Icon section (Effects tab) ─────────────────────────── + if (!isNpcInlineEdit()) { + AbilityIconData icon = AbilityIconData.fromAbility(this); + java.util.function.BooleanSupplier isCustom = icon::isEnabled; + + defs.add(FieldDef.section("ability.section.icon").tab("Effects")); + defs.add(FieldDef.boolField("ability.hasIcon", icon::isEnabled, icon::setEnabled) + .tab("Effects")); + defs.add(FieldDef.row( + FieldDef.intField("gui.width", icon::getWidth, icon::setWidth).range(1, 256), + FieldDef.intField("gui.height", icon::getHeight, icon::setHeight).range(1, 256) + ).tab("Effects").visibleWhen(isCustom)); + defs.add(FieldDef.floatField("gui.scale", icon::getScale, icon::setScale) + .tab("Effects").range(0.1f, 10.0f).visibleWhen(isCustom)); + defs.add(FieldDef.intField("ability.icon.layers", icon::getLayerCount, icon::setLayerCount) + .tab("Effects").range(1, AbilityIconData.MAX_LAYERS).visibleWhen(isCustom)); + + addIconLayerFields(defs, icon, 0, isCustom); + addIconLayerFields(defs, icon, 1, () -> isCustom.getAsBoolean() && icon.getLayerCount() >= 2); + addIconLayerFields(defs, icon, 2, () -> isCustom.getAsBoolean() && icon.getLayerCount() >= 3); + + // Animation + defs.add(FieldDef.section("Animation").tab("Effects").visibleWhen(isCustom)); + defs.add(FieldDef.boolField("gui.animated", icon::isAnimated, icon::setAnimated) + .tab("Effects").visibleWhen(isCustom).hover("gui.animated.hover")); + defs.add(FieldDef.intField("gui.frameCount", icon::getFrameCount, icon::setFrameCount) + .tab("Effects").range(1, 256).visibleWhen(() -> isCustom.getAsBoolean() && icon.isAnimated())); + defs.add(FieldDef.intField("gui.frameTime", icon::getFrameTime, icon::setFrameTime) + .tab("Effects").range(1, 100).visibleWhen(() -> isCustom.getAsBoolean() && icon.isAnimated())); + } + // External field providers (e.g., DBC Addon injecting a "DBC" tab) for (IAbilityFieldProvider provider : AbilityController.Instance.getFieldProviders()) { provider.addFieldDefinitions(this, defs); @@ -613,6 +952,28 @@ public abstract class Ability implements IAbility { return defs; } + private void addIconLayerFields(List defs, AbilityIconData icon, int layerIndex, + java.util.function.BooleanSupplier visible) { + String sectionLabel = StatCollector.translateToLocal("ability.icon.layer") + " " + (layerIndex + 1); + defs.add(FieldDef.section(sectionLabel).tab("Effects").visibleWhen(visible)); + defs.add(FieldDef.textureSubGui("gui.texture", + () -> icon.getLayer(layerIndex).texture, + t -> icon.setLayerTexture(layerIndex, t)) + .tab("Effects").visibleWhen(visible)); + defs.add(FieldDef.row( + FieldDef.intField("ability.icon.x", + () -> icon.getLayer(layerIndex).iconX, + x -> icon.setLayerIconX(layerIndex, x)).range(0, 4096), + FieldDef.intField("ability.icon.y", + () -> icon.getLayer(layerIndex).iconY, + y -> icon.setLayerIconY(layerIndex, y)).range(0, 4096) + ).tab("Effects").visibleWhen(visible)); + defs.add(FieldDef.colorSubGui("ability.icon.tint", + () -> icon.getLayer(layerIndex).tintColor, + c -> icon.setLayerTintColor(layerIndex, c)) + .tab("Effects").visibleWhen(visible)); + } + /** * Creates the GUI for configuring this ability. * Override this method to provide a custom GUI subclass for type-specific settings. @@ -632,7 +993,7 @@ public abstract class Ability implements IAbility { * Create a telegraph instance for this ability. * Override for custom telegraph shapes. * - * @param caster The caster + * @param caster The caster * @param target The target (for position calculation) * @return The telegraph instance, or null if no telegraph */ @@ -671,25 +1032,29 @@ public abstract class Ability implements IAbility { telegraph = Telegraph.circle(getTelegraphRadius()); break; case RING: - telegraph = Telegraph.ring(getTelegraphRadius(), getTelegraphRadius() * 0.5f); + telegraph = Telegraph.ring(getTelegraphRadius(), getTelegraphInnerRadius()); break; case LINE: telegraph = Telegraph.line(getTelegraphLength(), getTelegraphWidth()); break; case CONE: - telegraph = Telegraph.cone(getTelegraphLength(), getTelegraphAngle()); + telegraph = Telegraph.cone(getTelegraphLength(), getTelegraphAngle(), getTelegraphInnerRadius()); break; case POINT: telegraph = new Telegraph("", TelegraphType.POINT); break; + case SQUARE: + telegraph = Telegraph.square(getTelegraphRadius()); + break; default: return null; } - telegraph.setDurationTicks(windUpTicks); + int windUp = getWindUpTicks(); + telegraph.setDurationTicks(windUp); telegraph.setColor(windUpColor); telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setWarningStartTick(Math.max(5, windUp / 4)); telegraph.setHeightOffset(telegraphHeightOffset); TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); @@ -700,11 +1065,17 @@ public abstract class Ability implements IAbility { // AOE_SELF abilities: telegraph follows caster during windup instance.setEntityIdToFollow(caster.getEntityId()); - // For LINE/CONE telegraphs: track target direction during windup + // For LINE/CONE telegraphs: track direction during windup // Only track if rotation is NOT locked during windup (NPC can still turn) - if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { + if (telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) { if (!isRotationLockedDuringWindup()) { - instance.setTargetEntityId(target.getEntityId()); + if (target != null) { + // Face the target entity + instance.setTargetEntityId(target.getEntityId()); + } else { + // No target (AOE_SELF etc.): track caster's own rotationYaw + instance.setTrackFollowedEntityYaw(true); + } } // If rotation is locked, yaw stays fixed at creation time } @@ -716,85 +1087,74 @@ 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. + * Uses default search range of 3 blocks — if no ground is found, + * returns slightly below the entity for airborne telegraph placement. * * @param world The world * @param x X coordinate * @param startY Starting Y coordinate (entity feet position) * @param z Z coordinate - * @return The Y coordinate of the ground surface + * @return The Y coordinate of the ground surface, or startY - 0.5 if airborne */ public static double findGroundLevel(World world, double x, double startY, double z) { - if (world == null) return startY; + return findGroundLevel(world, x, startY, z, 3); + } + + /** + * Find the ground level at a given position with configurable search range. + * Searches downward from the given Y to find a solid block. + * + * @param world The world + * @param x X coordinate + * @param startY Starting Y coordinate (entity feet position) + * @param z Z coordinate + * @param maxSearchDown Maximum blocks to search downward + * @return The Y coordinate of the ground surface, or startY - 0.5 if no ground found + */ + public static double findGroundLevel(World world, double x, double startY, double z, int maxSearchDown) { + if (world == null) return startY - 0.5; int blockX = (int) Math.floor(x); int blockZ = (int) Math.floor(z); int startBlockY = (int) Math.floor(startY); - // Search downward for solid ground (max 10 blocks down) - for (int checkY = startBlockY; checkY >= startBlockY - 10 && checkY >= 0; checkY--) { + for (int checkY = startBlockY; checkY >= startBlockY - maxSearchDown && checkY >= 0; checkY--) { Block block = world.getBlock(blockX, checkY, blockZ); if (block != null && block.getMaterial().isSolid()) { - // Found solid block, telegraph goes on top of it return checkY + 1; } } - // No ground found, use original position - return startY; + // No ground found within range — place slightly under entity + return startY - 0.5; } /** - * Calculates offset position near the given coordinates. - * Used to place effects near a target rather than exactly on them. - * - * @param baseX Base X coordinate - * @param baseY Base Y coordinate - * @param baseZ Base Z coordinate - * @param minOffset Minimum offset distance - * @param maxOffset Maximum offset distance - * @param randomOffset Whether to use random offset within range, or fixed at max - * @param random Random instance to use - * @return Array of [x, y, z] with offset applied + * Get the current telegraph instances. */ - public static double[] calculateOffsetPosition(double baseX, double baseY, double baseZ, - float minOffset, float maxOffset, - boolean randomOffset, java.util.Random random) { - if (maxOffset <= 0) { - return new double[]{baseX, baseY, baseZ}; - } - - double offsetDist; - double offsetAngle; - - if (randomOffset) { - offsetDist = minOffset + random.nextDouble() * (maxOffset - minOffset); - offsetAngle = random.nextDouble() * Math.PI * 2; - } else { - offsetDist = maxOffset; - offsetAngle = random.nextDouble() * Math.PI * 2; - } - - double offsetX = Math.cos(offsetAngle) * offsetDist; - double offsetZ = Math.sin(offsetAngle) * offsetDist; - - return new double[]{baseX + offsetX, baseY, baseZ + offsetZ}; + public List getTelegraphInstances() { + return telegraphInstances; } /** - * Get the current telegraph instance. + * Set the telegraph instances (called by DataAbilities). */ - public TelegraphInstance getTelegraphInstance() { - return telegraphInstance; - } - - /** - * Set the telegraph instance (called by DataAbilities). - */ - public void setTelegraphInstance(TelegraphInstance instance) { - this.telegraphInstance = instance; + public void setTelegraphInstances(List instances) { + this.telegraphInstances = instances != null ? instances : new ArrayList<>(); } // ═══════════════════════════════════════════════════════════════════ @@ -812,7 +1172,9 @@ public abstract class Ability implements IAbility { this.burstIndex = 0; this.burstEntities.clear(); - if (windUpTicks <= 0) { + // Use the effective windup, not the raw field: when the windup is synced to an + // animation the raw field is not the duration that actually applies. + if (getWindUpTicks() <= 0) { this.phase = AbilityPhase.ACTIVE; } else { this.phase = AbilityPhase.WINDUP; @@ -834,7 +1196,7 @@ public abstract class Ability implements IAbility { switch (phase) { case WINDUP: - if (currentTick >= windUpTicks) { + if (currentTick >= getWindUpTicks()) { phase = AbilityPhase.ACTIVE; currentTick = 0; return true; @@ -881,9 +1243,9 @@ public abstract class Ability implements IAbility { if (phase == AbilityPhase.ACTIVE) { // Check if more burst iterations remain if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) { - if (!burstOverlap) { - cleanup(); - } + // Reset transient state for next burst iteration (e.g., movement direction, hit lists) + // Does NOT kill entities - they may still be in flight (overlap mode) + resetForBurst(); burstIndex++; phase = AbilityPhase.BURST_DELAY; currentTick = 0; @@ -892,7 +1254,12 @@ public abstract class Ability implements IAbility { // Final completion - let burst entities die naturally (don't force-kill) burstEntities.clear(); - cleanup(); + if (freeOnCast) { + // Free on Cast: detach entities (let them live independently) instead of killing + detach(); + } else { + cleanup(); + } phase = AbilityPhase.IDLE; currentTick = 0; return true; @@ -907,8 +1274,8 @@ public abstract class Ability implements IAbility { public void interrupt() { cleanupBurstEntities(); cleanup(); - if (interruptible && (phase == AbilityPhase.WINDUP || phase == AbilityPhase.BURST_DELAY)) { - // Interrupted during windup or burst delay - go to dazed state + if (interruptible && phase == AbilityPhase.WINDUP) { + // Interrupted during windup - go to dazed state phase = AbilityPhase.DAZED; currentTick = 0; } else { @@ -918,7 +1285,21 @@ public abstract class Ability implements IAbility { } burstIndex = 0; currentTarget = null; - telegraphInstance = null; + telegraphInstances.clear(); + } + + /** + * Cancel this ability (voluntary player action). Goes directly to IDLE, skipping DAZED. + * Entities are killed via cleanup(). Unlike interrupt(), this never enters DAZED phase. + */ + public void cancel() { + cleanupBurstEntities(); + cleanup(); + phase = AbilityPhase.IDLE; + currentTick = 0; + burstIndex = 0; + currentTarget = null; + telegraphInstances.clear(); } /** @@ -931,13 +1312,18 @@ public abstract class Ability implements IAbility { /** * Check if can be interrupted by this damage source. * Only direct physical hits (not magic, fire, or other indirect damage) can interrupt. - * Interruption only occurs during WINDUP phase - if ability is already active, it completes. + * Interruption only occurs during WINDUP phase (including burst replay windups). + * BURST_DELAY is not interruptible - only the windup animation itself can be interrupted. + * For chained abilities, windUpAll controls whether subsequent entries even have a windup. * * @param source The damage source * @return true if the ability should be interrupted */ public boolean canInterrupt(DamageSource source) { - if (!interruptible || (phase != AbilityPhase.WINDUP && phase != AbilityPhase.BURST_DELAY)) { + if (!interruptible || phase != AbilityPhase.WINDUP) { + return false; + } + if (isInvulnerableForCurrentPhase()) { return false; } @@ -970,9 +1356,10 @@ public abstract class Ability implements IAbility { currentTick = 0; burstIndex = 0; currentTarget = null; - telegraphInstance = null; + telegraphInstances.clear(); previewMode = false; previewEntityHandler = null; + instanceScript = null; } /** @@ -1021,11 +1408,14 @@ public abstract class Ability implements IAbility { * Spawn an entity during ability execution. * In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld(). */ - protected void spawnAbilityEntity(World world, Entity entity) { + protected void spawnAbilityEntity(Entity entity) { if (previewMode && previewEntityHandler != null) { previewEntityHandler.onEntitySpawned(entity); } else { - world.spawnEntityInWorld(entity); + entity.worldObj.spawnEntityInWorld(entity); + if (!entity.worldObj.isRemote && entity instanceof EntityEnergyProjectile) { + EventHooks.onEnergyProjectileFired((EntityEnergyProjectile) entity); + } } if (burstEnabled && burstOverlap) { burstEntities.add(entity); @@ -1058,7 +1448,15 @@ public abstract class Ability implements IAbility { // ═══════════════════════════════════════════════════════════════════ public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsNpc()) continue; + Boolean extendedCondition = AbilityController.Instance.fireCheckConditions(c, caster, target); + + if (extendedCondition != null) { + if (!extendedCondition) return false; + continue; + } + if (!c.check(caster, target)) return false; } return true; @@ -1068,8 +1466,16 @@ public abstract class Ability implements IAbility { * Check conditions for a player caster, skipping target-requiring conditions. */ public boolean checkConditionsForPlayer(EntityLivingBase caster) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsPlayer()) continue; if (c.requiresTarget()) continue; + Boolean extendedCondition = AbilityController.Instance.fireCheckConditionsForPlayer(c, caster); + + if (extendedCondition != null) { + if (!extendedCondition) return false; + continue; + } + if (!c.check(caster, null)) return false; } return true; @@ -1080,10 +1486,11 @@ public abstract class Ability implements IAbility { // NBT (config only, execution state is transient) // ═══════════════════════════════════════════════════════════════════ - public NBTTagCompound writeNBT() { + public NBTTagCompound writeNBT(boolean saveScripts) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setString("id", id); nbt.setString("name", name); + nbt.setString("displayName", displayName); nbt.setString("typeId", typeId); nbt.setInteger("weight", weight); nbt.setBoolean("enabled", enabled); @@ -1095,23 +1502,44 @@ public abstract class Ability implements IAbility { nbt.setBoolean("syncWindup", syncWindupWithAnimation); nbt.setInteger("recovery", dazedTicks); nbt.setBoolean("interruptible", interruptible); + nbt.setInteger("invulnerableMode", invulnerableMode.ordinal()); + nbt.setBoolean("ignoreIFrames", ignoreIFrames); nbt.setInteger("lockMovement", lockMovement.ordinal()); nbt.setInteger("rotationMode", rotationMode.ordinal()); nbt.setInteger("rotationPhase", rotationPhase.ordinal()); + nbt.setFloat("trackSpeed", trackSpeed); nbt.setInteger("windUpColor", windUpColor); nbt.setInteger("activeColor", activeColor); nbt.setString("windUpSound", windUpSound); nbt.setString("activeSound", activeSound); nbt.setInteger("windUpAnimationId", windUpAnimationId); nbt.setInteger("activeAnimationId", activeAnimationId); - nbt.setString("windUpAnimationName", windUpAnimationName); - nbt.setString("activeAnimationName", activeAnimationName); + nbt.setInteger("dazedAnimationId", dazedAnimationId); + // Resolve current animation names from controller before writing + nbt.setString("windUpAnimationName", resolveAnimationName(windUpAnimationId, windUpAnimationName)); + nbt.setString("activeAnimationName", resolveAnimationName(activeAnimationId, activeAnimationName)); + nbt.setString("dazedAnimationName", resolveAnimationName(dazedAnimationId, dazedAnimationName)); nbt.setBoolean("showTelegraph", showTelegraph); nbt.setString("telegraphType", telegraphType.name()); nbt.setFloat("telegraphHeightOffset", telegraphHeightOffset); - nbt.setTag("customData", customData); + nbt.setTag("customData", (NBTTagCompound) customData.copy()); + TagController.writeTagUUIDs(nbt, "TagUUIDs", tagUUIDs); + magicData.writeToNBT(nbt); nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); + nbt.setBoolean("perAbilityCooldown", perAbilityCooldown); + nbt.setBoolean("freeOnCast", freeOnCast); + + // Toggle + nbt.setInteger("toggleStates", toggleStates); + nbt.setBoolean("hasActiveToggle", hasActiveToggle); + if (toggleStateLabels != null && toggleStateLabels.length > 0) { + NBTTagList labelList = new NBTTagList(); + for (String label : toggleStateLabels) { + labelList.appendTag(new NBTTagString(label != null ? label : "")); + } + nbt.setTag("toggleStateLabels", labelList); + } // Burst nbt.setBoolean("burstEnabled", burstEnabled); @@ -1122,12 +1550,12 @@ public abstract class Ability implements IAbility { // Conditions NBTTagList condList = new NBTTagList(); - for (Condition c : conditions) condList.appendTag(c.writeNBT()); + for (AbilityCondition c : conditions) condList.appendTag(c.writeNBT()); nbt.setTag("conditions", condList); // Effects NBTTagList effectList = new NBTTagList(); - for (AbilityEffect effect : effects) { + for (AbilityPotionEffect effect : effects) { effectList.appendTag(effect.writeNBT()); } nbt.setTag("effects", effectList); @@ -1137,81 +1565,97 @@ public abstract class Ability implements IAbility { writeTypeNBT(typeNBT); nbt.setTag("typeData", typeNBT); + // Script handler data (matching CustomEffect.writeToNBT pattern) + if (saveScripts) { + AbilityScript handler = getScriptHandler(); + if (handler != null) { + NBTTagCompound scriptData = new NBTTagCompound(); + handler.writeToNBT(scriptData); + nbt.setTag("ScriptData", scriptData); + } + } + return nbt; } public void readNBT(NBTTagCompound nbt) { id = nbt.getString("id"); name = nbt.getString("name"); + displayName = nbt.getString("displayName"); typeId = nbt.getString("typeId"); - weight = nbt.getInteger("weight"); - enabled = nbt.getBoolean("enabled"); - targetingMode = TargetingMode.valueOf(nbt.getString("targetingMode")); + weight = nbt.hasKey("weight") ? nbt.getInteger("weight") : 10; + enabled = nbt.hasKey("enabled") ? nbt.getBoolean("enabled") : true; + try { + targetingMode = TargetingMode.valueOf(nbt.getString("targetingMode")); + } catch (Exception e) { + targetingMode = TargetingMode.AGGRO_TARGET; + } minRange = nbt.getFloat("minRange"); maxRange = nbt.getFloat("maxRange"); cooldownTicks = nbt.getInteger("cooldown"); windUpTicks = nbt.getInteger("windUp"); - syncWindupWithAnimation = !nbt.hasKey("syncWindup") || nbt.getBoolean("syncWindup"); - dazedTicks = nbt.getInteger("recovery"); - interruptible = nbt.getBoolean("interruptible"); - lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement")); - if (nbt.hasKey("rotationMode")) { - // Current format - rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); - rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); - } else if (nbt.hasKey("lockType")) { - // Legacy format migration: lockType was LockType enum (0=MOVEMENT, 1=ROTATION, 2=BOTH) - int oldLockType = nbt.getInteger("lockType"); - if (oldLockType == 0) { - // MOVEMENT only: movement locked, rotation was free - rotationMode = RotationMode.FREE; - } else if (oldLockType == 1) { - // ROTATION only: rotation locked same timing as old lockMovement, movement was free - rotationMode = RotationMode.LOCKED; - rotationPhase = lockMovement; - lockMovement = LockMovementType.NO; - } else { - // BOTH: both locked same timing - rotationMode = RotationMode.LOCKED; - rotationPhase = lockMovement; - } - } else { - rotationMode = RotationMode.FREE; - rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; - } - windUpColor = nbt.getInteger("windUpColor"); - activeColor = nbt.getInteger("activeColor"); + syncWindupWithAnimation = nbt.hasKey("syncWindup") ? nbt.getBoolean("syncWindup") : true; + dazedTicks = nbt.hasKey("recovery") ? nbt.getInteger("recovery") : 80; + interruptible = nbt.hasKey("interruptible") ? nbt.getBoolean("interruptible") : true; + invulnerableMode = nbt.hasKey("invulnerableMode") + ? InvulnerableMode.fromOrdinal(nbt.getInteger("invulnerableMode")) + : InvulnerableMode.NONE; + ignoreIFrames = nbt.hasKey("ignoreIFrames") && nbt.getBoolean("ignoreIFrames"); + lockMovement = LockMode.fromOrdinal(nbt.getInteger("lockMovement")); + rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); + rotationPhase = LockMode.fromOrdinal(nbt.getInteger("rotationPhase")); + trackSpeed = nbt.hasKey("trackSpeed") ? nbt.getFloat("trackSpeed") : 0; + windUpColor = nbt.hasKey("windUpColor") ? nbt.getInteger("windUpColor") : 0x80FF4400; + activeColor = nbt.hasKey("activeColor") ? nbt.getInteger("activeColor") : 0xC0FF0000; 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"); + dazedAnimationId = nbt.hasKey("dazedAnimationId") ? nbt.getInteger("dazedAnimationId") : -1; 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; - } + dazedAnimationName = nbt.hasKey("dazedAnimationName") ? nbt.getString("dazedAnimationName") : "Ability_Generic_Dazed"; + showTelegraph = nbt.hasKey("showTelegraph") ? nbt.getBoolean("showTelegraph") : true; + try { + telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); + } catch (Exception e) { + telegraphType = TelegraphType.CIRCLE; + } + telegraphHeightOffset = nbt.getFloat("telegraphHeightOffset"); + customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy(); + tagUUIDs = TagController.readTagUUIDs(nbt, "TagUUIDs"); + magicData.readToNBT(nbt); + allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); + ignoreCooldown = nbt.getBoolean("ignoreCooldown"); + perAbilityCooldown = nbt.getBoolean("perAbilityCooldown"); + freeOnCast = nbt.getBoolean("freeOnCast"); + + // Toggle + toggleStates = nbt.getInteger("toggleStates"); + hasActiveToggle = nbt.getBoolean("hasActiveToggle"); + if (nbt.hasKey("toggleStateLabels")) { + NBTTagList labelList = nbt.getTagList("toggleStateLabels", 8); + toggleStateLabels = new String[labelList.tagCount()]; + for (int i = 0; i < labelList.tagCount(); i++) { + String label = labelList.getStringTagAt(i); + toggleStateLabels[i] = (label != null && !label.isEmpty()) ? label : null; + } + } else { + toggleStateLabels = null; } - telegraphHeightOffset = nbt.hasKey("telegraphHeightOffset") ? nbt.getFloat("telegraphHeightOffset") : 0.1f; - customData = nbt.getCompoundTag("customData"); - allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH; - ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown"); // Burst - burstEnabled = nbt.hasKey("burstEnabled") && nbt.getBoolean("burstEnabled"); - burstAmount = nbt.hasKey("burstAmount") ? nbt.getInteger("burstAmount") : 0; - burstDelay = nbt.hasKey("burstDelay") ? nbt.getInteger("burstDelay") : 0; - burstReplayAnimations = !nbt.hasKey("burstReplayAnimations") || nbt.getBoolean("burstReplayAnimations"); - burstOverlap = nbt.hasKey("burstOverlap") && nbt.getBoolean("burstOverlap"); + burstEnabled = nbt.getBoolean("burstEnabled"); + burstAmount = nbt.getInteger("burstAmount"); + burstDelay = nbt.getInteger("burstDelay"); + burstReplayAnimations = nbt.hasKey("burstReplayAnimations") ? nbt.getBoolean("burstReplayAnimations") : true; + burstOverlap = nbt.getBoolean("burstOverlap"); // Conditions conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); for (int i = 0; i < condList.tagCount(); i++) { - Condition c = Condition.fromNBT(condList.getCompoundTagAt(i)); + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); if (c != null) conditions.add(c); } @@ -1220,14 +1664,28 @@ public abstract class Ability implements IAbility { 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)); + AbilityPotionEffect effect = AbilityPotionEffect.fromNBT(effectList.getCompoundTagAt(i)); if (effect != null && effect.isValid()) { effects.add(effect); } } } - readTypeNBT(nbt.getCompoundTag("typeData")); + // Type-specific + if (nbt.hasKey("typeData")) { + readTypeNBT(nbt.getCompoundTag("typeData")); + } + + // Script handler data (matching CustomEffect.readFromNBT pattern) + // Only create a new handler if one doesn't already exist in the global map, + // to avoid clobbering a live handler's script state during deepCopy/resolve. + if (nbt.hasKey("ScriptData", 10)) { + if (getScriptHandler() == null) { + AbilityScript handler = new AbilityScript(this.id); + handler.readFromNBT(nbt.getCompoundTag("ScriptData")); + setScriptHandler(handler); + } + } } // ═══════════════════════════════════════════════════════════════════ @@ -1247,13 +1705,112 @@ public abstract class Ability implements IAbility { } public void setName(String name) { - this.name = name; + if (builtIn) { + this.name = name != null ? name : ""; + return; + } + String fallback = (this.name != null && !this.name.isEmpty()) ? this.name : "Ability"; + this.name = FileNameHelper.sanitizeName(name, fallback); + } + + /** + * Get the display name for this ability. + * Returns displayName if set, otherwise falls back to name. + * Converts & color codes to § for rendering. + */ + public String getDisplayName() { + String result = (displayName != null && !displayName.isEmpty()) + ? displayName + : FileNameHelper.toDisplayName(name); + return result != null ? result.replaceAll("&([0-9a-fk-or])", "\u00A7$1") : ""; + } + + /** + * Get the raw display name (may be empty). + */ + public String getRawDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName != null ? displayName : ""; } public String getTypeId() { return typeId; } + public boolean isBuiltIn() { + return builtIn; + } + + /** + * Get the registry key for built-in abilities. + * Returns null for custom abilities. + */ + public String getRegistryKey() { + return registryKey; + } + + /** + * Configure this ability as a built-in ability with fixed config. + * Sets builtIn flag, assigns registry key, id, name, and derives typeId. + * Call this in the constructor of any ability that should be non-customizable. + */ + protected void configureAsBuiltIn(String registryKey) { + this.builtIn = true; + this.registryKey = registryKey; + this.id = registryKey; + this.name = registryKey; + this.typeId = "ability." + registryKey.replace(':', '.'); + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFAULT ICON + // ═══════════════════════════════════════════════════════════════════ + + public DefaultIconLayer[] getDefaultIconLayers() { + return defaultIconLayers; + } + + public int getDefaultIconWidth() { + return defaultIconWidth; + } + + public int getDefaultIconHeight() { + return defaultIconHeight; + } + + public boolean hasDefaultIcon() { + return defaultIconLayers != null && defaultIconLayers.length > 0 + && defaultIconLayers[0].texture != null && !defaultIconLayers[0].texture.isEmpty(); + } + + public Ability deepCopy() { + Ability copy = AbilityController.Instance.fromNBT(this.writeNBT(false)); + if (copy != null) + copy.playerRequirement = this.playerRequirement; + return copy; + } + + @Override + public boolean isChain() { + return false; + } + + @Override + public IAbilityAction deepCopyAction() { + return deepCopy(); + } + + public boolean isNpcInlineEdit() { + return npcInlineEdit; + } + + public void setNpcInlineEdit(boolean npcInlineEdit) { + this.npcInlineEdit = npcInlineEdit; + } + public int getWeight() { return weight; } @@ -1342,11 +1899,37 @@ public abstract class Ability implements IAbility { this.interruptible = interruptible; } - public LockMovementType getLockMovement() { + public InvulnerableMode getInvulnerableMode() { + return invulnerableMode; + } + + public void setInvulnerableMode(InvulnerableMode invulnerableMode) { + this.invulnerableMode = invulnerableMode != null ? invulnerableMode : InvulnerableMode.NONE; + } + + public boolean isInvulnerableDuringWindup() { + return invulnerableMode.invulnerableDuringWindup(); + } + + public boolean isInvulnerableDuringActive() { + return invulnerableMode.invulnerableDuringActive(); + } + + @Override + public boolean isIgnoreIFrames() { + return ignoreIFrames; + } + + @Override + public void setIgnoreIFrames(boolean ignore) { + this.ignoreIFrames = ignore; + } + + public LockMode getLockMovement() { return lockMovement; } - public void setLockMovement(LockMovementType lockMovement) { + public void setLockMovement(LockMode lockMovement) { this.lockMovement = lockMovement; } @@ -1358,16 +1941,26 @@ public abstract class Ability implements IAbility { this.rotationMode = rotationMode; } - public LockMovementType getRotationPhase() { + public LockMode getRotationPhase() { return rotationPhase; } - public void setRotationPhase(LockMovementType rotationPhase) { + public void setRotationPhase(LockMode rotationPhase) { this.rotationPhase = rotationPhase; } + public float getTrackSpeed() { + return trackSpeed; + } + + public void setTrackSpeed(float trackSpeed) { + this.trackSpeed = trackSpeed; + } + + /** * API method: Get lock movement type as integer. + * * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE */ @Override @@ -1377,15 +1970,17 @@ public abstract class Ability implements IAbility { /** * API method: Set lock movement type from integer. + * * @param type 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE */ @Override public void setLockMovementType(int type) { - this.lockMovement = LockMovementType.fromOrdinal(type); + this.lockMovement = LockMode.fromOrdinal(type); } /** * API method: Get rotation mode as integer. + * * @return 0=FREE, 1=LOCKED, 2=TRACK */ @Override @@ -1395,6 +1990,7 @@ public abstract class Ability implements IAbility { /** * API method: Set rotation mode from integer. + * * @param type 0=FREE, 1=LOCKED, 2=TRACK */ @Override @@ -1404,6 +2000,7 @@ public abstract class Ability implements IAbility { /** * API method: Get rotation phase as integer. + * * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE */ @Override @@ -1413,11 +2010,31 @@ public abstract class Ability implements IAbility { /** * 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); + this.rotationPhase = LockMode.fromOrdinal(type); + } + + /** + * API method: Get track speed for TRACK rotation mode (blocks/second). + * 0 = instant tracking. Comparable to player sprint speed (~5.6 blocks/sec). + */ + @Override + public float getTrackSpeedValue() { + return trackSpeed; + } + + /** + * API method: Set track speed for TRACK rotation mode (blocks/second). + * + * @param speed 0 = instant tracking. ~4 = dodgeable while sprinting. ~6 = barely undodgeable. + */ + @Override + public void setTrackSpeedValue(float speed) { + this.trackSpeed = Math.max(0, speed); } /** @@ -1468,6 +2085,20 @@ public abstract class Ability implements IAbility { } } + /** + * Check if this ability grants invulnerability during its current execution phase. + */ + public boolean isInvulnerableForCurrentPhase() { + return invulnerableMode.isInvulnerableInPhase(phase); + } + + /** + * Check if this ability grants invulnerability for a specific phase. + */ + public boolean isInvulnerableForPhase(AbilityPhase phase) { + return invulnerableMode.isInvulnerableInPhase(phase); + } + /** * Check if rotation should be locked during the current phase. */ @@ -1533,17 +2164,32 @@ public abstract class Ability implements IAbility { this.activeSound = activeSound; } + /** + * Resolves the current animation name for a custom animation ID. + * If the ID refers to a custom animation, looks up the current name from the controller. + * For built-in animations (id == -1), returns the stored name as-is. + */ + protected String resolveAnimationName(int animId, String storedName) { + if (animId >= 0 && AnimationController.Instance != null) { + Animation anim = (Animation) AnimationController.Instance.get(animId); + if (anim != null && anim.name != null && !anim.name.isEmpty()) { + return anim.name; + } + } + return storedName; + } + public Animation getWindUpAnimation() { if (AnimationController.Instance == null) return null; - // Built-in animation by name takes priority - if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(windUpAnimationName, true); - } - // Fall back to user animation by ID + // Custom animation by ID (most reliable, survives renames) if (windUpAnimationId >= 0) { return (Animation) AnimationController.Instance.get(windUpAnimationId); } + // Built-in animation by name + if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(windUpAnimationName, true); + } return null; } @@ -1566,14 +2212,14 @@ public abstract class Ability implements IAbility { public Animation getActiveAnimation() { if (AnimationController.Instance == null) return null; - // Built-in animation by name takes priority - if (activeAnimationName != null && !activeAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(activeAnimationName, true); - } - // Fall back to user animation by ID + // Custom animation by ID (most reliable, survives renames) if (activeAnimationId >= 0) { return (Animation) AnimationController.Instance.get(activeAnimationId); } + // Built-in animation by name + if (activeAnimationName != null && !activeAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(activeAnimationName, true); + } return null; } @@ -1593,6 +2239,36 @@ public abstract class Ability implements IAbility { this.activeAnimationName = activeAnimationName != null ? activeAnimationName : ""; } + public Animation getDazedAnimation() { + if (AnimationController.Instance == null) return null; + + // Custom animation by ID (most reliable, survives renames) + if (dazedAnimationId >= 0) { + return (Animation) AnimationController.Instance.get(dazedAnimationId); + } + // Built-in animation by name + if (dazedAnimationName != null && !dazedAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(dazedAnimationName, true); + } + return null; + } + + public int getDazedAnimationId() { + return dazedAnimationId; + } + + public void setDazedAnimationId(int dazedAnimationId) { + this.dazedAnimationId = dazedAnimationId; + } + + public String getDazedAnimationName() { + return dazedAnimationName; + } + + public void setDazedAnimationName(String dazedAnimationName) { + this.dazedAnimationName = dazedAnimationName != null ? dazedAnimationName : ""; + } + public boolean isShowTelegraph() { return showTelegraph; } @@ -1621,6 +2297,18 @@ public abstract class Ability implements IAbility { return phase; } + /** + * Get the damage multiplier applied by the ability itself (e.g. Slam height scaling). + * Extenders should apply this after their own damage calculation. + */ + public float getDamageMultiplier() { + return damageMultiplier; + } + + public void setDamageMultiplier(float damageMultiplier) { + this.damageMultiplier = damageMultiplier; + } + /** * Get the current execution phase as int (0=IDLE, 1=WINDUP, 2=ACTIVE, 3=DAZED). * Required for IAbility interface. @@ -1642,11 +2330,48 @@ public abstract class Ability implements IAbility { return customData; } - public List getConditions() { + public HashSet getTagUUIDs() { + return tagUUIDs; + } + + public void setTagUUIDs(HashSet tagUUIDs) { + this.tagUUIDs = tagUUIDs; + } + + public MagicData getMagicData() { + return magicData; + } + + /** + * Resolve magic data for this ability + caster combination. + * If the ability has its own magic data, use that (override). + * Otherwise, fall back to the caster's magic data (player or NPC). + * + * @return Resolved MagicData, or null if neither has magic + */ + public MagicData resolveMagicData(EntityLivingBase caster) { + if (!this.magicData.isEmpty()) { + return this.magicData; + } + if (caster instanceof EntityPlayer) { + PlayerData data = PlayerData.get((EntityPlayer) caster); + if (data != null && data.magicData != null && !data.magicData.isEmpty()) { + return data.magicData; + } + } else if (caster instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) caster; + if (npc.stats != null && npc.stats.magicData != null && !npc.stats.magicData.isEmpty()) { + return npc.stats.magicData; + } + } + return null; + } + + public List getConditions() { return conditions; } - public void addCondition(Condition c) { + public void addCondition(AbilityCondition c) { conditions.add(c); } @@ -1658,6 +2383,22 @@ public abstract class Ability implements IAbility { this.allowedBy = allowedBy; } + public Predicate getPlayerRequirement() { + return playerRequirement; + } + + public void setPlayerRequirement(Predicate requirement) { + this.playerRequirement = requirement; + } + + /** + * Check if this ability is available for the given player. + * Returns true if no requirement is set, or if the requirement predicate passes. + */ + public boolean isAvailableFor(EntityPlayer player) { + return playerRequirement == null || playerRequirement.test(player); + } + public boolean isIgnoreCooldown() { return ignoreCooldown; } @@ -1666,15 +2407,71 @@ public abstract class Ability implements IAbility { this.ignoreCooldown = ignoreCooldown; } - public List getEffects() { + public boolean isPerAbilityCooldown() { + return perAbilityCooldown; + } + + public void setPerAbilityCooldown(boolean perAbilityCooldown) { + this.perAbilityCooldown = perAbilityCooldown; + } + + public boolean isFreeOnCast() { + return freeOnCast; + } + + public void setFreeOnCast(boolean freeOnCast) { + this.freeOnCast = freeOnCast; + } + + public boolean isToggleable() { + return toggleStates > 0; + } + + public int getToggleStates() { + return toggleStates; + } + + public void setToggleStates(int toggleStates) { + this.toggleStates = Math.max(0, toggleStates); + } + + public boolean hasActiveToggle() { + return hasActiveToggle; + } + + public void setHasActiveToggle(boolean hasActiveToggle) { + this.hasActiveToggle = hasActiveToggle; + } + + /** + * Get the display label for a specific toggle state. + * @param state 1-based state index + * @return the label, or null if none set + */ + public String getToggleStateLabel(int state) { + if (toggleStateLabels != null && state >= 1 && state <= toggleStateLabels.length) { + return toggleStateLabels[state - 1]; + } + return null; + } + + /** + * Set display labels for toggle states (1-indexed). + * @param labels one label per state, null entries allowed + */ + public void setToggleStateLabels(String... labels) { + this.toggleStateLabels = (labels != null && labels.length > 0) ? labels : null; + } + + public List getEffects() { return effects; } - public void setEffects(List effects) { + public void setEffects(List effects) { this.effects = effects != null ? effects : new ArrayList<>(); } - public void addEffect(AbilityEffect effect) { + public void addEffect(AbilityPotionEffect effect) { if (effect != null && effect.isValid()) { effects.add(effect); } @@ -1742,7 +2539,7 @@ public abstract class Ability implements IAbility { } // ═══════════════════════════════════════════════════════════════════ - // SHIT FROM THE ASS + // WINDUP DURATION CALCULATION // ═══════════════════════════════════════════════════════════════════ private int calculateWindupFromAnimation() { @@ -1755,14 +2552,14 @@ public abstract class Ability implements IAbility { } Animation animation = null; - // Check for built-in animation (by name) first - if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { - animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true); - } - // Fall back to user animation (by ID) - else if (windUpAnimationId >= 0) { + // Custom animation by ID (most reliable, survives renames) + if (windUpAnimationId >= 0) { animation = (Animation) AnimationController.Instance.get(windUpAnimationId); } + // Built-in animation by name + else if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { + animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true); + } if (animation == null || animation.frames.isEmpty()) { return this.windUpTicks; @@ -1778,6 +2575,269 @@ 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; + } + + /** + * Check if a caster's movement in a given direction is blocked by a solid enemy barrier. + * Tests a short segment from the caster's current position along the movement direction + * against all active dome and panel barriers. + * + * @return true if a solid enemy barrier blocks the movement + */ + protected static boolean isMovementBlockedByBarrier(EntityLivingBase caster, double dirX, double dirZ, double speed) { + if (caster.worldObj == null) return false; + + double nextX = caster.posX + dirX * speed; + double nextZ = caster.posZ + dirZ * speed; + double eyeY = caster.posY + caster.getEyeHeight() * 0.5; + + java.util.List barriers = EntityEnergyBarrier.getActiveBarriers(caster.worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead || barrier.isCharging()) continue; + if (!barrier.getBarrierData().solid) continue; + + // Skip barriers owned by or allied to the caster + if (barrier.getOwnerEntityId() == caster.getEntityId()) continue; + Entity barrierOwner = barrier.getOwnerEntity(); + if (barrierOwner instanceof EntityLivingBase) { + if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue; + } + + if (barrier instanceof EntityEnergyDome) { + EntityEnergyDome dome = (EntityEnergyDome) barrier; + float radius = dome.getDomeRadius(); + + // Check if the movement segment crosses the dome boundary (either direction) + double ocX = caster.posX - dome.posX; + double ocY = eyeY - dome.posY; + double ocZ = caster.posZ - dome.posZ; + + double rdX = nextX - caster.posX; + double rdZ = nextZ - caster.posZ; + double a = rdX * rdX + rdZ * rdZ; + double b = 2.0 * (ocX * rdX + ocZ * rdZ); + double c = ocX * ocX + ocZ * ocZ - (double) radius * radius; + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0 || a < 1e-10) continue; + double sqrtD = Math.sqrt(discriminant); + double t1 = (-b - sqrtD) / (2.0 * a); + double t2 = (-b + sqrtD) / (2.0 * a); + if ((t1 >= 0.0 && t1 <= 1.0) || (t2 >= 0.0 && t2 <= 1.0)) return true; + } else if (barrier instanceof EntityEnergyPanel) { + EntityEnergyPanel panel = (EntityEnergyPanel) barrier; + float halfW = panel.getPanelData().getPanelWidth() * 0.5f; + float halfH = panel.getPanelData().getPanelHeight() * 0.5f; + float yawRad = (float) Math.toRadians(panel.getPanelYaw()); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + + double relX = caster.posX - panel.posX; + double relZ = caster.posZ - panel.posZ; + double prevDist = relX * normalX + relZ * normalZ; + + double relNX = nextX - panel.posX; + double relNZ = nextZ - panel.posZ; + double currDist = relNX * normalX + relNZ * normalZ; + + // Check if segment crosses the panel plane + if (prevDist * currDist > 0) continue; + + double rayDirX = nextX - caster.posX; + double rayDirZ = nextZ - caster.posZ; + double denom = rayDirX * normalX + rayDirZ * normalZ; + if (Math.abs(denom) < 1e-10) continue; + + double t = -prevDist / denom; + if (t < 0.0 || t > 1.0) continue; + + double hitX = caster.posX + rayDirX * t; + double hitZ = caster.posZ + rayDirZ * t; + + double localRight = (hitX - panel.posX) * cos + (hitZ - panel.posZ) * sin; + if (Math.abs(localRight) > halfW) continue; + double localY = eyeY - panel.posY; + if (Math.abs(localY) > halfH) continue; + + return true; + } + } + return false; + } + + // ═══════════════════════════════════════════════════════════════════ + // LINE-OF-SIGHT UTILITIES + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if there is a clear line of sight (no solid blocks) between caster and target. + * Raycasts from caster's eye position to target's body center. + * + * @return true if there IS line of sight (no blocks in the way) + */ + public static boolean hasLineOfSight(World world, EntityLivingBase caster, EntityLivingBase target) { + Vec3 start = Vec3.createVectorHelper(caster.posX, caster.posY + caster.getEyeHeight(), caster.posZ); + Vec3 end = Vec3.createVectorHelper(target.posX, target.posY + target.height * 0.5, target.posZ); + MovingObjectPosition result = world.rayTraceBlocks(start, end); + return result == null; + } + + /** + * Check if an enemy barrier (dome or panel) blocks the line between caster and target. + * Barriers owned by the caster or allies of the caster are not considered blocking. + * + * @return true if an enemy barrier blocks the attack + */ + @SuppressWarnings("unchecked") + public static boolean isBlockedByBarrier(World world, EntityLivingBase caster, EntityLivingBase target) { + // Barrier entities have tiny Minecraft bounding boxes (1x1 for domes, 0.5x0.5 for panels) + // but their actual collision geometry extends up to MAX_ENTITY_RADIUS (50) blocks. + // Must expand search to match EntityEnergyProjectile.checkBarrierCollision() pattern. + double searchRange = 55.0; // MAX_ENTITY_RADIUS(50) + 5 + double minX = Math.min(caster.posX, target.posX) - searchRange; + double minY = Math.min(caster.posY, target.posY) - searchRange; + double minZ = Math.min(caster.posZ, target.posZ) - searchRange; + double maxX = Math.max(caster.posX, target.posX) + searchRange; + double maxY = Math.max(caster.posY, target.posY) + searchRange; + double maxZ = Math.max(caster.posZ, target.posZ) + searchRange; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + List barriers = world.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); + + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead) continue; + if (barrier.isCharging()) continue; + + // Skip barriers owned by caster or allies + if (barrier.getOwnerEntityId() == caster.getEntityId()) continue; + Entity barrierOwner = barrier.getOwnerEntity(); + if (barrierOwner instanceof EntityLivingBase) { + if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue; + } + + if (barrier instanceof EntityEnergyDome) { + if (isDomeBlocking((EntityEnergyDome) barrier, caster, target)) return true; + } else if (barrier instanceof EntityEnergyPanel) { + if (isPanelBlocking((EntityEnergyPanel) barrier, caster, target)) return true; + } + } + + return false; + } + + /** + * Check if a dome blocks an attack from caster to target. + * Blocks when caster is outside and target is inside the dome. + */ + private static boolean isDomeBlocking(EntityEnergyDome dome, EntityLivingBase caster, EntityLivingBase target) { + float radius = dome.getDomeRadius(); + + double cdx = caster.posX - dome.posX; + double cdy = (caster.posY + caster.getEyeHeight()) - dome.posY; + double cdz = caster.posZ - dome.posZ; + double casterDist = Math.sqrt(cdx * cdx + cdy * cdy + cdz * cdz); + + double tdx = target.posX - dome.posX; + double tdy = (target.posY + target.height * 0.5) - dome.posY; + double tdz = target.posZ - dome.posZ; + double targetDist = Math.sqrt(tdx * tdx + tdy * tdy + tdz * tdz); + + // Block when caster is outside and target is inside + return casterDist > radius && targetDist < radius; + } + + /** + * Check if a panel blocks an attack from caster to target. + * Checks if the line from caster to target crosses through the panel bounds. + */ + private static boolean isPanelBlocking(EntityEnergyPanel panel, EntityLivingBase caster, EntityLivingBase target) { + float halfW = panel.getPanelData().panelWidth * 0.5f; + float halfH = panel.getPanelData().panelHeight * 0.5f; + + // Panel normal direction + float yawRad = (float) Math.toRadians(panel.getPanelYaw()); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + + // Line from caster to target + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + double dx = target.posX - startX; + double dy = (target.posY + target.height * 0.5) - startY; + double dz = target.posZ - startZ; + + // Dot product of line direction with panel normal + double denom = dx * normalX + dz * normalZ; + if (Math.abs(denom) < 0.0001) return false; // Line parallel to panel + + // Parameter t where line crosses panel plane + double relX = panel.posX - startX; + double relZ = panel.posZ - startZ; + double t = (relX * normalX + relZ * normalZ) / denom; + + if (t < 0 || t > 1) return false; // Intersection outside the line segment + + // Calculate intersection point + double hitX = startX + dx * t; + double hitY = startY + dy * t; + double hitZ = startZ + dz * t; + + // Transform to panel local space (right axis) + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + double localRight = (hitX - panel.posX) * cos + (hitZ - panel.posZ) * sin; + double localUp = hitY - panel.posY; + + // Check bounds + return Math.abs(localRight) <= halfW && Math.abs(localUp) <= halfH; + } + // ═══════════════════════════════════════════════════════════════════ // IAbility API METHODS // ═══════════════════════════════════════════════════════════════════ @@ -1794,11 +2854,56 @@ public abstract class Ability implements IAbility { @Override public INbt getNbt() { - return NpcAPI.Instance().getINbt(writeNBT()); + return NpcAPI.Instance().getINbt(writeNBT(false)); } @Override public void setNbt(INbt nbt) { readNBT(nbt.getMCNBT()); } + + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT HANDLER + // ═══════════════════════════════════════════════════════════════════ + + public AbilityScript getScriptHandler() { + if (this.id == null || this.id.isEmpty()) return null; + return AbilityController.Instance.abilityScriptHandlers.get(this.id); + } + + public void setScriptHandler(AbilityScript handler) { + if (this.id == null || this.id.isEmpty()) return; + AbilityController.Instance.abilityScriptHandlers.put(this.id, handler); + } + + public AbilityScript getOrCreateScriptHandler() { + if (this.id == null || this.id.isEmpty()) return null; + AbilityScript handler = getScriptHandler(); + if (handler == null) { + handler = new AbilityScript(this.id); + AbilityController.Instance.abilityScriptHandlers.put(this.id, handler); + } + return handler; + } + + /** + * Get or create a per-instance script handler for this ability execution. + * Shares the template's engine but creates isolated Bindings for variable state. + * Returns null if no script is configured on the template. + */ + public AbilityScript getOrCreateInstanceScript() { + if (instanceScript != null) return instanceScript; + + AbilityScript template = getScriptHandler(); + if (template == null || !template.getEnabled() || template.container == null) return null; + + instanceScript = new AbilityScript(this.id); + instanceScript.setLanguage(template.getLanguage()); + instanceScript.setEnabled(true); + + IScriptUnit clone = template.container.createInstanceScope(instanceScript); + instanceScript.addScriptUnit(clone); + + return instanceScript; + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java new file mode 100644 index 000000000..e9909bcf9 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java @@ -0,0 +1,323 @@ +package kamkeel.npcs.controllers.data.ability; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.UUID; + +/** + * Unified slot for storing any combat action: inline ability, ability reference, or chain reference. + * Support for all {@link IAbilityAction} types. + *

+ * References are lazy-resolved via their respective controllers and cached until + * the controller revision changes. + */ +public class AbilityAction { + + public enum SlotType { + INLINE_ABILITY, + ABILITY_REFERENCE, + CHAIN_REFERENCE, + INLINE_CHAIN + } + + private SlotType slotType; + private Ability inlineAbility; + private ChainedAbility inlineChain; + private String referenceId; + + /** + * Per-slot enabled override for reference slots (null = use master's default). + */ + private Boolean enabledOverride; + + // Cache + private transient IAbilityAction cachedAction; + private transient int cachedRevision = -1; + + private AbilityAction() { + } + + // ═══════════════════════════════════════════════════════════════════ + // FACTORY METHODS + // ═══════════════════════════════════════════════════════════════════ + + public static AbilityAction inline(Ability ability) { + AbilityAction slot = new AbilityAction(); + slot.slotType = SlotType.INLINE_ABILITY; + slot.inlineAbility = ability; + return slot; + } + + public static AbilityAction abilityReference(String referenceId) { + AbilityAction slot = new AbilityAction(); + slot.slotType = SlotType.ABILITY_REFERENCE; + slot.referenceId = referenceId; + return slot; + } + + public static AbilityAction chainReference(String referenceId) { + AbilityAction slot = new AbilityAction(); + slot.slotType = SlotType.CHAIN_REFERENCE; + slot.referenceId = referenceId; + return slot; + } + + public static AbilityAction inlineChain(ChainedAbility chain) { + AbilityAction slot = new AbilityAction(); + slot.slotType = SlotType.INLINE_CHAIN; + slot.inlineChain = chain; + return slot; + } + + // ═══════════════════════════════════════════════════════════════════ + // QUERIES + // ═══════════════════════════════════════════════════════════════════ + + public SlotType getSlotType() { + return slotType; + } + + public boolean isReference() { + return slotType == SlotType.ABILITY_REFERENCE || slotType == SlotType.CHAIN_REFERENCE; + } + + public boolean isChainReference() { + return slotType == SlotType.CHAIN_REFERENCE; + } + + public boolean isInlineChain() { + return slotType == SlotType.INLINE_CHAIN; + } + + public boolean isChain() { + return slotType == SlotType.CHAIN_REFERENCE || slotType == SlotType.INLINE_CHAIN; + } + + public boolean isAbilityReference() { + return slotType == SlotType.ABILITY_REFERENCE; + } + + public String getReferenceId() { + return referenceId; + } + + // ═══════════════════════════════════════════════════════════════════ + // RESOLUTION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Resolve the action. Inline returns directly; references resolve + * from the appropriate controller with version-based caching. + */ + public IAbilityAction getAction() { + switch (slotType) { + case INLINE_ABILITY: + return inlineAbility; + + case INLINE_CHAIN: + return inlineChain; + + case ABILITY_REFERENCE: { + AbilityController ctrl = AbilityController.Instance; + if (ctrl == null) return null; + int rev = ctrl.getCustomAbilityRevision(); + if (cachedAction != null && cachedRevision == rev) { + return cachedAction; + } + Ability resolved = ctrl.resolveAbility(referenceId); + cachedAction = resolved; + cachedRevision = rev; + return cachedAction; + } + + case CHAIN_REFERENCE: { + AbilityController ctrl = AbilityController.Instance; + if (ctrl == null) return null; + int rev = ctrl.getChainedAbilityRevision(); + if (cachedAction != null && cachedRevision == rev) { + return cachedAction; + } + ChainedAbility resolved = ctrl.resolveChainedAbility(referenceId); + cachedAction = resolved; + cachedRevision = rev; + return cachedAction; + } + + default: + return null; + } + } + + /** + * Get as Ability (returns null if this is a chain slot or resolution fails). + */ + public Ability getAbility() { + IAbilityAction action = getAction(); + return (action instanceof Ability) ? (Ability) action : null; + } + + /** + * Get as ChainedAbility (returns null if this is an ability slot or resolution fails). + */ + public ChainedAbility getChainedAbility() { + IAbilityAction action = getAction(); + return (action instanceof ChainedAbility) ? (ChainedAbility) action : null; + } + + // ═══════════════════════════════════════════════════════════════════ + // ENABLED OVERRIDE + // ═══════════════════════════════════════════════════════════════════ + + public void setEnabled(boolean enabled) { + if (slotType == SlotType.INLINE_ABILITY) { + if (inlineAbility != null) { + inlineAbility.setEnabled(enabled); + } + } else if (slotType == SlotType.INLINE_CHAIN) { + if (inlineChain != null) { + inlineChain.setEnabled(enabled); + } + } else { + this.enabledOverride = enabled; + } + } + + /** + * Check if this slot is enabled. For inline slots, delegates to the action directly. + * For reference slots, uses enabledOverride if set, otherwise the resolved action's own state. + * This avoids mutating the shared controller instance. + */ + public boolean isSlotEnabled() { + if (enabledOverride != null) { + return enabledOverride; + } + IAbilityAction action = getAction(); + return action != null && action.isEnabled(); + } + + // ═══════════════════════════════════════════════════════════════════ + // INLINE CONVERSION (ability references only) + // ═══════════════════════════════════════════════════════════════════ + + public Ability getInlineAbility() { + return inlineAbility; + } + + public ChainedAbility getInlineChain() { + return inlineChain; + } + + /** + * Convert this reference slot to an inline slot by copying the resolved data. + * Works for ability references (→ INLINE_ABILITY) and chain references (→ INLINE_CHAIN). + * Chain entries are kept as-is (not auto-converted to inline). + */ + public boolean convertToInline() { + if (slotType == SlotType.ABILITY_REFERENCE) { + Ability resolved = getAbility(); + if (resolved == null) return false; + + NBTTagCompound nbt = resolved.writeNBT(true); + nbt.setString("id", UUID.randomUUID().toString()); + inlineAbility = AbilityController.Instance.fromNBT(nbt); + slotType = SlotType.INLINE_ABILITY; + referenceId = null; + cachedAction = null; + cachedRevision = -1; + return true; + } + + if (slotType == SlotType.CHAIN_REFERENCE) { + ChainedAbility resolved = getChainedAbility(); + if (resolved == null) return false; + + inlineChain = new ChainedAbility(); + NBTTagCompound chainNbt = resolved.writeNBT(true); + chainNbt.setString("Id", UUID.randomUUID().toString()); + inlineChain.readNBT(chainNbt); + slotType = SlotType.INLINE_CHAIN; + referenceId = null; + cachedAction = null; + cachedRevision = -1; + return true; + } + + return false; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + public NBTTagCompound writeNBT(boolean saveScripts) { + switch (slotType) { + case INLINE_CHAIN: { + NBTTagCompound nbt = new NBTTagCompound(); + if (inlineChain != null) { + nbt.setTag("InlineChain", inlineChain.writeNBT(saveScripts)); + } + return nbt; + } + + case CHAIN_REFERENCE: { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("ChainReference", referenceId); + if (enabledOverride != null) { + nbt.setBoolean("RefEnabled", enabledOverride); + } + return nbt; + } + + case ABILITY_REFERENCE: { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("Reference", referenceId); + if (enabledOverride != null) { + nbt.setBoolean("RefEnabled", enabledOverride); + } + return nbt; + } + + case INLINE_ABILITY: + default: + return inlineAbility != null ? inlineAbility.writeNBT(saveScripts) : new NBTTagCompound(); + } + } + + public static AbilityAction fromNBT(NBTTagCompound nbt) { + if (nbt == null) return null; + + // Inline chain (new format) + if (nbt.hasKey("InlineChain")) { + ChainedAbility chain = new ChainedAbility(); + chain.readNBT(nbt.getCompoundTag("InlineChain")); + return inlineChain(chain); + } + + // Chain reference + if (nbt.hasKey("ChainReference")) { + AbilityAction slot = chainReference(nbt.getString("ChainReference")); + if (nbt.hasKey("RefEnabled")) { + slot.enabledOverride = nbt.getBoolean("RefEnabled"); + } + return slot; + } + + // Ability reference + if (nbt.hasKey("Reference")) { + AbilityAction slot = abilityReference(nbt.getString("Reference")); + if (nbt.hasKey("RefEnabled")) { + slot.enabledOverride = nbt.getBoolean("RefEnabled"); + } + return slot; + } + + // Inline ability + if (AbilityController.Instance == null) return null; + Ability ability = AbilityController.Instance.fromNBT(nbt); + if (ability == null) return null; + return inline(ability); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java deleted file mode 100644 index 294f9a765..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ /dev/null @@ -1,529 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import kamkeel.npcs.controllers.data.ability.type.*; -import kamkeel.npcs.controllers.SyncController; -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 java.io.File; -import java.util.*; -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. */ - 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. */ - private final List fieldProviders = new ArrayList<>(); - - /** External variant definitions registered by addons, keyed by typeId. */ - private final Map> externalVariants = new LinkedHashMap<>(); - - public AbilityController() { - registerBuiltinTypes(); - } - - // ═══════════════════════════════════════════════════════════════════════════ - // LOADING / SAVING CUSTOM ABILITIES - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * 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; - } - - File[] files = dir.listFiles(); - if (files == null) return; - - for (File file : files) { - if (!file.isFile() || !file.getName().endsWith(".json")) continue; - try { - String filename = file.getName(); - String uuid = filename.substring(0, filename.length() - 5); // strip .json - - NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); - Ability ability = fromNBT(nbt); - if (ability != null) { - ability.setId(uuid); - customAbilities.put(uuid, ability); - } - } catch (Exception e) { - LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e); - } - } - 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; - - String uuid = ability.getId(); - if (uuid == null || uuid.isEmpty()) { - uuid = UUID.randomUUID().toString(); - ability.setId(uuid); - } - - File dir = getDir(); - File fileNew = new File(dir, uuid + ".json_new"); - File fileCurrent = new File(dir, uuid + ".json"); - - try { - NBTTagCompound nbt = ability.writeNBT(); - NBTJsonUtil.SaveFile(fileNew, nbt); - - if (fileCurrent.exists()) { - fileCurrent.delete(); - } - fileNew.renameTo(fileCurrent); - if (fileNew.exists()) { - fileNew.delete(); - } - - customAbilities.put(uuid, ability); - version++; - LogWriter.info("Saved custom ability: " + ability.getName() + " [" + uuid + "]"); - SyncController.syncAllCustomAbilities(); - return true; - } catch (Exception e) { - LogWriter.error("Error saving custom ability: " + uuid, e); - return false; - } - } - - /** - * Delete a custom ability preset by UUID. - */ - public boolean deleteCustomAbility(String uuid) { - if (uuid == null || uuid.isEmpty()) return false; - - Ability removed = customAbilities.remove(uuid); - if (removed == null) return false; - - File dir = getDir(); - File file = new File(dir, uuid + ".json"); - if (file.exists()) { - file.delete(); - } - - version++; - 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 or registry key), - * then custom abilities (by UUID or name). Returns a copy safe to modify for - * custom abilities, or the singleton instance for built-in abilities. - * - * @param key The ability name, registry key (built-in) or UUID (custom) - * @return 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 (exact match by name) - Ability builtIn = abilities.get(key); - if (builtIn != null) { - return builtIn; - } - - // Check built-in abilities by name (case-insensitive) - for (Map.Entry entry : abilities.entrySet()) { - if (entry.getKey().equalsIgnoreCase(key)) { - return entry.getValue(); - } - } - - // Check built-in abilities by registry key / ID - for (Ability ability : abilities.values()) { - if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) { - return ability; - } - } - - // Check custom abilities (exact UUID match) - Ability custom = customAbilities.get(key); - if (custom != null) { - return fromNBT(custom.writeNBT()); - } - - // Check custom abilities by name (case-insensitive) - for (Ability ability : customAbilities.values()) { - if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { - return fromNBT(ability.writeNBT()); - } - } - - return null; - } - - /** - * Get all keys that can be used to look up abilities (for tab completion). - * Returns registry keys for built-in abilities (no spaces) and UUIDs for custom. - */ - public Set getAbilityKeys() { - Set keys = new LinkedHashSet<>(); - // Built-in abilities - use the ID (registry key for BuiltInAbility) - for (Ability ability : abilities.values()) { - String id = ability.getId(); - if (id != null && !id.isEmpty()) { - keys.add(id); - } - } - // Custom abilities - use UUID - keys.addAll(customAbilities.keySet()); - return keys; - } - - /** - * Get keys for player-usable abilities only (for tab completion). - */ - public Set getPlayerAbilityKeys() { - Set keys = new LinkedHashSet<>(); - // Built-in abilities - use the ID (registry key for BuiltInAbility) - for (Ability ability : abilities.values()) { - if (ability.getAllowedBy().allowsPlayer()) { - String id = ability.getId(); - if (id != null && !id.isEmpty()) { - keys.add(id); - } - } - } - // Custom abilities - use UUID (if player-usable) - for (Map.Entry entry : customAbilities.entrySet()) { - if (entry.getValue().getAllowedBy().allowsPlayer()) { - keys.add(entry.getKey()); - } - } - return keys; - } - - /** - * 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++; - } - - /** Get the version counter (incremented on custom ability changes). */ - public int getVersion() { - return version; - } - - // ═══════════════════════════════════════════════════════════════════════════ - // IAbilityHandler INTERFACE IMPLEMENTATION - // ═══════════════════════════════════════════════════════════════════════════ - - @Override - public String[] getTypes() { - return typeFactories.keySet().toArray(new String[0]); - } - - @Override - public boolean hasType(String typeId) { - return typeFactories.containsKey(typeId); - } - - @Override - public String[] getAbilityNameArray() { - return abilities.keySet().toArray(new String[0]); - } - - @Override - public boolean hasAbilityName(String name) { - return abilities.containsKey(name); - } - - @Override - public String[] getCustomAbilityIdArray() { - return customAbilities.keySet().toArray(new String[0]); - } - - @Override - public boolean hasCustomAbilityId(String uuid) { - return customAbilities.containsKey(uuid); - } - - @Override - public boolean deleteCustomAbilityById(String uuid) { - return deleteCustomAbility(uuid); - } - - // ═══════════════════════════════════════════════════════════════════════════ - // 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:disc", AbilityDisc::new); - registerType("cnpc:laser_shot", AbilityLaserShot::new); - registerType("cnpc:beam", AbilityBeam::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; - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EXTERNAL VARIANT REGISTRY - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register an external variant for an ability type. - * External mods can call this to add variant presets that appear - * alongside built-in variants in the variant selection SubGui. - * - * @param typeId The ability typeId (e.g., "ability.cnpc.beam") - * @param variant The variant to register - */ - public void registerVariant(String typeId, AbilityVariant variant) { - externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant); - } - - /** - * Get all variants for a given ability type (built-in + external). - * Returns the combined list of variants from the ability's getVariants() - * and any externally registered variants. - * - * @param typeId The ability typeId - * @return Combined list of variants, empty if none - */ - 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) { - result.addAll(ext); - } - return result; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java deleted file mode 100644 index 57f0cbf17..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java +++ /dev/null @@ -1,153 +0,0 @@ -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; - -/** - * Represents a configurable potion effect that can be applied by abilities. - * Provides a unified system for managing debuffs like slowness, weakness, poison, etc. - */ -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 int durationTicks = 60; - private int amplifier = 0; // 0-10 - - public AbilityEffect() { - } - - public AbilityEffect(EffectType type, int durationTicks, int amplifier) { - this.type = type; - this.durationTicks = Math.max(1, durationTicks); - this.amplifier = Math.max(0, Math.min(10, amplifier)); - } - - /** - * Creates a copy of this effect. - */ - public AbilityEffect copy() { - return new AbilityEffect(type, durationTicks, amplifier); - } - - /** - * Applies this effect to the given entity. - * Does nothing if type is NONE. - */ - public void apply(EntityLivingBase entity) { - if (entity == null || type == EffectType.NONE) { - return; - } - - int potionId = type.getPotionId(); - if (potionId >= 0) { - entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier)); - } - } - - /** - * Writes this effect to NBT. - */ - public NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("type", type.ordinal()); - nbt.setInteger("duration", durationTicks); - nbt.setInteger("amplifier", amplifier); - return nbt; - } - - /** - * 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; - } - - /** - * Creates an AbilityEffect from NBT. - */ - public static AbilityEffect fromNBT(NBTTagCompound nbt) { - AbilityEffect effect = new AbilityEffect(); - effect.readNBT(nbt); - return effect; - } - - // Getters & Setters - - public EffectType getType() { - return type; - } - - public void setType(EffectType type) { - this.type = type != null ? type : EffectType.NONE; - } - - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } - - public int getAmplifier() { - return amplifier; - } - - public void setAmplifier(int amplifier) { - this.amplifier = Math.max(0, Math.min(10, amplifier)); - } - - /** - * Returns true if this effect is configured (not NONE). - */ - public boolean isValid() { - return type != EffectType.NONE; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java deleted file mode 100644 index ca4e7471e..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java +++ /dev/null @@ -1,124 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * Wrapper that stores either an inline ability (full NBT) or a reference - * to a built-in/custom ability (by name or UUID). - *

- * References are lazy-resolved via {@link AbilityController#resolveAbility(String)} - * and cached until the controller version changes. - */ -public class AbilitySlot { - - private Ability inlineAbility; - private String referenceId; - - private transient Ability cachedAbility; - private transient int cachedVersion = -1; - - private AbilitySlot() {} - - /** - * Create a slot with an inline (embedded) ability. - */ - public static AbilitySlot inline(Ability ability) { - AbilitySlot slot = new AbilitySlot(); - slot.inlineAbility = ability; - slot.referenceId = null; - return slot; - } - - /** - * Create a slot that references a built-in ability (by name) or custom ability (by UUID). - */ - public static AbilitySlot reference(String referenceId) { - AbilitySlot slot = new AbilitySlot(); - slot.inlineAbility = null; - slot.referenceId = referenceId; - return slot; - } - - public boolean isReference() { - return referenceId != null; - } - - public String getReferenceId() { - return referenceId; - } - - /** - * Get the resolved ability. For inline slots, returns the ability directly. - * For reference slots, lazily resolves from AbilityController and caches. - * Returns null if the reference cannot be resolved (broken ref). - */ - public Ability getAbility() { - if (!isReference()) { - return inlineAbility; - } - - // Lazy resolve with version-based cache invalidation - AbilityController controller = AbilityController.Instance; - if (controller == null) return null; - - int currentVersion = controller.getVersion(); - if (cachedAbility != null && cachedVersion == currentVersion) { - return cachedAbility; - } - - cachedAbility = controller.resolveAbility(referenceId); - cachedVersion = currentVersion; - return cachedAbility; - } - - /** - * Get the inline ability directly (null for reference slots). - */ - public Ability getInlineAbility() { - return inlineAbility; - } - - /** - * Convert this reference slot to an inline slot by copying the resolved ability. - * No-op if already inline. Returns false if resolution fails. - */ - public boolean convertToInline() { - if (!isReference()) return true; - - Ability resolved = getAbility(); - if (resolved == null) return false; - - // Deep copy via NBT round-trip - inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT()); - referenceId = null; - cachedAbility = null; - cachedVersion = -1; - return true; - } - - // ═══════════════════════════════════════════════════════════════════ - // NBT - // ═══════════════════════════════════════════════════════════════════ - - public NBTTagCompound writeNBT() { - if (isReference()) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("Reference", referenceId); - return nbt; - } - return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound(); - } - - public static AbilitySlot fromNBT(NBTTagCompound nbt) { - if (nbt == null) return null; - - if (nbt.hasKey("Reference")) { - return reference(nbt.getString("Reference")); - } - - // Inline ability - Ability ability = AbilityController.Instance.fromNBT(nbt); - if (ability == null) return null; - return 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 index 797e6b20b..0ef3b9692 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java @@ -6,7 +6,7 @@ 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. */ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java deleted file mode 100644 index 904fad0b9..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java +++ /dev/null @@ -1,55 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * Abstract base class for built-in (non-customizable) abilities. - * Built-in abilities are registered by key, have fixed configurations, - * and cannot be modified through the preset GUI system. - *

- * Examples: simple utility abilities like Jump, Sprint, etc. - * Third-party mods can extend this class to create their own built-in abilities. - */ -public abstract class BuiltInAbility extends Ability { - - /** - * The registry key used to look up this ability (e.g., "cnpc:jump", "dbc:ki_blast"). - */ - private final String registryKey; - - public BuiltInAbility(String registryKey) { - this.registryKey = registryKey; - this.id = registryKey; - this.name = registryKey; - this.typeId = registryKey; - } - - /** - * Get the registry key for this built-in ability. - */ - public String getRegistryKey() { - return registryKey; - } - - /** - * Built-in abilities do not write type-specific NBT (they have fixed configs). - */ - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - // No-op: built-in abilities have fixed configurations - } - - /** - * Built-in abilities do not read type-specific NBT. - */ - @Override - public void readTypeNBT(NBTTagCompound nbt) { - // No-op: built-in abilities have fixed configurations - } - - /** - * Get the duration of the active phase in ticks. - * Built-in abilities must define their own active duration. - */ - public abstract int getActiveDurationTicks(); -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ConcurrentSlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ConcurrentSlot.java new file mode 100644 index 000000000..af9e31ba0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ConcurrentSlot.java @@ -0,0 +1,110 @@ +package kamkeel.npcs.controllers.data.ability; + +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import net.minecraft.entity.EntityLivingBase; + +/** + * Wraps a concurrent ability execution with its own independent lifecycle. + * Concurrent abilities skip animations, sounds, and movement/rotation locks. + * They run their execute/tick logic in parallel with the primary ability. + *

+ * Used by the chain system when an entry is concurrent-capable and concurrent-enabled. + */ +public class ConcurrentSlot { + + private final Ability ability; + private boolean started = false; + private boolean completed = false; + + public ConcurrentSlot(Ability ability) { + this.ability = ability; + } + + public Ability getAbility() { + return ability; + } + + public boolean isCompleted() { + return completed; + } + + /** + * Start the concurrent ability. Skips windup — goes straight to ACTIVE. + * Called once when the slot is activated. + */ + public void start(EntityLivingBase caster, EntityLivingBase target) { + // Skip windup for concurrent execution — fire immediately + ability.setWindUpTicks(0); + ability.start(target); + started = true; + + // Ability should now be in ACTIVE phase (0 windup → immediate) + if (ability.getPhase() == AbilityPhase.ACTIVE) { + ability.onExecute(caster, target); + } + + // Check if ability completed during onExecute (instant abilities like signalCompletion) + if (ability.getPhase() == AbilityPhase.IDLE) { + completed = true; + } + } + + /** + * Tick the concurrent ability. Called every game tick from AbstractDataAbilities. + * Handles phase transitions including burst delay → re-execute cycles. + */ + public void tick(EntityLivingBase caster, EntityLivingBase target) { + if (completed || !started) return; + + AbilityPhase oldPhase = ability.getPhase(); + boolean phaseChanged = ability.tick(); + AbilityPhase newPhase = ability.getPhase(); + + switch (newPhase) { + case ACTIVE: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Re-entering ACTIVE after burst delay → re-execute (burst re-fire) + ability.onExecute(caster, target); + if (ability.getPhase() == AbilityPhase.IDLE) { + completed = true; + return; + } + } + // Normal active tick + ability.onActiveTick(caster, target, ability.getCurrentTick()); + if (ability.getPhase() == AbilityPhase.IDLE) { + completed = true; + } + break; + + case BURST_DELAY: + // Waiting between bursts — nothing to do, tick() handles countdown + break; + + case WINDUP: + // Burst replay with windup — for concurrent, skip it by advancing + // (windUpTicks was set to 0 at start, but burst replay may re-enter WINDUP) + // The next tick() call will transition to ACTIVE + break; + + case IDLE: + completed = true; + break; + + case DAZED: + // Concurrent abilities don't get dazed — treat as completed + completed = true; + break; + } + } + + /** + * Force cleanup on interrupt. Called when the NPC is interrupted or combat ends. + */ + public void interrupt() { + if (!completed) { + ability.interrupt(); + completed = true; + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Condition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Condition.java deleted file mode 100644 index 1183fe858..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Condition.java +++ /dev/null @@ -1,313 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.entity.EntityNPCInterface; - -/** - * Interface for ability usage conditions. - * Conditions determine when an ability is eligible to be used. - */ -public interface Condition { - - /** - * Check if this condition is met. - * - * @param caster The entity that would use the ability (NPC or Player) - * @param target The current target (may be null for self-targeting abilities or players) - * @return true if the condition is satisfied - */ - boolean check(EntityLivingBase caster, EntityLivingBase target); - - /** - * Whether this condition requires a target entity to evaluate. - * Conditions that return true here will be skipped for player ability checks. - */ - default boolean requiresTarget() { - return false; - } - - /** - * Get the condition type ID for serialization. - */ - String getTypeId(); - - /** - * Write this condition to NBT. - */ - NBTTagCompound writeNBT(); - - /** - * Read this condition from NBT. - */ - void readNBT(NBTTagCompound nbt); - - /** - * Create a Condition from NBT data. - * Uses the "type" field to determine which implementation to create. - */ - static Condition fromNBT(NBTTagCompound nbt) { - if (nbt == null || !nbt.hasKey("type")) { - return null; - } - - String type = nbt.getString("type"); - Condition condition = null; - - switch (type) { - case "hp_above": - condition = new ConditionHPAbove(); - break; - case "hp_below": - condition = new ConditionHPBelow(); - break; - case "target_hp_above": - condition = new ConditionTargetHPAbove(); - break; - case "target_hp_below": - condition = new ConditionTargetHPBelow(); - break; - case "hit_count": - condition = new ConditionHitCount(); - break; - default: - return null; - } - - condition.readNBT(nbt); - return condition; - } - - // ═══════════════════════════════════════════════════════════════════ - // BUILT-IN CONDITION IMPLEMENTATIONS - // ═══════════════════════════════════════════════════════════════════ - - /** - * Condition: Caster HP is above a percentage threshold. - */ - class ConditionHPAbove implements Condition { - private float threshold = 0.5f; // 50% - - public ConditionHPAbove() { - } - - public ConditionHPAbove(float threshold) { - this.threshold = threshold; - } - - @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - return caster.getHealth() / caster.getMaxHealth() > threshold; - } - - @Override - public String getTypeId() { - return "hp_above"; - } - - @Override - public NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("type", getTypeId()); - nbt.setFloat("threshold", threshold); - return nbt; - } - - @Override - public void readNBT(NBTTagCompound nbt) { - threshold = nbt.getFloat("threshold"); - } - } - - /** - * Condition: Caster HP is below a percentage threshold. - */ - class ConditionHPBelow implements Condition { - private float threshold = 0.5f; - - public ConditionHPBelow() { - } - - public ConditionHPBelow(float threshold) { - this.threshold = threshold; - } - - @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - return caster.getHealth() / caster.getMaxHealth() < threshold; - } - - @Override - public String getTypeId() { - return "hp_below"; - } - - @Override - public NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("type", getTypeId()); - nbt.setFloat("threshold", threshold); - return nbt; - } - - @Override - public void readNBT(NBTTagCompound nbt) { - threshold = nbt.getFloat("threshold"); - } - } - - /** - * Condition: Target HP is above a percentage threshold. - * Requires a target - will be skipped for player ability checks. - */ - class ConditionTargetHPAbove implements Condition { - private float threshold = 0.5f; - - public ConditionTargetHPAbove() { - } - - public ConditionTargetHPAbove(float threshold) { - this.threshold = threshold; - } - - @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - if (target == null) return false; - return target.getHealth() / target.getMaxHealth() > threshold; - } - - @Override - public boolean requiresTarget() { - return true; - } - - @Override - public String getTypeId() { - return "target_hp_above"; - } - - @Override - public NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("type", getTypeId()); - nbt.setFloat("threshold", threshold); - return nbt; - } - - @Override - public void readNBT(NBTTagCompound nbt) { - threshold = nbt.getFloat("threshold"); - } - } - - /** - * Condition: Target HP is below a percentage threshold. - * Requires a target - will be skipped for player ability checks. - */ - class ConditionTargetHPBelow implements Condition { - private float threshold = 0.5f; - - public ConditionTargetHPBelow() { - } - - public ConditionTargetHPBelow(float threshold) { - this.threshold = threshold; - } - - @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - if (target == null) return false; - return target.getHealth() / target.getMaxHealth() < threshold; - } - - @Override - public boolean requiresTarget() { - return true; - } - - @Override - public String getTypeId() { - return "target_hp_below"; - } - - @Override - public NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("type", getTypeId()); - nbt.setFloat("threshold", threshold); - return nbt; - } - - @Override - public void readNBT(NBTTagCompound nbt) { - threshold = nbt.getFloat("threshold"); - } - } - - /** - * Condition: Caster has been hit X times within a time window. - * Useful for reactive abilities that trigger after receiving multiple hits. - * Currently only works for NPCs (requires DataAbilities hit tracking). - */ - class ConditionHitCount implements Condition { - private int requiredHits = 3; - private int withinTicks = 60; - - public ConditionHitCount() { - } - - public ConditionHitCount(int requiredHits, int withinTicks) { - this.requiredHits = requiredHits; - this.withinTicks = withinTicks; - } - - @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - // Check NPC's recent hit count from DataAbilities - if (caster instanceof EntityNPCInterface) { - EntityNPCInterface npc = (EntityNPCInterface) caster; - if (npc.abilities != null) { - return npc.abilities.getRecentHitCount(withinTicks) >= requiredHits; - } - } - // For players, hit count tracking is not yet supported - return false; - } - - @Override - public String getTypeId() { - return "hit_count"; - } - - @Override - public NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("type", getTypeId()); - nbt.setInteger("requiredHits", requiredHits); - nbt.setInteger("withinTicks", withinTicks); - return nbt; - } - - @Override - public void readNBT(NBTTagCompound nbt) { - requiredHits = nbt.getInteger("requiredHits"); - withinTicks = nbt.getInteger("withinTicks"); - } - - public int getRequiredHits() { - return requiredHits; - } - - public void setRequiredHits(int hits) { - this.requiredHits = hits; - } - - public int getWithinTicks() { - return withinTicks; - } - - public void setWithinTicks(int ticks) { - this.withinTicks = ticks; - } - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/CustomAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/CustomAbility.java new file mode 100644 index 000000000..fd9d32d39 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/CustomAbility.java @@ -0,0 +1,486 @@ +package kamkeel.npcs.controllers.data.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +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; +import noppes.npcs.api.ability.ICustomAbility; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * A blank-slate ability that does nothing by itself. + * All behavior is driven by script event hooks (abilityStart, abilityTick, abilityComplete, + * abilityToggle, abilityToggleTick). + *

+ * Supports two modes based on toggle configuration: + *

    + *
  • Instant mode (toggleStates = 0): Uses standard execution lifecycle with + * configurable duration. Script hooks: abilityStart, abilityTick, abilityComplete.
  • + *
  • Toggle mode (toggleStates >= 1): Uses toggle lifecycle. + * Script hooks: abilityToggle, abilityToggleTick.
  • + *
+ */ +public class CustomAbility extends Ability implements ICustomAbility { + + private int durationTicks = 20; + + // Telegraph dimension fields + private float tRadius = 5.0f; + private float tInnerRadius = 0.0f; + private float tLength = 5.0f; + private float tWidth = 2.0f; + private float tAngle = 45.0f; + + // Telegraph timing + private int telegraphActiveTicks = 0; + private boolean syncTelegraphWithDuration = true; + + public CustomAbility() { + this.typeId = "ability.cnpc.custom"; + this.name = "Custom"; + this.targetingMode = TargetingMode.SELF; + this.lockMovement = LockMode.NO; + this.cooldownTicks = 0; + this.windUpTicks = 0; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + } + + // ==================== EXECUTION ==================== + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (durationTicks <= 0) { + signalCompletion(); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (durationTicks > 0 && tick >= durationTicks) { + signalCompletion(); + } + } + + // ==================== PROPERTIES ==================== + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public boolean isTargetingModeLocked() { + return false; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public boolean hasOwnTelegraphControls() { + return true; + } + + // ==================== TELEGRAPH OVERRIDES ==================== + + @Override + public boolean keepTelegraphDuringActive() { + return getResolvedTelegraphActiveTicks() > 0; + } + + /** + * Returns the effective telegraph active ticks: synced from duration or manual value. + */ + public int getResolvedTelegraphActiveTicks() { + if (syncTelegraphWithDuration) { + return durationTicks; + } + return telegraphActiveTicks; + } + + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) { + return null; + } + + Telegraph telegraph; + double x, y, z; + float yaw = caster.rotationYaw; + TelegraphType tType = getTelegraphType(); + + boolean positionAtCaster = targetingMode == TargetingMode.AOE_SELF || + targetingMode == TargetingMode.SELF || + tType == TelegraphType.LINE || + tType == TelegraphType.CONE; + + if (positionAtCaster) { + x = caster.posX; + y = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ); + z = caster.posZ; + } else if (target != null) { + x = target.posX; + y = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ); + z = target.posZ; + } else { + x = caster.posX; + y = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ); + z = caster.posZ; + } + + switch (tType) { + case CIRCLE: + telegraph = Telegraph.circle(tRadius); + break; + case RING: + telegraph = Telegraph.ring(tRadius, tInnerRadius); + break; + case LINE: + telegraph = Telegraph.line(tLength, tWidth); + break; + case CONE: + telegraph = Telegraph.cone(tLength, tAngle, tInnerRadius); + break; + case POINT: + telegraph = new Telegraph("", TelegraphType.POINT); + break; + case SQUARE: + telegraph = Telegraph.square(tRadius); + break; + default: + return null; + } + + int activeTicks = getResolvedTelegraphActiveTicks(); + int totalDuration = windUpTicks + activeTicks; + telegraph.setDurationTicks(Math.max(1, totalDuration)); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + if (windUpTicks > 0) { + telegraph.setWarningStartTick(windUpTicks); + } else { + telegraph.setWarningStartTick(0); + } + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + instance.setCasterEntityId(caster.getEntityId()); + + if (positionAtCaster) { + instance.setEntityIdToFollow(caster.getEntityId()); + if (tType == TelegraphType.LINE || tType == TelegraphType.CONE) { + if (!isRotationLockedDuringWindup()) { + if (target != null) { + instance.setTargetEntityId(target.getEntityId()); + } else { + instance.setTrackFollowedEntityYaw(true); + } + } + } + } else if (target != null) { + instance.setEntityIdToFollow(target.getEntityId()); + } + + return instance; + } + + @Override + public float getTelegraphRadius() { + return tRadius; + } + + @Override + public float getTelegraphInnerRadius() { + return tInnerRadius; + } + + @Override + public float getTelegraphLength() { + return tLength; + } + + @Override + public float getTelegraphWidth() { + return tWidth; + } + + @Override + public float getTelegraphAngle() { + return tAngle; + } + + // ==================== FIELDS ==================== + + @Override + public int getDurationTicks() { + return durationTicks; + } + + @Override + public void setDurationTicks(int ticks) { + this.durationTicks = Math.max(0, ticks); + } + + public float getTRadius() { + return tRadius; + } + + public void setTRadius(float radius) { + this.tRadius = Math.max(0, radius); + } + + public float getTInnerRadius() { + return tInnerRadius; + } + + public void setTInnerRadius(float innerRadius) { + this.tInnerRadius = Math.max(0, innerRadius); + } + + public float getTLength() { + return tLength; + } + + public void setTLength(float length) { + this.tLength = Math.max(0, length); + } + + public float getTWidth() { + return tWidth; + } + + public void setTWidth(float width) { + this.tWidth = Math.max(0, width); + } + + public float getTAngle() { + return tAngle; + } + + public void setTAngle(float angle) { + this.tAngle = Math.max(0, angle); + } + + public int getTelegraphActiveTicks() { + return telegraphActiveTicks; + } + + public void setTelegraphActiveTicks(int ticks) { + this.telegraphActiveTicks = Math.max(0, ticks); + } + + public boolean isSyncTelegraphWithDuration() { + return syncTelegraphWithDuration; + } + + public void setSyncTelegraphWithDuration(boolean sync) { + this.syncTelegraphWithDuration = sync; + } + + // ==================== ICustomAbility ==================== + + @Override + public int getTelegraphShapeType() { + return getTelegraphType().ordinal(); + } + + @Override + public void setTelegraphShapeType(int type) { + TelegraphType[] values = TelegraphType.values(); + if (type >= 0 && type < values.length) { + setTelegraphType(values[type]); + } + } + + @Override + public void setTelegraphRadius(float radius) { + this.tRadius = Math.max(0, radius); + } + + @Override + public void setTelegraphInnerRadius(float innerRadius) { + this.tInnerRadius = Math.max(0, innerRadius); + } + + @Override + public void setTelegraphLength(float length) { + this.tLength = Math.max(0, length); + } + + @Override + public void setTelegraphWidth(float width) { + this.tWidth = Math.max(0, width); + } + + @Override + public void setTelegraphAngle(float angle) { + this.tAngle = Math.max(0, angle); + } + + @Override + public int getTargetingModeType() { + return getTargetingMode().ordinal(); + } + + @Override + public void setTargetingModeType(int type) { + TargetingMode[] values = TargetingMode.values(); + if (type >= 0 && type < values.length) { + setTargetingMode(values[type]); + } + } + + // ==================== NBT ==================== + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setFloat("tRadius", tRadius); + nbt.setFloat("tInnerRadius", tInnerRadius); + nbt.setFloat("tLength", tLength); + nbt.setFloat("tWidth", tWidth); + nbt.setFloat("tAngle", tAngle); + nbt.setInteger("telegraphActiveTicks", telegraphActiveTicks); + nbt.setBoolean("syncTelegraphWithDuration", syncTelegraphWithDuration); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + this.durationTicks = Math.max(0, nbt.getInteger("durationTicks")); + this.tRadius = nbt.hasKey("tRadius") ? nbt.getFloat("tRadius") : 5.0f; + this.tInnerRadius = nbt.hasKey("tInnerRadius") ? nbt.getFloat("tInnerRadius") : 0.0f; + this.tLength = nbt.hasKey("tLength") ? nbt.getFloat("tLength") : 5.0f; + this.tWidth = nbt.hasKey("tWidth") ? nbt.getFloat("tWidth") : 2.0f; + this.tAngle = nbt.hasKey("tAngle") ? nbt.getFloat("tAngle") : 45.0f; + this.telegraphActiveTicks = nbt.hasKey("telegraphActiveTicks") ? nbt.getInteger("telegraphActiveTicks") : 0; + this.syncTelegraphWithDuration = nbt.hasKey("syncTelegraphWithDuration") ? nbt.getBoolean("syncTelegraphWithDuration") : true; + } + + // ==================== GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + // User Type (NPC / Player / Both) + defs.add(FieldDef.enumField("ability.allowedBy", UserType.class, + this::getAllowedBy, this::setAllowedBy)); + + // Targeting Mode + defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, + this::getTargetingMode, this::setTargetingMode)); + + // Toggle section + defs.add(FieldDef.section("ability.section.toggle")); + defs.add(FieldDef.boolField("ability.toggleEnabled", + this::isToggleable, enabled -> setToggleStates(enabled ? Math.max(1, getToggleStates()) : 0))); + defs.add(FieldDef.intField("ability.toggleStates", this::getToggleStates, this::setToggleStates) + .range(1, 10) + .visibleWhen(this::isToggleable)); + defs.add(FieldDef.boolField("ability.hasActiveToggle", this::hasActiveToggle, this::setHasActiveToggle) + .visibleWhen(this::isToggleable)); + + // Duration (instant mode only) + defs.add(FieldDef.section("ability.section.execution") + .visibleWhen(() -> !this.isToggleable())); + defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) + .range(0, 6000) + .visibleWhen(() -> !this.isToggleable())); + + // ── Telegraph Controls (Effects tab) ───────────────────────── + defs.add(FieldDef.section("ability.section.telegraph").tab("Effects")); + defs.add(FieldDef.enumField("ability.telegraphShape", TelegraphType.class, + this::getTelegraphType, this::setTelegraphType).tab("Effects") + .hover("ability.hover.telegraphShape")); + defs.add(FieldDef.boolField("ability.showTelegraph", this::isShowTelegraph, this::setShowTelegraph) + .tab("Effects").visibleWhen(this::hasTelegraphShape) + .hover("ability.hover.showTelegraph")); + defs.add(FieldDef.colorSubGui("ability.windUpColor", this::getWindUpColor, this::setWindUpColor) + .tab("Effects").visibleWhen(this::isTelegraphVisible) + .hover("ability.hover.windUpColor")); + defs.add(FieldDef.colorSubGui("ability.activeColor", this::getActiveColor, this::setActiveColor) + .tab("Effects").visibleWhen(this::isTelegraphVisible) + .hover("ability.hover.activeColor")); + defs.add(FieldDef.floatField("ability.telegraphHeight", this::getTelegraphHeightOffset, this::setTelegraphHeightOffset) + .tab("Effects").visibleWhen(this::isTelegraphVisible) + .hover("ability.hover.telegraphHeight")); + + // Telegraph active duration with sync toggle (mirrors windup sync pattern) + defs.add(FieldDef.row( + FieldDef.intField("ability.telegraphActiveTicks", this::getTelegraphActiveTicks, this::setTelegraphActiveTicks).range(0, 6000) + .hover("ability.hover.telegraphActiveTicks"), + FieldDef.boolField("ability.syncTelegraph", this::isSyncTelegraphWithDuration, this::setSyncTelegraphWithDuration) + .hover("ability.hover.syncTelegraph") + ).tab("Effects").visibleWhen(() -> isTelegraphVisible() && !isSyncTelegraphWithDuration())); + defs.add(FieldDef.row( + FieldDef.labelField("ability.telegraphActiveTicks", () -> getResolvedTelegraphActiveTicks() + "t"), + FieldDef.boolField("ability.syncTelegraph", this::isSyncTelegraphWithDuration, this::setSyncTelegraphWithDuration) + .hover("ability.hover.syncTelegraph") + ).tab("Effects").visibleWhen(() -> isTelegraphVisible() && isSyncTelegraphWithDuration())); + + // Shape-specific dimension fields + defs.add(FieldDef.floatField("ability.telegraphRadius", this::getTRadius, this::setTRadius) + .tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsRadius()) + .hover("ability.hover.telegraphRadius")); + defs.add(FieldDef.floatField("ability.telegraphInnerRadius", this::getTInnerRadius, this::setTInnerRadius) + .tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsInnerRadius()) + .hover("ability.hover.telegraphInnerRadius")); + defs.add(FieldDef.floatField("ability.telegraphLength", this::getTLength, this::setTLength) + .tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsLength()) + .hover("ability.hover.telegraphLength")); + defs.add(FieldDef.floatField("ability.telegraphWidth", this::getTWidth, this::setTWidth) + .tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsWidth()) + .hover("ability.hover.telegraphWidth")); + defs.add(FieldDef.floatField("ability.telegraphAngle", this::getTAngle, this::setTAngle) + .tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsAngle()) + .hover("ability.hover.telegraphAngle")); + } + + // ==================== TELEGRAPH VISIBILITY HELPERS ==================== + + private boolean hasTelegraphShape() { + return getTelegraphType() != TelegraphType.NONE; + } + + private boolean isTelegraphVisible() { + return hasTelegraphShape() && isShowTelegraph(); + } + + private boolean needsRadius() { + TelegraphType t = getTelegraphType(); + return t == TelegraphType.CIRCLE || t == TelegraphType.RING || t == TelegraphType.SQUARE; + } + + private boolean needsInnerRadius() { + TelegraphType t = getTelegraphType(); + return t == TelegraphType.RING || t == TelegraphType.CONE; + } + + private boolean needsLength() { + TelegraphType t = getTelegraphType(); + return t == TelegraphType.LINE || t == TelegraphType.CONE; + } + + private boolean needsWidth() { + return getTelegraphType() == TelegraphType.LINE; + } + + private boolean needsAngle() { + return getTelegraphType() == TelegraphType.CONE; + } +} 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/LockType.java b/src/main/java/kamkeel/npcs/controllers/data/ability/LockType.java deleted file mode 100644 index 904a6c876..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/LockType.java +++ /dev/null @@ -1,47 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -/** - * Defines what an ability locks when Lock Position is enabled. - */ -public enum LockType { - MOVEMENT, - ROTATION, - BOTH; - - public boolean locksMovement() { - return this == MOVEMENT || this == BOTH; - } - - public boolean locksRotation() { - return this == ROTATION || this == BOTH; - } - - public String getDisplayKey() { - switch (this) { - case MOVEMENT: - return "ability.lockType.movement"; - case ROTATION: - return "ability.lockType.rotation"; - case BOTH: - return "ability.lockType.both"; - default: - return "ability.lockType.both"; - } - } - - public static String[] getDisplayKeys() { - return new String[]{ - "ability.lockType.movement", - "ability.lockType.rotation", - "ability.lockType.both" - }; - } - - public static LockType fromOrdinal(int ordinal) { - LockType[] values = values(); - if (ordinal >= 0 && ordinal < values.length) { - return values[ordinal]; - } - return BOTH; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java new file mode 100644 index 000000000..5b3fc38ea --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -0,0 +1,127 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.LogWriter; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public abstract class AbilityCondition { + public static final int MAX_CONDITIONS = 5; + + protected String typeId = ""; + protected String name = ""; + protected UserType userType = UserType.BOTH; + protected ConditionFilter conditionFilter = ConditionFilter.CASTER; + + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + switch (getFilter()) { + case CASTER: + return checkEntity(caster); + case TARGET: + return target != null && checkEntity(target); + case BOTH: + return checkEntity(caster) && (target != null && checkEntity(target)); + default: + return checkEntity(caster); + } + } + + protected abstract boolean checkEntity(EntityLivingBase entity); + + public boolean requiresTarget() { + return false; + } + + /** + * Returns true if all required fields are filled in. + * Used to disable the Done button in SubGuiConditionEdit when incomplete. + */ + public boolean isConfigured() { + return true; + } + + public UserType getUserType() { + return userType; + } + + public String getTypeId() { + return typeId; + } + + public String getName() { + return name; + } + + public ConditionFilter getFilter() { + return conditionFilter; + } + + public void setFilter(ConditionFilter filter) { + this.conditionFilter = filter; + } + + @SideOnly(Side.CLIENT) + public abstract void getConditionDefinitions(List defs); + + /** + * Returns a human-readable summary of this condition's configuration. + * Used for tooltips when hovering over condition buttons. + */ + @SideOnly(Side.CLIENT) + public abstract String getConditionSummary(); + + @SideOnly(Side.CLIENT) + public final List getAllDefinitions() { + List defs = new ArrayList<>(); + + defs.add(FieldDef.labelField("ability.validFor", () -> + "\u00A7e" + StatCollector.translateToLocal("ability.userType." + getUserType().name()))); + defs.add(FieldDef.enumField("condition.filter", ConditionFilter.class, this::getFilter, this::setFilter)); + getConditionDefinitions(defs); + return defs; + } + + public final NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("typeId", getTypeId()); + nbt.setString("name", getName()); + nbt.setInteger("userType", getUserType().ordinal()); + nbt.setInteger("filter", getFilter().ordinal()); + writeTypeNBT(nbt); + return nbt; + } + + public abstract void writeTypeNBT(NBTTagCompound nbt); + + public abstract void readTypeNBT(NBTTagCompound nbt); + + public final void readNBT(NBTTagCompound nbt) { + typeId = nbt.getString("typeId"); + name = nbt.getString("name"); + userType = UserType.fromOrdinal(nbt.getInteger("userType")); + conditionFilter = ConditionFilter.fromOrdinal(nbt.getInteger("filter")); + readTypeNBT(nbt); + } + + public static AbilityCondition fromNBT(NBTTagCompound nbt) { + String typeId = nbt.getString("typeId"); + Supplier factory = AbilityController.Instance.getConditionType(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown condition type: " + typeId); + return null; + } + AbilityCondition condition = factory.get(); + condition.readNBT(nbt); + + return condition; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionCompare.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionCompare.java new file mode 100644 index 000000000..3460f43f4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionCompare.java @@ -0,0 +1,118 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for float comparison-based conditions. + * Provides shared CompareType enum, NBT serialization, and FieldDef generation. + */ +public abstract class ConditionCompare extends AbilityCondition { + + public enum CompareType { + ABOVE { + @Override + public boolean test(float value, float threshold) { + return value >= threshold; + } + }, + BELOW { + @Override + public boolean test(float value, float threshold) { + return value <= threshold; + } + }, + EQUAL { + @Override + public boolean test(float value, float threshold) { + return value == threshold; + } + }; + + public abstract boolean test(float value, float threshold); + + public static CompareType fromOrdinal(int ordinal) { + CompareType[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : ABOVE; + } + + @Override + public String toString() { + return "condition." + name().toLowerCase(); + } + } + + protected CompareType compareType = CompareType.ABOVE; + + /** + * Returns the value to be compared for this entity (e.g. level, skill level). + * Return -1 to indicate the condition should fail immediately. + */ + protected abstract float getEntityValue(EntityLivingBase entity); + + /** + * Returns the threshold that getEntityValue() is compared against. + */ + protected abstract float getThreshold(); + + /** + * Appends subclass-specific FieldDefs (e.g. skill picker, level input). + * Called before the shared compareType field is added. + */ + @SideOnly(Side.CLIENT) + protected abstract void getExtraDefinitions(List defs); + + /** + * Subclasses write their own NBT fields here. + */ + protected abstract void writeExtraNBT(NBTTagCompound nbt); + + /** + * Subclasses read their own NBT fields here. + */ + protected abstract void readExtraNBT(NBTTagCompound nbt); + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + float value = getEntityValue(entity); + if (value < 0) return false; + return compareType.test(value, getThreshold()); + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.enumField("condition.compare_type", CompareType.class, this::getCompareType, this::setCompareType)); + getExtraDefinitions(defs); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("compareType", compareType.ordinal()); + writeExtraNBT(nbt); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + compareType = CompareType.fromOrdinal(nbt.getInteger("compareType")); + readExtraNBT(nbt); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public CompareType getCompareType() { + return compareType; + } + + public void setCompareType(CompareType compareType) { + this.compareType = compareType; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java new file mode 100644 index 000000000..08c5b5da2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java @@ -0,0 +1,37 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +public enum ConditionFilter { + CASTER, + TARGET, + BOTH; + + public boolean checksCaster() { + return this == CASTER || this == BOTH; + } + + public boolean checksTarget() { + return this == TARGET || this == BOTH; + } + + public static ConditionFilter fromOrdinal(int ordinal) { + ConditionFilter[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return BOTH; + } + + @Override + public String toString() { + switch (this) { + case BOTH: + return "condition.filter.both"; + case CASTER: + return "condition.filter.caster"; + case TARGET: + return "condition.filter.target"; + default: + return name(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java new file mode 100644 index 000000000..dfb997526 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -0,0 +1,26 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; + +public class ConditionHPThreshold extends ConditionThreshold { + + public ConditionHPThreshold() { + this.typeId = "condition.cnpc.hp_threshold"; + this.name = "condition.hp_threshold"; + } + + @Override + protected float getEntityValue(EntityLivingBase entity) { + return entity.getHealth(); + } + + @Override + protected float getEntityMaxValue(EntityLivingBase entity) { + return entity.getMaxHealth(); + } + + @Override + protected String getStatName() { + return "HP"; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java new file mode 100644 index 000000000..a608a92e6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java @@ -0,0 +1,97 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.util.HashMap; +import java.util.List; + +public class ConditionHasEffect extends AbilityCondition { + private int effectId = -1; + private int effectIndex = 0; + + public ConditionHasEffect() { + this.typeId = "condition.cnpc.has_effect"; + this.name = "condition.has_effect"; + this.userType = UserType.PLAYER_ONLY; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + if (!(entity instanceof EntityPlayer)) return false; + if (effectId < 0) return false; + + EntityPlayer player = (EntityPlayer) entity; + return CustomEffectController.getInstance().hasEffect(player, effectId, effectIndex); + } + + public void setEffect(int effectId, int effectIndex) { + this.effectId = effectId; + this.effectIndex = effectIndex; + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(SubGuiCustomEffectSelect.createSelectField(this)); + } + + @SideOnly(Side.CLIENT) + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String effectName = "None"; + if (effectId >= 0) { + CustomEffect effect = getEffect(); + effectName = effect != null ? effect.getName() : "ID:" + effectId; + } + return "[" + filterLabel + "] Effect: " + effectName; + } + + @Override + public boolean isConfigured() { + return effectId >= 0; + } + + public CustomEffect getEffect() { + HashMap map = CustomEffectController.getInstance().getEffectMap(effectIndex); + return map != null ? map.get(effectId) : null; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("effectId", effectId); + nbt.setInteger("effectIndex", effectIndex); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + effectId = nbt.getInteger("effectId"); + effectIndex = nbt.getInteger("effectIndex"); + } + + public int getEffectId() { + return effectId; + } + + public void setEffectId(int effectId) { + this.effectId = effectId; + } + + public int getEffectIndex() { + return effectIndex; + } + + public void setEffectIndex(int effectIndex) { + this.effectIndex = effectIndex; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java new file mode 100644 index 000000000..f94d465e1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -0,0 +1,82 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +public class ConditionHitCount extends AbilityCondition { + private int requiredHits = 3; + private int withinTicks = 60; + + public ConditionHitCount() { + this.typeId = "condition.cnpc.hit_count"; + this.name = "condition.hit_count"; + this.conditionFilter = ConditionFilter.CASTER; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + // Not used — this condition overrides check() directly + return false; + } + + @Override + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + if (caster instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) caster; + if (npc.abilities != null) { + return npc.abilities.getRecentHitCount(withinTicks) >= requiredHits; + } + } + + // For players, hit count tracking is not yet supported + return false; + } + + public int getRequiredHits() { + return requiredHits; + } + + public void setRequiredHits(int requiredHits) { + this.requiredHits = Math.max(0, requiredHits); + } + + public int getWithinTicks() { + return withinTicks; + } + + public void setWithinTicks(int withinTicks) { + this.withinTicks = Math.max(0, withinTicks); + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.intField("condition.required_hits", this::getRequiredHits, this::setRequiredHits).min(1)); + defs.add(FieldDef.intField("condition.within_ticks", this::getWithinTicks, this::setWithinTicks).min(0)); + } + + @SideOnly(Side.CLIENT) + @Override + public String getConditionSummary() { + return "[Caster] Hit " + requiredHits + " times in " + withinTicks + " ticks"; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("requiredHits", requiredHits); + nbt.setInteger("withinTicks", withinTicks); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + requiredHits = Math.max(0, nbt.getInteger("requiredHits")); + withinTicks = Math.max(0, nbt.getInteger("withinTicks")); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java new file mode 100644 index 000000000..21c8669ea --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -0,0 +1,191 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +public class ConditionItem extends AbilityCondition { + + public enum UsageType { + ARMOR, HOLDING, COUNT, OFFHAND; + + public static UsageType fromOrdinal(int ordinal) { + UsageType[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : HOLDING; + } + } + + public enum ArmorSlot { + BOOTS, LEGS, CHEST, HELMET; + + public static ArmorSlot fromOrdinal(int ordinal) { + ArmorSlot[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : BOOTS; + } + } + + // Shared + private UsageType usageType = UsageType.HOLDING; + private String itemName = ""; + + // ARMOR only + private ArmorSlot armorSlot = ArmorSlot.BOOTS; + private boolean fullArmorSet = false; + + // COUNT + PLAYER only + private int requiredCount = 1; + + public ConditionItem() { + this.typeId = "condition.cnpc.item"; + this.name = "condition.item"; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + switch (usageType) { + case HOLDING: + return checkHolding(entity); + case ARMOR: + return checkArmor(entity); + case COUNT: + return checkCount(entity); + case OFFHAND: + return checkOffhand(entity); + default: + return false; + } + } + + private boolean checkHolding(EntityLivingBase entity) { + ItemStack held = entity.getHeldItem(); + return matchesItem(held); + } + + private boolean checkArmor(EntityLivingBase entity) { + // MC getEquipmentInSlot: 1=boots, 2=legs, 3=chest, 4=helmet + int slot = armorSlot.ordinal() + 1; // BOOTS=0, LEGS=1, CHEST=2, HELMET=3 + return matchesItem(entity.getEquipmentInSlot(slot)); + } + + private boolean checkCount(EntityLivingBase entity) { + if (entity instanceof EntityPlayer) { + return checkPlayerInventoryCount((EntityPlayer) entity); + } + if (entity instanceof EntityNPCInterface) { + return checkNPCProjectile((EntityNPCInterface) entity); + } + + return false; + } + + private boolean checkOffhand(EntityLivingBase entity) { + // No offhand for players + if (entity instanceof EntityPlayer) return false; + if (!(entity instanceof EntityNPCInterface)) return false; + + ItemStack item = ((EntityNPCInterface) entity).getOffHand(); + return matchesItem(item); + } + + private boolean checkPlayerInventoryCount(EntityPlayer player) { + int count = 0; + for (ItemStack stack : player.inventory.mainInventory) { + if (matchesItem(stack)) { + count += stack.stackSize; + } + } + return count >= requiredCount; + } + + private boolean checkNPCProjectile(EntityNPCInterface npc) { + ItemStack projectile = npc.inventory.getProjectile(); + return matchesItem(projectile); + } + + private boolean matchesItem(ItemStack stack) { + if (stack == null || itemName == null || itemName.isEmpty()) return false; + String registryName = net.minecraft.item.Item.itemRegistry.getNameForObject(stack.getItem()); + return itemName.equals(registryName); + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.enumField("condition.usage_type", UsageType.class, + this::getUsageType, this::setUsageType)); + + defs.add(FieldDef.stringField("condition.item_name", + this::getItemName, this::setItemName) + .hover("condition.hover.item_name")); + + defs.add(FieldDef.enumField("condition.armor_slot", ArmorSlot.class, + this::getArmorSlot, this::setArmorSlot) + .visibleWhen(() -> usageType == UsageType.ARMOR) + .hover("condition.hover.armor_slots")); + + defs.add(FieldDef.intField("condition.item_count", + this::getRequiredCount, this::setRequiredCount) + .range(1, 64) + .visibleWhen(() -> usageType == UsageType.COUNT && userType.allowsPlayer()) + .hover("condition.hover.required_count")); + } + + @SideOnly(Side.CLIENT) + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String usage = usageType.name(); + String item = itemName.isEmpty() ? "None" : itemName; + return "[" + filterLabel + "] " + usage + ": " + item; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setString("itemName", itemName); + nbt.setInteger("usageType", usageType.ordinal()); + nbt.setInteger("armorSlot", armorSlot.ordinal()); + nbt.setInteger("requiredCount", requiredCount); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + itemName = nbt.getString("itemName"); + usageType = UsageType.fromOrdinal(nbt.getInteger("usageType")); + armorSlot = ArmorSlot.fromOrdinal(nbt.getInteger("armorSlot")); + requiredCount = Math.max(1, nbt.getInteger("requiredCount")); + } + + + @Override + public boolean isConfigured() { + return itemName != null && !itemName.isEmpty(); + } + + public UsageType getUsageType() { return usageType; } + public void setUsageType(UsageType usageType) { this.usageType = usageType; } + + public String getItemName() { return itemName; } + public void setItemName(String itemName) { this.itemName = itemName; } + + public ArmorSlot getArmorSlot() { return armorSlot; } + public void setArmorSlot(ArmorSlot armorSlot) { this.armorSlot = armorSlot; } + + public boolean isFullArmorSet() { + return fullArmorSet; + } + + public void setFullArmorSet(boolean fullArmorSet) { + this.fullArmorSet = fullArmorSet; + } + + public int getRequiredCount() { return requiredCount; } + public void setRequiredCount(int requiredCount) { this.requiredCount = Math.max(1, requiredCount); } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java new file mode 100644 index 000000000..ac8a05272 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java @@ -0,0 +1,78 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.select.GuiQuestSelection; +import noppes.npcs.controllers.QuestController; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.Quest; + +import java.util.List; + +public class ConditionQuestCompleted extends AbilityCondition { + private int questId = -1; + + public ConditionQuestCompleted() { + this.typeId = "condition.cnpc.quest_completed"; + this.name = "condition.quest_completed"; + this.userType = UserType.PLAYER_ONLY; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + if (!(entity instanceof EntityPlayer)) return false; + if (questId < 0) return false; + + EntityPlayer player = (EntityPlayer) entity; + PlayerData data = PlayerData.get(player); + if (data == null || data.questData == null) return false; + return data.questData.hasFinishedQuest(questId); + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(GuiQuestSelection.createConditionField(this)); + } + + @SideOnly(Side.CLIENT) + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String questName = "None"; + if (questId >= 0) { + Quest q = QuestController.Instance.quests.get(questId); + questName = q != null ? q.title : "ID:" + questId; + } + return "[" + filterLabel + "] Quest: " + questName; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("questId", questId); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + questId = nbt.getInteger("questId"); + } + + @Override + public boolean isConfigured() { + return questId >= 0; + } + + public int getQuestId() { + return questId; + } + + public void setQuestId(int questId) { + this.questId = questId; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java new file mode 100644 index 000000000..bd368bef8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java @@ -0,0 +1,175 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for threshold-based conditions (HP, Ki, etc.). + * Provides shared percent/flat toggle, ThresholdType enum, and FieldDef generation. + */ +public abstract class ConditionThreshold extends AbilityCondition { + + public enum ThresholdType { + ABOVE { + @Override + public boolean test(float value, float threshold) { + return value >= threshold; + } + }, + BELOW { + @Override + public boolean test(float value, float threshold) { + return value <= threshold; + } + }, + EQUAL { + @Override + public boolean test(float value, float threshold) { + return Math.abs(value - threshold) < 0.001f; + } + }; + + public abstract boolean test(float value, float threshold); + + public static ThresholdType fromOrdinal(int ordinal) { + ThresholdType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return ABOVE; + } + + @Override + public String toString() { + switch (this) { + case ABOVE: + return "condition.above"; + case BELOW: + return "condition.below"; + case EQUAL: + return "condition.equal"; + default: + return name(); + } + } + } + + protected float thresholdFlat = 100f; + protected float thresholdPercent = 0.5f; + protected boolean percent = true; + protected ThresholdType thresholdType = ThresholdType.ABOVE; + + /** + * Returns the raw stat value for the entity (e.g. current HP, current Ki). + */ + protected abstract float getEntityValue(EntityLivingBase entity); + + /** + * Returns the maximum stat value for the entity (e.g. max HP, max Ki). + * Used to compute the percentage ratio. + */ + protected abstract float getEntityMaxValue(EntityLivingBase entity); + + /** + * Returns the display name for the stat being checked (e.g. "HP", "Ki"). + * Used in getConditionSummary(). + */ + protected abstract String getStatName(); + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + float value; + float threshold; + if (percent) { + float max = getEntityMaxValue(entity); + value = max > 0 ? getEntityValue(entity) / max : 0; + threshold = thresholdPercent; + } else { + value = getEntityValue(entity); + threshold = thresholdFlat; + } + return thresholdType.test(value, threshold); + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.floatField("condition.threshold_flat", this::getThresholdFlat, this::setThresholdFlat) + .min(0).visibleWhen(() -> !isPercent())); + defs.add(FieldDef.floatField("condition.threshold_percent", this::getThresholdPercent, this::setThresholdPercent) + .min(0).max(1).visibleWhen(this::isPercent)); + defs.add(FieldDef.boolField("condition.percent", this::isPercent, this::setIsPercent)); + defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, + this::getThresholdType, this::setThresholdType)); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("thresholdFlat", thresholdFlat); + nbt.setFloat("thresholdPercent", thresholdPercent); + nbt.setBoolean("percent", percent); + nbt.setInteger("thresholdType", thresholdType.ordinal()); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + thresholdFlat = nbt.getFloat("thresholdFlat"); + thresholdPercent = nbt.getFloat("thresholdPercent"); + percent = nbt.getBoolean("percent"); + thresholdType = ThresholdType.fromOrdinal(nbt.getInteger("thresholdType")); + } + + @SideOnly(Side.CLIENT) + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String typeName = getStatName(); + String typeLabel = StatCollector.translateToLocal(thresholdType.toString()); + String value = percent + ? String.format("%.0f%%", thresholdPercent * 100) + : String.format("%.0f", thresholdFlat); + return "[" + filterLabel + "] " + typeName + " " + typeLabel + " " + value; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public float getThresholdFlat() { + return thresholdFlat; + } + + public void setThresholdFlat(float value) { + this.thresholdFlat = Math.max(0, value); + } + + public float getThresholdPercent() { + return thresholdPercent; + } + + public void setThresholdPercent(float value) { + this.thresholdPercent = Math.max(0, Math.min(1, value)); + } + + public boolean isPercent() { + return percent; + } + + public void setIsPercent(boolean percent) { + this.percent = percent; + } + + public ThresholdType getThresholdType() { + return thresholdType; + } + + public void setThresholdType(ThresholdType type) { + this.thresholdType = type; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java new file mode 100644 index 000000000..8efb25791 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java @@ -0,0 +1,338 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +/** + * Icon data for abilities, stored in the ability's customData NBT under "AbilityIcon". + * Supports up to 3 layers, each with its own texture, UV coordinates, and tint color. + * Width, height, and scale are shared across all layers. + */ +public class AbilityIconData { + public static final String NBT_KEY = "AbilityIcon"; + public static final int MAX_LAYERS = 3; + + private final NBTTagCompound customData; + + // Shared across all layers + public int width = 32; + public int height = 32; + public float scale = 1.0f; + + /** Whether a custom icon override is active. Default false = use type's default icon. */ + private boolean enabled = false; + + /** Number of active layers (1-3). */ + private int layerCount = 1; + + /** Layer data (always 3 slots allocated). */ + private Layer[] layers = { new Layer(), new Layer(), new Layer() }; + + /** Per-state icon UV overrides for layer 0 (0-indexed, maps to toggle states 1, 2, ...). */ + private int[][] stateIcons = null; + + // Animation + private boolean animated = false; + private int frameCount = 1; + private int frametime = 2; + + // ═══════════════════════════════════════════════════════════════════ + // LAYER INNER CLASS + // ═══════════════════════════════════════════════════════════════════ + + public static class Layer { + public String texture = ""; + public int iconX = 0; + public int iconY = 0; + public int tintColor = 0xFFFFFF; + + public Layer() {} + + public boolean hasTexture() { + return texture != null && !texture.isEmpty(); + } + + public void writeToNBT(NBTTagCompound nbt) { + nbt.setString("Texture", texture); + nbt.setInteger("IconX", iconX); + nbt.setInteger("IconY", iconY); + nbt.setInteger("TintColor", tintColor); + } + + public void readFromNBT(NBTTagCompound nbt) { + texture = nbt.getString("Texture"); + iconX = nbt.getInteger("IconX"); + iconY = nbt.getInteger("IconY"); + tintColor = nbt.hasKey("TintColor") ? nbt.getInteger("TintColor") : 0xFFFFFF; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // CONSTRUCTION + // ═══════════════════════════════════════════════════════════════════ + + private AbilityIconData(NBTTagCompound customData) { + this.customData = customData; + } + + /** + * Create an AbilityIconData instance from a raw customData compound. + * Reads existing values if present, otherwise uses defaults. + */ + public static AbilityIconData fromCustomData(NBTTagCompound customData) { + AbilityIconData icon = new AbilityIconData(customData); + if (customData.hasKey(NBT_KEY)) { + icon.readFromNBT(customData.getCompoundTag(NBT_KEY)); + } + return icon; + } + + /** + * Create an AbilityIconData instance from an ability's customData. + */ + public static AbilityIconData fromAbility(Ability ability) { + return fromCustomData(ability.getCustomData()); + } + + /** + * Create an AbilityIconData instance from a chained ability's customData. + */ + public static AbilityIconData fromChainedAbility(ChainedAbility chain) { + return fromCustomData(chain.getCustomData()); + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Write current state back to the customData NBT. + */ + public void save() { + NBTTagCompound tag = new NBTTagCompound(); + writeToNBT(tag); + customData.setTag(NBT_KEY, tag); + } + + public void writeToNBT(NBTTagCompound nbt) { + nbt.setBoolean("Enabled", enabled); + nbt.setInteger("Width", width); + nbt.setInteger("Height", height); + nbt.setFloat("Scale", scale); + nbt.setInteger("LayerCount", layerCount); + + NBTTagList layerList = new NBTTagList(); + for (int i = 0; i < MAX_LAYERS; i++) { + NBTTagCompound layerNBT = new NBTTagCompound(); + layers[i].writeToNBT(layerNBT); + layerList.appendTag(layerNBT); + } + nbt.setTag("Layers", layerList); + + nbt.setBoolean("Animated", animated); + nbt.setInteger("FrameCount", frameCount); + nbt.setInteger("FrameTime", frametime); + + if (stateIcons != null && stateIcons.length > 0) { + NBTTagList list = new NBTTagList(); + for (int[] pair : stateIcons) { + NBTTagCompound comp = new NBTTagCompound(); + comp.setInteger("IconX", pair[0]); + comp.setInteger("IconY", pair[1]); + list.appendTag(comp); + } + nbt.setTag("StateIcons", list); + } + } + + public void readFromNBT(NBTTagCompound nbt) { + enabled = nbt.getBoolean("Enabled"); + width = nbt.getInteger("Width"); + if (width <= 0) width = 32; + height = nbt.getInteger("Height"); + if (height <= 0) height = 32; + scale = nbt.getFloat("Scale"); + if (scale <= 0) scale = 1.0f; + + layerCount = nbt.getInteger("LayerCount"); + if (layerCount < 1) layerCount = 1; + if (layerCount > MAX_LAYERS) layerCount = MAX_LAYERS; + + if (nbt.hasKey("Animated")) + animated = nbt.getBoolean("Animated"); + if (nbt.hasKey("FrameCount")) + frameCount = Math.max(1, nbt.getInteger("FrameCount")); + if (nbt.hasKey("FrameTime")) + frametime = Math.max(1, nbt.getInteger("FrameTime")); + + if (nbt.hasKey("Layers")) { + NBTTagList layerList = nbt.getTagList("Layers", 10); + for (int i = 0; i < MAX_LAYERS; i++) { + layers[i] = new Layer(); + if (i < layerList.tagCount()) { + layers[i].readFromNBT(layerList.getCompoundTagAt(i)); + } + } + } + + if (nbt.hasKey("StateIcons")) { + NBTTagList list = nbt.getTagList("StateIcons", 10); + stateIcons = new int[list.tagCount()][2]; + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound comp = list.getCompoundTagAt(i); + stateIcons[i][0] = comp.getInteger("IconX"); + stateIcons[i][1] = comp.getInteger("IconY"); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // LAYER API + // ═══════════════════════════════════════════════════════════════════ + + public int getLayerCount() { + return layerCount; + } + + public void setLayerCount(int count) { + this.layerCount = Math.max(1, Math.min(MAX_LAYERS, count)); + save(); + } + + public Layer getLayer(int index) { + return (index >= 0 && index < MAX_LAYERS) ? layers[index] : layers[0]; + } + + public void setLayerTexture(int index, String tex) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].texture = tex != null ? tex : ""; + save(); + } + } + + public void setLayerIconX(int index, int x) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].iconX = Math.max(0, x); + save(); + } + } + + public void setLayerIconY(int index, int y) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].iconY = Math.max(0, y); + save(); + } + } + + public void setLayerTintColor(int index, int color) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].tintColor = color & 0xFFFFFF; + save(); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // SHARED PROPERTY GETTERS/SETTERS (with auto-save) + // ═══════════════════════════════════════════════════════════════════ + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + save(); + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = Math.max(1, width); + save(); + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = Math.max(1, height); + save(); + } + + public float getScale() { + return scale; + } + + public void setScale(float scale) { + this.scale = Math.max(0.1f, scale); + save(); + } + + // ═══════════════════════════════════════════════════════════════════ + // ANIMATION + // ═══════════════════════════════════════════════════════════════════ + + public boolean isAnimated() { + return animated; + } + + public void setAnimated(boolean animated) { + this.animated = animated; + save(); + } + + public int getFrameCount() { + return frameCount; + } + + public void setFrameCount(int frameCount) { + this.frameCount = Math.max(1, frameCount); + save(); + } + + public int getFrameTime() { + return frametime; + } + + public void setFrameTime(int frametime) { + this.frametime = Math.max(1, frametime); + save(); + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-STATE ICON OVERRIDES (applies to layer 0) + // ═══════════════════════════════════════════════════════════════════ + + public void setStateIcons(int[][] stateIcons) { + this.stateIcons = stateIcons; + save(); + } + + /** + * Get iconX for a specific toggle state (layer 0). + * Falls back to layer 0 iconX if no state override exists. + * @param state 1-indexed toggle state (0 = off/default) + */ + public int getIconXForState(int state) { + if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { + return stateIcons[state - 1][0]; + } + return layers[0].iconX; + } + + /** + * Get iconY for a specific toggle state (layer 0). + * Falls back to layer 0 iconY if no state override exists. + * @param state 1-indexed toggle state (0 = off/default) + */ + public int getIconYForState(int state) { + if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { + return stateIcons[state - 1][1]; + } + return layers[0].iconY; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java new file mode 100644 index 000000000..dce3e274e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java @@ -0,0 +1,561 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.api.ability.IChainedAbility; +import noppes.npcs.controllers.data.IScriptUnit; +import kamkeel.npcs.util.FileNameHelper; + +import java.util.ArrayList; +import java.util.List; + +/** + * A chained ability is an ordered sequence of ability references that execute + * one after another. It has its own conditions, cooldown, weight, and per-entry + * delay configuration. Individual ability conditions are skipped during chain execution. + *

+ * All entries must be ability references (by name/key). Inline abilities are not supported. + * When saving, all references are validated against {@link AbilityController}. + */ +public class ChainedAbility implements IChainedAbility, IAbilityAction { + + // ═══════════════════════════════════════════════════════════════════ + // CONFIGURATION (saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + private String id = ""; // UUID (stable persistent reference) + private String name = ""; // Unique file key / identifier + private String displayName = ""; // Cosmetic name (falls back to name when empty) + + private boolean enabled = true; + + /** + * Weight for NPC weighted random selection. + */ + private int weight = 10; + + /** + * Whether each ability in the chain uses its own windup phase. + */ + private boolean windUpAll = true; + + /** + * Chain-level cooldown in ticks (applied after entire chain completes). + */ + private int cooldownTicks = 100; + + /** + * If true, only this chain goes on cooldown (not the global cooldown). + */ + private boolean perAbilityCooldown = false; + + /** + * If true, skip cooldown entirely after chain completes. + */ + private boolean ignoreCooldown = false; + + /** + * Minimum range for NPC eligibility check. + */ + private float minRange = 0; + + /** + * Maximum range for NPC eligibility check. + */ + private float maxRange = 20; + + /** + * Chain-level conditions (individual ability conditions are ignored). + */ + private List conditions = new ArrayList<>(); + + /** + * Ordered list of ability entries to execute. + */ + private List entries = new ArrayList<>(); + + /** + * Extension data for external mods (e.g., icons, DBC stats). + */ + private NBTTagCompound customData = new NBTTagCompound(); + + // Per-instance script (isolated per execution, not saved to NBT) + private transient ChainedAbilityScript instanceScript; + + public ChainedAbility() { + } + + public ChainedAbility(String name) { + setName(name); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id != null ? id : ""; + } + + public String getName() { + return name; + } + + public void setName(String name) { + String fallback = (this.name != null && !this.name.isEmpty()) ? this.name : "Chain"; + this.name = FileNameHelper.sanitizeName(name, fallback); + } + + /** + * Get the display name for this chained ability. + * Returns displayName if set, otherwise falls back to name. + * Converts & color codes to § for rendering. + */ + public String getDisplayName() { + String result = (displayName != null && !displayName.isEmpty()) + ? displayName + : FileNameHelper.toDisplayName(name); + return result != null ? result.replaceAll("&([0-9a-fk-or])", "\u00A7$1") : ""; + } + + public String getRawDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName != null ? displayName : ""; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = Math.max(1, weight); + } + + public boolean isWindUpAll() { + return windUpAll; + } + + public void setWindUpAll(boolean windUpAll) { + this.windUpAll = windUpAll; + } + + public int getCooldownTicks() { + return cooldownTicks; + } + + public void setCooldownTicks(int cooldownTicks) { + this.cooldownTicks = Math.max(0, cooldownTicks); + } + + public boolean isPerAbilityCooldown() { + return perAbilityCooldown; + } + + public void setPerAbilityCooldown(boolean perAbilityCooldown) { + this.perAbilityCooldown = perAbilityCooldown; + } + + public boolean isIgnoreCooldown() { + return ignoreCooldown; + } + + public void setIgnoreCooldown(boolean ignoreCooldown) { + this.ignoreCooldown = ignoreCooldown; + } + + public float getMinRange() { + return minRange; + } + + public void setMinRange(float minRange) { + this.minRange = Math.max(0, minRange); + } + + public float getMaxRange() { + return maxRange; + } + + public void setMaxRange(float maxRange) { + this.maxRange = Math.max(0, maxRange); + } + + /** + * Compute the allowed user type from child abilities. + * A chain allows players if ALL resolved entries allow players. + * A chain allows NPCs if ALL resolved entries allow NPCs. + * Unresolvable entries are skipped (don't restrict). + */ + public UserType getAllowedBy() { + if (entries.isEmpty()) return UserType.BOTH; + boolean allAllowPlayer = true; + boolean allAllowNpc = true; + for (ChainedAbilityEntry entry : entries) { + Ability a = entry.resolve(); + if (a == null) continue; + UserType ut = a.getAllowedBy(); + if (!ut.allowsPlayer()) allAllowPlayer = false; + if (!ut.allowsNpc()) allAllowNpc = false; + } + if (allAllowPlayer && allAllowNpc) return UserType.BOTH; + if (allAllowPlayer) return UserType.PLAYER_ONLY; + if (allAllowNpc) return UserType.NPC_ONLY; + return UserType.NONE; + } + + public List getConditions() { + return conditions; + } + + public void setConditions(List conditions) { + this.conditions = conditions != null ? conditions : new ArrayList<>(); + } + + public List getEntries() { + return entries; + } + + public void setEntries(List entries) { + this.entries = entries != null ? entries : new ArrayList<>(); + } + + public NBTTagCompound getCustomData() { + return customData; + } + + // ═══════════════════════════════════════════════════════════════════ + // IChainedAbility INTERFACE + // ═══════════════════════════════════════════════════════════════════ + + @Override + public int getEntryCount() { + return entries.size(); + } + + @Override + public String getEntryReference(int index) { + if (index < 0 || index >= entries.size()) return null; + ChainedAbilityEntry entry = entries.get(index); + if (entry.isInline()) { + Ability a = entry.getInlineAbility(); + return a != null ? a.getName() : ""; + } + return entry.getAbilityReference(); + } + + @Override + public boolean isEntryInline(int index) { + if (index < 0 || index >= entries.size()) return false; + return entries.get(index).isInline(); + } + + @Override + public int getEntryDelay(int index) { + if (index < 0 || index >= entries.size()) return 0; + return entries.get(index).getDelayTicks(); + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTRY MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + public void addEntry(ChainedAbilityEntry entry) { + if (entry != null) { + entries.add(entry); + } + } + + public void addEntry(String abilityReference, int delayTicks) { + entries.add(new ChainedAbilityEntry(abilityReference, delayTicks)); + } + + public void removeEntry(int index) { + if (index >= 0 && index < entries.size()) { + entries.remove(index); + } + } + + public void moveEntryUp(int index) { + if (index > 0 && index < entries.size()) { + ChainedAbilityEntry entry = entries.remove(index); + entries.add(index - 1, entry); + } + } + + public void moveEntryDown(int index) { + if (index >= 0 && index < entries.size() - 1) { + ChainedAbilityEntry entry = entries.remove(index); + entries.add(index + 1, entry); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // CONDITIONS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check all chain-level conditions against the caster and target. + */ + public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { + for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsNpc()) continue; + Boolean extendedCondition = AbilityController.Instance.fireCheckConditions(c, caster, target); + + if (extendedCondition != null) { + if (!extendedCondition) return false; + continue; + } + + if (!c.check(caster, target)) return false; + } + return true; + } + + /** + * Check conditions for player use (skip target-requiring conditions). + */ + public boolean checkConditionsForPlayer(EntityLivingBase caster) { + for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsPlayer()) continue; + if (c.requiresTarget()) continue; + Boolean extendedCondition = AbilityController.Instance.fireCheckConditionsForPlayer(c, caster); + + if (extendedCondition != null) { + if (!extendedCondition) return false; + continue; + } + + if (!c.check(caster, null)) return false; + } + return true; + } + + // ═══════════════════════════════════════════════════════════════════ + // VALIDATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Validate this chained ability. Returns a list of error messages. + * An empty list means valid. + */ + public List validate() { + List errors = new ArrayList<>(); + + if (name == null || name.isEmpty()) { + errors.add("Name is required"); + } + + if (entries.isEmpty()) { + errors.add("At least one ability entry is required"); + } + + AbilityController controller = AbilityController.Instance; + if (controller != null) { + for (int i = 0; i < entries.size(); i++) { + ChainedAbilityEntry entry = entries.get(i); + if (entry.isInline()) { + if (entry.getInlineAbility() == null) { + errors.add("Entry " + (i + 1) + ": inline ability is null"); + } + } else { + String ref = entry.getAbilityReference(); + if (ref == null || ref.isEmpty()) { + errors.add("Entry " + (i + 1) + ": ability reference is empty"); + } else if (!controller.canResolveAbility(ref)) { + errors.add("Entry " + (i + 1) + ": cannot resolve ability '" + ref + "'"); + } + } + } + } + + return errors; + } + + // ═══════════════════════════════════════════════════════════════════ + // DEEP COPY + // ═══════════════════════════════════════════════════════════════════ + + /** + * Create a deep copy via NBT round-trip. + */ + public ChainedAbility deepCopy() { + ChainedAbility copy = new ChainedAbility(); + copy.readNBT(this.writeNBT(false)); + return copy; + } + + @Override + public boolean isChain() { + return true; + } + + @Override + public IAbilityAction deepCopyAction() { + return deepCopy(); + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + public NBTTagCompound writeNBT(boolean saveScripts) { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("Id", id); + nbt.setString("Name", name); + nbt.setString("DisplayName", displayName); + nbt.setBoolean("Enabled", enabled); + nbt.setInteger("Weight", weight); + nbt.setBoolean("WindUpAll", windUpAll); + nbt.setInteger("CooldownTicks", cooldownTicks); + nbt.setBoolean("PerAbilityCooldown", perAbilityCooldown); + nbt.setBoolean("IgnoreCooldown", ignoreCooldown); + nbt.setFloat("MinRange", minRange); + nbt.setFloat("MaxRange", maxRange); + + // Conditions + NBTTagList condList = new NBTTagList(); + for (AbilityCondition c : conditions) { + condList.appendTag(c.writeNBT()); + } + nbt.setTag("Conditions", condList); + + // Entries + NBTTagList entryList = new NBTTagList(); + for (ChainedAbilityEntry entry : entries) { + entryList.appendTag(entry.writeNBT(saveScripts)); + } + nbt.setTag("Entries", entryList); + + // Custom data (for external mods) + nbt.setTag("customData", (NBTTagCompound) customData.copy()); + + // Script handler data (matching CustomEffect.writeToNBT pattern) + if (saveScripts) { + ChainedAbilityScript handler = getScriptHandler(); + if (handler != null) { + NBTTagCompound scriptData = new NBTTagCompound(); + handler.writeToNBT(scriptData); + nbt.setTag("ScriptData", scriptData); + } + } + + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + id = nbt.getString("Id"); + setName(nbt.getString("Name")); + displayName = nbt.getString("DisplayName"); + enabled = !nbt.hasKey("Enabled") || nbt.getBoolean("Enabled"); + weight = nbt.hasKey("Weight") ? nbt.getInteger("Weight") : 10; + windUpAll = !nbt.hasKey("WindUpAll") || nbt.getBoolean("WindUpAll"); + cooldownTicks = nbt.hasKey("CooldownTicks") ? nbt.getInteger("CooldownTicks") : 100; + perAbilityCooldown = nbt.getBoolean("PerAbilityCooldown"); + ignoreCooldown = nbt.getBoolean("IgnoreCooldown"); + minRange = nbt.getFloat("MinRange"); + maxRange = nbt.hasKey("MaxRange") ? nbt.getFloat("MaxRange") : 20; + // AllowedBy is computed from child abilities + + // Conditions + conditions.clear(); + NBTTagList condList = nbt.getTagList("Conditions", 10); + for (int i = 0; i < condList.tagCount(); i++) { + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); + if (c != null) { + conditions.add(c); + } + } + + // Entries + entries.clear(); + NBTTagList entryList = nbt.getTagList("Entries", 10); + for (int i = 0; i < entryList.tagCount(); i++) { + ChainedAbilityEntry entry = ChainedAbilityEntry.fromNBT(entryList.getCompoundTagAt(i)); + if (entry != null) { + entries.add(entry); + } + } + + // Custom data (for external mods) + customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy(); + + // Script handler data (matching CustomEffect.readFromNBT pattern) + if (nbt.hasKey("ScriptData", 10)) { + if (getScriptHandler() == null) { + ChainedAbilityScript handler = new ChainedAbilityScript(this.id); + handler.readFromNBT(nbt.getCompoundTag("ScriptData")); + setScriptHandler(handler); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT HANDLER + // ═══════════════════════════════════════════════════════════════════ + + public ChainedAbilityScript getScriptHandler() { + return AbilityController.Instance.chainedAbilityScriptHandlers.get(this.id); + } + + public void setScriptHandler(ChainedAbilityScript handler) { + AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler); + } + + public ChainedAbilityScript getOrCreateScriptHandler() { + ChainedAbilityScript handler = getScriptHandler(); + if (handler == null) { + handler = new ChainedAbilityScript(this.id); + AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler); + } + return handler; + } + + /** + * Get or create a per-instance script handler for this chain execution. + * Shares the template's engine but creates isolated Bindings for variable state. + * Returns null if no script is configured on the template. + */ + public ChainedAbilityScript getOrCreateInstanceScript() { + if (instanceScript != null) return instanceScript; + + ChainedAbilityScript template = getScriptHandler(); + if (template == null || !template.getEnabled() || template.container == null) return null; + + instanceScript = new ChainedAbilityScript(this.id); + instanceScript.setLanguage(template.getLanguage()); + instanceScript.setEnabled(true); + + IScriptUnit clone = template.container.createInstanceScope(instanceScript); + instanceScript.addScriptUnit(clone); + + return instanceScript; + } + + /** + * Clear the per-instance script handler (call on chain completion/reset). + */ + public void clearInstanceScript() { + this.instanceScript = null; + } +} 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 deleted file mode 100644 index 52f5368f0..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java +++ /dev/null @@ -1,112 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.data; - -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.api.ability.data.IEnergyCombatData; - -/** - * Groups combat properties shared by energy projectile abilities. - * Used as a parameter object for entity constructors and ability configuration. - */ -public class EnergyCombatData implements IEnergyCombatData { - public float damage = 7.0f; - public float knockback = 1.0f; - public float knockbackUp = 0.1f; - public boolean explosive = false; - public float explosionRadius = 3.0f; - public float explosionDamageFalloff = 0.5f; - - public EnergyCombatData() {} - - public EnergyCombatData(float damage, float knockback, float knockbackUp, - boolean explosive, float explosionRadius, float explosionDamageFalloff) { - this.damage = damage; - this.knockback = knockback; - this.knockbackUp = knockbackUp; - this.explosive = explosive; - this.explosionRadius = explosionRadius; - this.explosionDamageFalloff = explosionDamageFalloff; - } - - @Override - public float getDamage() { - return damage; - } - - @Override - public void setDamage(float damage) { - this.damage = damage; - } - - @Override - public float getKnockback() { - return knockback; - } - - @Override - public void setKnockback(float knockback) { - this.knockback = knockback; - } - - @Override - public float getKnockbackUp() { - return knockbackUp; - } - - @Override - public void setKnockbackUp(float knockbackUp) { - this.knockbackUp = knockbackUp; - } - - @Override - public boolean isExplosive() { - return explosive; - } - - @Override - public void setExplosive(boolean explosive) { - this.explosive = explosive; - } - - @Override - public float getExplosionRadius() { - return explosionRadius; - } - - @Override - public void setExplosionRadius(float explosionRadius) { - this.explosionRadius = explosionRadius; - } - - @Override - public float getExplosionDamageFalloff() { - return explosionDamageFalloff; - } - - @Override - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - this.explosionDamageFalloff = explosionDamageFalloff; - } - - public void writeNBT(NBTTagCompound nbt) { - nbt.setFloat("damage", damage); - nbt.setFloat("knockback", knockback); - nbt.setFloat("knockbackUp", knockbackUp); - nbt.setBoolean("explosive", explosive); - nbt.setFloat("explosionRadius", explosionRadius); - nbt.setFloat("explosionDamageFalloff", explosionDamageFalloff); - } - - 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; - } - - public EnergyCombatData copy() { - return new EnergyCombatData(damage, knockback, knockbackUp, - explosive, explosionRadius, explosionDamageFalloff); - } -} 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 deleted file mode 100644 index 7cc15a706..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java +++ /dev/null @@ -1,288 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.data; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.common.util.Constants; -import noppes.npcs.api.IPos; -import noppes.npcs.api.ability.data.IEnergyTrajectoryData; -import noppes.npcs.scripted.NpcAPI; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.BiConsumer; - -public class EnergyTrajectoryData implements IEnergyTrajectoryData { - public int currentPath = 0; - private final List trajectory = new ArrayList<>(); - - public EnergyTrajectoryData() {} - - public EnergyTrajectoryData(int startingPath, Path... paths) { - trajectory.addAll(Arrays.asList(paths)); - this.currentPath = startingPath < trajectory.size() && startingPath >= 0 ? startingPath : 0; - } - - @Override - public int getCurrentPath() { - return currentPath; - } - - @Override - public void setCurrentPath(int currentPath) { - this.currentPath = currentPath; - } - - @Override - public int getDelay(int path) { - if (getPath(path) == null) return -1; - return getPath(path).getDelay(); - } - - @Override - public void setDelay(int path, int ticks) { - if (getPath(path) == null) return; - getPath(path).setDelay(ticks); - } - - @Override - public IPos getPos(int path) { - IPath p = getPath(path); - return p == null ? null : p.getPos(); - } - - @Override - public void setPos(int path, IPos pos) { - IPath p = getPath(path); - if (p != null) p.setPos(pos); - } - - @Override - public boolean isConcluded(int path) { - IPath p = getPath(path); - return p != null && p.isConcluded(); - } - - @Override - public void setConcluded(int path, boolean concluded) { - IPath p = getPath(path); - if (p != null) p.setConcluded(concluded); - } - - @Override - public double getX(int path) { - IPath p = getPath(path); - return p == null ? 0 : p.getX(); - } - - @Override - public double getY(int path) { - IPath p = getPath(path); - return p == null ? 0 : p.getY(); - } - - @Override - public double getZ(int path) { - IPath p = getPath(path); - return p == null ? 0 : p.getZ(); - } - @Override - public void setX(int path, double x) { - IPath p = getPath(path); - if (p != null) p.setX(x); - } - - @Override - public void setY(int path, double y) { - IPath p = getPath(path); - if (p != null) p.setY(y); - } - - @Override - public void setZ(int path, double z) { - IPath p = getPath(path); - if (p != null) p.setZ(z); - } - - public IPath getPath(int path) { - if (path < 0 || path >= trajectory.size()) return null; - return trajectory.get(path); - } - - @Override - public void setPath(int path, IPos pos) { - setPath(path, pos, 0); - } - - @Override - public void setPath(int path, IPos pos, int delay) { - setPath(path, pos.getX(), pos.getY(), pos.getZ(), delay); - } - - @Override - public void setPath(int path, double x, double y, double z) { - setPath(path, x, y, z, 0); - } - - @Override - public void setPath(int path, double x, double y, double z, int delay) { - Path newPath = new Path( - NpcAPI.Instance().getIPos(x, y, z), - delay - ); - - while (trajectory.size() <= path) { - trajectory.add(null); - } - - trajectory.set(path, newPath); - } - - @Override - public IPath createPath(IPos pos) { - return new Path(pos, 0); - } - - @Override - public IPath createPath(IPos pos, int delay) { - return new Path(pos, delay); - } - - @Override - public IPath createPath(double x, double y, double z) { - return createPath(x, y, z, 0); - } - - @Override - public IPath createPath(double x, double y, double z, int delay) { - return new Path(NpcAPI.Instance().getIPos(x, y, z), delay); - } - - @Override - public void forEach(BiConsumer lambda) { - for (int i = 0; i < trajectory.size(); i++) { - lambda.accept(i, trajectory.get(i)); - } - } - - public int size() { - return trajectory.size(); - } - - public boolean isEmpty() { - return trajectory.isEmpty(); - } - - public void writeNBT(NBTTagCompound nbt) { - nbt.setInteger("currentPath", currentPath); - - for (int i = 0; i < trajectory.size(); i++) { - Path path = trajectory.get(i); - NBTTagCompound pathNbt = new NBTTagCompound(); - path.writeNBT(pathNbt); - nbt.setTag("Path_" + i, pathNbt); - } - } - - public void readNBT(NBTTagCompound nbt) { - this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0; - - int i = 0; - while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) { - NBTTagCompound pathNbt = nbt.getCompoundTag("Path_" + i); - Path path = (Path) createPath(0, 0, 0); - path.readNBT(pathNbt); - trajectory.add(path); - i++; - } - } - - public static class Path implements IEnergyTrajectoryData.IPath{ - public IPos pos; - public int delayTicks; - public boolean concluded; - - public Path(IPos pos, int delayTicks) { - this.pos = pos; - this.delayTicks = delayTicks; - } - - @Override - public IPos getPos() { - return pos; - } - - @Override - public void setPos(IPos pos) { - this.pos = pos; - } - - @Override - public int getDelay() { - return delayTicks; - } - - @Override - public void setDelay(int delayTicks) { - this.delayTicks = delayTicks; - } - - @Override - public boolean isConcluded() { - return concluded; - } - - @Override - public void setConcluded(boolean concluded) { - this.concluded = concluded; - } - - @Override - public double getX() { - return pos.getX(); - } - - @Override - public void setX(double x) { - this.pos = NpcAPI.Instance().getIPos(x, getY(), getZ()); - } - - @Override - public double getY() { - return pos.getY(); - } - - @Override - public void setY(double y) { - this.pos = NpcAPI.Instance().getIPos(getX(), y, getZ()); - } - - @Override - public double getZ() { - return pos.getZ(); - } - - @Override - public void setZ(double z) { - this.pos = NpcAPI.Instance().getIPos(pos.getX(), pos.getY(), z); - } - - public void writeNBT(NBTTagCompound nbt) { - nbt.setInteger("delay", delayTicks); - nbt.setBoolean("concluded", concluded); - nbt.setDouble("X", getX()); - nbt.setDouble("Y", getY()); - nbt.setDouble("Z", getZ()); - } - - public void readNBT(NBTTagCompound nbt) { - this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0; - this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded"); - - double x = nbt.getDouble("X"); - double y = nbt.getDouble("Y"); - double z = nbt.getDouble("Z"); - - this.pos = NpcAPI.Instance().getIPos(x, y, z); - } - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java new file mode 100644 index 000000000..164215f3c --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java @@ -0,0 +1,64 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityAction; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.List; + +/** + * Common interface for all combat actions that can be assigned to NPCs or players. + * Implemented by {@link Ability} (individual ability) and {@link ChainedAbility} (sequence). + *

+ * This enables unified storage via {@link AbilityAction}, unified weighted random selection, + * and unified eligibility checking without instanceof or separate codepaths. + */ +public interface IAbilityAction { + + String getName(); + + boolean isEnabled(); + + void setEnabled(boolean enabled); + + int getWeight(); + + int getCooldownTicks(); + + float getMinRange(); + + float getMaxRange(); + + UserType getAllowedBy(); + + List getConditions(); + + boolean checkConditions(EntityLivingBase caster, EntityLivingBase target); + + boolean checkConditionsForPlayer(EntityLivingBase caster); + + /** + * Check if this action is available for the given player. + * Used for visibility filtering (HUD, selection) and activation gating. + * Returns true by default (no requirement). + */ + default boolean isAvailableFor(EntityPlayer player) { + return true; + } + + /** + * Whether this action is a chained ability (sequence of abilities) vs an individual ability. + */ + boolean isChain(); + + /** + * Create a deep copy of this action. + */ + IAbilityAction deepCopyAction(); + + NBTTagCompound writeNBT(boolean saveScripts); +} 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 index 49ee50f7e..a54f526ee 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -1,6 +1,8 @@ package kamkeel.npcs.controllers.data.ability.data; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; import net.minecraft.nbt.NBTTagCompound; /** @@ -24,10 +26,12 @@ public class ProjectileData { * If colorOverride is true, returns a copy with overridden inner/outer colors. */ public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) { - if (!colorOverride) return primary; + // Always return a copy so entity mutations never bleed back into the ability template. EnergyDisplayData resolved = primary.copy(); - resolved.innerColor = this.innerColor; - resolved.outerColor = this.outerColor; + if (colorOverride) { + resolved.innerColor = this.innerColor; + resolved.outerColor = this.outerColor; + } return resolved; } @@ -44,8 +48,8 @@ public class ProjectileData { anchor.readNBT(nbt); colorOverride = nbt.getBoolean("colorOverride"); if (colorOverride) { - innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF; + innerColor = nbt.getInteger("overrideInnerColor"); + outerColor = nbt.getInteger("overrideOuterColor"); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/AbilityCustomEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/AbilityCustomEffect.java new file mode 100644 index 000000000..4ded168d5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/AbilityCustomEffect.java @@ -0,0 +1,112 @@ +package kamkeel.npcs.controllers.data.ability.data.effect; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.util.ValueUtil; + +/** + * Represents a custom effect reference that can be applied by abilities. + * Wraps the CustomEffectController system (player-only effects with script callbacks). + */ +public class AbilityCustomEffect { + + private int effectId = -1; + private int durationTicks = 60; + private byte level = 0; + private int index = 0; + + public AbilityCustomEffect() { + } + + public AbilityCustomEffect(int effectId, int durationTicks, byte level) { + this.effectId = effectId; + this.durationTicks = Math.max(1, durationTicks); + this.level = (byte) Math.max(0, Math.min(10, level)); + this.index = 0; + } + + public AbilityCustomEffect(int effectId, int durationTicks, byte level, int index) { + this(effectId, durationTicks, level); + this.index = index; + } + + public AbilityCustomEffect copy() { + return new AbilityCustomEffect(effectId, durationTicks, level, index); + } + + /** + * Applies this custom effect to the given entity. + * Only works on players (CustomEffectController is player-only). + */ + public void apply(EntityLivingBase entity) { + if (entity == null || effectId <= 0) return; + if (entity instanceof EntityPlayer) { + CustomEffectController.getInstance().applyEffect( + (EntityPlayer) entity, effectId, durationTicks, level, index); + } + } + + public boolean isValid() { + return effectId > 0; + } + + // ── NBT ── + + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("effectId", effectId); + nbt.setInteger("duration", durationTicks); + nbt.setByte("level", level); + nbt.setInteger("index", index); + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + this.effectId = nbt.getInteger("effectId"); + this.durationTicks = nbt.getInteger("duration"); + this.level = nbt.getByte("level"); + this.index = nbt.getInteger("index"); + } + + public static AbilityCustomEffect fromNBT(NBTTagCompound nbt) { + AbilityCustomEffect e = new AbilityCustomEffect(); + e.readNBT(nbt); + return e; + } + + // ── Getters/Setters ── + + public int getEffectId() { + return effectId; + } + + public void setEffectId(int effectId) { + this.effectId = effectId; + } + + public int getDurationTicks() { + return durationTicks; + } + + public void setDurationTicks(int durationTicks) { + this.durationTicks = Math.max(1, durationTicks); + } + + public byte getLevel() { + return level; + } + + public void setLevel(byte level) { + this.level = (byte) ValueUtil.clamp(level, 0, 10); + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = Math.max(0, index); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/AbilityPotionEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/AbilityPotionEffect.java new file mode 100644 index 000000000..52a05a8af --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/AbilityPotionEffect.java @@ -0,0 +1,132 @@ +package kamkeel.npcs.controllers.data.ability.data.effect; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.potion.PotionEffect; +import noppes.npcs.constants.EnumPotionType; + +/** + * Represents a configurable potion effect that can be applied by abilities. + * Uses the unified EnumPotionType enum shared across melee, ranged, and ability systems. + */ +public class AbilityPotionEffect { + + private EnumPotionType type = EnumPotionType.None; + private int manualPotionId = 0; + private int durationTicks = 60; + private int amplifier = 0; // 0-255 (Manual), 0-10 (preset) + + public AbilityPotionEffect() { + } + + public AbilityPotionEffect(EnumPotionType type, int durationTicks, int amplifier) { + this.type = type; + this.durationTicks = Math.max(1, durationTicks); + this.amplifier = Math.max(0, Math.min(255, amplifier)); + } + + /** + * Creates a copy of this effect. + */ + public AbilityPotionEffect copy() { + AbilityPotionEffect copy = new AbilityPotionEffect(type, durationTicks, amplifier); + copy.manualPotionId = this.manualPotionId; + return copy; + } + + /** + * Applies this effect to the given entity. + * Does nothing if type is None. Validates potion IDs before applying. + */ + public void apply(EntityLivingBase entity) { + if (entity == null || type == EnumPotionType.None) { + return; + } + + 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)); + } + } + + /** + * Writes this effect to NBT. + */ + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("potionType", type.ordinal()); + nbt.setInteger("duration", durationTicks); + nbt.setInteger("amplifier", amplifier); + if (type == EnumPotionType.Manual) { + nbt.setInteger("manualPotionId", manualPotionId); + } + return nbt; + } + + /** + * Reads this effect from NBT. + */ + public void readNBT(NBTTagCompound nbt) { + 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"); + } + } + + /** + * Creates an AbilityPotionEffect from NBT. + */ + public static AbilityPotionEffect fromNBT(NBTTagCompound nbt) { + AbilityPotionEffect effect = new AbilityPotionEffect(); + effect.readNBT(nbt); + return effect; + } + + // Getters & Setters + + public EnumPotionType getType() { + return type; + } + + 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() { + return durationTicks; + } + + public void setDurationTicks(int durationTicks) { + this.durationTicks = Math.max(1, durationTicks); + } + + public int getAmplifier() { + return amplifier; + } + + public void setAmplifier(int amplifier) { + this.amplifier = Math.max(0, Math.min(255, amplifier)); + } + + /** + * Returns true if this effect is configured (not None). + */ + public boolean isValid() { + return type != EnumPotionType.None; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/IEffectAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/IEffectAction.java new file mode 100644 index 000000000..b674bd51f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/effect/IEffectAction.java @@ -0,0 +1,42 @@ +package kamkeel.npcs.controllers.data.ability.data.effect; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Interface for mod-registered effect actions that can be applied by AbilityEffect. + *

+ * Mods register implementations via {@code Register.EffectActions} or + * {@code AbilityController.Instance.registerEffectAction()}. + * Each action has a unique ID, display name, and apply logic. + * Actions can optionally provide custom configuration fields for the GUI. + */ +public interface IEffectAction { + + /** + * Unique identifier, e.g. "dbc:kiRestore", "mymod:buffSpeed". + */ + String getId(); + + /** + * Localized display name shown in the GUI selector. + */ + String getDisplayName(); + + /** + * Apply this action to a target entity. + * Called once per affected entity during ability execution. + * + * @param caster The entity that used the ability + * @param target The entity being affected + * @param config Action-specific configuration NBT (from GUI) + */ + void apply(EntityLivingBase caster, EntityLivingBase target, NBTTagCompound config); + + /** + * Create default configuration NBT for a new instance of this action. + */ + default NBTTagCompound createDefaultConfig() { + return new NBTTagCompound(); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyAnchorData.java similarity index 72% rename from src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyAnchorData.java index 2187802a5..f618ae3f7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyAnchorData.java @@ -1,6 +1,6 @@ -package kamkeel.npcs.controllers.data.ability.data; +package kamkeel.npcs.controllers.data.ability.data.energy; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.ability.data.IEnergyAnchorData; @@ -9,6 +9,7 @@ public class EnergyAnchorData implements IEnergyAnchorData { public float anchorOffsetX = 0; public float anchorOffsetY = 0; public float anchorOffsetZ = 0; + public boolean launchFromAnchor = false; public EnergyAnchorData() { } @@ -83,21 +84,35 @@ public class EnergyAnchorData implements IEnergyAnchorData { this.anchorOffsetZ = anchorOffsetZ; } + @Override + public boolean getLaunchFromAnchor() { + return launchFromAnchor; + } + + @Override + public void setLaunchFromAnchor(boolean launchFromAnchor) { + this.launchFromAnchor = launchFromAnchor; + } + public void writeNBT(NBTTagCompound nbt) { nbt.setInteger("anchorPoint", anchorPoint.ordinal()); nbt.setFloat("anchorOffsetX", anchorOffsetX); nbt.setFloat("anchorOffsetY", anchorOffsetY); nbt.setFloat("anchorOffsetZ", anchorOffsetZ); + nbt.setBoolean("launchFromAnchor", launchFromAnchor); } 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"); + this.launchFromAnchor = nbt.getBoolean("launchFromAnchor"); } public EnergyAnchorData copy() { - return new EnergyAnchorData(anchorPoint, anchorOffsetX, anchorOffsetY, anchorOffsetZ); + EnergyAnchorData copy = new EnergyAnchorData(anchorPoint, anchorOffsetX, anchorOffsetY, anchorOffsetZ); + copy.launchFromAnchor = this.launchFromAnchor; + return copy; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java new file mode 100644 index 000000000..40c30fe95 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java @@ -0,0 +1,234 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; + +import java.util.HashMap; +import java.util.Map; + +/** + * Groups barrier properties shared by energy barrier abilities (Dome, Wall, Shield). + * Handles health/durability, duration, and per-projectile-type damage multipliers. + * + * Properties: + * - Solid: Hard wall — entities cannot pass through the barrier boundary (either direction) + * - Knockback: Repulsion field — entities near the surface get pushed away + * - Absorbing: Caster's incoming damage is redirected to the barrier + * - Allows Melee: Barrier can be hit by melee attacks (punching) + */ +public class EnergyBarrierData { + + public float maxHealth = 100.0f; + public boolean useHealth = true; + public int durationTicks = 200; + public boolean useDuration = true; + public float defaultMultiplier = 1.0f; + + // Solid: entities cannot pass through the barrier boundary + public boolean solid = false; + + // Knockback: repulsion field pushing entities away from surface + public boolean knockbackEnabled = false; + public float knockbackStrength = 1.0f; + + // Absorbing: caster's damage is redirected to the barrier + public boolean absorbing = false; + // Absorb radius: max distance from barrier's current position for absorption to work + // -1 = no radius limit (absorb regardless of distance) + // 0 = use barrier's own extent as the radius (dome radius, panel half-size, etc.) + // positive = owner must be within this many blocks of the barrier entity + public float absorbRadius = 0.0f; + + // Melee: barrier can be hit by melee attacks + public boolean meleeEnabled = false; + public float meleeDamageMultiplier = 1.0f; + + // Reflection: rebound projectiles that fail to break the barrier + public boolean reflect = false; + public float reflectStrengthPct = 25.0f; + public boolean targetOwner = false; + + /** + * Per-projectile-type damage multipliers. + * Key is the ability typeId (e.g., "ability.cnpc.orb", "ability.cnpc.beam"). + * Value is the multiplier applied to damage dealt to this barrier. + */ + private Map damageMultipliers = new HashMap<>(); + + public EnergyBarrierData() { + } + + public EnergyBarrierData(float maxHealth, boolean useHealth, int durationTicks, boolean useDuration) { + this.maxHealth = maxHealth; + this.useHealth = useHealth; + this.durationTicks = durationTicks; + this.useDuration = useDuration; + } + + // ==================== MULTIPLIER METHODS ==================== + + public float getMultiplier(String abilityTypeId) { + Float mult = damageMultipliers.get(abilityTypeId); + return mult != null ? mult : defaultMultiplier; + } + + public void setMultiplier(String abilityTypeId, float multiplier) { + damageMultipliers.put(abilityTypeId, multiplier); + } + + public void removeMultiplier(String abilityTypeId) { + damageMultipliers.remove(abilityTypeId); + } + + public Map getDamageMultipliers() { + return damageMultipliers; + } + + public void setDamageMultipliers(Map multipliers) { + this.damageMultipliers = multipliers != null ? multipliers : new HashMap<>(); + } + + // ==================== GETTERS & SETTERS ==================== + + public float getMaxHealth() { + return maxHealth; + } + + public void setMaxHealth(float maxHealth) { + this.maxHealth = Math.max(1.0f, maxHealth); + } + + public boolean isUseHealth() { + return useHealth; + } + + public void setUseHealth(boolean useHealth) { + this.useHealth = useHealth; + } + + public int getDurationTicks() { + return durationTicks; + } + + public void setDurationTicks(int durationTicks) { + this.durationTicks = Math.max(1, durationTicks); + } + + public boolean isUseDuration() { + return useDuration; + } + + public void setUseDuration(boolean useDuration) { + this.useDuration = useDuration; + } + + public float getDefaultMultiplier() { + return defaultMultiplier; + } + + public void setDefaultMultiplier(float defaultMultiplier) { + this.defaultMultiplier = defaultMultiplier; + } + + public boolean isReflect() { + return reflect; + } + + public void setReflect(boolean reflect) { + this.reflect = reflect; + } + + public float getReflectStrengthPct() { + return reflectStrengthPct; + } + + public void setReflectStrengthPct(float reflectStrengthPct) { + this.reflectStrengthPct = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct)); + } + + public boolean isTargetOwner() { + return targetOwner; + } + + public void setTargetOwner(boolean targetOwner) { + this.targetOwner = targetOwner; + } + + public float getAbsorbRadius() { + return absorbRadius; + } + + public void setAbsorbRadius(float absorbRadius) { + this.absorbRadius = absorbRadius; + } + + // ==================== NBT ==================== + + public void writeNBT(NBTTagCompound nbt) { + nbt.setFloat("barrierMaxHealth", maxHealth); + nbt.setBoolean("barrierUseHealth", useHealth); + nbt.setInteger("barrierDuration", durationTicks); + nbt.setBoolean("barrierUseDuration", useDuration); + nbt.setFloat("barrierDefaultMult", defaultMultiplier); + nbt.setBoolean("barrierSolid", solid); + nbt.setBoolean("barrierKnockback", knockbackEnabled); + nbt.setFloat("barrierKnockbackStr", knockbackStrength); + nbt.setBoolean("barrierAbsorbing", absorbing); + nbt.setFloat("barrierAbsorbRadius", absorbRadius); + nbt.setBoolean("barrierMelee", meleeEnabled); + nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier); + nbt.setBoolean("barrierReflect", reflect); + nbt.setFloat("barrierReflectStrPct", reflectStrengthPct); + nbt.setBoolean("barrierTargetOwner", targetOwner); + + NBTTagCompound multNbt = new NBTTagCompound(); + for (Map.Entry entry : damageMultipliers.entrySet()) { + multNbt.setFloat(entry.getKey(), entry.getValue()); + } + nbt.setTag("barrierMultipliers", multNbt); + } + + public void readNBT(NBTTagCompound nbt) { + maxHealth = nbt.hasKey("barrierMaxHealth") ? nbt.getFloat("barrierMaxHealth") : 100.0f; + useHealth = !nbt.hasKey("barrierUseHealth") || nbt.getBoolean("barrierUseHealth"); + durationTicks = nbt.hasKey("barrierDuration") ? nbt.getInteger("barrierDuration") : 200; + useDuration = !nbt.hasKey("barrierUseDuration") || nbt.getBoolean("barrierUseDuration"); + defaultMultiplier = nbt.hasKey("barrierDefaultMult") ? nbt.getFloat("barrierDefaultMult") : 1.0f; + solid = nbt.hasKey("barrierSolid") && nbt.getBoolean("barrierSolid"); + knockbackEnabled = nbt.hasKey("barrierKnockback") && nbt.getBoolean("barrierKnockback"); + knockbackStrength = nbt.hasKey("barrierKnockbackStr") ? nbt.getFloat("barrierKnockbackStr") : 1.0f; + absorbing = nbt.hasKey("barrierAbsorbing") && nbt.getBoolean("barrierAbsorbing"); + absorbRadius = nbt.hasKey("barrierAbsorbRadius") ? nbt.getFloat("barrierAbsorbRadius") : 0.0f; + meleeEnabled = nbt.hasKey("barrierMelee") && nbt.getBoolean("barrierMelee"); + meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f; + reflect = nbt.hasKey("barrierReflect") && nbt.getBoolean("barrierReflect"); + setReflectStrengthPct(nbt.hasKey("barrierReflectStrPct") ? nbt.getFloat("barrierReflectStrPct") : 25.0f); + targetOwner = nbt.hasKey("barrierTargetOwner") && nbt.getBoolean("barrierTargetOwner"); + + damageMultipliers.clear(); + if (nbt.hasKey("barrierMultipliers")) { + NBTTagCompound multNbt = nbt.getCompoundTag("barrierMultipliers"); + @SuppressWarnings("unchecked") + java.util.Set keys = multNbt.func_150296_c(); + for (String key : keys) { + damageMultipliers.put(key, multNbt.getFloat(key)); + } + } + } + + public EnergyBarrierData copy() { + EnergyBarrierData copy = new EnergyBarrierData(maxHealth, useHealth, durationTicks, useDuration); + copy.defaultMultiplier = defaultMultiplier; + copy.solid = solid; + copy.knockbackEnabled = knockbackEnabled; + copy.knockbackStrength = knockbackStrength; + copy.absorbing = absorbing; + copy.absorbRadius = absorbRadius; + copy.meleeEnabled = meleeEnabled; + copy.meleeDamageMultiplier = meleeDamageMultiplier; + copy.reflect = reflect; + copy.reflectStrengthPct = reflectStrengthPct; + copy.targetOwner = targetOwner; + copy.damageMultipliers = new HashMap<>(damageMultipliers); + return copy; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyChargingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyChargingData.java new file mode 100644 index 000000000..ec53aaeb5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyChargingData.java @@ -0,0 +1,83 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; + +public class EnergyChargingData { + + public int chargeDuration = 60; + public int chargeDelay = 0; + public int maxCharge = 100; + public boolean hasCharge = true; + public boolean chargeWindUpSync = true; + + public EnergyChargingData() { + } + + public EnergyChargingData(int chargeDuration, int chargeDelay, int maxCharge, boolean hasCharge, boolean chargeWindUpSync) { + this.chargeDuration = chargeDuration; + this.chargeDelay = chargeDelay; + this.maxCharge = maxCharge; + this.hasCharge = hasCharge; + this.chargeWindUpSync = chargeWindUpSync; + } + + public boolean hasCharge() { + return hasCharge; + } + + public void setHasCharge(boolean hasCharge) { + this.hasCharge = hasCharge; + } + + public boolean isChargeWindUpSync() { + return chargeWindUpSync; + } + + public void setChargeWindUpSync(boolean chargeWindUpSync) { + this.chargeWindUpSync = chargeWindUpSync; + } + + public int getChargeDuration() { + return chargeDuration; + } + + public void setChargeDuration(int chargeDuration) { + this.chargeDuration = chargeDuration; + } + + public int getChargeDelay() { + return chargeDelay; + } + + public void setChargeDelay(int chargeDelay) { + this.chargeDelay = chargeDelay; + } + + public int getMaxCharge() { + return maxCharge; + } + + public void setMaxCharge(int maxCharge) { + this.maxCharge = Math.max(0, maxCharge); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("chargeDuration", chargeDuration); + nbt.setInteger("chargeDelay", chargeDelay); + nbt.setInteger("maxCharge", maxCharge); + nbt.setBoolean("hasCharge", hasCharge); + nbt.setBoolean("chargeWindUpSync", chargeWindUpSync); + } + + public void readNBT(NBTTagCompound nbt) { + chargeDuration = nbt.hasKey("chargeDuration") ? nbt.getInteger("chargeDuration") : 60; + chargeDelay = nbt.hasKey("chargeDelay") ? nbt.getInteger("chargeDelay") : 0; + maxCharge = nbt.hasKey("maxCharge") ? nbt.getInteger("maxCharge") : 100; + hasCharge = !nbt.hasKey("hasCharge") || nbt.getBoolean("hasCharge"); + chargeWindUpSync = !nbt.hasKey("chargeWindUpSync") || nbt.getBoolean("chargeWindUpSync"); + } + + public EnergyChargingData copy() { + return new EnergyChargingData(chargeDuration, chargeDelay, maxCharge, hasCharge, chargeWindUpSync); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyCombatData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyCombatData.java new file mode 100644 index 000000000..88103197f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyCombatData.java @@ -0,0 +1,176 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import kamkeel.npcs.controllers.data.ability.enums.HitType; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyCombatData; + +/** + * Groups combat properties shared by energy projectile abilities. + * Used as a parameter object for entity constructors and ability configuration. + */ +public class EnergyCombatData implements IEnergyCombatData { + public static final float MAX_EXPLOSION_RADIUS = 15.0f; + public static final int DEFAULT_MAX_HITS = 5; + public static final int MAX_HITS = 200; + + public float damage = 7.0f; + public float knockback = 1.0f; + public float knockbackUp = 0.1f; + public boolean explosive = false; + public float explosionRadius = 3.0f; + public float explosionDamageFalloff = 0.5f; + public HitType hitType = HitType.SINGLE; + public int multiHitDelayTicks = 5; + public int maxHits = DEFAULT_MAX_HITS; + + public EnergyCombatData() { + } + + public EnergyCombatData(float damage, float knockback, float knockbackUp, + boolean explosive, float explosionRadius, float explosionDamageFalloff, + HitType hitType, int multiHitDelay) { + this(damage, knockback, knockbackUp, explosive, explosionRadius, explosionDamageFalloff, hitType, multiHitDelay, DEFAULT_MAX_HITS); + } + + public EnergyCombatData(float damage, float knockback, float knockbackUp, + boolean explosive, float explosionRadius, float explosionDamageFalloff, + HitType hitType, int multiHitDelay, int maxHits) { + this.damage = damage; + this.knockback = knockback; + this.knockbackUp = knockbackUp; + this.explosive = explosive; + this.explosionRadius = clampExplosionRadius(explosionRadius); + this.explosionDamageFalloff = explosionDamageFalloff; + this.hitType = hitType; + this.multiHitDelayTicks = multiHitDelay; + this.maxHits = clampMaxHits(maxHits); + } + + public EnergyCombatData(float damage, float knockback, float knockbackUp, + boolean explosive, float explosionRadius, float explosionDamageFalloff) { + this.damage = damage; + this.knockback = knockback; + this.knockbackUp = knockbackUp; + this.explosive = explosive; + this.explosionRadius = clampExplosionRadius(explosionRadius); + this.explosionDamageFalloff = explosionDamageFalloff; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getKnockback() { + return knockback; + } + + @Override + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + @Override + public float getKnockbackUp() { + return knockbackUp; + } + + @Override + public void setKnockbackUp(float knockbackUp) { + this.knockbackUp = knockbackUp; + } + + @Override + public boolean isExplosive() { + return explosive; + } + + @Override + public void setExplosive(boolean explosive) { + this.explosive = explosive; + } + + @Override + public float getExplosionRadius() { + return explosionRadius; + } + + @Override + public void setExplosionRadius(float explosionRadius) { + this.explosionRadius = clampExplosionRadius(explosionRadius); + } + + @Override + public float getExplosionDamageFalloff() { + return explosionDamageFalloff; + } + + @Override + public void setExplosionDamageFalloff(float explosionDamageFalloff) { + this.explosionDamageFalloff = explosionDamageFalloff; + } + + public int getMaxHits() { + return maxHits; + } + + public void setMaxHits(int maxHits) { + this.maxHits = clampMaxHits(maxHits); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setFloat("damage", damage); + nbt.setFloat("knockback", knockback); + nbt.setFloat("knockbackUp", knockbackUp); + nbt.setBoolean("explosive", explosive); + nbt.setFloat("explosionRadius", explosionRadius); + nbt.setFloat("explosionDamageFalloff", explosionDamageFalloff); + nbt.setInteger("hitType", hitType.ordinal()); + nbt.setInteger("multiHitDelayTicks", multiHitDelayTicks); + nbt.setInteger("maxHits", maxHits); + } + + 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; + hitType = HitType.fromOrdinal(nbt.hasKey("hitType") ? nbt.getInteger("hitType") : 0); + multiHitDelayTicks = nbt.hasKey("multiHitDelayTicks") ? nbt.getInteger("multiHitDelayTicks") : 5; + maxHits = nbt.hasKey("maxHits") ? nbt.getInteger("maxHits") : DEFAULT_MAX_HITS; + + // Sanitize + if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 7.0f; + if (Float.isNaN(knockback) || Float.isInfinite(knockback) || knockback < 0) knockback = 1.0f; + if (Float.isNaN(explosionRadius) || Float.isInfinite(explosionRadius) || explosionRadius < 0) explosionRadius = 3.0f; + explosionRadius = clampExplosionRadius(explosionRadius); + if (multiHitDelayTicks < 1) multiHitDelayTicks = 1; + maxHits = clampMaxHits(maxHits); + } + + private static float clampExplosionRadius(float explosionRadius) { + if (Float.isNaN(explosionRadius) || Float.isInfinite(explosionRadius)) return 0.0f; + return Math.max(0.0f, Math.min(MAX_EXPLOSION_RADIUS, explosionRadius)); + } + + private static int clampMaxHits(int maxHits) { + return Math.max(1, Math.min(MAX_HITS, maxHits)); + } + + public EnergyCombatData copy() { + EnergyCombatData copy = new EnergyCombatData(damage, knockback, knockbackUp, + explosive, explosionRadius, explosionDamageFalloff); + copy.hitType = hitType; + copy.multiHitDelayTicks = multiHitDelayTicks; + copy.maxHits = maxHits; + return 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/energy/EnergyDisplayData.java similarity index 77% rename from src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java index 0d91e1012..72bcffbb8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability.data; +package kamkeel.npcs.controllers.data.ability.data.energy; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.ability.data.IEnergyDisplayData; @@ -13,9 +13,11 @@ public class EnergyDisplayData implements IEnergyDisplayData { public boolean outerColorEnabled = true; public float outerColorWidth = 0.4f; public float outerColorAlpha = 0.5f; + public float innerAlpha = 1.0f; public float rotationSpeed = 4.0f; - public EnergyDisplayData() {} + public EnergyDisplayData() { + } public EnergyDisplayData(int innerColor, int outerColor) { this.innerColor = innerColor; @@ -32,6 +34,12 @@ public class EnergyDisplayData implements IEnergyDisplayData { this.rotationSpeed = rotationSpeed; } + public EnergyDisplayData(int innerColor, int outerColor, boolean outerColorEnabled, + float outerColorWidth, float outerColorAlpha, float innerAlpha, float rotationSpeed) { + this(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed); + this.innerAlpha = innerAlpha; + } + @Override public int getInnerColor() { return innerColor; @@ -82,6 +90,16 @@ public class EnergyDisplayData implements IEnergyDisplayData { this.outerColorAlpha = outerColorAlpha; } + @Override + public float getInnerAlpha() { + return innerAlpha; + } + + @Override + public void setInnerAlpha(float innerAlpha) { + this.innerAlpha = innerAlpha; + } + @Override public float getRotationSpeed() { return rotationSpeed; @@ -98,6 +116,7 @@ public class EnergyDisplayData implements IEnergyDisplayData { nbt.setBoolean("outerColorEnabled", outerColorEnabled); nbt.setFloat("outerColorWidth", outerColorWidth); nbt.setFloat("outerColorAlpha", outerColorAlpha); + nbt.setFloat("innerAlpha", innerAlpha); nbt.setFloat("rotationSpeed", rotationSpeed); } @@ -107,10 +126,12 @@ public class EnergyDisplayData implements IEnergyDisplayData { 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; + innerAlpha = nbt.hasKey("innerAlpha") ? nbt.getFloat("innerAlpha") : 1.0f; rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; } public EnergyDisplayData copy() { - return new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed); + EnergyDisplayData copy = new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, innerAlpha, rotationSpeed); + return 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/energy/EnergyHomingData.java similarity index 88% rename from src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyHomingData.java index 1e81882c7..a0825fac1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyHomingData.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability.data; +package kamkeel.npcs.controllers.data.ability.data.energy; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.ability.data.IEnergyHomingData; @@ -14,7 +14,8 @@ public class EnergyHomingData implements IEnergyHomingData { public float homingStrength = 0.15f; public float homingRange = 20.0f; - public EnergyHomingData() {} + public EnergyHomingData() { + } public EnergyHomingData(float speed, boolean homing, float homingStrength, float homingRange) { this.speed = speed; @@ -30,7 +31,7 @@ public class EnergyHomingData implements IEnergyHomingData { @Override public void setSpeed(float speed) { - this.speed = speed; + this.speed = Math.max(0.01f, speed); } @Override @@ -75,6 +76,9 @@ public class EnergyHomingData implements IEnergyHomingData { 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; + + // Sanitize speed to prevent stuck projectiles + if (Float.isNaN(speed) || Float.isInfinite(speed) || speed <= 0) speed = 0.5f; } 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/energy/EnergyLifespanData.java similarity index 63% rename from src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLifespanData.java index 9e017e2a5..fcb516242 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLifespanData.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability.data; +package kamkeel.npcs.controllers.data.ability.data.energy; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.ability.data.IEnergyLifespanData; @@ -8,10 +8,11 @@ import noppes.npcs.api.ability.data.IEnergyLifespanData; * Used as a parameter object for entity constructors and ability configuration. */ public class EnergyLifespanData implements IEnergyLifespanData { - public float maxDistance = 30.0f; + public float maxDistance = 150.0f; public int maxLifetime = 200; - public EnergyLifespanData() {} + public EnergyLifespanData() { + } public EnergyLifespanData(float maxDistance, int maxLifetime) { this.maxDistance = maxDistance; @@ -25,7 +26,7 @@ public class EnergyLifespanData implements IEnergyLifespanData { @Override public void setMaxDistance(float maxDistance) { - this.maxDistance = maxDistance; + this.maxDistance = Float.isNaN(maxDistance) || maxDistance <= 0 ? 150.0f : maxDistance; } @Override @@ -35,7 +36,7 @@ public class EnergyLifespanData implements IEnergyLifespanData { @Override public void setMaxLifetime(int maxLifetime) { - this.maxLifetime = maxLifetime; + this.maxLifetime = maxLifetime <= 0 ? 200 : maxLifetime; } public void writeNBT(NBTTagCompound nbt) { @@ -44,8 +45,12 @@ 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"); + + // Sanitize: ensure minimum values so entities don't die instantly or live forever + if (Float.isNaN(maxDistance) || Float.isInfinite(maxDistance) || maxDistance <= 0) maxDistance = 150.0f; + if (maxLifetime <= 0) maxLifetime = 200; } 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/energy/EnergyLightningData.java similarity index 92% rename from src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLightningData.java index 00d0eaa96..72a412cfd 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLightningData.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability.data; +package kamkeel.npcs.controllers.data.ability.data.energy; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.ability.data.IEnergyLightningData; @@ -13,7 +13,8 @@ public class EnergyLightningData implements IEnergyLightningData { public float lightningRadius = 0.5f; public int lightningFadeTime = 6; - public EnergyLightningData() {} + public EnergyLightningData() { + } public EnergyLightningData(boolean lightningEffect, float lightningDensity, float lightningRadius, int lightningFadeTime) { @@ -60,7 +61,7 @@ public class EnergyLightningData implements IEnergyLightningData { @Override public void setLightningFadeTime(int lightningFadeTime) { - this.lightningFadeTime = lightningFadeTime; + this.lightningFadeTime = Math.max(1, lightningFadeTime); } public void writeNBT(NBTTagCompound nbt) { @@ -75,6 +76,7 @@ public class EnergyLightningData implements IEnergyLightningData { 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; + if (lightningFadeTime <= 0) lightningFadeTime = 1; } public EnergyLightningData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java new file mode 100644 index 000000000..aaef76cf6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java @@ -0,0 +1,125 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * Groups panel-specific properties for energy wall/shield abilities. + * Handles dimensions, positioning, and launch behavior. + */ +public class EnergyPanelData { + public float panelWidth = 3.0f; + public float panelHeight = 3.0f; + public float heightOffset = 0.0f; + public float offsetX = 0.0f; + public float offsetZ = 0.0f; + + // Launch properties (Wall only) + public boolean launching = false; + public float launchSpeed = 0.5f; + public float launchDamage = 8.0f; + public float launchKnockback = 2.0f; + + public EnergyPanelData() { + } + + public EnergyPanelData(float panelWidth, float panelHeight, float heightOffset) { + this.panelWidth = panelWidth; + this.panelHeight = panelHeight; + this.heightOffset = heightOffset; + } + + // ==================== GETTERS & SETTERS ==================== + + public float getPanelWidth() { + return panelWidth; + } + + public void setPanelWidth(float panelWidth) { + this.panelWidth = Math.max(0.5f, panelWidth); + } + + public float getPanelHeight() { + return panelHeight; + } + + public void setPanelHeight(float panelHeight) { + this.panelHeight = Math.max(0.5f, panelHeight); + } + + public float getHeightOffset() { + return heightOffset; + } + + public void setHeightOffset(float heightOffset) { + this.heightOffset = heightOffset; + } + + public boolean isLaunching() { + return launching; + } + + public void setLaunching(boolean launching) { + this.launching = launching; + } + + public float getLaunchSpeed() { + return launchSpeed; + } + + public void setLaunchSpeed(float launchSpeed) { + this.launchSpeed = Math.max(0.1f, launchSpeed); + } + + public float getLaunchDamage() { + return launchDamage; + } + + public void setLaunchDamage(float launchDamage) { + this.launchDamage = Math.max(0, launchDamage); + } + + public float getLaunchKnockback() { + return launchKnockback; + } + + public void setLaunchKnockback(float launchKnockback) { + this.launchKnockback = Math.max(0, launchKnockback); + } + + // ==================== NBT ==================== + + public void writeNBT(NBTTagCompound nbt) { + nbt.setFloat("panelWidth", panelWidth); + nbt.setFloat("panelHeight", panelHeight); + nbt.setFloat("panelHeightOffset", heightOffset); + nbt.setFloat("panelOffsetX", offsetX); + nbt.setFloat("panelOffsetZ", offsetZ); + nbt.setBoolean("panelLaunching", launching); + nbt.setFloat("panelLaunchSpeed", launchSpeed); + nbt.setFloat("panelLaunchDamage", launchDamage); + nbt.setFloat("panelLaunchKnockback", launchKnockback); + } + + public void readNBT(NBTTagCompound nbt) { + panelWidth = nbt.hasKey("panelWidth") ? nbt.getFloat("panelWidth") : 3.0f; + panelHeight = nbt.hasKey("panelHeight") ? nbt.getFloat("panelHeight") : 3.0f; + heightOffset = nbt.hasKey("panelHeightOffset") ? nbt.getFloat("panelHeightOffset") : 0.0f; + offsetX = nbt.hasKey("panelOffsetX") ? nbt.getFloat("panelOffsetX") : 0.0f; + offsetZ = nbt.hasKey("panelOffsetZ") ? nbt.getFloat("panelOffsetZ") : 0.0f; + launching = nbt.hasKey("panelLaunching") && nbt.getBoolean("panelLaunching"); + launchSpeed = nbt.hasKey("panelLaunchSpeed") ? nbt.getFloat("panelLaunchSpeed") : 0.5f; + launchDamage = nbt.hasKey("panelLaunchDamage") ? nbt.getFloat("panelLaunchDamage") : 8.0f; + launchKnockback = nbt.hasKey("panelLaunchKnockback") ? nbt.getFloat("panelLaunchKnockback") : 2.0f; + } + + public EnergyPanelData copy() { + EnergyPanelData copy = new EnergyPanelData(panelWidth, panelHeight, heightOffset); + copy.offsetX = offsetX; + copy.offsetZ = offsetZ; + copy.launching = launching; + copy.launchSpeed = launchSpeed; + copy.launchDamage = launchDamage; + copy.launchKnockback = launchKnockback; + return copy; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/AbilityEffectActionEntry.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/AbilityEffectActionEntry.java new file mode 100644 index 000000000..6540e1f5e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/AbilityEffectActionEntry.java @@ -0,0 +1,87 @@ +package kamkeel.npcs.controllers.data.ability.data.entry; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; + +/** + * A configured instance of an {@link IEffectAction} stored on an ability. + * Holds the action ID and its configuration NBT. + */ +public class AbilityEffectActionEntry { + + private String actionId = ""; + private NBTTagCompound config = new NBTTagCompound(); + + public AbilityEffectActionEntry() { + } + + public AbilityEffectActionEntry(String actionId) { + this.actionId = actionId != null ? actionId : ""; + IEffectAction action = AbilityController.Instance.getEffectAction(this.actionId); + if (action != null) { + this.config = action.createDefaultConfig(); + } + } + + public AbilityEffectActionEntry copy() { + AbilityEffectActionEntry copy = new AbilityEffectActionEntry(); + copy.actionId = this.actionId; + copy.config = (NBTTagCompound) this.config.copy(); + return copy; + } + + /** + * Apply this action to a target entity. + */ + public void apply(EntityLivingBase caster, EntityLivingBase target) { + if (actionId.isEmpty()) return; + IEffectAction action = AbilityController.Instance.getEffectAction(actionId); + if (action != null) { + action.apply(caster, target, config); + } + } + + public boolean isValid() { + return !actionId.isEmpty() && AbilityController.Instance.getEffectAction(actionId) != null; + } + + // ── NBT ── + + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("actionId", actionId); + nbt.setTag("config", config); + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + this.actionId = nbt.getString("actionId"); + this.config = nbt.hasKey("config") ? nbt.getCompoundTag("config") : new NBTTagCompound(); + } + + public static AbilityEffectActionEntry fromNBT(NBTTagCompound nbt) { + AbilityEffectActionEntry entry = new AbilityEffectActionEntry(); + entry.readNBT(nbt); + return entry; + } + + // ── Getters/Setters ── + + public String getActionId() { + return actionId; + } + + public void setActionId(String actionId) { + this.actionId = actionId != null ? actionId : ""; + } + + public NBTTagCompound getConfig() { + return config; + } + + public void setConfig(NBTTagCompound config) { + this.config = config != null ? config : new NBTTagCompound(); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/AbilityToggleEntry.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/AbilityToggleEntry.java new file mode 100644 index 000000000..d200fefa6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/AbilityToggleEntry.java @@ -0,0 +1,42 @@ +package kamkeel.npcs.controllers.data.ability.data.entry; + +import kamkeel.npcs.controllers.data.ability.Ability; + +/** + * Tracks the state of a single active toggle for an entity. + * Stored in AbstractDataAbilities.activeToggles map. + *

+ * State is 1-based: state 1 = first ON state, state 2 = second, etc. + * State 0 means OFF (entry should not exist in the map). + */ +public class AbilityToggleEntry { + private final Ability ability; + private int tickCount; + private int state; + + public AbilityToggleEntry(Ability ability, int state) { + this.ability = ability; + this.tickCount = 0; + this.state = Math.max(1, state); + } + + public Ability getAbility() { + return ability; + } + + public int getTickCount() { + return tickCount; + } + + public void incrementTick() { + tickCount++; + } + + public int getState() { + return state; + } + + public void setState(int state) { + this.state = Math.max(1, state); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java new file mode 100644 index 000000000..ec7fade19 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java @@ -0,0 +1,223 @@ +package kamkeel.npcs.controllers.data.ability.data.entry; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.UUID; + +/** + * A single entry in a {@link ChainedAbility}, representing one ability + * to execute in sequence along with its delay configuration. + *

+ * Entries can be either a reference to a registered ability (by name/key) + * or an inline ability that is owned directly by this entry. + */ +public class ChainedAbilityEntry { + + public enum EntryType {REFERENCE, INLINE} + + private EntryType entryType = EntryType.REFERENCE; + + /** + * Reference key (built-in name or custom ability name). Used when entryType == REFERENCE. + */ + private String abilityReference = ""; + + /** + * Inline ability data. Used when entryType == INLINE. + */ + private Ability inlineAbility = null; + + /** + * Delay in ticks BEFORE this ability starts (after previous entry completes). + */ + private int delayTicks = 0; + + /** + * Whether this entry should execute concurrently (alongside the previous ability) + * rather than sequentially. Only takes effect if the resolved ability isConcurrentCapable(). + */ + private boolean concurrentEnabled = true; + + public ChainedAbilityEntry() { + } + + public ChainedAbilityEntry(String abilityReference, int delayTicks) { + this.entryType = EntryType.REFERENCE; + this.abilityReference = abilityReference != null ? abilityReference : ""; + this.delayTicks = Math.max(0, delayTicks); + } + + // ═══════════════════════════════════════════════════════════════════ + // FACTORY METHODS + // ═══════════════════════════════════════════════════════════════════ + + public static ChainedAbilityEntry reference(String ref, int delay) { + ChainedAbilityEntry entry = new ChainedAbilityEntry(); + entry.entryType = EntryType.REFERENCE; + entry.abilityReference = ref != null ? ref : ""; + entry.delayTicks = Math.max(0, delay); + return entry; + } + + public static ChainedAbilityEntry inline(Ability ability, int delay) { + ChainedAbilityEntry entry = new ChainedAbilityEntry(); + entry.entryType = EntryType.INLINE; + entry.inlineAbility = ability; + entry.delayTicks = Math.max(0, delay); + return entry; + } + + // ═══════════════════════════════════════════════════════════════════ + // TYPE QUERIES + // ═══════════════════════════════════════════════════════════════════ + + public EntryType getEntryType() { + return entryType; + } + + public boolean isInline() { + return entryType == EntryType.INLINE; + } + + public boolean isReference() { + return entryType == EntryType.REFERENCE; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public String getAbilityReference() { + return abilityReference; + } + + public void setAbilityReference(String abilityReference) { + this.abilityReference = abilityReference != null ? abilityReference : ""; + } + + public Ability getInlineAbility() { + return inlineAbility; + } + + public void setInlineAbility(Ability ability) { + this.inlineAbility = ability; + } + + public int getDelayTicks() { + return delayTicks; + } + + public void setDelayTicks(int delayTicks) { + this.delayTicks = Math.max(0, delayTicks); + } + + public boolean isConcurrentEnabled() { + return concurrentEnabled; + } + + public void setConcurrentEnabled(boolean concurrentEnabled) { + this.concurrentEnabled = concurrentEnabled; + } + + // ═══════════════════════════════════════════════════════════════════ + // RESOLUTION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Resolve this entry to an Ability instance. + * Inline entries return their ability directly. + * Reference entries resolve via AbilityController. + */ + public Ability resolve() { + if (entryType == EntryType.INLINE) { + return inlineAbility; + } + AbilityController ctrl = AbilityController.Instance; + if (ctrl == null) return null; + return ctrl.resolveAbility(abilityReference); + } + + // ═══════════════════════════════════════════════════════════════════ + // CONVERSION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Convert a reference entry to inline by cloning the resolved ability. + * Returns false if already inline or the reference cannot be resolved. + */ + public boolean convertToInline() { + if (entryType != EntryType.REFERENCE) return false; + + AbilityController ctrl = AbilityController.Instance; + if (ctrl == null) return false; + + Ability resolved = ctrl.resolveAbility(abilityReference); + if (resolved == null) return false; + + NBTTagCompound nbt = resolved.writeNBT(true); + nbt.setString("id", UUID.randomUUID().toString()); + inlineAbility = ctrl.fromNBT(nbt); + entryType = EntryType.INLINE; + abilityReference = ""; + return true; + } + + // ═══════════════════════════════════════════════════════════════════ + // DEEP COPY + // ═══════════════════════════════════════════════════════════════════ + + /** + * Create a deep copy of this entry. Inline abilities are copied via NBT round-trip. + */ + public ChainedAbilityEntry deepCopy() { + ChainedAbilityEntry copy = new ChainedAbilityEntry(); + copy.entryType = this.entryType; + copy.abilityReference = this.abilityReference; + copy.delayTicks = this.delayTicks; + copy.concurrentEnabled = this.concurrentEnabled; + if (this.inlineAbility != null) { + copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT(true)); + } + return copy; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + public NBTTagCompound writeNBT(boolean saveScripts) { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("Delay", delayTicks); + nbt.setBoolean("Concurrent", concurrentEnabled); + + if (entryType == EntryType.INLINE && inlineAbility != null) { + nbt.setTag("InlineAbility", inlineAbility.writeNBT(saveScripts)); + } else { + nbt.setString("Reference", abilityReference); + } + return nbt; + } + + public static ChainedAbilityEntry fromNBT(NBTTagCompound nbt) { + if (nbt == null) return null; + + ChainedAbilityEntry entry = new ChainedAbilityEntry(); + entry.delayTicks = Math.max(0, nbt.getInteger("Delay")); + entry.concurrentEnabled = nbt.hasKey("Concurrent") ? nbt.getBoolean("Concurrent") : true; + + if (nbt.hasKey("InlineAbility")) { + NBTTagCompound abilityNBT = nbt.getCompoundTag("InlineAbility"); + entry.entryType = EntryType.INLINE; + entry.inlineAbility = AbilityController.Instance != null + ? AbilityController.Instance.fromNBT(abilityNBT) : null; + } else { + entry.entryType = EntryType.REFERENCE; + entry.abilityReference = nbt.getString("Reference"); + } + + return entry; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AbilityPhase.java similarity index 85% rename from src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/enums/AbilityPhase.java index af1bd8d30..a0549b09a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AbilityPhase.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.enums; public enum AbilityPhase { IDLE, // Not executing diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AnchorPoint.java similarity index 65% rename from src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/enums/AnchorPoint.java index 1c308493c..567713d34 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AnchorPoint.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.enums; /** * Defines anchor points for ability charging effects. @@ -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; @@ -49,13 +50,22 @@ public enum AnchorPoint { @Override public String toString() { switch (this) { - case FRONT: return "ability.anchor.front"; - case CENTER: return "ability.anchor.center"; - case RIGHT_HAND: return "ability.anchor.rightHand"; - case LEFT_HAND: return "ability.anchor.leftHand"; - case ABOVE_HEAD: return "ability.anchor.aboveHead"; - case CHEST: return "ability.anchor.chest"; - default: return name(); + case FRONT: + return "ability.anchor.front"; + case CENTER: + return "ability.anchor.center"; + case RIGHT_HAND: + return "ability.anchor.rightHand"; + 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/enums/HitType.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/HitType.java new file mode 100644 index 000000000..ad1f07d0e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/HitType.java @@ -0,0 +1,32 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Shared hit behavior for energy projectiles. + */ +public enum HitType { + SINGLE, + PIERCE, + MULTI; + + public static HitType fromOrdinal(int ordinal) { + HitType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return SINGLE; + } + + @Override + public String toString() { + switch (this) { + case SINGLE: + return "ability.hitType.single"; + case PIERCE: + return "ability.hitType.pierce"; + case MULTI: + return "ability.hitType.multi"; + default: + return name(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/enums/InvulnerableMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/InvulnerableMode.java new file mode 100644 index 000000000..fc6dc5169 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/InvulnerableMode.java @@ -0,0 +1,66 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Defines when a caster is invulnerable while an ability is executing. + */ +public enum InvulnerableMode { + NONE, + WINDUP, + ACTIVE, + BOTH; + + public boolean invulnerableDuringWindup() { + return this == WINDUP || this == BOTH; + } + + public boolean invulnerableDuringActive() { + return this == ACTIVE || this == BOTH; + } + + /** + * Treat BURST_DELAY as windup-like for interruption/damage immunity checks. + */ + public boolean isInvulnerableInPhase(AbilityPhase phase) { + if (phase == null) return false; + switch (phase) { + case WINDUP: + case BURST_DELAY: + return invulnerableDuringWindup(); + case ACTIVE: + return invulnerableDuringActive(); + default: + return false; + } + } + + public String getDisplayKey() { + switch (this) { + case WINDUP: + return "ability.invulnerable.windup"; + case ACTIVE: + return "ability.invulnerable.active"; + case BOTH: + return "ability.invulnerable.both"; + case NONE: + default: + return "ability.invulnerable.none"; + } + } + + public static String[] getDisplayKeys() { + return new String[]{ + "ability.invulnerable.none", + "ability.invulnerable.windup", + "ability.invulnerable.active", + "ability.invulnerable.both" + }; + } + + public static InvulnerableMode fromOrdinal(int ordinal) { + InvulnerableMode[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return NONE; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/LockMovementType.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/LockMode.java similarity index 87% rename from src/main/java/kamkeel/npcs/controllers/data/ability/LockMovementType.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/enums/LockMode.java index 1b81a3bb3..47d7b1d1d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/LockMovementType.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/LockMode.java @@ -1,9 +1,9 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.enums; /** * Defines when an ability locks NPC movement and rotation. */ -public enum LockMovementType { +public enum LockMode { /** * No movement lock - NPC can move freely during both phases. */ @@ -71,10 +71,10 @@ public enum LockMovementType { } /** - * Get LockMovementType from ordinal, with fallback to WINDUP. + * Get LockMode from ordinal, with fallback to WINDUP. */ - public static LockMovementType fromOrdinal(int ordinal) { - LockMovementType[] values = values(); + public static LockMode fromOrdinal(int ordinal) { + LockMode[] values = values(); if (ordinal >= 0 && ordinal < values.length) { return values[ordinal]; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/RotationMode.java similarity index 92% rename from src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/enums/RotationMode.java index e1142b571..f8f1ec860 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/RotationMode.java @@ -1,8 +1,8 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.enums; /** * Defines what happens to NPC rotation during ability phases. - * Used with a LockMovementType to control WHEN it applies. + * Used with a LockMode to control WHEN it applies. */ public enum RotationMode { /** diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetFilter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetFilter.java new file mode 100644 index 000000000..91d5b2434 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetFilter.java @@ -0,0 +1,32 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Filter for determining which entities an ability should affect in AOE mode. + */ +public enum TargetFilter { + ALLIES, + ENEMIES, + ALL; + + @Override + public String toString() { + switch (this) { + case ALLIES: + return "ability.targetFilter.allies"; + case ENEMIES: + return "ability.targetFilter.enemies"; + case ALL: + return "ability.targetFilter.all"; + default: + return name(); + } + } + + public static TargetFilter fromString(String name) { + try { + return valueOf(name); + } catch (Exception e) { + return ALLIES; + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetingMode.java similarity index 51% rename from src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetingMode.java index 9bdbdac6f..b32b04c9a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetingMode.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.enums; /** * Defines how an ability selects its target(s). @@ -27,11 +27,16 @@ public enum TargetingMode { @Override public String toString() { switch (this) { - case AGGRO_TARGET: return "ability.target.aggro_target"; - case SELF: return "ability.target.self"; - case AOE_SELF: return "ability.target.aoe_self"; - case AOE_TARGET: return "ability.target.aoe_target"; - default: return name(); + case AGGRO_TARGET: + return "ability.target.aggro_target"; + case SELF: + return "ability.target.self"; + case AOE_SELF: + return "ability.target.aoe_self"; + case AOE_TARGET: + return "ability.target.aoe_target"; + default: + return name(); } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/UserType.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/UserType.java similarity index 87% rename from src/main/java/kamkeel/npcs/controllers/data/ability/UserType.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/enums/UserType.java index d68693f59..cc5960ff6 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/UserType.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/UserType.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.enums; /** * Defines which entity types can use an ability. @@ -6,7 +6,8 @@ package kamkeel.npcs.controllers.data.ability; public enum UserType { NPC_ONLY, PLAYER_ONLY, - BOTH; + BOTH, + NONE; public boolean allowsNpc() { return this == NPC_ONLY || this == BOTH; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/extender/IAbilityExtender.java b/src/main/java/kamkeel/npcs/controllers/data/ability/extender/IAbilityExtender.java new file mode 100644 index 000000000..2a0b90344 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/extender/IAbilityExtender.java @@ -0,0 +1,149 @@ +package kamkeel.npcs.controllers.data.ability.extender; + +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.entity.EntityEnergyBarrier; +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 + * @param damageMultiplier Accumulated proportional damage multiplier (0.0-1.0). + * 1.0 means full damage (no reduction). Extenders that recalculate + * damage from stats should multiply by this value. + * @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, + float damageMultiplier) { + return false; + } + + /** + * Called to modify outgoing projectile damage before it hits a barrier or is used in other contexts. + * Unlike onAbilityDamage (chain of responsibility), this is cumulative — all extenders apply their + * modifications in sequence, each receiving the previous extender's output. + * + * @param ability The source ability of the projectile + * @param caster The entity that fired the projectile + * @param baseDamage The base damage from the ability configuration + * @return The modified damage value + */ + default float modifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { + return baseDamage; + } + + /** + * Called when a barrier entity is about to be created, allowing extenders to modify its max health. + * Cumulative: all extenders apply in sequence, each receiving the previous output. + * + * @param ability The barrier ability being executed + * @param caster The entity creating the barrier + * @param baseHealth The base max health from EnergyBarrierData.maxHealth + * @return The modified max health value + */ + default float modifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) { + return baseHealth; + } + + /** + * Called when a barrier entity takes a melee hit, allowing extenders to scale the damage. + * A barrier is a plain Entity, so no LivingHurtEvent fires for it and an extender has no + * other opportunity to scale melee against it the way it scales {@link #modifyBarrierHealth}. + * Cumulative: all extenders apply in sequence, each receiving the previous output. + * + * @param barrier The barrier being hit + * @param attacker The entity dealing the hit + * @param baseDamage The damage after the barrier's own melee multiplier + * @return The modified damage value + */ + default float modifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) { + return baseDamage; + } + + /** + * Called when an ability is about to heal an entity. + * Return true to handle the healing (skip default entity.heal()). + * Chain of responsibility: first returning true wins. + * + * @param ability The ability performing the heal + * @param caster The entity casting the ability + * @param target The entity being healed + * @param healAmount The heal amount calculated by the ability + * @return true if healing was handled (skip default), false to pass to next extender or default + */ + default boolean onAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) { + return false; + } + + default Boolean onCheckCondition(AbilityCondition condition, EntityLivingBase caster, EntityLivingBase target) { + return null; + } + + default Boolean onCheckConditionForPlayer(AbilityCondition condition, EntityLivingBase player) { + return null; + } +} 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..6438f6ba1 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 @@ -2,9 +2,14 @@ package kamkeel.npcs.controllers.data.ability.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityCustomEffect; +import kamkeel.npcs.controllers.data.ability.data.entry.AbilityEffectActionEntry; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.builder.FieldType; import noppes.npcs.client.gui.builder.GuiFieldBuilder; @@ -12,23 +17,37 @@ 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 noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.TreeMap; /** * Ability-specific extension of {@link GuiFieldBuilder} that handles - * the EFFECTS_LIST field type. + * the EFFECTS_LIST, CUSTOM_EFFECTS_LIST, and EFFECT_ACTIONS_LIST field types. */ @SideOnly(Side.CLIENT) public class AbilityFieldBuilder extends GuiFieldBuilder { - // Effects list metadata: widgetId -> [effectIndex, action] - // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add + // Unified metadata: widgetId -> [index, action] + // EFFECTS_LIST actions: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text) + // CUSTOM_EFFECTS_LIST actions: 0=effectName, 1=duration(text), 2=level, 3=delete, 4=add + // EFFECT_ACTIONS_LIST actions: 0=actionSelector, 3=delete, 4=add private final Map effectWidgetMeta = new HashMap<>(); + // Cached sorted custom effect data for GUI selectors + private int[] sortedCustomEffectIds; + private String[] sortedCustomEffectNames; + + // Cached effect action data for GUI selectors + private String[] effectActionIds; + private String[] effectActionDisplayNames; + public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { super(parent, fontRenderer); } @@ -36,6 +55,10 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @Override protected int build(List fields) { effectWidgetMeta.clear(); + sortedCustomEffectIds = null; + sortedCustomEffectNames = null; + effectActionIds = null; + effectActionDisplayNames = null; return super.build(fields); } @@ -44,33 +67,184 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { if (def.getType() == FieldType.EFFECTS_LIST) { return renderEffectsList(def, y); } + if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) { + return renderCustomEffectsList(def, y); + } + if (def.getType() == FieldType.EFFECT_ACTIONS_LIST) { + return renderEffectActionsList(def, y); + } return -1; // not handled } + // ═══════════════════════════════════════════════════════════════════ + // POTION EFFECTS LIST (existing) + // ═══════════════════════════════════════════════════════════════════ + @SuppressWarnings("unchecked") private int renderEffectsList(FieldDef def, int y) { - // Section header y += 3; sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); y += 15; - List effects = (List) def.getValue(); + 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); + AbilityPotionEffect effect = effects.get(e); - // Type selector button - int typeIdx = effect.getType().ordinal(); - GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx); + 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}); widgetId++; + GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks())); + durField.setIntegersOnly(); + durField.setMinMaxDefault(1, 12000, 60); + sw.addTextField(durField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 1}); + widgetId++; + + if (effect.getType() != EnumPotionType.Fire) { + if (effect.getType() == EnumPotionType.Manual) { + GuiNpcTextField ampField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 158, y, 40, 20, String.valueOf(effect.getAmplifier())); + ampField.setIntegersOnly(); + ampField.setMinMaxDefault(0, 255, 0); + sw.addTextField(ampField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 2}); + widgetId++; + } else { + 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++; + } + + GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); + sw.addButton(delBtn); + clearFieldMap.put(clearId, def); + effectWidgetMeta.put(clearId, new int[]{e, 3}); + clearId++; + + y += rowHeight; + + 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; + } + } + + if (effects.size() < 5) { + GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); + sw.addButton(addBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{effects.size(), 4}); + widgetId++; + clearId++; + y += rowHeight; + } + + return y; + } + + // ═══════════════════════════════════════════════════════════════════ + // CUSTOM EFFECTS LIST + // ═══════════════════════════════════════════════════════════════════ + + private void ensureCustomEffectCache() { + if (sortedCustomEffectIds != null) return; + + HashMap allEffects = CustomEffectController.getInstance().getCustomEffects(); + // Sort by name for consistent ordering + TreeMap nameToId = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (CustomEffect ce : allEffects.values()) { + if (ce.getName() != null && !ce.getName().isEmpty()) { + nameToId.put(ce.getName(), ce.id); + } + } + + sortedCustomEffectIds = new int[nameToId.size()]; + sortedCustomEffectNames = new String[nameToId.size()]; + int i = 0; + for (Map.Entry entry : nameToId.entrySet()) { + sortedCustomEffectIds[i] = entry.getValue(); + sortedCustomEffectNames[i] = entry.getKey(); + i++; + } + } + + private String getCustomEffectName(int effectId, int index) { + HashMap allEffects = CustomEffectController.getInstance().getEffectMap(index); + if (allEffects != null) { + CustomEffect ce = allEffects.get(effectId); + if (ce != null && ce.getName() != null && !ce.getName().isEmpty()) { + return ce.getName(); + } + } + // Fallback: check index 0 + if (index != 0) { + return getCustomEffectName(effectId, 0); + } + return "?"; + } + + private boolean hasAnyEffects() { + for (HashMap map : CustomEffectController.getInstance().indexMapper.values()) { + if (map != null && !map.isEmpty()) return true; + } + return false; + } + + @SuppressWarnings("unchecked") + private int renderCustomEffectsList(FieldDef def, int y) { + ensureCustomEffectCache(); + + y += 3; + sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); + y += 15; + + if (!hasAnyEffects()) { + sw.addLabel(new GuiNpcLabel(labelId++, "ability.noCustomEffects", colLLabel, y + 5, 0x888888)); + y += rowHeight; + return y; + } + + List effects = (List) def.getValue(); + if (effects == null) effects = new ArrayList<>(); + + String[] levelValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + + for (int e = 0; e < effects.size() && e < 5; e++) { + AbilityCustomEffect effect = effects.get(e); + + // Effect name button — opens SubGui picker + String effectName = getCustomEffectName(effect.getEffectId(), effect.getIndex()); + GuiNpcButton nameBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, effectName); + sw.addButton(nameBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 0}); + widgetId++; + // Duration text field GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer, colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks())); @@ -81,9 +255,9 @@ 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); + // Level selector (0-10) + GuiNpcButton lvlBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, levelValues, effect.getLevel()); + sw.addButton(lvlBtn); buttonFieldMap.put(widgetId, def); effectWidgetMeta.put(widgetId, new int[]{e, 2}); widgetId++; @@ -98,7 +272,6 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { y += rowHeight; } - // Add button (if < 5 effects) if (effects.size() < 5) { GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); sw.addButton(addBtn); @@ -112,6 +285,77 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { return y; } + // ═══════════════════════════════════════════════════════════════════ + // EFFECT ACTIONS LIST + // ═══════════════════════════════════════════════════════════════════ + + private void ensureEffectActionCache() { + if (effectActionIds != null) return; + + String[] ids = AbilityController.Instance.getEffectActionIds(); + effectActionIds = ids; + effectActionDisplayNames = new String[ids.length]; + for (int i = 0; i < ids.length; i++) { + IEffectAction action = AbilityController.Instance.getEffectAction(ids[i]); + effectActionDisplayNames[i] = action != null ? action.getDisplayName() : ids[i]; + } + } + + private int findEffectActionIndex(String actionId) { + ensureEffectActionCache(); + for (int i = 0; i < effectActionIds.length; i++) { + if (effectActionIds[i].equals(actionId)) return i; + } + return -1; + } + + @SuppressWarnings("unchecked") + private int renderEffectActionsList(FieldDef def, int y) { + ensureEffectActionCache(); + + if (effectActionIds.length == 0) return y; + + y += 3; + sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); + y += 15; + + List entries = (List) def.getValue(); + if (entries == null) entries = new ArrayList<>(); + + for (int e = 0; e < entries.size() && e < 5; e++) { + AbilityEffectActionEntry entry = entries.get(e); + + // Action selector + int selectedIdx = Math.max(0, findEffectActionIndex(entry.getActionId())); + GuiNpcButton actionBtn = new GuiNpcButton(widgetId, colLLabel, y, 180, 20, effectActionDisplayNames, selectedIdx); + sw.addButton(actionBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 0}); + widgetId++; + + // Delete button + GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); + sw.addButton(delBtn); + clearFieldMap.put(clearId, def); + effectWidgetMeta.put(clearId, new int[]{e, 3}); + clearId++; + + y += rowHeight; + } + + if (entries.size() < 5) { + GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); + sw.addButton(addBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{entries.size(), 4}); + widgetId++; + clearId++; + y += rowHeight; + } + + return y; + } + // ═══════════════════════════════════════════════════════════════════ // EVENT HANDLING OVERRIDES // ═══════════════════════════════════════════════════════════════════ @@ -119,36 +363,106 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @Override @SuppressWarnings("unchecked") public boolean handleButtonEvent(int buttonId, GuiButton button) { - // Check effects list buttons via metadata int[] meta = effectWidgetMeta.get(buttonId); if (meta != null) { FieldDef def = buttonFieldMap.get(buttonId); if (def == null) def = clearFieldMap.get(buttonId); - if (def != null && def.getType() == FieldType.EFFECTS_LIST) { - List effects = (List) def.getValue(); - if (effects == null) return false; - int effectIdx = meta[0]; - int action = meta[1]; + if (def == null) return false; + int idx = meta[0]; + int action = meta[1]; + + // ── Potion Effects ── + if (def.getType() == FieldType.EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects == null) return false; switch (action) { - case 0: // Type changed - if (effectIdx < effects.size()) { - effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue())); + case 0: + if (idx < effects.size()) { + EnumPotionType oldType = effects.get(idx).getType(); + EnumPotionType newType = EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue()); + if (oldType == EnumPotionType.Manual && newType != EnumPotionType.Manual) { + effects.get(idx).setAmplifier(0); + } + effects.get(idx).setType(newType); } return true; - case 2: // Amp changed - if (effectIdx < effects.size()) { - effects.get(effectIdx).setAmplifier(((GuiNpcButton) button).getValue()); + case 2: + if (idx < effects.size()) + effects.get(idx).setAmplifier(((GuiNpcButton) button).getValue()); + return true; + case 3: + if (idx < effects.size()) effects.remove(idx); + return true; + case 4: + if (effects.size() < 5) effects.add(new AbilityPotionEffect(EnumPotionType.Slowness, 60, 0)); + return true; + } + } + + // ── Custom Effects ── + if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects == null) return false; + ensureCustomEffectCache(); + switch (action) { + case 0: // Open effect picker SubGui + if (idx < effects.size()) { + int currentId = effects.get(idx).getEffectId(); + int currentIndex = effects.get(idx).getIndex(); + parent.setSubGuiWithResult(new SubGuiCustomEffectSelect(currentId, currentIndex), sub -> { + SubGuiCustomEffectSelect select = (SubGuiCustomEffectSelect) sub; + int selectedId = select.getSelectedEffectId(); + if (selectedId >= 0 && idx < effects.size()) { + effects.get(idx).setEffectId(selectedId); + effects.get(idx).setIndex(select.getSelectedIndex()); + } + }); } return true; + case 2: // Level changed + if (idx < effects.size()) + effects.get(idx).setLevel((byte) ((GuiNpcButton) button).getValue()); + return true; case 3: // Delete - if (effectIdx < effects.size()) { - effects.remove(effectIdx); - } + if (idx < effects.size()) effects.remove(idx); return true; case 4: // Add if (effects.size() < 5) { - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0)); + parent.setSubGuiWithResult(new SubGuiCustomEffectSelect(-1), sub -> { + SubGuiCustomEffectSelect select = (SubGuiCustomEffectSelect) sub; + int selectedId = select.getSelectedEffectId(); + if (selectedId >= 0 && effects.size() < 5) { + effects.add(new AbilityCustomEffect(selectedId, 60, (byte) 0, select.getSelectedIndex())); + } + }); + } + return true; + } + } + + // ── Effect Actions ── + if (def.getType() == FieldType.EFFECT_ACTIONS_LIST) { + List entries = (List) def.getValue(); + if (entries == null) return false; + ensureEffectActionCache(); + switch (action) { + case 0: // Action selector changed + if (idx < entries.size()) { + int btnVal = ((GuiNpcButton) button).getValue(); + if (btnVal >= 0 && btnVal < effectActionIds.length) { + entries.get(idx).setActionId(effectActionIds[btnVal]); + IEffectAction ea = AbilityController.Instance.getEffectAction(effectActionIds[btnVal]); + if (ea != null) entries.get(idx).setConfig(ea.createDefaultConfig()); + } + } + return true; + case 3: // Delete + if (idx < entries.size()) entries.remove(idx); + return true; + case 4: // Add + if (entries.size() < 5 && effectActionIds.length > 0) { + entries.add(new AbilityEffectActionEntry(effectActionIds[0])); } return true; } @@ -162,12 +476,29 @@ 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 (def == null) return false; + + int idx = meta[0]; + int action = meta[1]; + + // ── Potion Effects ── + if (def.getType() == FieldType.EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects != null && idx < effects.size()) { + if (action == 1) effects.get(idx).setDurationTicks(field.getInteger()); + else if (action == 2) effects.get(idx).setAmplifier(field.getInteger()); + else if (action == 5) effects.get(idx).setManualPotionId(field.getInteger()); + } + return true; + } + + // ── Custom Effects ── + if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects != null && idx < effects.size()) { + if (action == 1) effects.get(idx).setDurationTicks(field.getInteger()); } return true; } @@ -176,5 +507,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { return super.handleTextFieldEvent(textFieldId, field); } - public Map getEffectWidgetMeta() { return effectWidgetMeta; } + public Map getEffectWidgetMeta() { + return effectWidgetMeta; + } } 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 6e419b943..3bbd80f9b 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 @@ -2,7 +2,9 @@ package kamkeel.npcs.controllers.data.ability.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityCustomEffect; +import kamkeel.npcs.controllers.data.ability.data.entry.AbilityEffectActionEntry; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.builder.FieldType; @@ -18,10 +20,23 @@ import java.util.function.Supplier; public class AbilityFieldDefs { @SuppressWarnings("unchecked") - public static FieldDef effectsListField(String label, Supplier> getter, Consumer> setter) { + public static FieldDef effectsListField(String label, Supplier> getter, Consumer> setter) { return FieldDef.custom(label, FieldType.EFFECTS_LIST, () -> getter.get(), - v -> setter.accept((List) v)); + v -> setter.accept((List) v)); } + @SuppressWarnings("unchecked") + public static FieldDef customEffectsListField(String label, Supplier> getter, Consumer> setter) { + return FieldDef.custom(label, FieldType.CUSTOM_EFFECTS_LIST, + () -> getter.get(), + v -> setter.accept((List) v)); + } + + @SuppressWarnings("unchecked") + public static FieldDef effectActionsListField(String label, Supplier> getter, Consumer> setter) { + return FieldDef.custom(label, FieldType.EFFECT_ACTIONS_LIST, + () -> getter.get(), + v -> setter.accept((List) v)); + } } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/GuiAbilityInterface.java similarity index 91% rename from src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/gui/GuiAbilityInterface.java index 3d0573bf2..0ff9b31f1 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/GuiAbilityInterface.java @@ -1,4 +1,4 @@ -package noppes.npcs.client.gui.util; +package kamkeel.npcs.controllers.data.ability.gui; import kamkeel.npcs.client.renderer.TelegraphRenderer; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; @@ -11,6 +11,8 @@ 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.gui.util.GuiNPCInterface2; +import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.entity.EntityNPCInterface; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; @@ -21,7 +23,7 @@ import java.util.List; /** * Base GUI class for ability preview with fixed camera. - * + *

* Key concepts: * - NPC positioned on left side of preview area * - NPC faces a fixed direction (NPC_FACING_YAW) @@ -33,15 +35,23 @@ import java.util.List; public class GuiAbilityInterface extends GuiNPCInterface2 { // ==================== FIXED CAMERA SETTINGS ==================== - /** Fixed camera zoom level (higher = more zoomed in) */ + /** + * Fixed camera zoom level (higher = more zoomed in) + */ protected static float CAMERA_ZOOM = 45.0f; - /** NPC facing direction - affects anchor points and visual facing */ - protected static float NPC_FACING_YAW = 160.0f; - /** Camera pitch (slight downward angle) */ + /** + * NPC facing direction - affects anchor points and visual facing + */ + public static float NPC_FACING_YAW = 160.0f; + /** + * Camera pitch (slight downward angle) + */ protected static float CAMERA_PITCH = 10.0f; // ==================== VIEWING ROTATION ==================== - /** Viewing direction rotation (rotates entire 3D space) */ + /** + * Viewing direction rotation (rotates entire 3D space) + */ protected static float viewRotation = 0.0f; private GuiNpcButton btnLeft, btnRight; @@ -49,21 +59,33 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { // ==================== NPC STATE ==================== public EntityNPCInterface npc; - /** NPC starting position (saved when preview starts, used to track movement) */ + /** + * NPC starting position (saved when preview starts, used to track movement) + */ protected double npcStartX, npcStartY, npcStartZ; - /** Whether we're tracking NPC movement */ + /** + * Whether we're tracking NPC movement + */ protected boolean trackingNpcMovement = false; - /** Entities to render in preview space */ + /** + * Entities to render in preview space + */ protected List previewEntities = new ArrayList<>(); - /** Current telegraph to render in preview */ + /** + * Current telegraph to render in preview + */ protected TelegraphInstance previewTelegraph; // ==================== LAYOUT ==================== - /** Preview area bounds */ + /** + * Preview area bounds + */ protected int previewX, previewY, previewWidth, previewHeight; - /** NPC render position on screen */ + /** + * NPC render position on screen + */ protected int npcScreenX, npcScreenY; public int xOffset = 0; @@ -74,7 +96,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { } /** - * @param npc The NPC for preview rendering + * @param npc The NPC for preview rendering * @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden. * Use false when opened from the global menu without a real NPC. */ @@ -99,8 +121,8 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { previewHeight = 180; // NPC position: left side of preview, slightly below center - npcScreenX = previewX + (int)(previewWidth * 0.33f) + xOffset; - npcScreenY = previewY + (int)(previewHeight * 0.85f) + yOffset; + npcScreenX = previewX + (int) (previewWidth * 0.33f) + xOffset; + npcScreenY = previewY + (int) (previewHeight * 0.85f) + yOffset; // Viewing rotation buttons (below preview area) int btnY = guiTop + 192; @@ -351,7 +373,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { super.drawBackground(); drawGradientRect(previewX, previewY, previewX + previewWidth, previewY + previewHeight, - 0xc0101010, 0xd0101010); + 0xc0101010, 0xd0101010); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } @@ -364,8 +386,9 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { @Override public void keyTyped(char par1, int par2) { + boolean hadSubGui = hasSubGui(); super.keyTyped(par1, par2); - if (par2 == 1) { + if (par2 == 1 && !hadSubGui) { close(); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityFieldProvider.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IAbilityFieldProvider.java similarity index 89% rename from src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityFieldProvider.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/gui/IAbilityFieldProvider.java index f196b307b..615234a7c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityFieldProvider.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IAbilityFieldProvider.java @@ -1,5 +1,6 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.gui; +import kamkeel.npcs.controllers.data.ability.Ability; import noppes.npcs.client.gui.builder.FieldDef; import java.util.List; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IChainedAbilityFieldProvider.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IChainedAbilityFieldProvider.java new file mode 100644 index 000000000..8eec036f5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IChainedAbilityFieldProvider.java @@ -0,0 +1,26 @@ +package kamkeel.npcs.controllers.data.ability.gui; + +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * External field definition provider for chained abilities. + * Called during GUI initialization to allow mods to inject custom tabs/fields + * into the chained ability configuration GUI. + *

+ * Note: Although this interface references FieldDef (client-only), it is safe to + * register on both sides because the generic type is erased at bytecode level. + * The addFieldDefinitions method is only ever called from client-side GUI code. + */ +public interface IChainedAbilityFieldProvider { + /** + * Add field definitions to the chained ability's GUI. + * Fields added here should use .tab() to assign them to a custom tab. + * + * @param chain The chained ability being configured + * @param defs The mutable list of field definitions to add to + */ + void addFieldDefinitions(ChainedAbility chain, List defs); +} diff --git a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java similarity index 64% rename from src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java index 7d856d916..aa2f5492f 100644 --- a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java @@ -1,13 +1,16 @@ -package noppes.npcs.client.gui.util; +package kamkeel.npcs.controllers.data.ability.preview; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; 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.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import kamkeel.npcs.controllers.data.ability.gui.GuiAbilityInterface; import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.entity.EntityCustomNpc; @@ -19,10 +22,10 @@ import java.util.List; /** * Client-side executor for previewing abilities in the GUI. - * + *

* Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick) * with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true. - * + *

* Lifecycle: * 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn * 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated @@ -36,8 +39,11 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { private Ability previewAbility; private EntityNPCInterface previewNpc; - /** Executor's own phase tracking (separate from ability.getPhase()) */ - private enum ExecutorPhase { IDLE, WINDUP, ACTIVE, EXTENDED } + /** + * Executor's own phase tracking (separate from ability.getPhase()) + */ + private enum ExecutorPhase {IDLE, WINDUP, ACTIVE, EXTENDED, CHAIN_DELAY} + private ExecutorPhase executorPhase = ExecutorPhase.IDLE; private int currentTick = 0; @@ -54,11 +60,20 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { // ==================== NPC START POSITION ==================== private double npcStartX, npcStartY, npcStartZ; + private boolean hasStartPosition = false; // ==================== PREVIEW CONTENT ==================== private TelegraphInstance previewTelegraph; private List previewEntities = new ArrayList<>(); + // ==================== CHAIN PREVIEW ==================== + private ChainedAbility previewChain; + private List chainAbilities; + private List chainDelays; + private int chainIndex = -1; + private int chainDelayRemaining = 0; + private boolean chainWindUpAll = true; + // ==================== CALLBACKS ==================== private GuiAbilityInterface parentGui; @@ -70,27 +85,21 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { } /** - * Start previewing an ability using unified execution. + * Start previewing a single ability using unified execution. * Sets previewMode=true on the ability, then calls its real methods. */ public void startPreview(Ability ability, EntityNPCInterface npc) { stop(); - this.previewAbility = ability; this.previewNpc = npc; - this.currentTick = 0; this.playing = true; this.paused = false; - 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); + this.hasStartPosition = true; // Create invisible fake target NPC for targeting createFakeTarget(npc); @@ -100,10 +109,87 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { parentGui.startTrackingMovement(); } + beginAbilityPreview(ability); + } + + /** + * Start previewing a chained ability — plays all entries in sequence with delays. + * Each entry is resolved and deep-copied to avoid modifying originals. + */ + public void startChainPreview(ChainedAbility chain, EntityNPCInterface npc) { + stop(); + + this.previewNpc = npc; + this.playing = true; + this.paused = false; + this.previewChain = chain; + this.chainWindUpAll = chain.isWindUpAll(); + + // Save NPC start position for restoring later + this.npcStartX = npc.posX; + this.npcStartY = npc.posY; + this.npcStartZ = npc.posZ; + this.hasStartPosition = true; + + // Resolve all entries to deep-copied abilities + chainAbilities = new ArrayList<>(); + chainDelays = new ArrayList<>(); + for (ChainedAbilityEntry entry : chain.getEntries()) { + Ability resolved = entry.resolve(); + if (resolved != null && AbilityController.Instance != null) { + Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT(true)); + if (copy != null) { + chainAbilities.add(copy); + chainDelays.add(entry.getDelayTicks()); + } + } + } + + if (chainAbilities.isEmpty()) { + playing = false; + return; + } + + // Create invisible fake target NPC for targeting + createFakeTarget(npc); + + // Start tracking NPC movement + if (parentGui != null) { + parentGui.startTrackingMovement(); + } + + chainIndex = 0; + beginAbilityPreview(chainAbilities.get(0)); + } + + /** + * Begin previewing a single ability (shared by single and chain preview). + * Cleans up the previous ability if any (for chain advancement). + */ + private void beginAbilityPreview(Ability ability) { + // Clean up previous ability if any (for chain advancement) + if (previewAbility != null) { + previewAbility.cleanup(); + previewAbility.setPreviewMode(false); + previewAbility.setPreviewEntityHandler(null); + previewAbility.reset(); + } + + this.previewAbility = ability; + this.currentTick = 0; + this.maxPreviewDuration = ability.getMaxPreviewDuration(); + + // Enable preview mode on the ability + ability.setPreviewMode(true); + ability.setPreviewEntityHandler(this); + // Use the ability's real start() method with the fake target ability.start(fakeTarget); - if (ability.getWindUpTicks() <= 0) { + // Skip windup for non-first chain entries when windUpAll is false + boolean skipWindup = previewChain != null && !chainWindUpAll && chainIndex > 0; + + if (ability.getWindUpTicks() <= 0 || skipWindup) { // No windup — go straight to active this.executorPhase = ExecutorPhase.ACTIVE; transitionToActive(); @@ -112,12 +198,12 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { this.executorPhase = ExecutorPhase.WINDUP; // Create telegraph for preview - previewTelegraph = ability.createTelegraph(npc, fakeTarget); + previewTelegraph = ability.createTelegraph(previewNpc, fakeTarget); // Start windup animation Animation windUpAnim = ability.getWindUpAnimation(); if (windUpAnim != null) { - AnimationData data = npc.display.animationData; + AnimationData data = previewNpc.display.animationData; data.setEnabled(true); data.setAnimation(windUpAnim); data.animation.paused = false; @@ -213,6 +299,13 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { executorPhase = ExecutorPhase.IDLE; currentTick = 0; + // Clear chain state + previewChain = null; + chainAbilities = null; + chainDelays = null; + chainIndex = -1; + chainDelayRemaining = 0; + previewTelegraph = null; if (parentGui != null) { @@ -225,7 +318,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { previewEntities.clear(); // Reset NPC position to start position (undo movement from Slam/Charge/Dash) - if (previewNpc != null && npcStartX != 0 && npcStartY != 0 && npcStartZ != 0) { + if (previewNpc != null && hasStartPosition) { previewNpc.posX = npcStartX; previewNpc.posY = npcStartY; previewNpc.posZ = npcStartZ; @@ -283,6 +376,9 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { case EXTENDED: tickExtended(); break; + case CHAIN_DELAY: + tickChainDelay(); + break; default: break; } @@ -290,7 +386,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { private void tickWindup() { // Call the REAL windup tick method - previewAbility.onWindUpTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); + previewAbility.onWindUpTick(previewNpc, fakeTarget, currentTick); if (currentTick >= previewAbility.getWindUpTicks()) { transitionToActive(); @@ -299,20 +395,28 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { private void tickActive() { // Call the REAL active tick method - previewAbility.onActiveTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); + previewAbility.onActiveTick(previewNpc, fakeTarget, currentTick); // Simulate physics for movement abilities simulatePhysics(); // Check if the ability signaled completion (phase went to IDLE) if (previewAbility.getPhase() == AbilityPhase.IDLE) { - transitionToExtended(); + if (hasNextChainEntry()) { + transitionToChainDelay(); + } else { + transitionToExtended(); + } return; } // Safety timeout if (currentTick >= maxPreviewDuration) { - transitionToExtended(); + if (hasNextChainEntry()) { + transitionToChainDelay(); + } else { + transitionToExtended(); + } } } @@ -323,6 +427,44 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { } } + // ==================== CHAIN ADVANCEMENT ==================== + + private boolean hasNextChainEntry() { + return previewChain != null && chainAbilities != null && chainIndex < chainAbilities.size() - 1; + } + + private void transitionToChainDelay() { + executorPhase = ExecutorPhase.CHAIN_DELAY; + currentTick = 0; + + // Use the NEXT entry's delay + int nextIndex = chainIndex + 1; + chainDelayRemaining = (nextIndex < chainDelays.size()) ? chainDelays.get(nextIndex) : 0; + + // Clear current animation + if (previewNpc != null) { + AnimationData data = previewNpc.display.animationData; + data.setAnimation(new Animation()); + } + } + + private void tickChainDelay() { + if (chainDelayRemaining > 0) { + chainDelayRemaining--; + return; + } + advanceChainEntry(); + } + + private void advanceChainEntry() { + chainIndex++; + if (chainIndex >= chainAbilities.size()) { + transitionToExtended(); + return; + } + beginAbilityPreview(chainAbilities.get(chainIndex)); + } + private void transitionToActive() { executorPhase = ExecutorPhase.ACTIVE; currentTick = 0; @@ -330,7 +472,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { previewTelegraph = null; // Call the REAL onExecute method (fires entities, initiates movement, etc.) - previewAbility.onExecute(previewNpc, fakeTarget, previewNpc.worldObj); + previewAbility.onExecute(previewNpc, fakeTarget); // Start active animation Animation activeAnim = previewAbility.getActiveAnimation(); @@ -424,33 +566,73 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { // ==================== GETTERS ==================== - public boolean isPlaying() { return playing; } - public boolean isPaused() { return paused; } - public boolean isActive() { return playing || paused; } + public boolean isPlaying() { + return playing; + } + + public boolean isPaused() { + return paused; + } + + public boolean isActive() { + return playing || paused; + } + + public boolean isChainPreview() { + return previewChain != null; + } + public AbilityPhase getPhase() { switch (executorPhase) { - case WINDUP: return AbilityPhase.WINDUP; - case ACTIVE: return AbilityPhase.ACTIVE; - default: return AbilityPhase.IDLE; + 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; } - public Ability getPreviewAbility() { return previewAbility; } - public EntityNPCInterface getPreviewNpc() { return previewNpc; } + + public int getCurrentTick() { + return currentTick; + } + + public TelegraphInstance getTelegraph() { + return previewTelegraph; + } + + public List getPreviewEntities() { + return previewEntities; + } + + public Ability getPreviewAbility() { + return previewAbility; + } + + public EntityNPCInterface getPreviewNpc() { + return previewNpc; + } public String getStatusString() { if (!playing && !paused) { return "Stopped"; - } else if (paused) { - return "Paused"; + } + + String chainPrefix = ""; + if (previewChain != null && chainAbilities != null) { + chainPrefix = "Chain " + (chainIndex + 1) + "/" + chainAbilities.size() + " - "; + } + + if (paused) { + return chainPrefix + "Paused"; } else if (executorPhase == ExecutorPhase.WINDUP) { - return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0); + return chainPrefix + "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0); } else if (executorPhase == ExecutorPhase.ACTIVE) { - return "Active: " + currentTick + "/" + maxPreviewDuration; + return chainPrefix + "Active: " + currentTick + "/" + maxPreviewDuration; } else if (executorPhase == ExecutorPhase.EXTENDED) { - return "Extended: " + currentTick + "/" + EXTENDED_DURATION; + return chainPrefix + "Extended: " + currentTick + "/" + EXTENDED_DURATION; + } else if (executorPhase == ExecutorPhase.CHAIN_DELAY) { + return chainPrefix + "Delay: " + chainDelayRemaining; } return ""; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/PreviewEntityHandler.java similarity index 86% rename from src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/preview/PreviewEntityHandler.java index 77fae9774..d5917260c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/PreviewEntityHandler.java @@ -1,4 +1,4 @@ -package kamkeel.npcs.controllers.data.ability; +package kamkeel.npcs.controllers.data.ability.preview; import net.minecraft.entity.Entity; @@ -9,5 +9,6 @@ import net.minecraft.entity.Entity; */ public interface PreviewEntityHandler { void onEntitySpawned(Entity entity); + void onEntityRemoved(Entity entity); } 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 deleted file mode 100644 index f99a03528..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ /dev/null @@ -1,637 +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.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.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBeam; -import kamkeel.npcs.util.AnchorPointHelper; -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 java.util.Arrays; -import java.util.List; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; - -/** - * Energy Beam ability: A homing head with a trailing path. - * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. - */ -public class AbilityBeam extends Ability implements IAbilityEnergyBeam { - - private static final int MAX_PROJECTILES = 8; - - // Beam shape properties (shared) - private float beamWidth = 0.4f; - private float headSize = 0.6f; - - // Projectile count and fire stagger - private int projectileCount = 1; - private int fireDelay = 0; - - // Shared visual data (all projectiles use these) - private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Shared combat/movement data - 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 EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - - // Per-projectile data (anchor + optional color override) - private ProjectileData[] projectiles; - - // Transient entity state - private transient EntityAbilityBeam[] beamEntities; - - public AbilityBeam() { - this.typeId = "ability.cnpc.beam"; - this.name = "Beam"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 20.0f; - this.minRange = 5.0f; - 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; - this.windUpAnimationName = "Ability_Beam_Windup"; - this.activeAnimationName = "Ability_Beam_Active"; - initProjectiles(1); - } - - private 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)); - } - } - - private AnchorPoint getDefaultAnchor(int index) { - switch (index) { - case 0: return AnchorPoint.RIGHT_HAND; - case 1: return AnchorPoint.LEFT_HAND; - default: return AnchorPoint.FRONT; - } - } - - 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); - } - - // Legacy compat - public int getDualFireDelay() { return fireDelay; } - public void setDualFireDelay(int delay) { setFireDelay(delay); } - - @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); - // Set color override for second beam - 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"); - }) - ); - } - - @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}; - } - - /** - * Create beam entities. - * NPC: target is the aggro target — beams will home toward it. - * Player: target is null — beams fire in caster's look direction. - */ - private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) { - EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount]; - float offsetDist = 1.0f; - for (int i = 0; i < projectileCount; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor, offsetDist); - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - entities[i] = new EntityAbilityBeam( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - beamWidth, headSize, - resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, - lockMovement.locksActive()); - entities[i].setEffects(this.effects); - entities[i].setSourceAbility(this); - } - if (projectileCount == 2 && entities[0] != null && entities[1] != null) { - entities[0].setSiblingEntityId(entities[1].getEntityId()); - entities[1].setSiblingEntityId(entities[0].getEntityId()); - } - return entities; - } - - private void fireBeamEntity(EntityAbilityBeam beam, EntityLivingBase target) { - if (beam == null || beam.isDead) return; - if (isPreview()) { - beam.startPreviewFiring(); - } else { - beam.startFiring(target); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - beamEntities = createBeamEntities(caster, target, world); - float offsetDist = 1.0f; - for (int i = 0; i < projectileCount; i++) { - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - if (isPreview()) { - beamEntities[i].setupPreview(caster, beamWidth, headSize, resolved, lightningData, projectiles[i].anchor, windUpTicks, offsetDist); - } else { - beamEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, offsetDist); - } - spawnAbilityEntity(world, beamEntities[i]); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - beamEntities = createBeamEntities(caster, target, world); - for (EntityAbilityBeam beam : beamEntities) { - spawnAbilityEntity(world, beam); - } - for (EntityAbilityBeam beam : beamEntities) { - fireBeamEntity(beam, target); - } - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (beamEntities == null) return; - - fireBeamEntity(beamEntities[0], target); - - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireBeamEntity(beamEntities[i], target); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (beamEntities == null) { - signalCompletion(); - return; - } - - if (fireDelay > 0) { - for (int i = 1; i < projectileCount; i++) { - if (tick == fireDelay * i) { - fireBeamEntity(beamEntities[i], target); - } - } - } - - boolean allDead = true; - for (EntityAbilityBeam beam : beamEntities) { - if (beam != null && !beam.isDead) { - allDead = false; - break; - } - } - if (allDead) { - 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() { - if (beamEntities != null) { - for (int i = 0; i < beamEntities.length; i++) { - if (beamEntities[i] != null && !beamEntities[i].isDead) { - beamEntities[i].setDead(); - } - beamEntities[i] = null; - } - } - beamEntities = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - // NPC: telegraph on aggro target position - // Player: no telegraph (beam fires in look direction, no fixed position to mark) - if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { - return null; - } - - 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); - - 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.setInteger("projectileCount", projectileCount); - nbt.setInteger("fireDelay", fireDelay); - - // Shared visual data - displayData.writeNBT(nbt); - lightningData.writeNBT(nbt); - - // Shared combat/movement data - 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 void readTypeNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; - - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; - initProjectiles(count); - - if (nbt.hasKey("fireDelay")) { - this.fireDelay = nbt.getInteger("fireDelay"); - } else if (nbt.hasKey("dualFireDelay")) { - this.fireDelay = nbt.getInteger("dualFireDelay"); - } else { - this.fireDelay = 0; - } - - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - if (nbt.hasKey("Projectile_0")) { - NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); - if (proj0.hasKey("colorOverride")) { - // NEW format - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } - } else { - // OLD per-projectile format - displayData.readNBT(proj0); - lightningData.readNBT(proj0); - projectiles[0].anchor.readNBT(proj0); - - for (int i = 1; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); - projectiles[i].anchor.readNBT(projNbt); - - EnergyDisplayData tempDisplay = new EnergyDisplayData(); - tempDisplay.readNBT(projNbt); - if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { - projectiles[i].colorOverride = true; - projectiles[i].innerColor = tempDisplay.innerColor; - projectiles[i].outerColor = tempDisplay.outerColor; - } - } - } - } - } else { - // LEGACY flat format - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - projectiles[0].anchor.readNBT(nbt); - } - } - - // ═══════════════════════════════════════════════════════════════════ - // API GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ - - 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 float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { this.homingData.speed = speed; } - - 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; } - - 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 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; } - - 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; } - - // Shared display data (primary colors) - 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 boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { displayData.outerColorEnabled = outerColorEnabled; } - - 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 float getRotationSpeed() { return displayData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { displayData.rotationSpeed = rotationSpeed; } - - // Shared lightning data - 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; } - - // Anchor - default to projectile 0 - public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { projectiles[0].anchor.anchorPoint = anchorPoint; } - - 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; } - - private int clampIndex(int index) { - return Math.max(0, Math.min(index, projectileCount - 1)); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(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)); - - // Visual tab - shared 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")); - - // Visual tab - shared 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")); - - // 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), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) - ).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)); - - // 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/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index 4ae81bfcb..d5c293c64 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,9 +2,11 @@ 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.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +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; @@ -12,13 +14,8 @@ 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; import noppes.npcs.api.ability.type.IAbilityCharge; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.HashSet; @@ -26,9 +23,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 +34,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"; @@ -48,7 +43,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { this.targetingMode = TargetingMode.AGGRO_TARGET; this.maxRange = 20.0f; this.minRange = 4.0f; - this.lockMovement = LockMovementType.WINDUP; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; this.cooldownTicks = 0; this.windUpTicks = 20; // LINE telegraph showing charge path @@ -56,6 +51,16 @@ 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_Charge_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/charge.png") + }; + } + + @Override + public boolean hasAbilityMovement() { + return true; // This ability drives the NPC's motion itself } @Override @@ -68,139 +73,92 @@ 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. + * During windup, NPCs face toward their target for animation purposes. + * Players aim freely — the telegraph follows their look direction on the client, + * and direction is locked at the end of windup in onExecute(). */ @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (tick == 1) { - // Lock direction on first windup tick (same time telegraph is created) - lockChargeDirection(caster, target); - } - // Keep caster facing the locked direction during windup - enforceLockedRotation(caster); - } - - /** - * Locks the charge direction. Called once at windup start — direction won't change even if target moves. - * NPC: charges toward aggro target. - * Player: charges in look direction. - */ - private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) { + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (!isPlayerCaster(caster) && target != null) { - // NPC: charge toward aggro target - 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 { - // Player: charge in look direction - 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; - hitEntities.clear(); - - // If direction wasn't set during windup (shouldn't happen), set it now - if (chargeDirection == null) { - lockChargeDirection(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 - if (!isPreview()) { + lockDirectionToTarget(caster, target); enforceLockedRotation(caster); } + } - // Calculate distance traveled - double distanceTraveled = Math.sqrt( - Math.pow(caster.posX - startX, 2) + - Math.pow(caster.posZ - startZ, 2) - ); + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // Lock final direction at end of windup so it matches the telegraph + lockDirection(caster, target); + initMovement(caster, maxRange, chargeSpeed); + hitEntities.clear(); - // Check if reached max distance - if (distanceTraveled >= maxRange) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; - } - signalCompletion(); - return; - } + enforceLockedRotation(caster); + } - // Block detection (skip in preview - no real world collision) - if (!isPreview() && isChargeBlocked(caster)) { + @Override + 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; - if (!isPreview()) { - caster.velocityChanged = true; + if (movementDirection == null) { + stopMomentum(caster); + signalCompletion(); + return; } + 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 (!world.isRemote && !isPreview()) { + 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; if (entity == caster) continue; if (hitEntities.contains(entity.getEntityId())) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; 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); } } } @@ -218,25 +176,15 @@ public class AbilityCharge extends Ability implements IAbilityCharge { super.onInterrupt(caster, source, damage); } - private void stopMomentum(EntityLivingBase caster) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - 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 cleanup() { + super.cleanup(); + hitEntities.clear(); } @Override - public void reset() { - super.reset(); - chargeDirection = null; + public void resetForBurst() { + super.resetForBurst(); hitEntities.clear(); } @@ -287,6 +235,11 @@ public class AbilityCharge extends Ability implements IAbilityCharge { // Telegraph follows caster during windup - allows caster to reposition instance.setEntityIdToFollow(caster.getEntityId()); + // For player casters, track their rotation so telegraph follows look direction + if (isPlayerCaster(caster)) { + instance.setTrackFollowedEntityYaw(true); + } + return instance; } @@ -305,16 +258,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.chargeSpeed = nbt.hasKey("chargeSpeed") ? Math.max(0.01f, 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.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 1.5f; } // Getters & Setters @@ -334,6 +281,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getKnockback() { return knockback; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java new file mode 100644 index 000000000..64fb10743 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java @@ -0,0 +1,260 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.addon.DBCAddon; +import noppes.npcs.AbstractDataAbilities; +import noppes.npcs.controllers.AnimationController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.api.ability.type.IAbilityCounter; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.Arrays; +import java.util.List; + +/** + * Counter ability: Absorbs incoming damage and counter-attacks the attacker. + */ +public class AbilityCounter extends AbilityDefend implements IAbilityCounter { + + private CounterType counterType = CounterType.FLAT; + private float counterValue = 6.0f; + private int counterAnimationId = -1; + private String counterAnimationName = "Ability_Guard_Counter"; + + // True only while this counter is synchronously dispatching its retaliation damage. + // Another counter that is hit by that retaliation inspects this flag on the source + // entity's active counter to avoid reacting and creating infinite mutual retaliation. + private transient boolean retaliating; + + public AbilityCounter() { + this.typeId = "ability.cnpc.counter"; + this.name = "Counter"; + this.cooldownTicks = 0; + this.windUpTicks = 20; + this.allowedBy = UserType.BOTH; + this.activeSound = "random.anvil_land"; + + this.activeAnimationName = "Ability_Guard_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png") + }; + } + + public enum CounterType { + FLAT, + PERCENT; + + @Override + public String toString() { + switch (this) { + case FLAT: + return "ability.counter.flat"; + case PERCENT: + return "ability.counter.percent"; + default: + return name(); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOKS + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected boolean isValidDamageSource(DamageSource source) { + if (!super.isValidDamageSource(source)) { + return false; + } + // Break counter-vs-counter recursion: if the hit is itself a retaliation + // from another counter that is mid-dispatch, don't counter it back. + Entity sourceEntity = source.getEntity(); + AbstractDataAbilities abilities = getAbilitiesOf(sourceEntity); + if (abilities != null) { + Ability current = abilities.getCurrentAbility(); + if (current instanceof AbilityCounter && ((AbilityCounter) current).retaliating) { + return false; + } + } + return true; + } + + private static AbstractDataAbilities getAbilitiesOf(Entity entity) { + if (entity instanceof EntityPlayer) { + PlayerData pData = PlayerData.get((EntityPlayer) entity); + return pData != null ? pData.abilityData : null; + } + if (entity instanceof EntityNPCInterface) { + return ((EntityNPCInterface) entity).abilities; + } + return null; + } + + @Override + protected float performDefend(EntityLivingBase attacker, float amount) { + // For PERCENT mode with DBC, use the full DBC-calculated damage, not vanilla base + float incomingDamage = amount; + if (DBCAddon.IsAvailable()) { + incomingDamage = DBCAddon.instance.getAttackerDBCDamage(amount); + } + + // Calculate counter damage + float damage; + if (counterType == CounterType.FLAT) { + damage = counterValue; + } else { + damage = incomingDamage * (counterValue / 100.0f); + } + + // Counter-attack through the standard ability damage pipeline. + // DBCAbilityExtender handles DBC stat routing (ignore flags, scaling, etc.) automatically. + if (caster != null && attacker != null && attacker.isEntityAlive() && damage > 0) { + retaliating = true; + try { + applyAbilityDamage(caster, attacker, damage, 0); + } finally { + retaliating = false; + } + } + + return 0; + } + + @Override + public void reset() { + super.reset(); + retaliating = false; + } + + // ═══════════════════════════════════════════════════════════════════ + // OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean hasDamage() { + return true; + } + + @Override + protected Animation getDefendAnimation() { + return getCounterAnimation(); + } + + public Animation getCounterAnimation() { + if (AnimationController.Instance == null) return null; + if (counterAnimationId >= 0) { + return (Animation) AnimationController.Instance.get(counterAnimationId); + } + if (counterAnimationName != null && !counterAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(counterAnimationName, true); + } + return null; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void writeSubTypeNBT(NBTTagCompound nbt) { + nbt.setString("counterType", counterType.name()); + nbt.setFloat("counterValue", counterValue); + nbt.setInteger("counterAnimationId", counterAnimationId); + nbt.setString("counterAnimationName", resolveAnimationName(counterAnimationId, counterAnimationName)); + } + + @Override + protected void readSubTypeNBT(NBTTagCompound nbt) { + try { + this.counterType = CounterType.valueOf(nbt.getString("counterType")); + } catch (Exception e) { + this.counterType = CounterType.FLAT; + } + this.counterValue = nbt.getFloat("counterValue"); + this.counterAnimationId = nbt.getInteger("counterAnimationId"); + this.counterAnimationName = nbt.getString("counterAnimationName"); + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + protected void getTypeDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.enumField("gui.type", CounterType.class, this::getCounterTypeEnum, this::setCounterTypeEnum) + .hover("ability.hover.counterType"), + FieldDef.floatField("gui.value", this::getCounterValue, this::setCounterValue), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + + FieldDef.insertAfter(defs, "ability.dazedAnimation", + FieldDef.animSubGui("ability.counterAnimation", + this::getCounterAnimationId, this::setCounterAnimationId, + this::getCounterAnimationName, this::setCounterAnimationName) + .tab("Effects")); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public CounterType getCounterTypeEnum() { + return counterType; + } + + public void setCounterTypeEnum(CounterType counterType) { + this.counterType = counterType; + } + + @Override + public int getCounterType() { + return counterType.ordinal(); + } + + @Override + public void setCounterType(int type) { + CounterType[] values = CounterType.values(); + this.counterType = type >= 0 && type < values.length ? values[type] : CounterType.FLAT; + } + + @Override + public float getCounterValue() { + return counterValue; + } + + @Override + public void setCounterValue(float counterValue) { + this.counterValue = counterValue; + } + + @Override + public int getCounterAnimationId() { + return counterAnimationId; + } + + @Override + public void setCounterAnimationId(int counterAnimationId) { + this.counterAnimationId = counterAnimationId; + } + + public String getCounterAnimationName() { + return counterAnimationName; + } + + public void setCounterAnimationName(String name) { + this.counterAnimationName = name != null ? name : ""; + } +} 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 22831f4ff..7454dd3f0 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 @@ -1,23 +1,23 @@ 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.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +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 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.IAbilityCutter; - import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import java.util.Arrays; import java.util.HashSet; @@ -38,9 +38,12 @@ public class AbilityCutter extends Ability implements IAbilityCutter { @Override public String toString() { switch (this) { - case SWIPE: return "ability.sweep.swipe"; - case SPIN: return "ability.sweep.spin"; - default: return name(); + case SWIPE: + return "ability.sweep.swipe"; + case SPIN: + return "ability.sweep.spin"; + default: + return name(); } } } @@ -60,13 +63,15 @@ 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"; this.name = "Cutter"; this.targetingMode = TargetingMode.AOE_SELF; this.maxRange = 8.0f; - this.lockMovement = LockMovementType.NO; + this.lockMovement = LockMode.NO; this.cooldownTicks = 0; this.windUpTicks = 20; this.telegraphType = TelegraphType.CONE; @@ -74,6 +79,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { this.activeSound = "random.break"; this.windUpAnimationName = "Ability_Cutter_Windup"; this.activeAnimationName = "Ability_Cutter_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/cutter.png", + this::getActiveColor) + }; } @Override @@ -86,6 +95,58 @@ 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(), getTelegraphInnerRadius()); + 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()); + } else { + // No target to track yaw from — track the caster's rotation instead + // so the telegraph follows where the player/NPC is facing + instance.setTrackFollowedEntityYaw(true); + } + + return instance; + } + @Override public float getTelegraphRadius() { return range; @@ -102,32 +163,64 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - hitEntities.clear(); - currentRotation = -arcAngle / 2.0f; + public float getTelegraphInnerRadius() { + return innerRadius; } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + hitEntities.clear(); + currentRotation = -arcAngle / 2.0f; + activeSoundPlayed = false; + + // Compute sweep direction from caster/target at execution time. + // Server-side telegraph instances are not ticked, so their yaw is stale + // from windup start — use the caster's current rotation instead. + 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, 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) { if (!isPreview()) { - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevRotation, arcAngle / 2.0f); } signalCompletion(); return; } if (!isPreview()) { - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); + 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(); return; @@ -136,18 +229,25 @@ public class AbilityCutter extends Ability implements IAbilityCutter { currentRotation = (currentRotation + sweepSpeed) % 360.0f; if (!isPreview()) { hitEntities.clear(); - performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); + 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. */ private void performSweepDamageRange(EntityLivingBase caster, World world, float minDist, float maxDist, - float startAngle, float endAngle) { + float startAngle, float endAngle) { // Calculate the angular range covered this tick float minAngle = Math.min(startAngle, endAngle); float maxAngle = Math.max(startAngle, endAngle); @@ -163,6 +263,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { for (EntityLivingBase entity : entities) { if (entity == caster) continue; if (hitEntities.contains(entity.getEntityId())) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; // If not piercing, stop after hitting one entity this sweep if (!piercing && !hitEntities.isEmpty()) break; @@ -171,7 +272,11 @@ 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; + + // Line-of-sight check: skip targets behind solid blocks or enemy barriers + if (!hasLineOfSight(world, caster, entity)) continue; + if (isBlockedByBarrier(world, caster, entity)) continue; hitEntities.add(entity.getEntityId()); @@ -198,12 +303,6 @@ public class AbilityCutter extends Ability implements IAbilityCutter { return entityRelative >= minAngle && entityRelative <= maxAngle; } - private boolean isInArc(double dx, double dz, float casterYaw, float arcWidth) { - double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); - double angleDiff = normalizeAngle(angleToEntity - casterYaw); - return Math.abs(angleDiff) <= arcWidth / 2.0; - } - private double normalizeAngle(double angle) { while (angle > 180) angle -= 360; while (angle < -180) angle += 360; @@ -214,12 +313,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 @@ -237,19 +340,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 @@ -277,6 +380,9 @@ public class AbilityCutter extends Ability implements IAbilityCutter { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getKnockback() { return knockback; } @@ -355,6 +461,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { FieldDef.row( FieldDef.floatField("ability.arcAngle", this::getArcAngle, this::setArcAngle), FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius) + .hover("ability.hover.innerRadius") ), FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed), FieldDef.intField("ability.spinDuration", this::getSpinDurationTicks, this::setSpinDurationTicks) 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 0f8cbe374..88c520c21 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,20 +2,14 @@ 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.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.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; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; @@ -23,23 +17,29 @@ 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. */ public enum DashMode { AGGRESSIVE, - DEFENSIVE; + DEFENSIVE, + DIRECTIONAL; @Override public String toString() { switch (this) { - case AGGRESSIVE: return "ability.dash.aggressive"; - case DEFENSIVE: return "ability.dash.defensive"; - default: return name(); + case AGGRESSIVE: + return "ability.dash.aggressive"; + case DEFENSIVE: + return "ability.dash.defensive"; + case DIRECTIONAL: + return "ability.dash.directional"; + default: + return name(); } } } @@ -55,7 +55,8 @@ public class AbilityDash extends Ability implements IAbilityDash { RIGHT(-90), DIAGONAL_BACK_LEFT(135), DIAGONAL_BACK_RIGHT(-135), - BACK(180); + BACK(180), + CUSTOM(0); private final float angleOffset; @@ -66,6 +67,40 @@ public class AbilityDash extends Ability implements IAbilityDash { public float getAngleOffset() { return angleOffset; } + + @Override + public String toString() { + switch (this) { + case FORWARD: + return "ability.dash.forward"; + case DIAGONAL_FORWARD_LEFT: + return "ability.dash.diagonalForwardLeft"; + case DIAGONAL_FORWARD_RIGHT: + return "ability.dash.diagonalForwardRight"; + case LEFT: + return "ability.dash.left"; + case RIGHT: + return "ability.dash.right"; + case DIAGONAL_BACK_LEFT: + return "ability.dash.diagonalBackLeft"; + case DIAGONAL_BACK_RIGHT: + return "ability.dash.diagonalBackRight"; + case BACK: + return "ability.dash.back"; + case CUSTOM: + return "ability.dash.custom"; + default: + return name(); + } + } + + public static DashDirection fromOrdinal(int ordinal) { + DashDirection[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return DashDirection.FORWARD; + } } private static final Random RANDOM = new Random(); @@ -86,15 +121,15 @@ public class AbilityDash extends Ability implements IAbilityDash { // Type-specific parameters private DashMode dashMode = DashMode.DEFENSIVE; + private DashDirection dashDirection = DashDirection.FORWARD; private float dashDistance = 4.0f; private float dashSpeed = 0.5f; + private float dashAngle = 0.0f; - // 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; - private transient int maxActiveTicks; + private transient double preDashMotionX; + private transient double preDashMotionZ; public AbilityDash() { this.typeId = "ability.cnpc.dash"; @@ -102,14 +137,16 @@ public class AbilityDash extends Ability implements IAbilityDash { this.targetingMode = TargetingMode.AGGRO_TARGET; this.maxRange = 20.0f; this.minRange = 0.0f; - this.lockMovement = LockMovementType.NO; + this.lockMovement = LockMode.NO; this.cooldownTicks = 0; this.windUpTicks = 5; // No telegraph for dash - it's a quick evasive move this.telegraphType = TelegraphType.NONE; this.showTelegraph = false; this.windUpSound = "mob.bat.takeoff"; - this.activeSound = "mob.endermen.portal"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/dash.png") + }; } @Override @@ -128,136 +165,109 @@ public class AbilityDash extends Ability implements IAbilityDash { } @Override - public boolean hasAbilityMovement() { - return true; // This ability moves the NPC - } + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + preDashMotionX = caster.motionX; + preDashMotionZ = caster.motionZ; + initMovement(caster, dashDistance, dashSpeed); - @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; - - // Safety timeout: expected ticks + generous buffer to prevent infinite dash - maxActiveTicks = dashSpeed > 0 ? (int)(dashDistance / dashSpeed) + 10 : 10; - - // Choose random direction based on mode - DashDirection[] directions = dashMode == DashMode.AGGRESSIVE - ? AGGRESSIVE_DIRECTIONS - : DEFENSIVE_DIRECTIONS; - chosenDirection = directions[RANDOM.nextInt(directions.length)]; - - // NPC: dash direction is relative to aggro target facing - // Player: dash direction is relative to look direction - float baseYaw; - if (!isPlayerCaster(caster) && target != null) { - double dx = target.posX - caster.posX; - double dz = target.posZ - caster.posZ; - baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + if (dashMode == DashMode.DIRECTIONAL) { + // Dash straight in the caster's look direction + chosenDirection = dashDirection; + float baseYaw = getBaseYaw(caster, target); + float angleOffset = chosenDirection == DashDirection.CUSTOM ? dashAngle : chosenDirection.getAngleOffset(); + float dashYaw = baseYaw + angleOffset; + setDirectionFromYaw(dashYaw); } else { - baseYaw = caster.rotationYaw; + // Choose random direction based on mode + DashDirection[] directions = dashMode == DashMode.AGGRESSIVE + ? AGGRESSIVE_DIRECTIONS + : DEFENSIVE_DIRECTIONS; + chosenDirection = directions[RANDOM.nextInt(directions.length)]; + + // Calculate direction: base yaw (toward target or look dir) + direction offset + float baseYaw = getBaseYaw(caster, target); + float dashYaw = baseYaw + chosenDirection.getAngleOffset(); + setDirectionFromYaw(dashYaw); } - // Apply direction offset - float dashYaw = baseYaw + chosenDirection.getAngleOffset(); - float yawRad = (float) Math.toRadians(dashYaw); - - dashDirection = Vec3.createVectorHelper( - -Math.sin(yawRad), - 0, - Math.cos(yawRad) - ); - // 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) { - // Safety timeout or missing state: force-complete to prevent stuck NPC - if (!isPreview() && (dashDirection == null || tick > maxActiveTicks)) { - stopDash(caster); + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (checkTimeout(tick)) { + finishDash(caster); signalCompletion(); return; } - if (dashDirection == null) { + if (movementDirection == null) { + finishDash(caster); signalCompletion(); return; } - // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall - if (!isPreview() && tick > 1) { - double dx = caster.posX - prevTickX; - double dz = caster.posZ - prevTickZ; - if (dx * dx + dz * dz < 0.0001) { - stopDash(caster); - signalCompletion(); - return; - } + if (checkStall(caster, tick)) { + finishDash(caster); + signalCompletion(); + return; } - prevTickX = caster.posX; - prevTickZ = caster.posZ; + updatePrevPosition(caster); - // Check if reached max distance - double travelDx = caster.posX - startX; - double travelDz = caster.posZ - startZ; - if (travelDx * travelDx + travelDz * travelDz >= (double) dashDistance * dashDistance) { - stopDash(caster); + if (getDistanceTraveledSq(caster) >= (double) dashDistance * dashDistance) { + finishDash(caster); signalCompletion(); return; } - // Block detection (skip in preview - no real world collision) - if (!isPreview() && isDashBlocked(caster)) { - stopDash(caster); + if (checkBlocked(caster, dashSpeed)) { + finishDash(caster); signalCompletion(); return; } - // Move caster (motionY left to gravity for skip arc) - caster.motionX = dashDirection.xCoord * dashSpeed; - caster.motionZ = dashDirection.zCoord * dashSpeed; + // Move caster (motionY left to gravity for skip arc). + // Directional mode layers the dash over incoming movement so momentum + // entering/exiting the dash stays fluid. + if (dashMode == DashMode.DIRECTIONAL) { + applyHorizontalMomentum(caster, + preDashMotionX + movementDirection.xCoord * dashSpeed, + preDashMotionZ + movementDirection.zCoord * dashSpeed); + } else { + applyVelocity(caster, dashSpeed); + } + if (!isPreview()) { - caster.velocityChanged = true; - // Trail particles - world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); - } - } - - private void stopDash(EntityLivingBase caster) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; + caster.worldObj.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); } } @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - stopDash(caster); + finishDash(caster); } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - stopDash(caster); + finishDash(caster); } @Override public void cleanup() { - dashDirection = null; + super.cleanup(); chosenDirection = null; - maxActiveTicks = 0; + preDashMotionX = 0; + preDashMotionZ = 0; } - 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(); + @Override + public void resetForBurst() { + super.resetForBurst(); + chosenDirection = null; + preDashMotionX = 0; + preDashMotionZ = 0; } @Override @@ -273,8 +283,10 @@ public class AbilityDash extends Ability implements IAbilityDash { @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setString("dashMode", dashMode.name()); + nbt.setString("dashDirection", dashDirection.name()); nbt.setFloat("dashDistance", dashDistance); nbt.setFloat("dashSpeed", dashSpeed); + nbt.setFloat("dashAngle", dashAngle); } @Override @@ -284,8 +296,16 @@ public class AbilityDash extends Ability implements IAbilityDash { } catch (Exception e) { this.dashMode = DashMode.DEFENSIVE; } + + try { + this.dashDirection = DashDirection.valueOf(nbt.getString("dashDirection")); + } catch (Exception e) { + this.dashDirection = DashDirection.FORWARD; + } + this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; - this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 0.5f; + this.dashSpeed = nbt.hasKey("dashSpeed") ? Math.max(0.01f, nbt.getFloat("dashSpeed")) : 0.5f; + this.dashAngle = nbt.hasKey("dashAngle") ? nbt.getFloat("dashAngle") : 0.0f; } // Getters & Setters @@ -324,10 +344,46 @@ public class AbilityDash extends Ability implements IAbilityDash { this.dashSpeed = dashSpeed; } + public float getDashAngle() { + return dashAngle; + } + + public void setDashAngle(float dashAngle) { + this.dashAngle = dashAngle; + } + + public DashDirection getDashDirectionEnum() { + return dashDirection; + } + + public void setDashDirectionEnum(DashDirection dashDirection) { + this.dashDirection = dashDirection; + } + + @Override + public int getDashDirection() { + return dashDirection.ordinal(); + } + + @Override + public void setDashDirection(int mode) { + DashDirection[] values = DashDirection.values(); + this.dashDirection = mode >= 0 && mode < values.length ? values[mode] : DashDirection.FORWARD; + } + + public DashDirection getChosenDirection() { return chosenDirection; } + private void finishDash(EntityLivingBase caster) { + if (dashMode == DashMode.DIRECTIONAL) { + applyHorizontalMomentum(caster, preDashMotionX, preDashMotionZ); + } else { + stopMomentum(caster); + } + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { @@ -337,7 +393,12 @@ public class AbilityDash extends Ability implements IAbilityDash { FieldDef.row( FieldDef.floatField("ability.dashDistance", this::getDashDistance, this::setDashDistance), FieldDef.floatField("ability.dashSpeed", this::getDashSpeed, this::setDashSpeed) - ) + ), + FieldDef.row( + FieldDef.enumField("ability.dashDirection", DashDirection.class, this::getDashDirectionEnum, this::setDashDirectionEnum), + FieldDef.floatField("ability.dashAngle", this::getDashAngle, this::setDashAngle) + .min(Float.NEGATIVE_INFINITY).visibleWhen(() -> getDashDirectionEnum() == DashDirection.CUSTOM) + ).visibleWhen(() -> this.getDashModeEnum() == DashMode.DIRECTIONAL) )); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java new file mode 100644 index 000000000..4826daee4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java @@ -0,0 +1,349 @@ +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.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import noppes.npcs.EventHooks; +import noppes.npcs.api.ability.type.IAbilityDefend; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.scripted.event.AbilityEvent; + +import java.util.List; + +/** + * Abstract base class for defensive abilities (Guard, Counter, Dodge). + *

+ * {@link #onDefend} handles shared checks then delegates to {@link #performDefend(EntityLivingBase, float)} + * which subclasses override for their specific behavior. + *

+ * Damage source filtering is controlled by {@link #isValidDamageSource(DamageSource)}. + * By default only physical melee is accepted; subclasses can override to widen (e.g. Guard accepts all). + */ +public abstract class AbilityDefend extends Ability implements IAbilityDefend { + + // ═══════════════════════════════════════════════════════════════════ + // SHARED PERSIST STATE + // ═══════════════════════════════════════════════════════════════════ + + protected int durationTicks = 60; + protected int maxHitAmount = 3; + + // ═══════════════════════════════════════════════════════════════════ + // TRANSIENT RUNTIME STATE + // ═══════════════════════════════════════════════════════════════════ + + protected transient EntityLivingBase caster; + protected transient int hitCount; + protected transient EntityLivingBase lastAttacker; + protected transient float lastDamageTaken; + protected transient Animation pendingDefendAnimation; + protected transient int defendAnimEndTick = -1; + /** Prevents double-counting hits when multiple damage paths call onDefend for the same hit in a single tick. */ + protected transient long lastDefendTick = -1; + /** Defers signalCompletion to the next tick so all damage paths for the last hit still see isDefending()=true. */ + protected transient boolean pendingCompletion; + + // ═══════════════════════════════════════════════════════════════════ + // CONSTRUCTOR DEFAULTS + // ═══════════════════════════════════════════════════════════════════ + + protected AbilityDefend() { + this.targetingMode = TargetingMode.SELF; + this.lockMovement = LockMode.ACTIVE; + this.interruptible = false; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + this.windUpTicks = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // LIFECYCLE + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + this.caster = caster; + hitCount = 0; + lastAttacker = null; + lastDamageTaken = 0.0f; + // NPCs reuse one ability instance, so every transient field has to be cleared here. + // A leftover pendingCompletion would end the next activation on its first tick. + pendingDefendAnimation = null; + defendAnimEndTick = -1; + lastDefendTick = -1; + pendingCompletion = false; + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (pendingCompletion || tick >= durationTicks) { + signalCompletion(); + } + } + + @Override + public void reset() { + super.reset(); + caster = null; + hitCount = 0; + lastAttacker = null; + lastDamageTaken = 0.0f; + pendingDefendAnimation = null; + defendAnimEndTick = -1; + lastDefendTick = -1; + pendingCompletion = false; + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOK + // ═══════════════════════════════════════════════════════════════════ + + /** + * Called when the caster is hit while defending. + * Checks damage source validity via {@link #isValidDamageSource}, then delegates + * to {@link #performDefend(EntityLivingBase, float)}. + * + * @param attacker The entity that hit the caster + * @param source The damage source + * @param amount The original incoming damage + * @return The modified damage to apply (unchanged if source is invalid) + */ + public final float onDefend(EntityLivingBase attacker, DamageSource source, float amount) { + if (!isDefending()) { + return amount; + } + if (attacker == null || source == null) { + return amount; + } + + if (!isValidDamageSource(source)) { + return amount; + } + + // Deduplicate per tick: when multiple damage paths (e.g. vanilla + DBC) call onDefend + // for the same hit, only count it once for hitCount / signalCompletion / animation. + long currentTick = (caster != null && caster.worldObj != null) + ? caster.worldObj.getTotalWorldTime() : -1; + boolean firstCallThisTick = (currentTick < 0 || currentTick != lastDefendTick); + + // If max hits reached on a previous tick and this is a NEW hit, reject it + if (pendingCompletion && firstCallThisTick) { + return amount; + } + + if (firstCallThisTick) { + lastDefendTick = currentTick; + lastAttacker = attacker; + lastDamageTaken = amount; + hitCount++; + + // Queue defend reaction animation (played on next tick by AbstractDataAbilities) + pendingDefendAnimation = getDefendAnimation(); + + // Defer completion to next tick so all damage paths in this tick + // still see isDefending()=true and apply guard reduction. + if (maxHitAmount > 0 && hitCount >= maxHitAmount) { + pendingCompletion = true; + } + } + + //inject defend event + AbilityEvent.DefendEvent event = new AbilityEvent.DefendEvent(caster, this, attacker, lastAttacker, amount); + if (EventHooks.onAbilityDefend(this, event)) { + return event.getDamage(); + } + + // Always calculate the correct reduction for the caller's damage amount + return performDefend(attacker, event.getDamage()); + } + + /** + * Subclass-specific defend behavior. Called only for valid hits while defending + * (as determined by {@link #isValidDamageSource}). + * + * @param attacker The entity that hit the caster + * @param amount The incoming damage + * @return The modified damage the caster should take + */ + protected abstract float performDefend(EntityLivingBase attacker, float amount); + + /** + * Determines whether this defend ability reacts to the given damage source. + * Default implementation accepts only physical melee damage (rejects magic, fire, explosion, projectile). + * Subclasses can override to accept additional damage types (e.g. Guard accepts all). + */ + protected boolean isValidDamageSource(DamageSource source) { + return !source.isMagicDamage() && !source.isFireDamage() && !source.isExplosion() && !source.isProjectile(); + } + + // ═══════════════════════════════════════════════════════════════════ + // SUBCLASS HOOKS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Subclass-specific NBT persistence. + */ + protected abstract void writeSubTypeNBT(NBTTagCompound nbt); + protected abstract void readSubTypeNBT(NBTTagCompound nbt); + + @SideOnly(Side.CLIENT) + protected abstract void getTypeDefinitions(List defs); + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND ANIMATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Returns the animation to play when this defend ability reacts to a hit. + * Subclasses override to provide their specific animation (counter strike, dodge roll, etc). + * Guard returns null (no reaction animation). + */ + protected Animation getDefendAnimation() { + return null; + } + + /** + * Consume and return the pending defend animation (set during onDefend). + * Called by AbstractDataAbilities to play the animation on the next tick. + */ + public Animation consumeDefendAnimation() { + Animation anim = pendingDefendAnimation; + pendingDefendAnimation = null; + return anim; + } + + /** + * Schedule return to active animation after the defend animation finishes. + */ + public void scheduleReturnToActive(int currentTick, Animation defendAnim) { + if (defendAnim != null) { + defendAnimEndTick = currentTick + (int) defendAnim.getTotalTime(); + } + } + + /** + * Check if the defend animation has finished and we should return to the active animation. + */ + public boolean shouldReturnToActiveAnimation(int currentTick) { + if (defendAnimEndTick >= 0 && currentTick >= defendAnimEndTick) { + defendAnimEndTick = -1; + return true; + } + return false; + } + + // ═══════════════════════════════════════════════════════════════════ + // STATE QUERIES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean isDefending() { + return isExecuting() && getPhase() == AbilityPhase.ACTIVE; + } + + // ═══════════════════════════════════════════════════════════════════ + // OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.SELF}; + } + + @Override + public float getTelegraphRadius() { + return 0; + } + + /** + * Suppresses the auto-play of activeSound on ACTIVE phase entry. + * Defend abilities play their sound on hit reaction, not on phase start. + */ + @Override + public boolean keepTelegraphDuringActive() { + return true; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + public final void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setInteger("maxHitAmount", maxHitAmount); + writeSubTypeNBT(nbt); + } + + @Override + public final void readTypeNBT(NBTTagCompound nbt) { + this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; + this.maxHitAmount = nbt.hasKey("maxHitAmount") ? nbt.getInteger("maxHitAmount") : 3; + readSubTypeNBT(nbt); + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + public final void getAbilityDefinitions(List defs) { + defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 6000)); + defs.add(FieldDef.intField("ability.maxHitAmount", this::getMaxHitAmount, this::setMaxHitAmount).range(0, 100) + .hover("ability.hover.maxHitAmount")); + + getTypeDefinitions(defs); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + @Override + public int getDurationTicks() { + return durationTicks; + } + + @Override + public void setDurationTicks(int ticks) { + this.durationTicks = Math.max(1, ticks); + } + + @Override + public int getMaxHitAmount() { + return maxHitAmount; + } + + @Override + public void setMaxHitAmount(int amount) { + this.maxHitAmount = Math.max(0, amount); + } + + public int getHitCount() { + return hitCount; + } +} 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 deleted file mode 100644 index 21d4073ed..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ /dev/null @@ -1,672 +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.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.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 java.util.Arrays; -import java.util.List; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; - -/** - * 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 { - - private static final int MAX_PROJECTILES = 8; - - // Disc geometry (shared) - private float discRadius = 1.0f; - private float discThickness = 0.2f; - private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) - - // Boomerang properties (shared) - private boolean boomerang = false; - private int boomerangDelay = 40; - - // Projectile count and fire stagger - private int projectileCount = 1; - private int fireDelay = 0; - - // Shared visual data (all projectiles use these) - private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Shared combat/movement data - 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 EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - - // Per-projectile data (anchor + optional color override) - private ProjectileData[] projectiles; - - // Transient entity state - private transient EntityAbilityDisc[] discEntities; - - public AbilityDisc() { - this.typeId = "ability.cnpc.disc"; - this.name = "Disc"; - 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; - this.windUpAnimationName = "Ability_Disc_Windup"; - this.activeAnimationName = "Ability_Disc_Active"; - initProjectiles(1); - } - - private 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)); - } - } - - /** - * Disc anchor order is REVERSED from Orb/Beam: [0]=LEFT_HAND, [1]=RIGHT_HAND - */ - private AnchorPoint getDefaultAnchor(int index) { - switch (index) { - case 0: return AnchorPoint.RIGHT_HAND; - case 1: return AnchorPoint.LEFT_HAND; - default: return AnchorPoint.FRONT; - } - } - - 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); - } - - // Legacy compat - public int getDualFireDelay() { return fireDelay; } - public void setDualFireDelay(int delay) { setFireDelay(delay); } - - @Override - 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(10); - // Set color override for second disc - 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"); - }) - ); - } - - @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}; - } - - /** - * Create disc entities. - * NPC: target is the aggro target — discs will home toward it. - * Player: target is null — discs fire in caster's look direction. - */ - private EntityAbilityDisc[] createDiscEntities(EntityLivingBase caster, EntityLivingBase target, World world) { - EntityAbilityDisc[] entities = new EntityAbilityDisc[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - entities[i] = new EntityAbilityDisc( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - discRadius, discThickness, - resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, - boomerang, boomerangDelay); - entities[i].setEffects(this.effects); - entities[i].setSourceAbility(this); - } - if (projectileCount == 2 && entities[0] != null && entities[1] != null) { - entities[0].setSiblingEntityId(entities[1].getEntityId()); - entities[1].setSiblingEntityId(entities[0].getEntityId()); - } - return entities; - } - - private void fireDiscEntity(EntityAbilityDisc disc, EntityLivingBase target) { - if (disc == null || disc.isDead) return; - if (isPreview()) { - disc.startPreviewFiring(); - } else { - disc.startMoving(target); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - discEntities = createDiscEntities(caster, target, world); - for (int i = 0; i < projectileCount; i++) { - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - if (isPreview()) { - discEntities[i].setupPreview(caster, discRadius, discThickness, resolved, lightningData, projectiles[i].anchor, windUpTicks, vertical); - } else { - discEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, vertical); - } - spawnAbilityEntity(world, discEntities[i]); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - discEntities = createDiscEntities(caster, target, world); - for (EntityAbilityDisc disc : discEntities) { - spawnAbilityEntity(world, disc); - } - for (EntityAbilityDisc disc : discEntities) { - fireDiscEntity(disc, target); - } - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (discEntities == null) return; - - // Fire first projectile immediately - fireDiscEntity(discEntities[0], target); - - // Fire remaining projectiles if no delay - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireDiscEntity(discEntities[i], target); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (discEntities == null) { - signalCompletion(); - return; - } - - // Fire staggered projectiles - if (fireDelay > 0) { - for (int i = 1; i < projectileCount; i++) { - if (tick == fireDelay * i) { - fireDiscEntity(discEntities[i], target); - } - } - } - - // Check if all entities are dead - boolean allDead = true; - for (EntityAbilityDisc disc : discEntities) { - if (disc != null && !disc.isDead) { - allDead = false; - break; - } - } - if (allDead) { - 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() { - if (discEntities != null) { - for (int i = 0; i < discEntities.length; i++) { - if (discEntities[i] != null && !discEntities[i].isDead) { - discEntities[i].setDead(); - } - discEntities[i] = null; - } - } - discEntities = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - // NPC: telegraph on aggro target position - // Player: no telegraph (discs fire in look direction, no fixed position to mark) - if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || 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("vertical", vertical); - nbt.setBoolean("boomerang", boomerang); - nbt.setInteger("boomerangDelay", boomerangDelay); - nbt.setInteger("projectileCount", projectileCount); - nbt.setInteger("fireDelay", fireDelay); - - // Shared visual data - displayData.writeNBT(nbt); - lightningData.writeNBT(nbt); - - // Shared combat/movement data - 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 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.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); - this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); - this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; - - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; - initProjectiles(count); - - // Read fireDelay with fallback to old dualFireDelay key - if (nbt.hasKey("fireDelay")) { - this.fireDelay = nbt.getInteger("fireDelay"); - } else if (nbt.hasKey("dualFireDelay")) { - this.fireDelay = nbt.getInteger("dualFireDelay"); - } else { - this.fireDelay = 0; - } - - // Shared combat/movement data - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - // Determine format and read accordingly - if (nbt.hasKey("Projectile_0")) { - NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); - if (proj0.hasKey("colorOverride")) { - // NEW format: shared visuals at root + ProjectileData per projectile - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } - } else { - // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) - // Read primary visuals from Projectile_0 - displayData.readNBT(proj0); - lightningData.readNBT(proj0); - projectiles[0].anchor.readNBT(proj0); - - // Read remaining projectiles, set color override if colors differ - for (int i = 1; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); - projectiles[i].anchor.readNBT(projNbt); - - // Check if this projectile had different colors - EnergyDisplayData tempDisplay = new EnergyDisplayData(); - tempDisplay.readNBT(projNbt); - if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { - projectiles[i].colorOverride = true; - projectiles[i].innerColor = tempDisplay.innerColor; - projectiles[i].outerColor = tempDisplay.outerColor; - } - } - } - } - } else { - // LEGACY flat format: all data at root level - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - projectiles[0].anchor.readNBT(nbt); - } - } - - // ═══════════════════════════════════════════════════════════════════ - // API GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ - - 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 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 float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float d) { lifespanData.maxDistance = d; } - - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } - - public float getDamage() { return combatData.damage; } - public void setDamage(float d) { combatData.damage = d; } - - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float k) { combatData.knockback = k; } - - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float k) { combatData.knockbackUp = k; } - - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean h) { homingData.homing = h; } - - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float s) { homingData.homingStrength = s; } - - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float r) { homingData.homingRange = r; } - - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean e) { combatData.explosive = e; } - - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float r) { combatData.explosionRadius = r; } - - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } - - // Shared display data (primary colors) - public int getInnerColor() { return displayData.innerColor; } - public void setInnerColor(int c) { displayData.innerColor = c; } - - public int getOuterColor() { return displayData.outerColor; } - public void setOuterColor(int c) { displayData.outerColor = c; } - - public float getOuterColorWidth() { return displayData.outerColorWidth; } - public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } - - public float getOuterColorAlpha() { return displayData.outerColorAlpha; } - public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } - - public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } - public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } - - public float getRotationSpeed() { return displayData.rotationSpeed; } - public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } - - // Shared lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } - - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float d) { lightningData.lightningDensity = d; } - - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float r) { lightningData.lightningRadius = r; } - - public int getLightningFadeTime() { return lightningData.lightningFadeTime; } - public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } - - // Anchor - default to projectile 0 - public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } - public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } - - 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; } - - private int clampIndex(int index) { - return Math.max(0, Math.min(index, projectileCount - 1)); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - // Type tab - projectile count and fire delay - 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) - )); - - // Type tab - disc properties - 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)); - - // Visual tab - shared 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")); - - // Visual tab - shared 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")); - - // 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)); - - // Anchor point - 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), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) - ).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)); - - // 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/ability/type/AbilityDodge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDodge.java new file mode 100644 index 000000000..2938af70b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDodge.java @@ -0,0 +1,196 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import noppes.npcs.controllers.AnimationController; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.api.ability.type.IAbilityDodge; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.ArrayList; +import java.util.List; + +/** + * Dodge ability: Completely cancels incoming attacks and plays a random dodge animation. + */ +public class AbilityDodge extends AbilityDefend implements IAbilityDodge { + + private int dodgeAnimation1Id = -1; + private String dodgeAnimation1Name = ""; + private int dodgeAnimation2Id = -1; + private String dodgeAnimation2Name = ""; + private int dodgeAnimation3Id = -1; + private String dodgeAnimation3Name = ""; + + public AbilityDodge() { + this.typeId = "ability.cnpc.dodge"; + this.name = "Dodge"; + this.cooldownTicks = 0; + this.windUpTicks = 10; + this.allowedBy = UserType.BOTH; + + this.activeAnimationName = ""; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png") + }; + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOKS + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected float performDefend(EntityLivingBase attacker, float amount) { + return 0; + } + + @Override + protected Animation getDefendAnimation() { + return getRandomDodgeAnimation(); + } + + /** + * Returns a random dodge animation from the configured slots (non-empty only). + */ + public Animation getRandomDodgeAnimation() { + if (AnimationController.Instance == null) return null; + + List available = new ArrayList<>(); + Animation a1 = getDodgeAnimation(dodgeAnimation1Id, dodgeAnimation1Name); + Animation a2 = getDodgeAnimation(dodgeAnimation2Id, dodgeAnimation2Name); + Animation a3 = getDodgeAnimation(dodgeAnimation3Id, dodgeAnimation3Name); + if (a1 != null) available.add(a1); + if (a2 != null) available.add(a2); + if (a3 != null) available.add(a3); + + if (available.isEmpty()) return null; + return available.get((int) (Math.random() * available.size())); + } + + private Animation getDodgeAnimation(int id, String name) { + if (id >= 0) { + return (Animation) AnimationController.Instance.get(id); + } + if (name != null && !name.isEmpty()) { + return (Animation) AnimationController.Instance.get(name, true); + } + return null; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void writeSubTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("dodgeAnimation1Id", dodgeAnimation1Id); + nbt.setString("dodgeAnimation1Name", resolveAnimationName(dodgeAnimation1Id, dodgeAnimation1Name)); + nbt.setInteger("dodgeAnimation2Id", dodgeAnimation2Id); + nbt.setString("dodgeAnimation2Name", resolveAnimationName(dodgeAnimation2Id, dodgeAnimation2Name)); + nbt.setInteger("dodgeAnimation3Id", dodgeAnimation3Id); + nbt.setString("dodgeAnimation3Name", resolveAnimationName(dodgeAnimation3Id, dodgeAnimation3Name)); + } + + @Override + protected void readSubTypeNBT(NBTTagCompound nbt) { + this.dodgeAnimation1Id = nbt.getInteger("dodgeAnimation1Id"); + this.dodgeAnimation1Name = nbt.getString("dodgeAnimation1Name"); + this.dodgeAnimation2Id = nbt.getInteger("dodgeAnimation2Id"); + this.dodgeAnimation2Name = nbt.getString("dodgeAnimation2Name"); + this.dodgeAnimation3Id = nbt.getInteger("dodgeAnimation3Id"); + this.dodgeAnimation3Name = nbt.getString("dodgeAnimation3Name"); + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + protected void getTypeDefinitions(List defs) { + FieldDef.insertAfter(defs, "ability.dazedAnimation", + FieldDef.section("ability.section.dodgeAnimations").tab("Effects")); + + FieldDef.insertAfter(defs, "ability.section.dodgeAnimations", + FieldDef.animSubGui("ability.dodgeAnimation1", + this::getDodgeAnimation1Id, this::setDodgeAnimation1Id, + this::getDodgeAnimation1Name, this::setDodgeAnimation1Name) + .tab("Effects")); + + FieldDef.insertAfter(defs, "ability.dodgeAnimation1", + FieldDef.animSubGui("ability.dodgeAnimation2", + this::getDodgeAnimation2Id, this::setDodgeAnimation2Id, + this::getDodgeAnimation2Name, this::setDodgeAnimation2Name) + .tab("Effects")); + + FieldDef.insertAfter(defs, "ability.dodgeAnimation2", + FieldDef.animSubGui("ability.dodgeAnimation3", + this::getDodgeAnimation3Id, this::setDodgeAnimation3Id, + this::getDodgeAnimation3Name, this::setDodgeAnimation3Name) + .tab("Effects")); + + FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); + FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + @Override + public int getDodgeAnimation1Id() { + return dodgeAnimation1Id; + } + + @Override + public void setDodgeAnimation1Id(int animationId) { + this.dodgeAnimation1Id = animationId; + } + + public String getDodgeAnimation1Name() { + return dodgeAnimation1Name; + } + + public void setDodgeAnimation1Name(String name) { + this.dodgeAnimation1Name = name != null ? name : ""; + } + + @Override + public int getDodgeAnimation2Id() { + return dodgeAnimation2Id; + } + + @Override + public void setDodgeAnimation2Id(int animationId) { + this.dodgeAnimation2Id = animationId; + } + + public String getDodgeAnimation2Name() { + return dodgeAnimation2Name; + } + + public void setDodgeAnimation2Name(String name) { + this.dodgeAnimation2Name = name != null ? name : ""; + } + + @Override + public int getDodgeAnimation3Id() { + return dodgeAnimation3Id; + } + + @Override + public void setDodgeAnimation3Id(int animationId) { + this.dodgeAnimation3Id = animationId; + } + + public String getDodgeAnimation3Name() { + return dodgeAnimation3Name; + } + + public void setDodgeAnimation3Name(String name) { + this.dodgeAnimation3Name = name != null ? name : ""; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java new file mode 100644 index 000000000..ae27b98a9 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java @@ -0,0 +1,524 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityCustomEffect; +import kamkeel.npcs.controllers.data.ability.data.entry.AbilityEffectActionEntry; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +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.nbt.NBTTagList; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.world.World; +import noppes.npcs.api.ability.type.IAbilityEffect; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Effect ability: Apply healing, potion effects, custom effects, and mod-registered + * effect actions to self or nearby entities. + *

+ * Supports: + *

    + *
  • SELF or AOE_SELF targeting modes
  • + *
  • AOE target filtering: ALLIES, ENEMIES, or ALL
  • + *
  • Healing (fixed amount + percentage)
  • + *
  • Potion effects via base Ability.effects list
  • + *
  • Custom effects from CustomEffectController (player-only)
  • + *
  • Mod-registered effect actions via IEffectAction registry
  • + *
  • Burst system for repeated reapplication (auras, debuffs)
  • + *
  • Concurrent execution alongside other abilities in chains
  • + *
+ */ +public class AbilityEffect extends Ability implements IAbilityEffect { + + // Type-specific parameters + private int durationTicks = 60; + private float healAmount = 10.0f; + private float healPercent = 0.0f; + private boolean includeSelf = true; + private float radius = 8.0f; + private boolean instantHeal = true; + private TargetFilter targetFilter = TargetFilter.ALLIES; + + // Custom effects (from CustomEffectController — player-only) + private List customEffects = new ArrayList<>(); + + // Mod-registered effect actions + private List effectActions = new ArrayList<>(); + + // Runtime state + private transient List affectedEntities; + + private List getAffectedEntities() { + if (affectedEntities == null) { + affectedEntities = new ArrayList<>(); + } + return affectedEntities; + } + + public AbilityEffect() { + this.typeId = "ability.cnpc.effect"; + this.name = "Effect"; + this.targetingMode = TargetingMode.SELF; + this.lockMovement = LockMode.WINDUP; + this.cooldownTicks = 0; + this.windUpTicks = 30; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/effect.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/effect_overlay.png", + this::getActiveColor) + }; + } + + // ==================== ABILITY TYPE OVERRIDES ==================== + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean allowBurst() { + return true; + } + + @Override + public boolean isTargetingModeLocked() { + return false; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.SELF, TargetingMode.AOE_SELF}; + } + + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public float getTelegraphRadius() { + return targetingMode == TargetingMode.AOE_SELF && radius > 0 ? radius : 0; + } + + // ==================== EXECUTION ==================== + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) return; + + if (!isPreview()) { + getAffectedEntities().clear(); + + if (targetingMode == TargetingMode.AOE_SELF && radius > 0) { + findEntitiesInRadius(caster, caster.worldObj); + } else { + if (includeSelf) { + getAffectedEntities().add(caster); + } + } + + if (instantHeal) { + for (EntityLivingBase entity : getAffectedEntities()) { + healEntity(caster, entity); + applyAllEffects(caster, entity); + spawnHealParticles(caster.worldObj, entity); + } + } + } + + if (instantHeal) { + signalCompletion(); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if ((caster.worldObj.isRemote && !isPreview()) || instantHeal) return; + + if (tick % 10 == 0) { + float tickHealFixed = (healAmount / (float) durationTicks) * 10; + + for (EntityLivingBase entity : getAffectedEntities()) { + if (entity.isDead) continue; + + float totalTickHeal = tickHealFixed; + if (healPercent > 0) { + totalTickHeal += (entity.getMaxHealth() * healPercent / (float) durationTicks) * 10; + } + + if (totalTickHeal > 0) { + if (!AbilityController.Instance.fireOnAbilityHeal(this, caster, entity, totalTickHeal)) { + entity.heal(totalTickHeal); + } + } + + if (tick % 20 == 0) { + applyAllEffects(caster, entity); + spawnHealParticles(caster.worldObj, entity); + } + } + } + + if (tick >= durationTicks) { + signalCompletion(); + return; + } + + // Early completion if all affected entities are dead + boolean allDead = true; + for (EntityLivingBase entity : getAffectedEntities()) { + if (!entity.isDead) { + allDead = false; + break; + } + } + if (!getAffectedEntities().isEmpty() && allDead) { + signalCompletion(); + } + } + + // ==================== EFFECT APPLICATION ==================== + + /** + * Applies all configured effect types to a single entity: + * vanilla potion effects, custom effects, and mod-registered effect actions. + */ + private void applyAllEffects(EntityLivingBase caster, EntityLivingBase entity) { + applyEffects(entity); + applyCustomEffects(entity); + applyEffectActions(caster, entity); + } + + private void applyCustomEffects(EntityLivingBase entity) { + for (AbilityCustomEffect ce : customEffects) { + if (ce.isValid()) { + ce.apply(entity); + } + } + } + + private void applyEffectActions(EntityLivingBase caster, EntityLivingBase entity) { + for (AbilityEffectActionEntry ea : effectActions) { + if (ea.isValid()) { + ea.apply(caster, entity); + } + } + } + + // ==================== TARGET GATHERING ==================== + + @SuppressWarnings("unchecked") + private void findEntitiesInRadius(EntityLivingBase caster, World world) { + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox( + caster.posX - radius, caster.posY - 2, caster.posZ - radius, + caster.posX + radius, caster.posY + 3, caster.posZ + radius + ); + + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, aabb); + + for (Entity entity : entities) { + if (!(entity instanceof EntityLivingBase)) continue; + EntityLivingBase living = (EntityLivingBase) entity; + + float dist = caster.getDistanceToEntity(living); + if (dist > radius) continue; + + if (!AbilityTargetHelper.shouldAffect(caster, living, targetFilter, includeSelf)) continue; + + getAffectedEntities().add(living); + } + } + + private void healEntity(EntityLivingBase caster, EntityLivingBase entity) { + float totalHeal = healAmount; + if (healPercent > 0) { + totalHeal += entity.getMaxHealth() * healPercent; + } + if (totalHeal > 0) { + if (!AbilityController.Instance.fireOnAbilityHeal(this, caster, entity, totalHeal)) { + entity.heal(totalHeal); + } + } + } + + private void spawnHealParticles(World world, EntityLivingBase entity) { + for (int i = 0; i < 10; i++) { + double offsetX = (world.rand.nextDouble() - 0.5) * entity.width; + double offsetY = world.rand.nextDouble() * entity.height; + double offsetZ = (world.rand.nextDouble() - 0.5) * entity.width; + world.spawnParticle("happyVillager", + entity.posX + offsetX, + entity.posY + offsetY, + entity.posZ + offsetZ, + 0, 0.1, 0); + } + } + + // ==================== LIFECYCLE ==================== + + @Override + public void resetForBurst() { + getAffectedEntities().clear(); + } + + @Override + public void cleanup() { + getAffectedEntities().clear(); + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.selfHeal", a -> { + AbilityEffect e = (AbilityEffect) a; + a.setName("Self Heal"); + e.setTargetingMode(TargetingMode.SELF); + e.setIncludeSelf(true); + e.setInstantHeal(true); + }), + new AbilityVariant("ability.variant.healingAura", a -> { + AbilityEffect e = (AbilityEffect) a; + a.setName("Healing Aura"); + e.setTargetingMode(TargetingMode.AOE_SELF); + e.setTargetFilter(TargetFilter.ALLIES); + e.setIncludeSelf(true); + e.setRadius(8.0f); + e.setBurstEnabled(true); + e.setBurstAmount(5); + e.setBurstDelay(20); + }), + new AbilityVariant("ability.variant.poisonDebuff", a -> { + AbilityEffect e = (AbilityEffect) a; + a.setName("Poison Debuff"); + e.setTargetingMode(TargetingMode.AOE_SELF); + e.setTargetFilter(TargetFilter.ENEMIES); + e.setIncludeSelf(false); + e.setHealAmount(0); + e.setHealPercent(0); + e.setRadius(6.0f); + e.setBurstEnabled(true); + e.setBurstAmount(3); + e.setBurstDelay(40); + }) + ); + } + + // ==================== NBT ==================== + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setFloat("healAmount", healAmount); + nbt.setFloat("healPercent", healPercent); + nbt.setBoolean("includeSelf", includeSelf); + nbt.setFloat("radius", radius); + nbt.setBoolean("instantHeal", instantHeal); + nbt.setString("targetFilter", targetFilter.name()); + + // Custom effects + NBTTagList ceList = new NBTTagList(); + for (AbilityCustomEffect ce : customEffects) { + ceList.appendTag(ce.writeNBT()); + } + nbt.setTag("customEffects", ceList); + + // Effect actions + NBTTagList eaList = new NBTTagList(); + for (AbilityEffectActionEntry ea : effectActions) { + eaList.appendTag(ea.writeNBT()); + } + nbt.setTag("effectActions", eaList); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + this.durationTicks = nbt.getInteger("durationTicks"); + this.healAmount = nbt.getFloat("healAmount"); + this.healPercent = nbt.getFloat("healPercent"); + this.includeSelf = nbt.getBoolean("includeSelf"); + this.radius = nbt.getFloat("radius"); + this.instantHeal = nbt.getBoolean("instantHeal"); + this.targetFilter = TargetFilter.fromString(nbt.getString("targetFilter")); + + // Custom effects + customEffects.clear(); + if (nbt.hasKey("customEffects")) { + NBTTagList ceList = nbt.getTagList("customEffects", 10); + for (int i = 0; i < ceList.tagCount(); i++) { + AbilityCustomEffect ce = AbilityCustomEffect.fromNBT(ceList.getCompoundTagAt(i)); + if (ce.isValid()) customEffects.add(ce); + } + } + + // Effect actions + effectActions.clear(); + if (nbt.hasKey("effectActions")) { + NBTTagList eaList = nbt.getTagList("effectActions", 10); + for (int i = 0; i < eaList.tagCount(); i++) { + AbilityEffectActionEntry ea = AbilityEffectActionEntry.fromNBT(eaList.getCompoundTagAt(i)); + effectActions.add(ea); + } + } + } + + // ==================== GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.boolField("ability.instantHeal", this::isInstantHeal, this::setInstantHeal) + .hover("ability.hover.instant"), + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) + .range(1, 1000).visibleWhen(() -> !this.isInstantHeal()), + FieldDef.section("ability.section.healing"), + FieldDef.row( + FieldDef.floatField("ability.healAmount", this::getHealAmount, this::setHealAmount), + FieldDef.floatField("ability.healPercent", this::getHealPercent, this::setHealPercent) + ), + FieldDef.section("ability.section.targeting") + .tab("Target").visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF), + FieldDef.enumField("ability.targetFilter", TargetFilter.class, + this::getTargetFilter, this::setTargetFilter) + .tab("Target").visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF), + FieldDef.row( + FieldDef.boolField("ability.includeSelf", this::isIncludeSelf, this::setIncludeSelf) + .visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF), + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius) + .visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF) + ).tab("Target"), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), + AbilityFieldDefs.customEffectsListField("ability.customEffects", this::getCustomEffects, this::setCustomEffects), + AbilityFieldDefs.effectActionsListField("ability.effectActions", this::getEffectActionEntries, this::setEffectActionEntries) + .visibleWhen(() -> AbilityController.Instance.hasEffectActions()) + )); + } + + // ==================== GETTERS & SETTERS ==================== + + @Override + public int getDurationTicks() { + return durationTicks; + } + + @Override + public void setDurationTicks(int durationTicks) { + this.durationTicks = Math.max(1, durationTicks); + } + + @Override + public float getHealAmount() { + return healAmount; + } + + @Override + public void setHealAmount(float healAmount) { + this.healAmount = healAmount; + } + + @Override + public float getHealPercent() { + return healPercent; + } + + @Override + public void setHealPercent(float healPercent) { + this.healPercent = healPercent; + } + + @Override + public boolean isIncludeSelf() { + return includeSelf; + } + + @Override + public void setIncludeSelf(boolean includeSelf) { + this.includeSelf = includeSelf; + } + + @Override + public float getRadius() { + return radius; + } + + @Override + public void setRadius(float radius) { + this.radius = radius; + } + + @Override + public boolean isInstantHeal() { + return instantHeal; + } + + @Override + public void setInstantHeal(boolean instantHeal) { + this.instantHeal = instantHeal; + } + + public TargetFilter getTargetFilter() { + return targetFilter; + } + + public void setTargetFilter(TargetFilter targetFilter) { + this.targetFilter = targetFilter; + } + + @Override + public int getTargetFilterType() { + return targetFilter.ordinal(); + } + + @Override + public void setTargetFilterType(int filter) { + TargetFilter[] values = TargetFilter.values(); + if (filter >= 0 && filter < values.length) { + this.targetFilter = values[filter]; + } + } + + public List getCustomEffects() { + return customEffects; + } + + public void setCustomEffects(List customEffects) { + this.customEffects = customEffects != null ? customEffects : new ArrayList<>(); + } + + @Override + public int getCustomEffectCount() { + return customEffects.size(); + } + + public List getEffectActionEntries() { + return effectActions; + } + + public void setEffectActionEntries(List effectActions) { + this.effectActions = effectActions != null ? effectActions : new ArrayList<>(); + } + + @Override + public int getEffectActionCount() { + return effectActions.size(); + } +} 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 477be2cc4..62d0dc1e1 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 @@ -1,283 +1,82 @@ package kamkeel.npcs.controllers.data.ability.type; -import kamkeel.npcs.controllers.data.ability.*; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; -import net.minecraft.world.World; -import noppes.npcs.api.handler.data.IAnimation; -import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.data.Animation; -import noppes.npcs.controllers.data.PlayerData; -import noppes.npcs.entity.EntityNPCInterface; - -import noppes.npcs.api.ability.type.IAbilityGuard; - -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import noppes.npcs.util.ValueUtil; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.ability.type.IAbilityGuard; +import noppes.npcs.client.gui.builder.FieldDef; -import java.util.Arrays; import java.util.List; /** * Guard ability: Defensive stance that reduces incoming damage. - * Can optionally counter-attack when hit. */ -public class AbilityGuard extends Ability implements IAbilityGuard { +public class AbilityGuard extends AbilityDefend implements IAbilityGuard { - private int durationTicks = 60; private float damageReduction = 0.5f; - private AbilityGuard.CounterType counterType = AbilityGuard.CounterType.FLAT; - private float counterValue = 6.0f; - private String counterSound = "random.anvil_land"; - private boolean canCounter = false; - private int counterWindow = 10; - private int counterAnimationId = -1; - private String counterAnimationName; - - // Runtime state - private transient EntityLivingBase lastAttacker; - private transient boolean counterTriggered; - private transient boolean counterEligible; - private transient float lastDamageTaken; public AbilityGuard() { this.typeId = "ability.cnpc.guard"; this.name = "Guard"; - this.targetingMode = TargetingMode.SELF; - this.lockMovement = LockMovementType.ACTIVE; this.cooldownTicks = 0; - this.windUpTicks = 0; - this.interruptible = false; // Hard to interrupt while guarding - // No telegraph for guard - it's a defensive stance - this.telegraphType = TelegraphType.NONE; - this.showTelegraph = false; - this.activeSound = "random.anvil_use"; this.allowedBy = UserType.BOTH; this.activeAnimationName = "Ability_Guard_Active"; - this.counterAnimationName = "Ability_Guard_Counter"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png") + }; } + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOKS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Guard accepts ALL damage types (melee, projectile, magic, fire, explosion). + */ @Override - public boolean hasDamage() { - return false; - } - - @Override - public boolean allowBurst() { - return false; - } - - public enum CounterType { - FLAT, - PERCENT; - - @Override - public String toString() { - switch (this) { - case FLAT: return "ability.counter.flat"; - case PERCENT: return "ability.counter.percent"; - default: return name(); - } - } - } - - @Override - public boolean isTargetingModeLocked() { + protected boolean isValidDamageSource(DamageSource source) { return true; } @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.SELF}; + protected float performDefend(EntityLivingBase attacker, float amount) { + return Math.max(0, amount * (1.0f - damageReduction)); } + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - lastAttacker = null; - counterTriggered = false; - lastDamageTaken = 0.0f; - counterEligible = true; - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !world.isRemote) { - performCounter(caster, world); - } - - if (tick > counterWindow && counterEligible) { - counterEligible = false; - } - - if (tick >= durationTicks) { - signalCompletion(); - } - - // Just enough to see the counter animation - if (counterTriggered && tick >= counterWindow + 10) { - signalCompletion(); - } - } - - public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) { - if (!isGuarding() || attacker == null) return; - - 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); - } else { - caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); - counterTriggered = true; - } - } - - private boolean isDirectHit(DamageSource source) { - if (source == null) return false; - if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) return false; - return source.getEntity() instanceof EntityLivingBase; - } - - private void performCounter(EntityLivingBase caster, World world) { - float counterDamage = counterType == AbilityGuard.CounterType.PERCENT - ? lastDamageTaken * (counterValue / 100.0f) - : counterValue; - - boolean wasHit = applyAbilityDamage(caster, lastAttacker, counterDamage, 0.5f); - if (wasHit && counterSound != null && !counterSound.isEmpty()) { - world.playSoundAtEntity(caster, counterSound, 1.0f, 1.2f); - } - // Use shared animation utility - only available for NPCs - if (caster instanceof EntityNPCInterface) { - if (getCounterAnimation() instanceof IAnimation) { - ((EntityNPCInterface) caster).abilities.playAbilityAnimation((Animation) getCounterAnimation()); - } - } else if (caster instanceof EntityPlayer) { - if (getCounterAnimation() instanceof IAnimation) { - PlayerData.get((EntityPlayer) caster).abilityData.playAbilityAnimation((Animation) getCounterAnimation()); - } - } - - counterEligible = false; - lastAttacker = null; - lastDamageTaken = 0.0f; - } - - private IAnimation getCounterAnimation() { - if (AnimationController.Instance == null) return null; - - if (counterAnimationId > 0) { - return AnimationController.Instance.get(counterAnimationId); - } - - if (!counterAnimationName.isEmpty()) { - return AnimationController.Instance.get(counterAnimationName, true); - } - - return null; - } - - /** - * Get the damage reduction factor while guarding. - * Returns 0.5 for 50% reduction. - */ - public float getDamageReductionFactor() { - if (isExecuting() && getPhase() == AbilityPhase.ACTIVE) { - return damageReduction; - } - return 0.0f; - } - - /** - * Check if the caster is currently in guard stance. - */ - public boolean isGuarding() { - return isExecuting() && getPhase() == AbilityPhase.ACTIVE; - } - - @Override - public void reset() { - super.reset(); - lastAttacker = null; - counterTriggered = false; - lastDamageTaken = 0.0f; - } - - @Override - public float getTelegraphRadius() { - return 0; // No telegraph for guard - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); + protected void writeSubTypeNBT(NBTTagCompound nbt) { nbt.setFloat("damageReduction", damageReduction); - nbt.setBoolean("canCounter", canCounter); - nbt.setInteger("counterWindow", counterWindow); - nbt.setString("counterType", counterType.name()); - nbt.setFloat("counterValue", counterValue); - nbt.setString("counterSound", counterSound); - nbt.setInteger("counterAnimationId", counterAnimationId); - nbt.setString("counterAnimationName", counterAnimationName); } @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; + protected void readSubTypeNBT(NBTTagCompound nbt) { 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; - 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"; } - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) @Override - public int getCounterWindow() { - return this.counterWindow; + protected void getTypeDefinitions(List defs) { + defs.add(FieldDef.floatField("ability.damageReduction", this::getDamageReduction, this::setDamageReduction)); + + FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); + FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); } - @Override - public void setCounterWindow(int ticks) { - this.counterWindow = Math.min(durationTicks, ticks); - } + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ @Override public float getDamageReduction() { @@ -288,101 +87,4 @@ public class AbilityGuard extends Ability implements IAbilityGuard { public void setDamageReduction(float damageReduction) { this.damageReduction = damageReduction; } - - - @Override - public boolean canCounter() { - return canCounter; - } - - public void setCanCounter(boolean canCounter) { - this.canCounter = canCounter; - } - - public CounterType getCounterTypeEnum() { - return counterType; - } - - public void setCounterTypeEnum(CounterType counterType) { - this.counterType = counterType; - } - - @Override - public int getCounterType() { - return counterType.ordinal(); - } - - @Override - public void setCounterType(int type) { - CounterType[] values = CounterType.values(); - this.counterType = type >= 0 && type < values.length ? values[type] : CounterType.FLAT; - } - - public float getCounterValue() { - return counterValue; - } - - public void setCounterValue(float counterValue) { - this.counterValue = counterValue; - } - - public String getCounterSound() { - return counterSound; - } - - public void setCounterSound(String counterSound) { - this.counterSound = counterSound; - } - - public int getCounterAnimationId() { - return counterAnimationId; - } - - public void setCounterAnimationId(int counterAnimationId) { - this.counterAnimationId = counterAnimationId; - } - - public String getCounterAnimationName() { - return counterAnimationName; - } - - public void setCounterAnimationName(String name) { - this.counterAnimationName = name; - } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 1000), - FieldDef.floatField("ability.damageReduction", this::getDamageReduction, this::setDamageReduction), - FieldDef.section("ability.section.counter"), - FieldDef.boolField("gui.enabled", this::canCounter, this::setCanCounter).hover("ability.hover.canCounter"), - FieldDef.enumField("gui.type", CounterType.class, this::getCounterTypeEnum, this::setCounterTypeEnum) - .hover("ability.hover.counterType").visibleWhen(this::canCounter), - FieldDef.row( - FieldDef.floatField("gui.value", this::getCounterValue, this::setCounterValue) - .visibleWhen(this::canCounter), - FieldDef.intField("ability.counterWindow", this::getCounterWindow, this::setCounterWindow) - .visibleWhen(this::canCounter) - ), - FieldDef.stringField("gui.sound", this::getCounterSound, this::setCounterSound) - .visibleWhen(this::canCounter), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) - - )); - - FieldDef.insertAfter(defs, "ability.activeSound", - FieldDef.soundSubGui("ability.counterSound", this::getCounterSound, this::setCounterSound) - .tab("Effects").visibleWhen(this::canCounter)); - - FieldDef.insertAfter(defs, "ability.activeAnimation", - FieldDef.animSubGui("ability.counterAnimation", - this::getCounterAnimationId, this::setCounterAnimationId, - this::getCounterAnimationName, this::setCounterAnimationName) - .tab("Effects").visibleWhen(this::canCounter)); - - FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); - FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); - } } 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 58c2560a4..2086d4e8f 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,443 +1,114 @@ 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.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -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; - -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.data.energy.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 noppes.npcs.api.ability.type.IAbilityHazard; +import noppes.npcs.client.gui.builder.FieldDef; +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.allowedBy = UserType.NPC_ONLY; + this.windUpAnimationName = "Ability_Zone_Windup"; + this.activeAnimationName = "Ability_Zone_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/hazard.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/hazard_overlay.png", + this::getActiveColor) + }; } @Override - public boolean allowBurst() { - return false; - } - - @Override - public boolean isTargetingModeLocked() { + public boolean isConcurrentCapable() { 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: - 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]; - 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, + isIgnoreIFrames(), affectsCaster, + durationTicks, + colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, + zoneHeight, + particleDensity, particleScale, animSpeed, lightningDensity, + getEffects()); + entity.setSourceAbility(this); - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; + applyVisualToEntity(entity); - // Check if hazard duration has ended - if (tick >= durationTicks) { - signalCompletion(); - return; - } - - if (!isPreview()) { - 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 (isPreview()) { + entity.setupPreview(caster); } - 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()); - } - } + spawnAbilityEntity(entity); + activeEntities.add(entity); } } - 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; - } - } - - 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"); - } - - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); + readZoneNBT(nbt, 300); + this.radius = nbt.getFloat("radius"); + this.damagePerSecond = nbt.getFloat("damagePerSecond"); + setDamageInterval(nbt.getInteger("damageInterval")); + this.affectsCaster = nbt.getBoolean("affectsCaster"); } public float getRadius() { @@ -448,60 +119,6 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.radius = radius; } - 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; } @@ -510,68 +127,18 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.damagePerSecond = damagePerSecond; } + @Override + public float getDisplayDamage() { return damagePerSecond; } + + @Override + public boolean isDisplayDamageDPS() { return true; } + 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; + this.damageInterval = Math.max(EntityAbilityZone.MIN_DAMAGE_INTERVAL, damageInterval); } public boolean isAffectsCaster() { @@ -582,87 +149,35 @@ public class AbilityHazard extends Ability implements IAbilityHazard { 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; - } - @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) + .range(EntityAbilityZone.MIN_DAMAGE_INTERVAL, 2000) ), - 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.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 deleted file mode 100644 index d913fe586..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ /dev/null @@ -1,318 +0,0 @@ -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.TelegraphType; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; - -import noppes.npcs.client.gui.builder.FieldDef; -import noppes.npcs.api.ability.type.IAbilityHeal; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Heal ability: Restore health to self or allies. - * Can heal a fixed amount or percentage of max health. - */ -public class AbilityHeal extends Ability implements IAbilityHeal { - - // Type-specific parameters - private int durationTicks = 60; - private float healAmount = 10.0f; - private float healPercent = 0.0f; - private boolean healSelf = true; - private boolean healAllies = false; - private float healRadius = 0.0f; - private boolean instantHeal = true; - - // Runtime state - private transient List healedAllies; - - private List getHealedAllies() { - if (healedAllies == null) { - healedAllies = new ArrayList<>(); - } - return healedAllies; - } - - public AbilityHeal() { - this.typeId = "ability.cnpc.heal"; - this.name = "Heal"; - this.targetingMode = TargetingMode.SELF; - this.lockMovement = LockMovementType.WINDUP; - this.cooldownTicks = 0; - this.windUpTicks = 30; - // No telegraph for heal - it's a self/ally buff - this.telegraphType = TelegraphType.NONE; - this.showTelegraph = false; - } - - @Override - public boolean hasDamage() { - return false; - } - - @Override - public boolean allowBurst() { - return false; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.SELF}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) return; - - 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); - } - - if (instantHeal) { - // Instant heal - apply all healing now - if (healSelf) { - healEntity(caster); - spawnHealParticles(world, caster); - } - - for (EntityLivingBase ally : getHealedAllies()) { - healEntity(ally); - spawnHealParticles(world, ally); - } - } - } - - if (instantHeal) { - // Instant heal completes immediately - signalCompletion(); - } - // If not instant, HoT healing is applied in onActiveTick - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if ((world.isRemote && !isPreview()) || instantHeal) return; - - // Heal over time - distribute heal across duration ticks - if (tick % 10 == 0) { - // Calculate tick-based heal for fixed amount - float tickHeal = (healAmount / (float) durationTicks) * 10; - - if (healSelf) { - float selfTickHeal = tickHeal; - // Add percentage-based heal portion - if (healPercent > 0) { - selfTickHeal += (caster.getMaxHealth() * healPercent / (float) durationTicks) * 10; - } - caster.heal(selfTickHeal); - if (tick % 20 == 0) { - spawnHealParticles(world, caster); - } - } - - if (healAllies && healRadius > 0) { - for (EntityLivingBase ally : getHealedAllies()) { - if (!ally.isDead) { - float allyTickHeal = tickHeal; - // Add percentage-based heal portion for each ally - if (healPercent > 0) { - allyTickHeal += (ally.getMaxHealth() * healPercent / (float) durationTicks) * 10; - } - ally.heal(allyTickHeal); - if (tick % 20 == 0) { - spawnHealParticles(world, ally); - } - } - } - } - } - - // Check if heal duration has ended - if (tick >= durationTicks) { - signalCompletion(); - } - } - - /** - * Find all allies in radius and add them to healedAllies list. - */ - private void findAlliesInRadius(EntityLivingBase caster, World world) { - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox( - caster.posX - healRadius, caster.posY - 2, caster.posZ - healRadius, - caster.posX + healRadius, caster.posY + 3, caster.posZ + healRadius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, aabb); - - for (Entity entity : entities) { - if (!(entity instanceof EntityLivingBase)) continue; - if (entity == caster) continue; - - EntityLivingBase living = (EntityLivingBase) entity; - - // Only heal other NPCs (allies) - if (living instanceof EntityNPCInterface) { - float dist = caster.getDistanceToEntity(living); - if (dist <= healRadius) { - getHealedAllies().add(living); - } - } - } - } - - private void healEntity(EntityLivingBase entity) { - float totalHeal = healAmount; - if (healPercent > 0) { - totalHeal += entity.getMaxHealth() * healPercent; - } - entity.heal(totalHeal); - } - - private void spawnHealParticles(World world, EntityLivingBase entity) { - for (int i = 0; i < 10; i++) { - double offsetX = (world.rand.nextDouble() - 0.5) * entity.width; - double offsetY = world.rand.nextDouble() * entity.height; - double offsetZ = (world.rand.nextDouble() - 0.5) * entity.width; - world.spawnParticle("happyVillager", - entity.posX + offsetX, - entity.posY + offsetY, - entity.posZ + offsetZ, - 0, 0.1, 0); - } - } - - @Override - public void cleanup() { - getHealedAllies().clear(); - } - - @Override - public float getTelegraphRadius() { - return healRadius > 0 ? healRadius : 0; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); - nbt.setFloat("healAmount", healAmount); - nbt.setFloat("healPercent", healPercent); - nbt.setBoolean("healSelf", healSelf); - nbt.setBoolean("healAllies", healAllies); - nbt.setFloat("healRadius", healRadius); - nbt.setBoolean("instantHeal", instantHeal); - } - - @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"); - } - - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } - - public float getHealAmount() { - return healAmount; - } - - public void setHealAmount(float healAmount) { - this.healAmount = healAmount; - } - - public float getHealPercent() { - return healPercent; - } - - public void setHealPercent(float healPercent) { - this.healPercent = healPercent; - } - - public boolean isHealSelf() { - return healSelf; - } - - public void setHealSelf(boolean healSelf) { - this.healSelf = healSelf; - } - - public boolean isHealAllies() { - return healAllies; - } - - public void setHealAllies(boolean healAllies) { - this.healAllies = healAllies; - } - - public float getHealRadius() { - return healRadius; - } - - public void setHealRadius(float healRadius) { - this.healRadius = healRadius; - } - - public boolean isInstantHeal() { - return instantHeal; - } - - public void setInstantHeal(boolean instantHeal) { - this.instantHeal = instantHeal; - } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - FieldDef.boolField("ability.instantHeal", this::isInstantHeal, this::setInstantHeal) - .hover("ability.hover.instant"), - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) - .range(1, 1000).visibleWhen(() -> !this.isInstantHeal()), - FieldDef.section("ability.section.healing"), - FieldDef.row( - FieldDef.floatField("ability.healAmount", this::getHealAmount, this::setHealAmount), - FieldDef.floatField("ability.healPercent", this::getHealPercent, this::setHealPercent) - ), - FieldDef.floatField("ability.healRadius", this::getHealRadius, this::setHealRadius), - FieldDef.row( - FieldDef.boolField("ability.healSelf", this::isHealSelf, this::setHealSelf) - .hover("ability.hover.healSelf"), - FieldDef.boolField("ability.healAllies", this::isHealAllies, this::setHealAllies) - .hover("ability.hover.healAllies") - ) - )); - } -} 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 dd5d5fc09..56458b1ab 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 @@ -3,16 +3,17 @@ 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.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; 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; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; @@ -28,6 +29,8 @@ 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 hitDelayTicks = 0; + private int activeDisplayTicks = 10; // How long active animation plays before completing public AbilityHeavyHit() { this.typeId = "ability.cnpc.heavy_hit"; @@ -35,7 +38,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.targetingMode = TargetingMode.AOE_SELF; this.maxRange = 5.0f; this.minRange = 0.0f; - this.lockMovement = LockMovementType.WINDUP; + this.lockMovement = LockMode.WINDUP; this.cooldownTicks = 0; this.windUpTicks = 30; this.telegraphType = TelegraphType.LINE; @@ -44,6 +47,11 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.activeSound = "random.anvil_land"; this.windUpAnimationName = "Ability_HeavyHit_Windup"; this.activeAnimationName = "Ability_HeavyHit_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/heavy_hit.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/heavy_hit_overlay.png", + this::getActiveColor) + }; } @Override @@ -67,13 +75,27 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) { + signalCompletion(); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (isPreview()) { + if (tick >= (activeDisplayTicks + hitDelayTicks)) + signalCompletion(); + + return; + } + + if (tick >= (activeDisplayTicks + hitDelayTicks)) { signalCompletion(); return; } - if (!isPreview()) { + if (tick == hitDelayTicks && !caster.worldObj.isRemote) { // Calculate forward and right vectors from caster yaw float yawRad = (float) Math.toRadians(caster.rotationYaw); double forwardX = -Math.sin(yawRad); @@ -84,13 +106,14 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { // Search area: AABB that encompasses the rectangle float searchDist = Math.max(hitLength, hitWidth) + 1.0f; @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity( + 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; + if (!AbilityTargetHelper.shouldAffect(caster, livingTarget, TargetFilter.ENEMIES, false)) continue; double dx = livingTarget.posX - caster.posX; double dz = livingTarget.posZ - caster.posZ; @@ -103,6 +126,10 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { double sideDist = dx * rightX + dz * rightZ; if (Math.abs(sideDist) > hitWidth) continue; + // Line-of-sight check: skip targets behind solid blocks or enemy barriers + if (!hasLineOfSight(caster.worldObj, caster, livingTarget)) continue; + if (isBlockedByBarrier(caster.worldObj, caster, livingTarget)) continue; + // Entity is within the rectangle - apply damage boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); if (wasHit) { @@ -113,32 +140,29 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { // Play hit sound even if nothing was hit (the attack still happens) if (!anyHit) { - world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + 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) - signalCompletion(); - } - @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("damage", damage); nbt.setFloat("knockback", knockback); nbt.setFloat("hitLength", hitLength); nbt.setFloat("hitWidth", hitWidth); + nbt.setInteger("activeDisplayTicks", activeDisplayTicks); + nbt.setInteger("hitDelayTicks", hitDelayTicks); } @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.hitDelayTicks = nbt.getInteger("hitDelayTicks"); + this.activeDisplayTicks = nbt.getInteger("activeDisplayTicks"); } // Getters & Setters @@ -150,6 +174,9 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getKnockback() { return knockback; } @@ -174,6 +201,22 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.hitWidth = hitWidth; } + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; + } + + public int getHitDelayTicks() { + return hitDelayTicks; + } + + public void setHitDelayTicks(int hitDelayTicks) { + this.hitDelayTicks = hitDelayTicks; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { @@ -187,6 +230,11 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { FieldDef.floatField("ability.hitLength", this::getHitLength, this::setHitLength), FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) ), + FieldDef.section("ability.section.timing"), + FieldDef.row( + FieldDef.intField("ability.hitDelayTicks", this::getHitDelayTicks, this::setHitDelayTicks).min(0), + 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 deleted file mode 100644 index afffa9c13..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ /dev/null @@ -1,324 +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.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.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityLaser; -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 net.minecraft.world.World; -import noppes.npcs.api.ability.type.IAbilityLaserShot; - -import java.util.Arrays; -import java.util.List; - -/** - * Laser Shot ability: Fast expanding thin line that pierces through targets. - * Travels in a straight line from origin, damaging all entities it passes through. - */ -public class AbilityLaserShot extends Ability 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.FRONT); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Transient state for laser entity (used for movement locking) - private transient EntityAbilityLaser laserEntity = null; - - public AbilityLaserShot() { - this.typeId = "ability.cnpc.laser_shot"; - this.name = "Laser Shot"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 35.0f; - this.minRange = 3.0f; - 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"; - } - - @Override - public boolean allowOverlap() { - return true; - } - - @Override - public boolean isTargetingModeLocked() { - return false; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public float getTelegraphLength() { - return lifespanData.maxDistance; - } - - @Override - public float getTelegraphWidth() { - return laserWidth * 2.0f; // Make telegraph slightly wider for visibility - } - - /** - * Spawn laser entity. - * NPC: target is the aggro target — laser expands toward it. - * Player: target is null — laser expands in caster's look direction. - */ - private EntityAbilityLaser spawnLaserEntity(EntityLivingBase caster, EntityLivingBase target, World world) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - EntityAbilityLaser entity = new EntityAbilityLaser( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - laserWidth, - colorData, combatData, lightningData, lifespanData, trajectoryData, - expansionSpeed, lingerTicks - ); - entity.setEffects(this.effects); - entity.setSourceAbility(this); - spawnAbilityEntity(world, entity); - return entity; - } - - private void fireLaserEntity(EntityAbilityLaser laser, EntityLivingBase target) { - if (laser == null || laser.isDead) return; - laser.setLockVerticalDirection(true); - laser.startMoving(target); - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - laserEntity = spawnLaserEntity(caster, target, world); - if (isPreview()) { - laserEntity.setupPreview(caster, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); - } else { - laserEntity.setupCharging(anchorData, windUpTicks); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - laserEntity = spawnLaserEntity(caster, target, world); - fireLaserEntity(laserEntity, target); - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (laserEntity == null) { - signalCompletion(); - return; - } - - fireLaserEntity(laserEntity, target); - } - - @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(); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn laser entity if still alive - if (laserEntity != null && !laserEntity.isDead) { - laserEntity.setDead(); - } - laserEntity = null; - } - - @Override - public void writeTypeNBT(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); - } - - // Getters & Setters - Standalone fields - 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 - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; - } - - @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.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), - FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .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") - )); - } -} 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..020b8e8e3 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java @@ -0,0 +1,302 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.play.server.S12PacketEntityVelocity; +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 = 8; + 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; + } + + @Override + public void resetForBurst() { + 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 or solid barriers. + * + * @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) + || isMovementBlockedByBarrier(caster, movementDirection.xCoord, movementDirection.zCoord, speed); + } + + // ═══════════════════════════════════════════════════════════════════ + // VELOCITY APPLICATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Send an authoritative velocity packet to a player. + *

+ * The ability tick runs BEFORE moveEntityWithHeading (at PlayerTickEvent.START). + * If we use velocityChanged, the entity tracker sends S12 AFTER friction has + * reduced the motion (~55% of set value). The client then moves at reduced speed, + * reports a short position via C04, and the server resets to the client's position. + *

+ * By sending S12 manually here — before friction — the client receives the full + * velocity and moves at the correct speed. + */ + protected void sendPlayerVelocity(EntityLivingBase caster) { + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } + } + + /** + * Apply horizontal momentum and sync to client. + */ + protected void applyHorizontalMomentum(EntityLivingBase caster, double motionX, double motionZ) { + caster.motionX = motionX; + caster.motionZ = motionZ; + if (!isPreview()) { + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } + } + } + + /** + * Apply movement velocity to the caster (horizontal only, Y unchanged). + */ + protected void applyVelocity(EntityLivingBase caster, float speed) { + applyHorizontalMomentum(caster, movementDirection.xCoord * speed, movementDirection.zCoord * speed); + } + + /** + * Apply movement velocity with zero vertical motion. + * Used for ground-locked movement like Charge. + * motionY is set BEFORE sending velocity packet to prevent client-server desync + * (which causes "moved too fast" kicks when used in mid-air). + */ + protected void applyVelocityFlat(EntityLivingBase caster, float speed) { + caster.motionY = 0; + applyHorizontalMomentum(caster, movementDirection.xCoord * speed, movementDirection.zCoord * speed); + } + + /** + * Stop all horizontal momentum. + */ + protected void stopMomentum(EntityLivingBase caster) { + applyHorizontalMomentum(caster, 0, 0); + } + + // ═══════════════════════════════════════════════════════════════════ + // 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 deleted file mode 100644 index 17b878305..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ /dev/null @@ -1,650 +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.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.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 java.util.Arrays; -import java.util.List; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; - -/** - * 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 { - - private static final int MAX_PROJECTILES = 8; - - // Orb properties - private float orbSize = 1.0f; - - // Projectile count and fire stagger - private int projectileCount = 1; - private int fireDelay = 0; - - // Shared visual data (all projectiles use these) - private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Shared combat/movement data - private final EnergyCombatData combatData = new EnergyCombatData(); - private final EnergyHomingData homingData = new EnergyHomingData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(); - - // Per-projectile data (anchor + optional color override) - private ProjectileData[] projectiles; - - // Transient entity state - private transient EntityAbilityOrb[] orbEntities; - - public AbilityOrb() { - this.typeId = "ability.cnpc.orb"; - this.name = "Orb"; - 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; - this.windUpAnimationName = "Ability_Orb_Windup"; - this.activeAnimationName = "Ability_Orb_Active"; - initProjectiles(1); - } - - private 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)); - } - } - - private AnchorPoint getDefaultAnchor(int index) { - switch (index) { - case 0: return AnchorPoint.RIGHT_HAND; - case 1: return AnchorPoint.LEFT_HAND; - default: return AnchorPoint.FRONT; - } - } - - public void setProjectileCount(int count) { - int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - if (newCount == projectileCount) return; - - ProjectileData[] oldProjectiles = projectiles; - initProjectiles(newCount); - - // Preserve existing projectile data - 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); - } - - // Legacy compat - public int getDualFireDelay() { return fireDelay; } - public void setDualFireDelay(int delay) { setFireDelay(delay); } - - @Override - 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(10); - a.setBurstReplayAnimations(false); - a.setBurstOverlap(true); - a.setWindUpAnimationName("Ability_BeamDual_Windup"); - a.setActiveAnimationName("Ability_BeamDual_Active"); - }) - ); - } - - @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}; - } - - /** - * Create orb entities. - * NPC: target is the aggro target — orbs will home toward it. - * Player: target is null — orbs fire in caster's look direction. - */ - private EntityAbilityOrb[] createOrbEntities(EntityLivingBase caster, EntityLivingBase target, World world) { - EntityAbilityOrb[] entities = new EntityAbilityOrb[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - entities[i] = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - resolved, combatData, homingData, lightningData, lifespanData, trajectoryData); - entities[i].setEffects(this.effects); - entities[i].setSourceAbility(this); - } - if (projectileCount == 2 && entities[0] != null && entities[1] != null) { - entities[0].setSiblingEntityId(entities[1].getEntityId()); - entities[1].setSiblingEntityId(entities[0].getEntityId()); - } - return entities; - } - - private void fireOrbEntity(EntityAbilityOrb orb, EntityLivingBase target) { - if (orb == null || orb.isDead) return; - if (isPreview()) { - orb.startPreviewFiring(); - } else { - orb.startMoving(target); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - orbEntities = createOrbEntities(caster, target, world); - for (int i = 0; i < projectileCount; i++) { - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - if (isPreview()) { - orbEntities[i].setupPreview(caster, orbSize, resolved, lightningData, projectiles[i].anchor, windUpTicks); - } else { - orbEntities[i].setupCharging(projectiles[i].anchor, windUpTicks); - } - spawnAbilityEntity(world, orbEntities[i]); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - orbEntities = createOrbEntities(caster, target, world); - for (EntityAbilityOrb orb : orbEntities) { - spawnAbilityEntity(world, orb); - } - for (EntityAbilityOrb orb : orbEntities) { - fireOrbEntity(orb, target); - } - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (orbEntities == null) return; - - // Fire first projectile immediately - fireOrbEntity(orbEntities[0], target); - - // Fire remaining projectiles if no delay - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireOrbEntity(orbEntities[i], target); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (orbEntities == null) { - signalCompletion(); - return; - } - - // Fire staggered projectiles - if (fireDelay > 0) { - for (int i = 1; i < projectileCount; i++) { - if (tick == fireDelay * i) { - fireOrbEntity(orbEntities[i], target); - } - } - } - - // Check if all entities are dead - boolean allDead = true; - for (EntityAbilityOrb orb : orbEntities) { - if (orb != null && !orb.isDead) { - allDead = false; - break; - } - } - if (allDead) { - 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() { - if (orbEntities != null) { - for (int i = 0; i < orbEntities.length; i++) { - if (orbEntities[i] != null && !orbEntities[i].isDead) { - orbEntities[i].setDead(); - } - orbEntities[i] = null; - } - } - orbEntities = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - // NPC: telegraph on aggro target position - // Player: no telegraph (orbs fire in look direction, no fixed position to mark) - if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { - return null; - } - - 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); - - 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("projectileCount", projectileCount); - nbt.setInteger("fireDelay", fireDelay); - - // Shared visual data - displayData.writeNBT(nbt); - lightningData.writeNBT(nbt); - - // Shared combat/movement data - 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); - } - - // Backward compat write - nbt.setFloat("orbSpeed", homingData.speed); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; - initProjectiles(count); - - // Read fireDelay with fallback to old dualFireDelay key - if (nbt.hasKey("fireDelay")) { - this.fireDelay = nbt.getInteger("fireDelay"); - } else if (nbt.hasKey("dualFireDelay")) { - this.fireDelay = nbt.getInteger("dualFireDelay"); - } else { - this.fireDelay = 0; - } - - // Shared combat/movement data - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - // Determine format and read accordingly - if (nbt.hasKey("Projectile_0")) { - NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); - if (proj0.hasKey("colorOverride")) { - // NEW format: shared visuals at root + ProjectileData per projectile - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } - } else { - // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) - // Read primary visuals from Projectile_0 - displayData.readNBT(proj0); - lightningData.readNBT(proj0); - projectiles[0].anchor.readNBT(proj0); - - // Read remaining projectiles, set color override if colors differ - for (int i = 1; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); - projectiles[i].anchor.readNBT(projNbt); - - // Check if this projectile had different colors - EnergyDisplayData tempDisplay = new EnergyDisplayData(); - tempDisplay.readNBT(projNbt); - if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { - projectiles[i].colorOverride = true; - projectiles[i].innerColor = tempDisplay.innerColor; - projectiles[i].outerColor = tempDisplay.outerColor; - } - } - } - } - } else { - // LEGACY flat format: all data at root level - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - projectiles[0].anchor.readNBT(nbt); - } - - // Backward compat - if (nbt.hasKey("orbSpeed")) { - homingData.speed = nbt.getFloat("orbSpeed"); - } - } - - // ═══════════════════════════════════════════════════════════════════ - // API GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ - - public float getOrbSpeed() { return homingData.speed; } - public void setOrbSpeed(float speed) { homingData.speed = speed; } - - public float getOrbSize() { return orbSize; } - public void setOrbSize(float size) { this.orbSize = size; } - - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float d) { lifespanData.maxDistance = d; } - - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } - - public float getDamage() { return combatData.damage; } - public void setDamage(float d) { combatData.damage = d; } - - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float k) { combatData.knockback = k; } - - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float k) { combatData.knockbackUp = k; } - - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean h) { homingData.homing = h; } - - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float s) { homingData.homingStrength = s; } - - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float r) { homingData.homingRange = r; } - - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean e) { combatData.explosive = e; } - - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float r) { combatData.explosionRadius = r; } - - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } - - // Shared display data (primary colors) - public int getInnerColor() { return displayData.innerColor; } - public void setInnerColor(int c) { displayData.innerColor = c; } - - public int getOuterColor() { return displayData.outerColor; } - public void setOuterColor(int c) { displayData.outerColor = c; } - - public float getOuterColorWidth() { return displayData.outerColorWidth; } - public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } - - public float getOuterColorAlpha() { return displayData.outerColorAlpha; } - public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } - - public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } - public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } - - public float getRotationSpeed() { return displayData.rotationSpeed; } - public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } - - // Shared lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } - - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float d) { lightningData.lightningDensity = d; } - - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float r) { lightningData.lightningRadius = r; } - - public int getLightningFadeTime() { return lightningData.lightningFadeTime; } - public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } - - // Anchor - default to projectile 0 - public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } - public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } - - 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; } - - 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; } - - private int clampIndex(int index) { - return Math.max(0, Math.min(index, projectileCount - 1)); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - // Type tab - projectile count and fire delay - 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) - )); - - // Type tab - orb properties - 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)); - - // Visual tab - shared 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")); - - // Visual tab - shared 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")); - - // 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)); - - // Anchor point - 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), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) - ).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)); - - // 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/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index 8abd5d01e..3caabc678 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 @@ -3,20 +3,17 @@ 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.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; 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; - import noppes.npcs.api.ability.type.IAbilityProjectile; - import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import java.util.Arrays; import java.util.List; @@ -45,7 +42,7 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { this.maxRange = 20.0f; this.cooldownTicks = 0; this.windUpTicks = 15; - this.lockMovement = LockMovementType.NO; + this.lockMovement = LockMode.NO; // No telegraph for projectile - it's a ranged attack this.telegraphType = TelegraphType.NONE; this.showTelegraph = false; @@ -67,18 +64,18 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { + 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, world); + executePlayerProjectile(caster, caster.worldObj); } else if (target != null) { // NPC: instant hit-scan on aggro target - executeNpcProjectile(caster, target, world); + executeNpcProjectile(caster, target, caster.worldObj); } signalCompletion(); @@ -94,7 +91,20 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { 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; + } + + // A rotation-locked NPC cannot turn to follow the target, so it can only hit what its + // frozen heading still covers - the same cone the player hit scan uses. + if (isRotationLockedForCurrentPhase()) { + Vec3 look = caster.getLookVec(); + if (look != null && (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) < 0.95) { + return; + } + } applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); @@ -167,7 +177,7 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { * Apply explosion splash damage around a point. */ private void applyExplosionDamage(EntityLivingBase caster, EntityLivingBase primaryTarget, World world, - double x, double y, double z) { + double x, double y, double z) { @SuppressWarnings("unchecked") List entities = world.getEntitiesWithinAABBExcludingEntity(primaryTarget, primaryTarget.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); @@ -250,7 +260,7 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } @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 } @@ -273,14 +283,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 @@ -292,6 +302,9 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getSpeed() { return speed; } 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 6788a3ea3..c5e860c09 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 @@ -3,19 +3,17 @@ 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.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; 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.world.World; -import noppes.npcs.entity.EntityNPCInterface; - -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityShockwave; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; @@ -29,14 +27,15 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { private float pushRadius = 8.0f; private float pushStrength = 1.5f; private float damage = 8.0f; - private int maxTargets = 10; + private boolean aoe = true; + private int activeDisplayTicks = 10; public AbilityShockwave() { this.typeId = "ability.cnpc.shockwave"; this.name = "Shockwave"; this.targetingMode = TargetingMode.AOE_SELF; - this.maxRange = 15.0f; - this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.maxRange = 8.0f; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; this.cooldownTicks = 0; this.windUpTicks = 25; this.telegraphType = TelegraphType.CIRCLE; @@ -44,6 +43,11 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.activeSound = "random.explode"; this.windUpAnimationName = "Ability_Shockwave_Windup"; this.activeAnimationName = "Ability_Shockwave_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/shockwave.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/shockwave_overlay.png", + this::getActiveColor) + }; } @Override @@ -62,58 +66,91 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (!isPreview()) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (!isPreview() && !caster.worldObj.isRemote) { // 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); + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + if (aoe) { + // ALL: push every valid enemy in range + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist > pushRadius) continue; + double dist = caster.getDistanceToEntity(entity); + if (dist > pushRadius) continue; - 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); - - 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); + applyShockwavePush(caster, entity, dist); + } + } else { + // SINGULAR: push one target + // NPC: push aggro target if valid, otherwise nearest enemy + // Player: push nearest enemy in range + if (!isPlayerCaster(caster) && target != null && !target.isDead) { + double dist = caster.getDistanceToEntity(target); + if (dist <= pushRadius && AbilityTargetHelper.shouldAffect(caster, target, TargetFilter.ENEMIES, false)) { + applyShockwavePush(caster, target, dist); + return; + } } - // 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); + // Find nearest valid enemy + EntityLivingBase nearest = null; + double nearestDist = Double.MAX_VALUE; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; - // Apply effects if hit connected - if (wasHit) { - applyEffects(entity); + double dist = caster.getDistanceToEntity(entity); + if (dist <= pushRadius && dist < nearestDist) { + nearest = entity; + nearestDist = dist; + } + } + if (nearest != null) { + applyShockwavePush(caster, nearest, nearestDist); } } } } + private void applyShockwavePush(EntityLivingBase caster, EntityLivingBase entity, double dist) { + // 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); + } + + // 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); + } + } + @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(); } @@ -122,15 +159,17 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { nbt.setFloat("pushRadius", pushRadius); nbt.setFloat("pushStrength", pushStrength); nbt.setFloat("damage", damage); - nbt.setInteger("maxTargets", maxTargets); + nbt.setBoolean("aoe", aoe); + 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.aoe = !nbt.hasKey("aoe") || nbt.getBoolean("aoe"); + this.activeDisplayTicks = nbt.hasKey("activeDisplayTicks") ? nbt.getInteger("activeDisplayTicks") : 10; } // Getters & Setters @@ -158,12 +197,23 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.damage = damage; } - public int getMaxTargets() { - return maxTargets; + @Override + public float getDisplayDamage() { return damage; } + + public boolean isAoe() { + return aoe; } - public void setMaxTargets(int maxTargets) { - this.maxTargets = maxTargets; + public void setAoe(boolean aoe) { + this.aoe = aoe; + } + + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; } @SideOnly(Side.CLIENT) @@ -176,7 +226,10 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { FieldDef.floatField("gui.radius", this::getPushRadius, this::setPushRadius), FieldDef.floatField("gui.strength", this::getPushStrength, this::setPushStrength) ), - FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets), + FieldDef.section("ability.section.aoe"), + FieldDef.boolField("gui.enabled", this::isAoe, this::setAoe) + .hover("ability.hover.aoe"), + 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 a03ecdf6a..9e917d2d2 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 @@ -3,23 +3,25 @@ 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.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +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 net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.play.server.S12PacketEntityVelocity; import net.minecraft.util.DamageSource; import net.minecraft.world.World; +import noppes.npcs.api.ability.type.IAbilitySlam; +import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.api.ability.type.IAbilitySlam; -import somehussar.gui.annotationHandling.GuiEditable; - -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import java.util.Arrays; import java.util.List; @@ -41,12 +43,30 @@ public class AbilitySlam extends Ability implements IAbilitySlam { private float leapSpeed = 1.0f; private float leapHeight = 4.0f; + /** + * Grace period (in active ticks) before landing detection activates. + * Players need more time because: + * - Server sets motionY and sends S12 velocity packet to client + * - Client receives S12 and starts moving upward + * - Client sends C03 position packet back to server with onGround=false + * Until the round trip completes, the server's player.onGround (from stale C03) + * remains true, which would falsely trigger landing detection. + */ + private static final int PLAYER_LANDING_GRACE_TICKS = 10; + private static final int NPC_LANDING_GRACE_TICKS = 3; + // Runtime state private transient double targetX, targetY, targetZ; + private transient double startY; // Y position at launch for rise detection private transient boolean hasLaunched = false; private transient boolean hasLanded = false; + private transient boolean hasRisen = false; // Whether entity has risen above launch position private transient int airTicks = 0; private transient int maxAirTicks = 60; // Timeout to prevent stuck in air + private transient boolean airSlam = false; // True when slam initiated while already in the air + private transient double airSlamStartY = 0; // Start height for air-slam damage scaling + private transient boolean wasFlying = false; // Restore player flight after air slam + private transient double peakY = 0; // Maximum Y position during arc (for height scaling) public AbilitySlam() { this.typeId = "ability.cnpc.slam"; @@ -54,7 +74,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { this.targetingMode = TargetingMode.AOE_SELF; // Can also be AOE_TARGET to leap to target this.windUpTicks = 30; this.cooldownTicks = 0; - this.lockMovement = LockMovementType.WINDUP; + this.lockMovement = LockMode.WINDUP; this.minRange = 2.0f; this.maxRange = 15.0f; this.telegraphType = TelegraphType.CIRCLE; @@ -63,6 +83,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { // Default built-in animations this.windUpAnimationName = "Ability_Slam_Windup"; this.activeAnimationName = "Ability_Slam_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/slam.png") + }; } /** @@ -84,12 +107,22 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (isPlayerCaster(caster)) { - // Player: slam will launch from current position, no target tracking needed - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; + // 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) { @@ -98,17 +131,20 @@ public class AbilitySlam extends Ability implements IAbilitySlam { targetZ = caster.posZ; } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { targetX = target.posX; - targetY = target.posY; + targetY = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ, 64); targetZ = target.posZ; } } } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; + startY = caster.posY; + peakY = caster.posY; caster.fallDistance = 0; if (isPlayerCaster(caster)) { @@ -128,7 +164,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { targetZ = caster.posZ; } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { targetX = target.posX; - targetY = target.posY; + targetY = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ, 64); targetZ = target.posZ; } else { targetX = caster.posX; @@ -139,18 +175,79 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } /** - * Player slam: Launch straight up. Player controls horizontal movement via WASD. - * AOE damage triggers wherever the player lands. + * Player slam: behavior depends on whether the player is on the ground or in the air. + *

+ * On ground: Launch in look direction using ballistic arc, full damage on landing. + * In air: Slam straight down from current height, damage scales with fall distance. + * Works regardless of flying state — position is forced downward each tick. */ private void executePlayerSlam(EntityLivingBase caster) { - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; + // Determine if this qualifies as an air slam (at least 3 blocks above ground) + boolean isAirborne = !caster.onGround; + boolean highEnoughForAirSlam = false; - double vy = calculateLaunchVelocity(Math.max(1.0, leapHeight)); - caster.motionY = vy; - hasLaunched = true; - caster.velocityChanged = true; + if (isAirborne) { + double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ, 64); + highEnoughForAirSlam = (caster.posY - groundY) >= 3.0; + } + + if (isAirborne && highEnoughForAirSlam) { + // Air slam: player is already airborne (flying, falling, jumping) and high enough + airSlam = true; + airSlamStartY = caster.posY; + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + + // If the player is flying, temporarily disable it so gravity/velocity apply normally. + if (caster instanceof EntityPlayerMP) { + EntityPlayerMP mp = (EntityPlayerMP) caster; + wasFlying = mp.capabilities.isFlying; + if (wasFlying) { + mp.capabilities.isFlying = false; + mp.sendPlayerAbilities(); + } + } + + hasLaunched = true; + hasRisen = true; // Skip rise detection — we're already above ground + + // Start descent smoothly; physics/collision handles exact landing surface. + // Only damp horizontal drift when movement is locked during ACTIVE. + if (isMovementLockedDuringActive()) { + caster.motionX *= 0.25; + caster.motionZ *= 0.25; + } + caster.motionY = Math.min(caster.motionY, -0.2); + + if (!isPreview()) { + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } else { + caster.velocityChanged = true; + } + caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + } + } else { + // Ground slam: normal ballistic arc (also used when airborne but not high enough) + airSlam = false; + airSlamStartY = 0; + wasFlying = false; + + // 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); + + double launchDist = Math.max(4.0, maxRange * 0.5); + + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + + launchTowardTarget(caster); + } } /** @@ -214,7 +311,12 @@ public class AbilitySlam extends Ability implements IAbilitySlam { ((EntityNPCInterface) caster).setNpcJumpingState(true); } if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } else { + caster.velocityChanged = true; + } caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); } return; @@ -262,7 +364,14 @@ public class AbilitySlam extends Ability implements IAbilitySlam { ((EntityNPCInterface) caster).setNpcJumpingState(true); } if (!isPreview()) { - caster.velocityChanged = true; + // Use direct S12 packet for players to ensure velocity reaches client + // before flight code can override it + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } else { + caster.velocityChanged = true; + } } // Face the target @@ -272,10 +381,14 @@ 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; + boolean playerCaster = isPlayerCaster(caster); + boolean activeMovementLocked = isMovementLockedDuringActive(); + boolean forceHorizontalControl = !playerCaster || activeMovementLocked; + airTicks++; // Continuously reset fall distance during slam to prevent fall damage @@ -283,27 +396,104 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.fallDistance = 0; } - // Check for landing - if (caster.onGround && airTicks > 3) { - // Landed! - onLanding(caster, world); - return; + // Track peak height for damage scaling + if (caster.posY > peakY) { + peakY = caster.posY; + } + + // Air slam: accelerate descent smoothly via velocity; landing uses normal collision. + if (airSlam && !isPreview() && !hasLanded) { + if (forceHorizontalControl) { + caster.motionX *= 0.2; + caster.motionZ *= 0.2; + } + double nextMotionY = caster.motionY - 0.18; + caster.motionY = Math.max(-1.6, nextMotionY); + if (caster instanceof EntityPlayerMP) { + // Only push authoritative velocity every tick when ACTIVE movement is locked. + if (forceHorizontalControl) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } + } else { + caster.velocityChanged = true; + } + } + + // Prevent NPC navigator from interfering with ballistic arc. + // lockMovement=WINDUP means applyMovementControl() doesn't clear + // the navigator during ACTIVE, so AI pathfinding could add motion. + if (!isPreview() && caster instanceof EntityNPCInterface) { + ((EntityNPCInterface) caster).getNavigator().clearPathEntity(); + } + + // Check if slam trajectory is blocked by a solid barrier + if (!isPreview() && !caster.worldObj.isRemote) { + double moveX = caster.motionX; + double moveZ = caster.motionZ; + double hSpeed = Math.sqrt(moveX * moveX + moveZ * moveZ); + if (hSpeed > 0.01) { + double normX = moveX / hSpeed; + double normZ = moveZ / hSpeed; + if (isMovementBlockedByBarrier(caster, normX, normZ, hSpeed)) { + caster.motionX = 0; + caster.motionZ = 0; + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } else { + caster.velocityChanged = true; + } + } + } + } + + // Track if entity has risen above launch position. + // This prevents premature landing detection for players, where + // server-side caster.onGround remains true from stale C03 packets + // until the velocity S12 round-trip completes (can take 4-8+ ticks). + if (!hasRisen && caster.posY > startY + 0.5) { + hasRisen = true; + } + + // Landing detection uses different grace periods for NPC vs Player. + // NPCs: server physics is authoritative, onGround is accurate after 3 ticks. + // Players: onGround depends on C03 packets, needs longer grace + rise confirmation. + int graceTicks = isPlayerCaster(caster) ? PLAYER_LANDING_GRACE_TICKS : NPC_LANDING_GRACE_TICKS; + if (airTicks > graceTicks) { + if (hasRisen && (caster.onGround || caster.isCollidedHorizontally)) { + onLanding(caster, caster.worldObj); + return; + } + // Safety: if entity hasn't risen after triple the grace period, + // the launch may have failed (blocked by ceiling, etc.) - force landing + if (!hasRisen && airTicks > graceTicks * 3) { + onLanding(caster, caster.worldObj); + return; + } } // Timeout protection - force landing after max air time if (airTicks >= maxAirTicks) { - onLanding(caster, world); + onLanding(caster, caster.worldObj); return; } - // NPC: face toward target destination while in air - // Player: free look — player controls their own camera - if (!isPreview() && !isPlayerCaster(caster)) { - 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 destination while in air unless player ACTIVE movement is unlocked. + // Unlocked players keep free horizontal drift/look control. + if (!isPreview()) { + if (forceHorizontalControl) { + 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 (playerCaster) { + caster.velocityChanged = true; + } + } + } } } @@ -315,13 +505,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam { if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } + restoreFlightIfNeeded(caster); - // Signal that the ability has completed its active phase - signalCompletion(); - - // Stop horizontal momentum - caster.motionX = 0; - caster.motionZ = 0; + // Stop horizontal momentum only when movement is controlled by the ability. + if (!isPlayerCaster(caster) || isMovementLockedDuringActive()) { + caster.motionX = 0; + caster.motionZ = 0; + } if (!isPreview()) { // Reset fall distance to prevent fall damage on landing @@ -335,6 +525,29 @@ public class AbilitySlam extends Ability implements IAbilitySlam { // Play slam impact sound on landing world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f); + // Scale damage based on height for both air and ground slams + float effectiveDamage = damage; + float heightMultiplier = 1.0f; + if (airSlam) { + // Air slam: scale based on total fall distance + double fallDistance = airSlamStartY - caster.posY; + if (fallDistance < 0) fallDistance = 0; + float heightFactor = (float) Math.min(1.0, fallDistance / Math.max(1.0, leapHeight)); + heightMultiplier = Math.max(0.25f, heightFactor); + effectiveDamage = damage * heightMultiplier; + } else { + // Ground slam: scale based on arc height reached + double arcHeight = peakY - startY; + if (arcHeight > 0) { + float heightFactor = (float) Math.min(1.0, arcHeight / Math.max(1.0, leapHeight)); + heightMultiplier = Math.max(0.25f, heightFactor); + effectiveDamage = damage * heightMultiplier; + } + } + + // Set multiplier so extenders (e.g. DBC Addon) can apply height scaling to their own damage calc + setDamageMultiplier(heightMultiplier); + // Find all entities in radius @SuppressWarnings("unchecked") List entities = world.getEntitiesWithinAABBExcludingEntity( @@ -343,19 +556,28 @@ public class AbilitySlam extends Ability implements IAbilitySlam { for (Entity entity : entities) { if (entity instanceof EntityLivingBase && entity != caster) { EntityLivingBase livingTarget = (EntityLivingBase) entity; + if (!AbilityTargetHelper.shouldAffect(caster, livingTarget, TargetFilter.ENEMIES, false)) continue; // Check if actually within radius (bounding box is a cube, we want a circle) double dx = livingTarget.posX - caster.posX; double dz = livingTarget.posZ - caster.posZ; if (dx * dx + dz * dz <= radius * radius) { // Apply damage with scripted event support - applyAbilityDamage(caster, livingTarget, damage, knockbackStrength); + boolean wasHit = applyAbilityDamage(caster, livingTarget, effectiveDamage, knockbackStrength); + if (wasHit) { + applyEffects(livingTarget); + } } } } + setDamageMultiplier(1.0f); // Reset after damage loop + // Spawn particles spawnSlamParticles(world, caster.posX, caster.posY, caster.posZ); + + // Signal completion AFTER damage — signalCompletion triggers onComplete which resets state + signalCompletion(); } /** @@ -399,9 +621,15 @@ public class AbilitySlam extends Ability implements IAbilitySlam { if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } + restoreFlightIfNeeded(caster); hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; + airSlam = false; + airSlamStartY = 0; + peakY = 0; + wasFlying = false; } @Override @@ -409,9 +637,28 @@ public class AbilitySlam extends Ability implements IAbilitySlam { if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } + restoreFlightIfNeeded(caster); hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; + airSlam = false; + airSlamStartY = 0; + peakY = 0; + wasFlying = false; + } + + @Override + public void cleanup() { + // Caster may be unavailable here; flight restoration is handled in onComplete/onInterrupt. + hasLaunched = false; + hasLanded = false; + hasRisen = false; + airTicks = 0; + airSlam = false; + airSlamStartY = 0; + peakY = 0; + wasFlying = false; } @Override @@ -419,7 +666,25 @@ public class AbilitySlam extends Ability implements IAbilitySlam { super.reset(); hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; + airSlam = false; + airSlamStartY = 0; + peakY = 0; + wasFlying = false; + } + + /** + * Restore player flight if it was disabled for an air slam. + */ + private void restoreFlightIfNeeded(EntityLivingBase caster) { + if (airSlam && wasFlying && caster instanceof EntityPlayerMP) { + EntityPlayerMP mp = (EntityPlayerMP) caster; + if (!mp.capabilities.isFlying) { + mp.capabilities.isFlying = true; + mp.sendPlayerAbilities(); + } + } } @Override @@ -452,8 +717,8 @@ public class AbilitySlam extends Ability implements IAbilitySlam { targetZ = caster.posZ; } - // Create telegraph at the appropriate position - double groundY = findGroundLevel(caster.worldObj, targetX, targetY, targetZ); + // Create telegraph at the appropriate position — always project to actual ground for landing zone + double groundY = findGroundLevel(caster.worldObj, targetX, targetY, targetZ, 64); Telegraph telegraph = Telegraph.circle(radius); telegraph.setDurationTicks(windUpTicks); @@ -461,6 +726,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { telegraph.setWarningColor(activeColor); telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); telegraph.setHeightOffset(telegraphHeightOffset); + telegraph.setGroundSearchRange(64); // Slam always projects to actual ground (landing zone) TelegraphInstance instance = new TelegraphInstance(telegraph, targetX, groundY, targetZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); @@ -490,11 +756,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 @@ -506,6 +772,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getRadius() { return radius; } 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 8e09c43e7..d22150c9e 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 @@ -1,9 +1,14 @@ 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.ability.UserType; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -13,15 +18,8 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; - import noppes.npcs.api.ability.type.IAbilityTeleport; - import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import java.util.Arrays; import java.util.List; @@ -43,10 +41,14 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { @Override public String toString() { switch (this) { - case BLINK: return "ability.teleport.blink"; - case BEHIND: return "ability.teleport.behind"; - case SINGLE: return "ability.teleport.single"; - default: return name(); + case BLINK: + return "ability.teleport.blink"; + case BEHIND: + return "ability.teleport.behind"; + case SINGLE: + return "ability.teleport.single"; + default: + return name(); } } } @@ -78,17 +80,15 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.minRange = 5.0f; this.cooldownTicks = 0; this.windUpTicks = 10; - this.lockMovement = LockMovementType.NO; + this.lockMovement = LockMode.NO; // No telegraph for teleport - it's instant repositioning this.telegraphType = TelegraphType.NONE; this.showTelegraph = false; this.windUpSound = "mob.endermen.portal"; this.activeSound = "mob.endermen.portal"; - } - - @Override - public boolean hasDamage() { - return false; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/teleport.png") + }; } @Override @@ -102,13 +102,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(); @@ -118,7 +118,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { ticksSinceLastBlink++; if (ticksSinceLastBlink >= blinkDelayTicks) { - performBlink(caster, target, world); + performBlink(caster, target, caster.worldObj); currentBlink++; ticksSinceLastBlink = 0; @@ -394,6 +394,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { for (Entity entity : entities) { if (!(entity instanceof EntityLivingBase)) continue; if (entity == caster) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; EntityLivingBase living = (EntityLivingBase) entity; double dist = Math.sqrt(Math.pow(living.posX - x, 2) + Math.pow(living.posZ - z, 2)); @@ -435,33 +436,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.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 @@ -548,6 +536,9 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getDamageRadius() { return damageRadius; } 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 494192e04..1c40b202e 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,58 +1,25 @@ 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.TelegraphInstance; -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.world.World; -import noppes.npcs.entity.EntityNPCInterface; - -import noppes.npcs.api.ability.type.IAbilityTrap; - -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.data.energy.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 noppes.npcs.api.ability.type.IAbilityTrap; +import noppes.npcs.client.gui.SubGuiTrapPresetSelector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.constants.EnumPotionType; +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; @@ -62,240 +29,184 @@ 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.allowedBy = UserType.NPC_ONLY; + this.windUpTicks = 30; + this.windUpAnimationName = "Ability_Zone_Windup"; + this.activeAnimationName = "Ability_Zone_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/trap.png", + this::getActiveColor) + }; } @Override - public boolean allowBurst() { - return false; - } - - @Override - public boolean isTargetingModeLocked() { + public boolean isConcurrentCapable() { 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: - 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: - 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]; - 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; - } - - if (!isPreview()) { - 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, + isIgnoreIFrames(), + colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, + zoneHeight, + particleDensity, particleScale, animSpeed, lightningDensity, + visible, + getEffects()); + entity.setSourceAbility(this); + + 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 AbilityPotionEffect(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 AbilityPotionEffect(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 AbilityPotionEffect(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 AbilityPotionEffect(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 AbilityPotionEffect(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); @@ -304,67 +215,19 @@ 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"); - } - - // 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; - } - - @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; + 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"); } public float getTriggerRadius() { @@ -407,6 +270,9 @@ public class AbilityTrap extends Ability implements IAbilityTrap { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getDamageRadius() { return damageRadius; } @@ -431,63 +297,39 @@ public class AbilityTrap extends Ability implements IAbilityTrap { 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; + @SideOnly(Side.CLIENT) + @Override + protected void addPresetFieldDef(List defs) { + defs.add(SubGuiTrapPresetSelector.createPresetField(this::applyTrapPresetDefaults)); } @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( @@ -497,5 +339,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 90aaf054b..8f9b3f3a0 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 @@ -1,27 +1,29 @@ 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.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; 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.AxisAlignedBB; 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; import noppes.npcs.api.ability.type.IAbilityVortex; +import noppes.npcs.client.gui.builder.FieldDef; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.player.EntityPlayer; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; +import java.util.HashMap; import java.util.List; -import java.util.Set; -import java.util.UUID; +import java.util.Map; /** * Vortex ability: Pulls targets toward the caster. @@ -33,19 +35,30 @@ public class AbilityVortex extends Ability implements IAbilityVortex { private float pullStrength = 0.8f; private float damage = 0.0f; private float knockback = 0.0f; - private boolean aoe = false; - private int maxTargets = 5; + private boolean aoe = true; private boolean damageOnPull = false; private float pullDamage = 0.0f; - // Runtime state - private transient Set pulledEntities; + // Runtime state — keyed by entity ID (not UUID, since cloned NPCs share UUIDs) + private transient Map pulledEntities; private transient boolean pullComplete = false; private transient int ticksSincePullDamage = 0; - private Set getPulledEntities() { + private static class PullState { + double lastX, lastY, lastZ; + int stuckTicks; + + PullState(EntityLivingBase entity) { + this.lastX = entity.posX; + this.lastY = entity.posY; + this.lastZ = entity.posZ; + this.stuckTicks = 0; + } + } + + private Map getPulledEntities() { if (pulledEntities == null) { - pulledEntities = new HashSet<>(); + pulledEntities = new HashMap<>(); } return pulledEntities; } @@ -55,12 +68,16 @@ public class AbilityVortex extends Ability implements IAbilityVortex { this.name = "Vortex"; this.targetingMode = TargetingMode.AOE_SELF; this.maxRange = 15.0f; - this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; this.cooldownTicks = 0; this.windUpTicks = 30; this.telegraphType = TelegraphType.CIRCLE; this.windUpSound = "mob.ghast.charge"; this.activeSound = "mob.ghast.fireball"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/vortex.png", + this::getActiveColor) + }; } @Override @@ -79,44 +96,62 @@ 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 (!isPreview()) { - if (aoe) { - AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + if (!isPreview() && !caster.worldObj.isRemote) { + AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); + @SuppressWarnings("unchecked") + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; + if (aoe) { + // ALL: pull every valid enemy in range for (EntityLivingBase entity : entities) { if (entity == caster) continue; if (entity.isDead) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; double dist = caster.getDistanceToEntity(entity); if (dist <= pullRadius) { - getPulledEntities().add(entity.getUniqueID()); - count++; - if (count >= maxTargets) break; + getPulledEntities().put(entity.getEntityId(), new PullState(entity)); } } } else { - // NPC single-target mode: pull the aggro target - // Player: single-target mode has no effect (no target to pull — use AOE mode instead) + // SINGULAR: pull one random target within range + // NPC: pull aggro target if valid, otherwise random enemy + // Player: pull random enemy in range if (!isPlayerCaster(caster) && target != null && !target.isDead) { double dist = caster.getDistanceToEntity(target); if (dist <= pullRadius) { - getPulledEntities().add(target.getUniqueID()); + getPulledEntities().put(target.getEntityId(), new PullState(target)); + return; } } + + // Collect all valid enemies, then pick one at random + List validTargets = new ArrayList<>(); + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; + + double dist = caster.getDistanceToEntity(entity); + if (dist <= pullRadius) { + validTargets.add(entity); + } + } + if (!validTargets.isEmpty()) { + EntityLivingBase chosen = validTargets.get(caster.worldObj.rand.nextInt(validTargets.size())); + getPulledEntities().put(chosen.getEntityId(), new PullState(chosen)); + } } } } @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(); @@ -128,17 +163,41 @@ public class AbilityVortex extends Ability implements IAbilityVortex { return; } + if (caster.worldObj.isRemote) return; + + // Safety cap: force-complete if active too long + int maxActiveTicks = Math.max(40, (int)(pullRadius / pullStrength * 3)); + if (tick >= maxActiveTicks) { + for (Map.Entry entry : new HashMap<>(getPulledEntities()).entrySet()) { + EntityLivingBase entity = findEntity(caster.worldObj, entry.getKey()); + if (entity != null && !entity.isDead) { + onTargetArrived(caster, entity, caster.worldObj); + } + } + getPulledEntities().clear(); + pullComplete = true; + signalCompletion(); + return; + } + double destX = caster.posX; double destY = caster.posY; double destZ = caster.posZ; boolean anyStillPulling = false; ticksSincePullDamage++; + boolean shouldDealPullDamage = damageOnPull && pullDamage > 0 && ticksSincePullDamage >= 10; + if (shouldDealPullDamage) { + ticksSincePullDamage = 0; + } - for (UUID uuid : new HashSet<>(getPulledEntities())) { - EntityLivingBase entity = findEntity(caster, world, uuid); + for (Map.Entry entry : new HashMap<>(getPulledEntities()).entrySet()) { + int entityId = entry.getKey(); + PullState state = entry.getValue(); + + EntityLivingBase entity = findEntity(caster.worldObj, entityId); if (entity == null || entity.isDead) { - getPulledEntities().remove(uuid); + getPulledEntities().remove(entityId); continue; } @@ -147,36 +206,64 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double dz = destZ - entity.posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= 1.5f) { - getPulledEntities().remove(uuid); - onTargetArrived(caster, entity, world); + if (dist <= 1.5) { + getPulledEntities().remove(entityId); + onTargetArrived(caster, entity, caster.worldObj); + continue; + } + + // Stuck detection: check if entity made progress since last tick + double lastDx = destX - state.lastX; + double lastDy = destY - state.lastY; + double lastDz = destZ - state.lastZ; + double lastDist = Math.sqrt(lastDx * lastDx + lastDy * lastDy + lastDz * lastDz); + double progress = lastDist - dist; // positive = entity moved closer + + double expectedProgress = Math.min(pullStrength, dist * 0.5); + if (progress < expectedProgress * 0.3) { + state.stuckTicks++; + } else { + state.stuckTicks = 0; + } + + if (state.stuckTicks >= 5) { + // Entity is stuck (wall, block, partial obstruction) - treat as arrived + getPulledEntities().remove(entityId); + onTargetArrived(caster, entity, caster.worldObj); continue; } anyStillPulling = true; + // Record position BEFORE movement so next tick's stuck detection + // can measure the actual progress (pull + AI movement combined) + state.lastX = entity.posX; + state.lastY = entity.posY; + state.lastZ = entity.posZ; + // Clamp speed to never exceed half the remaining distance, preventing overshoot/slingshot double maxSpeed = dist * 0.5; double effectiveSpeed = Math.min(pullStrength, maxSpeed); double factor = effectiveSpeed / dist; - double nextX = dx * factor; - double nextY = dy * factor * 0.5; - double nextZ = dz * factor; + double motionX = dx * factor; + double motionY = dy * factor * 0.5; + double motionZ = dz * factor; - AxisAlignedBB nextBox = entity.boundingBox.copy().offset(nextX, nextY, nextZ); - if (!world.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) { - getPulledEntities().remove(uuid); - continue; + if (entity instanceof EntityPlayer) { + // Players: send velocity packet — client applies movement + entity.motionX = motionX; + entity.motionY = motionY; + entity.motionZ = motionZ; + entity.velocityChanged = true; + } else { + // NPCs/mobs: directly apply movement with collision detection. + // Setting motionX alone is unreliable because the entity's AI tick + // (moveFlying/moveEntityWithHeading) can override the velocity before + // moveEntity runs, depending on entity tick order relative to the caster. + entity.moveEntity(motionX, motionY, motionZ); } - entity.motionX = nextX; - entity.motionY = nextY; - entity.motionZ = nextZ; - entity.velocityChanged = true; - - if (damageOnPull && pullDamage > 0 && ticksSincePullDamage >= 10) { - ticksSincePullDamage = 0; - entity.hurtResistantTime = 0; + if (shouldDealPullDamage) { applyAbilityDamage(caster, entity, pullDamage * 0.5f, 0); } } @@ -198,19 +285,12 @@ public class AbilityVortex extends Ability implements IAbilityVortex { } /** - * Find an entity by UUID within the vortex pull area. - * Uses AABB search instead of iterating all loaded entities. + * Find an entity by entity ID. */ - @SuppressWarnings("unchecked") - private EntityLivingBase findEntity(EntityLivingBase caster, World world, UUID uuid) { - // Search within pull radius (entities being pulled should be within this area) - AxisAlignedBB searchBox = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); - List nearbyEntities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); - - for (EntityLivingBase entity : nearbyEntities) { - if (entity.getUniqueID().equals(uuid)) { - return entity; - } + private EntityLivingBase findEntity(World world, int entityId) { + Entity entity = world.getEntityByID(entityId); + if (entity instanceof EntityLivingBase) { + return (EntityLivingBase) entity; } return null; } @@ -229,21 +309,19 @@ public class AbilityVortex extends Ability implements IAbilityVortex { nbt.setFloat("damage", damage); nbt.setFloat("knockback", knockback); nbt.setBoolean("aoe", aoe); - nbt.setInteger("maxTargets", maxTargets); nbt.setBoolean("damageOnPull", damageOnPull); nbt.setFloat("pullDamage", pullDamage); } @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.hasKey("aoe") || nbt.getBoolean("aoe"); + this.damageOnPull = nbt.getBoolean("damageOnPull"); + this.pullDamage = nbt.getFloat("pullDamage"); } // Getters & Setters @@ -271,6 +349,9 @@ public class AbilityVortex extends Ability implements IAbilityVortex { this.damage = damage; } + @Override + public float getDisplayDamage() { return damage; } + public float getKnockback() { return knockback; } @@ -287,14 +368,6 @@ public class AbilityVortex extends Ability implements IAbilityVortex { this.aoe = aoe; } - public int getMaxTargets() { - return maxTargets; - } - - public void setMaxTargets(int maxTargets) { - this.maxTargets = maxTargets; - } - public boolean isDamageOnPull() { return damageOnPull; } @@ -327,8 +400,6 @@ public class AbilityVortex extends Ability implements IAbilityVortex { FieldDef.section("ability.section.aoe"), FieldDef.boolField("gui.enabled", this::isAoe, this::setAoe) .hover("ability.hover.aoe"), - FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets) - .visibleWhen(this::isAoe), FieldDef.section("ability.section.pullDamage"), FieldDef.boolField("gui.enabled", this::isDamageOnPull, this::setDamageOnPull) .hover("ability.hover.dmgOnPull"), 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..a2f9fdeb7 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -0,0 +1,765 @@ +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.data.effect.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +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 net.minecraft.util.DamageSource; +import noppes.npcs.client.gui.SubGuiZonePresetSelector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.constants.EnumPotionType; + +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 = LockMode.WINDUP; + this.cooldownTicks = 0; + this.allowedBy = UserType.BOTH; + } + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + activeEntities.clear(); + preCalculatedPositions.clear(); + } + + @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) { + // Free on Cast: complete immediately — zones live independently + if (isFreeOnCast()) { + signalCompletion(); + return; + } + + 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 AbilityPotionEffect(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 AbilityPotionEffect(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 AbilityPotionEffect(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 AbilityPotionEffect(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 AbilityPotionEffect(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 float getInnerAlpha() { + return colorData.innerAlpha; + } + + public void setInnerAlpha(float alpha) { + colorData.innerAlpha = alpha; + } + + public float getOuterColorWidth() { + return colorData.outerColorWidth; + } + + public void setOuterColorWidth(float width) { + colorData.outerColorWidth = width; + } + + public float getOuterColorAlpha() { + return colorData.outerColorAlpha; + } + + public void setOuterColorAlpha(float alpha) { + colorData.outerColorAlpha = alpha; + } + + 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(SubGuiZonePresetSelector.createPresetField(this::applyPresetDefaults)); + } + + @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.row( + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor), + FieldDef.floatField("ability.innerAlpha", this::getInnerAlpha, this::setInnerAlpha).range(0, 1) + ).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") + )); + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java new file mode 100644 index 000000000..1e3df2e02 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java @@ -0,0 +1,424 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.controllers.data.MagicData; + +import java.util.List; + +/** + * Abstract base for energy barrier abilities (Dome, Wall, Shield). + * Handles shared visual data, barrier configuration, and lifecycle management. + */ +public abstract class AbilityBarrier extends AbilityEnergy { + + protected final EnergyBarrierData barrierData; + + // Spawn position offsets (relative to caster) + protected float offsetX = 0.0f; + protected float offsetY = 0.0f; + protected float offsetZ = 0.0f; + + // Runtime entity tracking + protected transient EntityEnergyBarrier barrierEntity; + + protected AbilityBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) { + super(displayData); + this.barrierData = barrierData; + } + + // ==================== ABSTRACT METHODS ==================== + + /** + * Create and spawn the barrier entity during execution. + */ + protected abstract EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); + + /** + * Add type-specific GUI field definitions. + */ + @SideOnly(Side.CLIENT) + protected abstract void addBarrierTypeDefinitions(List defs); + + /** + * Write type-specific fields to NBT. + */ + protected abstract void writeBarrierTypeNBT(NBTTagCompound nbt); + + /** + * Read type-specific fields from NBT. + */ + protected abstract void readBarrierTypeNBT(NBTTagCompound nbt); + + // ==================== LIFECYCLE ==================== + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean hasDamage() { + return false; // Barriers are defensive + } + + @Override + public boolean hasMagic() { + return true; // Barriers use magic for defense interactions + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + barrierEntity = null; + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (caster.worldObj.isRemote) return; + + if (tick == 1) { + barrierEntity = createBarrierEntity(caster, target); + if (barrierEntity != null) { + inheritMagicData(barrierEntity, caster); + applyBarrierHealthModifiers(caster); + barrierEntity.setupCharging(getWindUpTicks()); + spawnAbilityEntity(barrierEntity); + } + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (barrierEntity != null && !barrierEntity.isDead) { + // Barrier was spawned during windup — transition to active + barrierEntity.finishCharging(); + } else { + // No windup or entity died — create fresh + barrierEntity = createBarrierEntity(caster, target); + if (barrierEntity != null) { + inheritMagicData(barrierEntity, caster); + applyBarrierHealthModifiers(caster); + spawnAbilityEntity(barrierEntity); + } + } + } + + private void inheritMagicData(EntityEnergyBarrier entity, EntityLivingBase caster) { + MagicData resolved = resolveMagicData(caster); + if (resolved != null) { + entity.setMagicData(resolved.copy()); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (barrierEntity == null || barrierEntity.isDead) { + signalCompletion(); + return; + } + + // Free on Cast: complete immediately after barrier becomes active + if (isFreeOnCast()) { + signalCompletion(); + return; + } + + // Duration tracked by entity itself, but check here too as a failsafe + if (barrierData.useDuration && tick >= barrierData.durationTicks) { + cleanup(); + signalCompletion(); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + } + + /** + * Allow extenders to modify the barrier's max health at spawn time. + */ + private void applyBarrierHealthModifiers(EntityLivingBase caster) { + float modHealth = AbilityController.Instance.fireModifyBarrierHealth(this, caster, barrierData.maxHealth); + if (modHealth != barrierData.maxHealth) { + barrierEntity.setBarrierMaxHealth(modHealth); + } + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + if (barrierEntity != null && !barrierEntity.isDead) { + barrierEntity.setDead(); + } + barrierEntity = null; + } + + // ==================== NBT ==================== + + @Override + public final void writeTypeNBT(NBTTagCompound nbt) { + writeBarrierTypeNBT(nbt); + writeEnergyNBT(nbt); + barrierData.writeNBT(nbt); + nbt.setFloat("barrierOffsetX", offsetX); + nbt.setFloat("barrierOffsetY", offsetY); + nbt.setFloat("barrierOffsetZ", offsetZ); + } + + @Override + public final void readTypeNBT(NBTTagCompound nbt) { + offsetX = nbt.hasKey("barrierOffsetX") ? nbt.getFloat("barrierOffsetX") : 0.0f; + offsetY = nbt.hasKey("barrierOffsetY") ? nbt.getFloat("barrierOffsetY") : 0.0f; + offsetZ = nbt.hasKey("barrierOffsetZ") ? nbt.getFloat("barrierOffsetZ") : 0.0f; + readBarrierTypeNBT(nbt); + readEnergyNBT(nbt); + barrierData.readNBT(nbt); + } + + // ==================== API GETTERS & SETTERS ==================== + + // Display and lightning data inherited from AbilityEnergy + + // Barrier data + public float getBarrierMaxHealth() { + return barrierData.maxHealth; + } + + public void setBarrierMaxHealth(float maxHealth) { + barrierData.setMaxHealth(maxHealth); + } + + public boolean isUseHealth() { + return barrierData.useHealth; + } + + public void setUseHealth(boolean useHealth) { + barrierData.useHealth = useHealth; + } + + @Override + public float getDisplayBarrierHealth() { return barrierData.useHealth ? barrierData.maxHealth : 0; } + + @Override + public boolean isDisplayReflect() { return barrierData.reflect; } + + @Override + public float getDisplayReflectStrength() { return barrierData.reflectStrengthPct; } + + @Override + public boolean isDisplayAbsorbing() { return barrierData.absorbing; } + + public int getBarrierDuration() { + return barrierData.durationTicks; + } + + public void setBarrierDuration(int ticks) { + barrierData.setDurationTicks(ticks); + } + + public boolean isUseDuration() { + return barrierData.useDuration; + } + + public void setUseDuration(boolean useDuration) { + barrierData.useDuration = useDuration; + } + + public float getDefaultMultiplier() { + return barrierData.defaultMultiplier; + } + + public void setDefaultMultiplier(float mult) { + barrierData.defaultMultiplier = mult; + } + + public void setDamageMultiplier(String typeId, float mult) { + barrierData.setMultiplier(typeId, mult); + } + + public float getDamageMultiplier(String typeId) { + return barrierData.getMultiplier(typeId); + } + + // Solid data + public boolean isSolid() { + return barrierData.solid; + } + + public void setSolid(boolean solid) { + barrierData.solid = solid; + } + + // Knockback data + public boolean isKnockbackEnabled() { + return barrierData.knockbackEnabled; + } + + public void setKnockbackEnabled(boolean enabled) { + barrierData.knockbackEnabled = enabled; + } + + public float getKnockbackStrength() { + return barrierData.knockbackStrength; + } + + public void setKnockbackStrength(float strength) { + barrierData.knockbackStrength = strength; + } + + // Absorbing data + public boolean isAbsorbing() { + return barrierData.absorbing; + } + + public void setAbsorbing(boolean absorbing) { + barrierData.absorbing = absorbing; + } + + public float getAbsorbRadius() { + return barrierData.absorbRadius; + } + + public void setAbsorbRadius(float radius) { + barrierData.absorbRadius = radius; + } + + // Reflection data + public boolean isReflect() { + return barrierData.reflect; + } + + public void setReflect(boolean reflect) { + barrierData.reflect = reflect; + } + + public float getReflectStrengthPct() { + return barrierData.reflectStrengthPct; + } + + public void setReflectStrengthPct(float strengthPct) { + barrierData.setReflectStrengthPct(strengthPct); + } + + public boolean isTargetOwner() { + return barrierData.targetOwner; + } + + public void setTargetOwner(boolean targetOwner) { + barrierData.targetOwner = targetOwner; + } + + // Melee data + public boolean isMeleeEnabled() { + return barrierData.meleeEnabled; + } + + public void setMeleeEnabled(boolean enabled) { + barrierData.meleeEnabled = enabled; + } + + public float getMeleeDamageMultiplier() { + return barrierData.meleeDamageMultiplier; + } + + public void setMeleeDamageMultiplier(float mult) { + barrierData.meleeDamageMultiplier = mult; + } + + // Offset data + public float getOffsetX() { + return offsetX; + } + + public void setOffsetX(float offsetX) { + this.offsetX = offsetX; + } + + public float getOffsetY() { + return offsetY; + } + + public void setOffsetY(float offsetY) { + this.offsetY = offsetY; + } + + public float getOffsetZ() { + return offsetZ; + } + + public void setOffsetZ(float offsetZ) { + this.offsetZ = offsetZ; + } + + // ==================== GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + public final void getAbilityDefinitions(List defs) { + // Type-specific fields first + addBarrierTypeDefinitions(defs); + + // Offset section + defs.add(FieldDef.section("ability.section.offset")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.offsetX", this::getOffsetX, this::setOffsetX).min(Float.NEGATIVE_INFINITY), + FieldDef.floatField("ability.offsetY", this::getOffsetY, this::setOffsetY).min(Float.NEGATIVE_INFINITY) + )); + defs.add(FieldDef.floatField("ability.offsetZ", this::getOffsetZ, this::setOffsetZ).min(Float.NEGATIVE_INFINITY)); + + // Barrier section + defs.add(FieldDef.section("ability.section.barrier")); + defs.add(FieldDef.boolField("ability.useHealth", this::isUseHealth, this::setUseHealth)); + defs.add(FieldDef.floatField("ability.maxHealth", this::getBarrierMaxHealth, this::setBarrierMaxHealth) + .visibleWhen(this::isUseHealth)); + defs.add(FieldDef.boolField("ability.useDuration", this::isUseDuration, this::setUseDuration)); + defs.add(FieldDef.intField("ability.duration", this::getBarrierDuration, this::setBarrierDuration) + .range(1, 12000).visibleWhen(this::isUseDuration)); + defs.add(FieldDef.floatField("ability.defaultMultiplier", this::getDefaultMultiplier, this::setDefaultMultiplier)); + + // Properties section + defs.add(FieldDef.section("ability.section.properties")); + defs.add(FieldDef.boolField("ability.solid", this::isSolid, this::setSolid) + .hover("ability.hover.solid")); + defs.add(FieldDef.boolField("ability.knockbackEnabled", this::isKnockbackEnabled, this::setKnockbackEnabled) + .hover("ability.hover.knockbackEnabled")); + defs.add(FieldDef.floatField("ability.knockbackStrength", this::getKnockbackStrength, this::setKnockbackStrength) + .range(0, 10).visibleWhen(this::isKnockbackEnabled)); + defs.add(FieldDef.boolField("ability.absorbing", this::isAbsorbing, this::setAbsorbing) + .hover("ability.hover.absorbing")); + defs.add(FieldDef.floatField("ability.absorbRadius", this::getAbsorbRadius, this::setAbsorbRadius) + .range(-1, 128).visibleWhen(this::isAbsorbing) + .hover("ability.hover.absorbRadius")); + defs.add(FieldDef.boolField("ability.reflect", this::isReflect, this::setReflect) + .hover("ability.hover.reflect")); + defs.add(FieldDef.floatField("ability.reflectStrength", this::getReflectStrengthPct, this::setReflectStrengthPct) + .range(0, 100).visibleWhen(this::isReflect)); + defs.add(FieldDef.boolField("ability.targetOwner", this::isTargetOwner, this::setTargetOwner) + .hover("ability.hover.targetOwner") + .visibleWhen(this::isReflect)); + defs.add(FieldDef.boolField("ability.meleeEnabled", this::isMeleeEnabled, this::setMeleeEnabled) + .hover("ability.hover.meleeEnabled")); + defs.add(FieldDef.floatField("ability.meleeDamageMultiplier", this::getMeleeDamageMultiplier, this::setMeleeDamageMultiplier) + .range(0, 10).visibleWhen(this::isMeleeEnabled)); + + // Visual tab - colors + effects (from AbilityEnergy) + addEnergyVisualDefinitions(defs); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java new file mode 100644 index 000000000..f811cef9e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java @@ -0,0 +1,241 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.HitType; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.RotationMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.ProjectileData; +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.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; +import noppes.npcs.api.ability.type.IAbilityEnergyBeam; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Energy Beam ability: A homing head with a trailing path. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. + */ +public class AbilityBeam extends AbilityEnergyProjectile implements IAbilityEnergyBeam { + + private float beamWidth = 0.4f; + private float headSize = 0.6f; + private boolean freeAim = false; + + public AbilityBeam() { + super( + new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 10.0f), + new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f, HitType.SINGLE, 5), + new EnergyHomingData(0.4f, true, 0.1f, 15.0f), + new EnergyLifespanData(150.0f, 200) + ); + this.typeId = "ability.cnpc.beam"; + this.name = "Beam"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 20.0f; + this.minRange = 5.0f; + this.cooldownTicks = 0; + this.windUpTicks = 40; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.LOCKED; + this.rotationPhase = LockMode.ACTIVE; + this.telegraphType = TelegraphType.CIRCLE; + this.showTelegraph = true; + this.windUpAnimationName = "Ability_Beam_Windup"; + this.activeAnimationName = "Ability_Beam_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/beam.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityBeam createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + EntityAbilityBeam beam = new EntityAbilityBeam( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + beamWidth, headSize, + resolved, combatData, homingData, lightningData, lifespanData, + lockMovement.locksActive()); + beam.setFreeAim(freeAim); + return beam; + } + + @Override + protected void fireEntity(EntityAbilityBeam beam, EntityLivingBase target) { + if (isPreview()) { + beam.startPreviewFiring(); + } else { + beam.startFiring(target); + } + } + + @Override + protected void setupEntityCharging(EntityAbilityBeam beam, ProjectileData projData, int index) { + beam.setupCharging(projData.anchor, windUpTicks, 1.0f); + } + + @Override + 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 + protected EntityAbilityBeam[] createEntityArray(int size) { + return new EntityAbilityBeam[size]; + } + + @Override + public void detach() { + if (entities != null) { + for (EntityAbilityBeam beam : entities) { + if (beam != null && !beam.isDead) { + beam.setAttachedToOwner(false); + } + } + } + super.detach(); + } + + @Override + protected float getProjectileTelegraphRadius() { + return headSize * 2.0f; + } + + @Override + 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); + nbt.setBoolean("freeAim", freeAim); + } + + @Override + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.beamWidth = nbt.getFloat("beamWidth"); + this.headSize = nbt.getFloat("headSize"); + this.freeAim = nbt.getBoolean("freeAim"); + } + + // ==================== 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; + } + + public boolean isFreeAim() { + return freeAim; + } + + public void setFreeAim(boolean freeAim) { + this.freeAim = freeAim; + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + 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.boolField("ability.freeAim", this::isFreeAim, this::setFreeAim) + .hover("ability.hover.freeAim") + .enabledWhen(() -> lockMovement.locksActive() && rotationMode == RotationMode.FREE && !freeOnCast)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth).range(0.1f, 100.0f), + FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize).range(0.1f, 100.0f) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) + )); + 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) + .range(0.0f, EnergyCombatData.MAX_EXPLOSION_RADIUS) + .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/energy/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java new file mode 100644 index 000000000..1d3dacc19 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java @@ -0,0 +1,240 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.HitType; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.ProjectileData; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityDisc; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; +import noppes.npcs.api.ability.type.IAbilityDisc; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * 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 AbilityEnergyProjectile implements IAbilityDisc { + + private float discRadius = 1.0f; + private float discThickness = 0.2f; + private boolean vertical = false; + private boolean boomerang = false; + private int boomerangDelay = 40; + + public AbilityDisc() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 10.0f), + new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f, HitType.PIERCE, 5), + new EnergyHomingData(0.6f, true, 0.12f, 18.0f), + new EnergyLifespanData(150.0f, 200) + ); + this.typeId = "ability.cnpc.disc"; + this.name = "Disc"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 30.0f; + this.minRange = 5.0f; + this.cooldownTicks = 0; + this.windUpTicks = 60; + this.lockMovement = LockMode.WINDUP; + this.telegraphType = TelegraphType.CIRCLE; + this.showTelegraph = true; + this.windUpAnimationName = "Ability_Disc_Windup"; + this.activeAnimationName = "Ability_Disc_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/disc.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/disc_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + 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, + boomerang, boomerangDelay); + } + + @Override + protected void fireEntity(EntityAbilityDisc disc, EntityLivingBase target) { + if (isPreview()) { + disc.startPreviewFiring(); + } else { + disc.startMoving(target); + } + } + + @Override + protected void setupEntityCharging(EntityAbilityDisc disc, ProjectileData projData, int index) { + disc.setupCharging(projData.anchor, windUpTicks, vertical); + } + + @Override + 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 + protected EntityAbilityDisc[] createEntityArray(int size) { + return new EntityAbilityDisc[size]; + } + + @Override + protected float getProjectileTelegraphRadius() { + return discRadius * 1.5f; + } + + // ==================== VARIANTS ==================== + + @Override + 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); + } + + @Override + 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"); + } + + // ==================== 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 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; + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + 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).range(0.1f, 100.0f), + FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness).range(0.05f, 100.0f) + )); + 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).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) + )); + 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) + .range(0.0f, EnergyCombatData.MAX_EXPLOSION_RADIUS) + .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/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java new file mode 100644 index 000000000..cacda2061 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -0,0 +1,145 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Energy Dome ability: Spawns a spherical barrier centered on the caster. + * Blocks incoming energy projectiles with configurable damage multipliers. + * Duration and/or HP based. + */ +public class AbilityDome extends AbilityBarrier { + + private float domeRadius = 5.0f; + private boolean followCaster = false; + + public AbilityDome() { + super( + new EnergyDisplayData(0x44CCFF, 0x2288FF, true, 0.3f, 0.35f, 0.5f, 0.0f), + new EnergyBarrierData(100.0f, true, 200, true) + ); + this.typeId = "ability.cnpc.dome"; + this.name = "Dome"; + this.targetingMode = TargetingMode.SELF; + this.cooldownTicks = 100; + this.windUpTicks = 30; + this.lockMovement = LockMode.WINDUP; + this.telegraphType = TelegraphType.RING; + this.showTelegraph = true; + this.windUpAnimationName = ""; + this.activeAnimationName = ""; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/dome.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + EntityEnergyDome dome = new EntityEnergyDome( + caster.worldObj, caster, + caster.posX + offsetX, caster.posY + offsetY, caster.posZ + offsetZ, + domeRadius, displayData.copy(), lightningData.copy(), barrierData.copy() + ); + dome.setFollowCaster(followCaster); + dome.setOffsets(offsetX, offsetY, offsetZ); + dome.setSourceAbility(this); + return dome; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.SELF}; + } + + @Override + public float getTelegraphRadius() { + return domeRadius; + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.small", a -> { + AbilityDome dome = (AbilityDome) a; + a.setName("Small Dome"); + dome.setDomeRadius(3.0f); + dome.setBarrierMaxHealth(60.0f); + }), + new AbilityVariant("ability.variant.large", a -> { + AbilityDome dome = (AbilityDome) a; + a.setName("Large Dome"); + dome.setDomeRadius(8.0f); + dome.setBarrierMaxHealth(200.0f); + dome.setBarrierDuration(300); + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeBarrierTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("domeRadius", domeRadius); + nbt.setBoolean("followCaster", followCaster); + } + + @Override + protected void readBarrierTypeNBT(NBTTagCompound nbt) { + this.domeRadius = nbt.hasKey("domeRadius") ? nbt.getFloat("domeRadius") : 5.0f; + this.followCaster = nbt.hasKey("followCaster") && nbt.getBoolean("followCaster"); + } + + // ==================== GETTERS & SETTERS ==================== + + public float getDomeRadius() { + return domeRadius; + } + + public void setDomeRadius(float radius) { + this.domeRadius = Math.max(1.0f, radius); + } + + public boolean isFollowCaster() { + return followCaster; + } + + public void setFollowCaster(boolean follow) { + this.followCaster = follow; + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + protected void addBarrierTypeDefinitions(List defs) { + defs.add(FieldDef.floatField("ability.domeRadius", this::getDomeRadius, this::setDomeRadius) + .range(1.0f, 50.0f)); + defs.add(FieldDef.boolField("ability.followCaster", this::isFollowCaster, this::setFollowCaster) + .hover("ability.hover.followCaster")); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergy.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergy.java new file mode 100644 index 000000000..461f3b50d --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergy.java @@ -0,0 +1,189 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +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.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for all energy-based abilities (Projectile, Barrier, Sweeper, etc.). + * Provides shared visual data (colors, lightning) and corresponding API/GUI/NBT. + */ +public abstract class AbilityEnergy extends Ability { + + protected EnergyDisplayData displayData; + protected EnergyLightningData lightningData; + + protected AbilityEnergy(EnergyDisplayData displayData) { + this.displayData = displayData; + this.lightningData = new EnergyLightningData(); + } + + // ==================== DISPLAY DATA ==================== + + public int getInnerColor() { + return displayData.innerColor; + } + + public void setInnerColor(int color) { + displayData.innerColor = color; + } + + public float getInnerAlpha() { + return displayData.innerAlpha; + } + + public void setInnerAlpha(float alpha) { + displayData.innerAlpha = alpha; + } + + public int getOuterColor() { + return displayData.outerColor; + } + + public void setOuterColor(int color) { + displayData.outerColor = color; + } + + public boolean isOuterColorEnabled() { + return displayData.outerColorEnabled; + } + + public void setOuterColorEnabled(boolean enabled) { + displayData.outerColorEnabled = enabled; + } + + public float getOuterColorWidth() { + return displayData.outerColorWidth; + } + + public void setOuterColorWidth(float width) { + displayData.outerColorWidth = width; + } + + public float getOuterColorAlpha() { + return displayData.outerColorAlpha; + } + + public void setOuterColorAlpha(float alpha) { + displayData.outerColorAlpha = alpha; + } + + public float getRotationSpeed() { + return displayData.rotationSpeed; + } + + public void setRotationSpeed(float speed) { + displayData.rotationSpeed = speed; + } + + // ==================== LIGHTNING DATA ==================== + + public boolean hasLightningEffect() { + return lightningData.lightningEffect; + } + + public void setLightningEffect(boolean enabled) { + lightningData.lightningEffect = enabled; + } + + public float getLightningDensity() { + return lightningData.lightningDensity; + } + + public void setLightningDensity(float density) { + lightningData.lightningDensity = density; + } + + public float getLightningRadius() { + return lightningData.lightningRadius; + } + + public void setLightningRadius(float radius) { + lightningData.lightningRadius = radius; + } + + public int getLightningFadeTime() { + return lightningData.lightningFadeTime; + } + + public void setLightningFadeTime(int fadeTime) { + lightningData.lightningFadeTime = fadeTime; + } + + // ==================== NBT HELPERS ==================== + + protected void writeEnergyNBT(NBTTagCompound nbt) { + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + } + + protected void readEnergyNBT(NBTTagCompound nbt) { + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + } + + // ==================== GUI HELPERS ==================== + + /** + * Add complete visual tab definitions (colors section + effects/lightning section). + * Subclasses can call this directly or use the individual methods for more control. + */ + @SideOnly(Side.CLIENT) + protected void addEnergyVisualDefinitions(List defs) { + addEnergyColorDefinitions(defs); + addEnergyEffectDefinitions(defs); + } + + /** + * Add the colors section to the visual tab. + */ + @SideOnly(Side.CLIENT) + protected void addEnergyColorDefinitions(List defs) { + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor), + FieldDef.floatField("ability.innerAlpha", this::getInnerAlpha, this::setInnerAlpha).range(0, 1) + ).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")); + } + + /** + * Add the effects section (lightning) to the visual tab. + * Override to insert additional fields before lightning (e.g., rotationSpeed). + */ + @SideOnly(Side.CLIENT) + protected void addEnergyEffectDefinitions(List defs) { + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + addEnergyLightningDefinitions(defs); + } + + /** + * Add just the lightning fields (no section header) to the visual tab. + */ + @SideOnly(Side.CLIENT) + protected void addEnergyLightningDefinitions(List defs) { + 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")); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java new file mode 100644 index 000000000..723781d36 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java @@ -0,0 +1,936 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.enums.HitType; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.ProjectileData; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker; +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.EntityEnergyProjectile; +import kamkeel.npcs.network.packets.data.energycharge.EnergyChargeRemovePacket; +import kamkeel.npcs.network.packets.data.energycharge.EnergyChargeSpawnPacket; +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 noppes.npcs.api.ability.type.IAbilityEnergyProjectile; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.controllers.data.MagicData; + +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 AbilityEnergyProjectile extends AbilityEnergy implements IAbilityEnergyProjectile { + + protected static final int MAX_PROJECTILES = 8; + + // Multi-projectile support + protected int projectileCount = 1; + protected int fireDelay = 0; + + // 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; + protected transient boolean[] projectileSpawned; + protected transient int spawnedCount; + protected transient String[] chargeVisualIds; + protected transient EntityLivingBase chargeVisualCaster; + + // ==================== CONSTRUCTOR ==================== + + protected AbilityEnergyProjectile( + EnergyDisplayData displayData, + EnergyCombatData combatData, + EnergyHomingData homingData, + EnergyLifespanData lifespanData + ) { + super(displayData); + this.combatData = combatData; + this.homingData = homingData; + this.lifespanData = lifespanData; + this.burstOverlap = true; + initProjectiles(1); + } + + // ==================== ABSTRACT METHODS ==================== + + /** + * Create a single entity for the given projectile index. + * Called when a projectile actually fires. + */ + 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); + } + + protected int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); + } + + // ==================== ENTITY CREATION ==================== + + protected void initRuntimeState(EntityLivingBase caster) { + entities = createEntityArray(projectileCount); + projectileSpawned = new boolean[projectileCount]; + spawnedCount = 0; + chargeVisualIds = new String[projectileCount]; + chargeVisualCaster = caster; + } + + protected E createProjectileEntity(EntityLivingBase caster, EntityLivingBase target, int index) { + Vec3 spawnPos = getSpawnPosition(caster, index); + EnergyDisplayData resolved = projectiles[index].resolveDisplay(displayData); + E entity = createEntity(caster, target, spawnPos, resolved, index); + entity.setAnchorData(projectiles[index].anchor); + entity.setEffects(this.effects); + entity.setIgnoreIFrames(this.isIgnoreIFrames()); + entity.setSourceAbility(this); + MagicData resolvedMagic = resolveMagicData(caster); + if (resolvedMagic != null) { + entity.setMagicData(resolvedMagic.copy()); + } + return entity; + } + + protected void spawnProjectileEntity(E entity, int index) { + if (entity == null) return; + spawnAbilityEntity(entity); + entities[index] = entity; + if (!projectileSpawned[index]) { + projectileSpawned[index] = true; + spawnedCount++; + } + } + + protected void spawnAndFireProjectile(EntityLivingBase caster, EntityLivingBase target, int index) { + if (entities != null && entities[index] != null && !entities[index].isDead) return; + E entity = createProjectileEntity(caster, target, index); + + // Initialize launch position/motion BEFORE spawn so the + // initial spawn packet already has centered look-vector data on all clients. + fireEntitySafe(entity, caster, target); + spawnProjectileEntity(entity, index); + } + + /** + * Hook for launch target selection. + * Players launch along their look vector (crosshair-aligned), so target is ignored. + * NPCs use their resolved target so launch math can track the target immediately. + */ + protected EntityLivingBase getLaunchTarget(EntityLivingBase caster, EntityLivingBase target) { + if (isPlayerCaster(caster)) return null; + // A rotation-locked NPC cannot turn, so launching from the target's position would let + // it fire a perfectly aimed shot regardless of where it is facing. Fall back to the + // look vector, which reflects the frozen heading. + if (isRotationLockedForCurrentPhase()) return null; + return target; + } + + /** + * Fire an entity if it's valid. + * Clears charging state first so the entity can move and check collisions. + */ + protected void fireEntitySafe(E entity, EntityLivingBase caster, EntityLivingBase target) { + if (entity != null && !entity.isDead) { + if (entity.isCharging()) { + entity.setCharging(false); + } + fireEntity(entity, getLaunchTarget(caster, target)); + } + } + + protected String getChargeVisualId(EntityLivingBase caster, int index) { + return "energy_charge:" + caster.getEntityId() + ":" + executionStartTime + ":" + burstIndex + ":" + index; + } + + protected void spawnChargeVisual(EntityLivingBase caster, EntityLivingBase target, int index, int chargeDuration) { + if (isPreview() || caster == null || caster.worldObj == null || caster.worldObj.isRemote) return; + if (chargeVisualIds == null || index < 0 || index >= chargeVisualIds.length) return; + + E previewEntity = createProjectileEntity(caster, target, index); + previewEntity.setPreviewMode(true); + previewEntity.setPreviewOwner(caster); + setupEntityCharging(previewEntity, projectiles[index], index); + previewEntity.setChargeDuration(Math.max(1, chargeDuration)); + + String id = getChargeVisualId(caster, index); + chargeVisualIds[index] = id; + chargeVisualCaster = caster; + EnergyChargeSpawnPacket.sendToTracking(id, previewEntity, caster); + + // Register with server-side tracker for late-join support + EnergyChargeTracker.Instance.add(new EnergyChargeTracker.ChargeEntry( + id, + previewEntity.getClass().getName(), + previewEntity.exportSpawnNBT(), + caster.getEntityId(), + (int) caster.worldObj.getTotalWorldTime() + )); + } + + protected void removeChargeVisual(EntityLivingBase caster, int index) { + if (isPreview() || caster == null || caster.worldObj == null || caster.worldObj.isRemote) return; + if (chargeVisualIds == null || index < 0 || index >= chargeVisualIds.length) return; + + String id = chargeVisualIds[index]; + if (id != null && !id.isEmpty()) { + EnergyChargeRemovePacket.sendToTracking(id, caster); + EnergyChargeTracker.Instance.remove(id, caster.getEntityId()); + chargeVisualIds[index] = null; + } + } + + protected void removeAllChargeVisuals(EntityLivingBase caster) { + if (chargeVisualIds == null || caster == null) return; + for (int i = 0; i < chargeVisualIds.length; i++) { + removeChargeVisual(caster, i); + } + // Safety net: ensure tracker is fully cleaned for this caster + if (!isPreview() && caster.worldObj != null && !caster.worldObj.isRemote) { + EnergyChargeTracker.Instance.removeAllForCaster(caster.getEntityId()); + } + } + + // ==================== LIFECYCLE ==================== + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + entities = null; + projectileSpawned = null; + spawnedCount = 0; + } + + /** + * Remove a specific entity from this ability's tracking. + * Used when a projectile is reflected — it no longer belongs to this ability, + * so the ability should stop waiting for it and free the caster. + */ + public void detachEntity(Entity entity) { + if (entities == null || entity == null) return; + for (int i = 0; i < entities.length; i++) { + if (entities[i] == entity) { + entities[i] = null; + break; + } + } + } + + @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) { + initRuntimeState(caster); + + if (isPreview()) { + for (int i = 0; i < projectileCount; i++) { + E previewEntity = createProjectileEntity(caster, target, i); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + setupEntityPreview(previewEntity, caster, resolved, projectiles[i], i); + spawnAbilityEntity(previewEntity); + entities[i] = previewEntity; + projectileSpawned[i] = true; + spawnedCount++; + } + return; + } + + for (int i = 0; i < projectileCount; i++) { + spawnChargeVisual(caster, target, i, windUpTicks); + } + } + } + + @Override + public void resetForBurst() { + removeAllChargeVisuals(chargeVisualCaster); + + // Non-overlap: kill old entities before next burst creates new ones + if (!burstOverlap) { + cleanup(); + } + // Clear reference so the next iteration creates fresh entities. + // For overlap mode, old entities stay alive (tracked in burstEntities). + entities = null; + projectileSpawned = null; + spawnedCount = 0; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // GUI preview keeps the original non-world preview entity flow. + if (isPreview()) { + if (entities == null) { + initRuntimeState(caster); + for (int i = 0; i < projectileCount; i++) { + E previewEntity = createProjectileEntity(caster, target, i); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + setupEntityPreview(previewEntity, caster, resolved, projectiles[i], i); + spawnAbilityEntity(previewEntity); + entities[i] = previewEntity; + projectileSpawned[i] = true; + spawnedCount++; + } + } + + fireEntitySafe(entities[0], caster, target); + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireEntitySafe(entities[i], caster, target); + } + } + return; + } + + if (entities == null || projectileSpawned == null || entities.length != projectileCount) { + initRuntimeState(caster); + } + + removeAllChargeVisuals(caster); + + // Fire first projectile immediately. + spawnAndFireProjectile(caster, target, 0); + + // Fire remaining projectiles immediately if there is no stagger delay. + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + spawnAndFireProjectile(caster, target, i); + } + } else { + // During active stagger, keep client-only charging visuals for unfired projectiles. + for (int i = 1; i < projectileCount; i++) { + spawnChargeVisual(caster, target, i, fireDelay * i); + } + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (entities == null || projectileSpawned == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles: spawn real world entity only when it is time to fire. + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + removeChargeVisual(caster, i); + spawnAndFireProjectile(caster, target, i); + } + } + } + + // Free on Cast: complete once all projectiles have been fired + if (isFreeOnCast()) { + int lastFireTick = fireDelay > 0 ? fireDelay * (projectileCount - 1) : 0; + if (tick >= lastFireTick) { + signalCompletion(); + return; + } + } + + // Before all projectiles have fired, the ability is still active by definition. + boolean allDead = spawnedCount >= projectileCount; + if (allDead) { + for (E entity : entities) { + if (entity == null || entity.isDead) continue; + + if (!isPreview() && 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) { + removeAllChargeVisuals(caster); + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + removeAllChargeVisuals(caster); + cleanup(); + } + + @Override + public void cleanup() { + removeAllChargeVisuals(chargeVisualCaster); + + 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; + projectileSpawned = null; + spawnedCount = 0; + chargeVisualIds = null; + chargeVisualCaster = 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); + + double groundY = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ); + TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, groundY, 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 + writeEnergyNBT(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 + readEnergyNBT(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 getDisplayDamage() { return combatData.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.getExplosionRadius(); + } + + @Override + public void setExplosionRadius(float explosionRadius) { + combatData.setExplosionRadius(explosionRadius); + } + + @Override + public float getExplosionDamageFalloff() { + return combatData.explosionDamageFalloff; + } + + @Override + public void setExplosionDamageFalloff(float falloff) { + combatData.explosionDamageFalloff = falloff; + } + + public int getHitType() { + return combatData.hitType.ordinal(); + } + + public void setHitType(int hitType) { + this.combatData.hitType = HitType.fromOrdinal(hitType); + } + + public int getMultiHitDelayTicks() { + return combatData.multiHitDelayTicks; + } + + public void setMultiHitDelayTicks(int delay) { + this.combatData.multiHitDelayTicks = Math.max(1, delay); + } + + public int getMaxHits() { + return combatData.getMaxHits(); + } + + public void setMaxHits(int maxHits) { + combatData.setMaxHits(maxHits); + } + + // 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 and lightning data inherited from AbilityEnergy + + // 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; + } + + public boolean getLaunchFromAnchor() { + return projectiles[0].anchor.launchFromAnchor; + } + + public void setLaunchFromAnchor(boolean launchFromAnchor) { + projectiles[0].anchor.launchFromAnchor = launchFromAnchor; + } + + @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; + } + + public boolean getLaunchFromAnchor(int index) { + return projectiles[clampIndex(index)].anchor.launchFromAnchor; + } + + public void setLaunchFromAnchor(int index, boolean launchFromAnchor) { + projectiles[clampIndex(index)].anchor.launchFromAnchor = launchFromAnchor; + } + + // ==================== GUI FIELD DEFINITIONS ==================== + + @SideOnly(Side.CLIENT) + @Override + public final void getAbilityDefinitions(List defs) { + defs.add(FieldDef.enumField("ability.hitType", HitType.class, + () -> HitType.fromOrdinal(getHitType()), + (v) -> setHitType(v.ordinal())) + .hover("ability.hover.hitType")); + defs.add(FieldDef.intField("ability.multiHitDelay", this::getMultiHitDelayTicks, this::setMultiHitDelayTicks) + .range(1, 200) + .visibleWhen(() -> getHitType() == HitType.MULTI.ordinal()) + .hover("ability.hover.multiHitDelay")); + defs.add(FieldDef.intField("ability.maxHits", this::getMaxHits, this::setMaxHits) + .range(1, EnergyCombatData.MAX_HITS) + .visibleWhen(() -> getHitType() != HitType.SINGLE.ordinal()) + .hover("ability.hover.maxHits")); + + // Type-specific fields first + addTypeDefinitions(defs); + + // Shared visual tab - colors + effects (from AbilityEnergy) + addEnergyColorDefinitions(defs); + + // Effects section with projectile-specific rotationSpeed before lightning + 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")); + addEnergyLightningDefinitions(defs); + + // 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)); + defs.add(FieldDef.boolField("ability.launchFromAnchor", () -> projectiles[idx].anchor.launchFromAnchor, v -> projectiles[idx].anchor.launchFromAnchor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount) + .hover("ability.hover.launchFromAnchor")); + + // 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/ability/type/energy/AbilityLaser.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaser.java new file mode 100644 index 000000000..40d30be43 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaser.java @@ -0,0 +1,228 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.enums.*; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.ProjectileData; +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 net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; +import noppes.npcs.api.ability.type.IAbilityLaser; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Laser ability: Sweeping beam that follows the caster's look vector. + * Expands from origin to maxLength, then stays active until maxLifetime expires. + * Single-projectile only (always projectileCount=1). + */ +public class AbilityLaser extends AbilityEnergyProjectile implements IAbilityLaser { + + private float laserWidth = 0.3f; + private float expansionSpeed = 3.0f; + private float maxLength = 32.0f; + + public AbilityLaser() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 4.0f), + new EnergyCombatData(4.0f, 0.5f, 0.05f, false, 2.0f, 0.5f, HitType.MULTI, 5), + new EnergyHomingData(), + new EnergyLifespanData(150.0f, 100) + ); + this.typeId = "ability.cnpc.laser_shot"; + this.name = "Laser"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 30.0f; + this.minRange = 3.0f; + this.cooldownTicks = 0; + this.windUpTicks = 15; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMode.WINDUP_AND_ACTIVE; + this.trackSpeed = 4.0f; + this.telegraphType = TelegraphType.LINE; + this.showTelegraph = true; + this.windUpAnimationName = "Ability_Laser_Windup"; + this.activeAnimationName = "Ability_Laser_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/laser_shot.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/laser_shot_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + // ==================== OVERRIDES ==================== + + @Override + protected AnchorPoint getDefaultAnchor(int index) { + return AnchorPoint.FRONT; + } + + @Override + public boolean isTargetingModeLocked() { + return false; + } + + @Override + public int getMaxPreviewDuration() { + int lifetime = lifespanData.maxLifetime; + return lifetime > 0 ? Math.min(lifetime, 60) : 60; + } + + /** + * LINE telegraph: positioned at caster, aimed toward target. + * Overrides the circle telegraph from AbilityEnergyProjectile. + */ + @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); + + 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) { + instance.setTargetEntityId(target.getEntityId()); + } + return instance; + } + + @Override + public float getTelegraphLength() { + return maxLength; + } + + @Override + public float getTelegraphWidth() { + return laserWidth * 2.0f; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityLaser createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + EntityAbilityLaser laser = new EntityAbilityLaser( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + laserWidth, + resolved, combatData, lightningData, lifespanData, + expansionSpeed, maxLength); + return laser; + } + + @Override + protected void fireEntity(EntityAbilityLaser laser, EntityLivingBase target) { + laser.startMoving(target); + } + + @Override + protected void setupEntityCharging(EntityAbilityLaser laser, ProjectileData projData, int index) { + laser.setupCharging(projData.anchor, windUpTicks); + } + + @Override + protected void setupEntityPreview(EntityAbilityLaser laser, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + laser.setupPreview(caster, laserWidth, resolved, lightningData, projData.anchor, windUpTicks, expansionSpeed, maxLength); + } + + @Override + protected EntityAbilityLaser[] createEntityArray(int size) { + return new EntityAbilityLaser[size]; + } + + @Override + protected float getProjectileTelegraphRadius() { + return laserWidth * 2.0f; + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { + nbt.setFloat("laserWidth", laserWidth); + nbt.setFloat("expansionSpeed", expansionSpeed); + nbt.setFloat("maxLength", maxLength); + } + + @Override + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.laserWidth = nbt.getFloat("laserWidth"); + this.expansionSpeed = nbt.getFloat("expansionSpeed"); + this.maxLength = nbt.hasKey("maxLength") ? nbt.getFloat("maxLength") : 32.0f; + } + + // ==================== 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 float getMaxLength() { + return maxLength; + } + + public void setMaxLength(float maxLength) { + this.maxLength = maxLength; + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + 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).range(0.1f, 100.0f), + FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed).range(0.1f, 50.0f) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxLength", this::getMaxLength, this::setMaxLength).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) + )); + 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) + .range(0.0f, EnergyCombatData.MAX_EXPLOSION_RADIUS) + .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/energy/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java new file mode 100644 index 000000000..2d9b162e5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java @@ -0,0 +1,200 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.ProjectileData; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityOrb; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; +import noppes.npcs.api.ability.type.IAbilityOrb; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * 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 AbilityEnergyProjectile implements IAbilityOrb { + + private float orbSize = 1.0f; + + public AbilityOrb() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 10.0f), + new EnergyCombatData(), + new EnergyHomingData(), + new EnergyLifespanData() + ); + this.typeId = "ability.cnpc.orb"; + this.name = "Orb"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 25.0f; + this.minRange = 5.0f; + this.cooldownTicks = 0; + this.windUpTicks = 30; + this.lockMovement = LockMode.WINDUP; + this.telegraphType = TelegraphType.CIRCLE; + this.showTelegraph = true; + this.windUpAnimationName = "Ability_Orb_Windup"; + this.activeAnimationName = "Ability_Orb_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/orb.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + 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); + } + + @Override + protected void fireEntity(EntityAbilityOrb orb, EntityLivingBase target) { + if (isPreview()) { + orb.startPreviewFiring(); + } else { + orb.startMoving(target); + } + } + + @Override + protected void setupEntityCharging(EntityAbilityOrb orb, ProjectileData projData, int index) { + orb.setupCharging(projData.anchor, windUpTicks); + } + + @Override + protected void setupEntityPreview(EntityAbilityOrb orb, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + orb.setupPreview(caster, orbSize, resolved, lightningData, projData.anchor, windUpTicks); + } + + @Override + protected EntityAbilityOrb[] createEntityArray(int size) { + return new EntityAbilityOrb[size]; + } + + @Override + protected float getProjectileTelegraphRadius() { + return orbSize * 1.5f; + } + + // ==================== VARIANTS ==================== + + @Override + 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); + orb.setProjectileCount(2); + orb.setFireDelay(2); + a.setLockMovement(LockMode.WINDUP_AND_ACTIVE); + 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); + } + + @Override + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.orbSize = nbt.getFloat("orbSize"); + } + + // ==================== TYPE-SPECIFIC GETTERS ==================== + + public float getOrbSpeed() { + return homingData.speed; + } + + public void setOrbSpeed(float speed) { + homingData.speed = speed; + } + + public float getOrbSize() { + return orbSize; + } + + public void setOrbSize(float size) { + this.orbSize = size; + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + 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).range(0.1f, 100.0f), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) + )); + 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) + .range(0.0f, EnergyCombatData.MAX_EXPLOSION_RADIUS) + .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/energy/AbilityShield.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java new file mode 100644 index 000000000..0adf474ca --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java @@ -0,0 +1,159 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyPanel; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Energy Shield ability: Spawns a flat energy panel held in front of the caster. + * The shield follows the caster's position and rotates with their look direction. + * Cannot be placed — it's always held. + */ +public class AbilityShield extends AbilityBarrier { + + private float shieldWidth = 2.5f; + private float shieldHeight = 2.5f; + + public AbilityShield() { + super( + new EnergyDisplayData(0xFFDD44, 0xFFAA00, true, 0.3f, 0.4f, 0.5f, 0.0f), + new EnergyBarrierData(60.0f, true, 120, true) + ); + this.typeId = "ability.cnpc.shield"; + this.name = "Shield"; + this.targetingMode = TargetingMode.SELF; + this.cooldownTicks = 60; + this.windUpTicks = 10; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + this.windUpAnimationName = ""; + this.activeAnimationName = ""; + this.allowedBy = UserType.BOTH; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/shield.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, offsetY); + panelData.offsetX = offsetX; + panelData.offsetZ = offsetZ; + + float frontDist = 1.5f; + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double spawnX = caster.posX + (-Math.sin(yawRad) * frontDist) + offsetX; + double spawnY = caster.posY + (caster.height * 0.5f); + double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist) + offsetZ; + + EntityEnergyPanel panel = new EntityEnergyPanel( + caster.worldObj, caster, + spawnX, spawnY, spawnZ, caster.rotationYaw, + EntityEnergyPanel.PanelMode.HELD, + displayData.copy(), lightningData.copy(), barrierData.copy(), panelData + ); + panel.setSourceAbility(this); + return panel; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.SELF}; + } + + @Override + public float getTelegraphRadius() { + return 0; // No telegraph for shield + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.small", a -> { + AbilityShield shield = (AbilityShield) a; + a.setName("Small Shield"); + shield.setShieldWidth(1.5f); + shield.setShieldHeight(1.5f); + shield.setBarrierMaxHealth(40.0f); + }), + new AbilityVariant("ability.variant.large", a -> { + AbilityShield shield = (AbilityShield) a; + a.setName("Large Shield"); + shield.setShieldWidth(4.0f); + shield.setShieldHeight(4.0f); + shield.setBarrierMaxHealth(120.0f); + shield.setBarrierDuration(200); + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeBarrierTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("shieldWidth", shieldWidth); + nbt.setFloat("shieldHeight", shieldHeight); + } + + @Override + protected void readBarrierTypeNBT(NBTTagCompound nbt) { + this.shieldWidth = nbt.hasKey("shieldWidth") ? nbt.getFloat("shieldWidth") : 2.5f; + this.shieldHeight = nbt.hasKey("shieldHeight") ? nbt.getFloat("shieldHeight") : 2.5f; + } + + // ==================== GETTERS & SETTERS ==================== + + public float getShieldWidth() { + return shieldWidth; + } + + public void setShieldWidth(float width) { + this.shieldWidth = Math.max(0.5f, width); + } + + public float getShieldHeight() { + return shieldHeight; + } + + public void setShieldHeight(float height) { + this.shieldHeight = Math.max(0.5f, height); + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + protected void addBarrierTypeDefinitions(List defs) { + defs.add(FieldDef.row( + FieldDef.floatField("gui.width", this::getShieldWidth, this::setShieldWidth).range(0.5f, 100.0f), + FieldDef.floatField("gui.height", this::getShieldHeight, this::setShieldHeight).range(0.5f, 100.0f) + )); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java new file mode 100644 index 000000000..fb5dc88e8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java @@ -0,0 +1,188 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.ProjectileData; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityEnergySlicer; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Energy Slicer ability: Fires a thin, wide blade projectile in a straight line. + * JJK Cleave/Dismantle inspired. + * Extends AbilityEnergyProjectile to leverage the existing projectile infrastructure. + */ +public class AbilitySlicer extends AbilityEnergyProjectile { + + private float sliceWidth = 3.0f; + private float sliceThickness = 0.15f; + + public AbilitySlicer() { + super( + new EnergyDisplayData(0xFF4444, 0xFF0000, true, 0.2f, 0.6f, 0.0f), + new EnergyCombatData(12.0f, 0.5f, 0.0f, false, 3.0f, 0.5f), + new EnergyHomingData(0.8f, false, 0.0f, 0.0f), + new EnergyLifespanData(150.0f, 100) + ); + this.typeId = "ability.cnpc.slicer"; + this.name = "Slicer"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 30.0f; + this.minRange = 3.0f; + this.cooldownTicks = 40; + this.windUpTicks = 15; + this.lockMovement = LockMode.WINDUP; + this.telegraphType = TelegraphType.LINE; + this.showTelegraph = true; + this.windUpAnimationName = ""; + this.activeAnimationName = ""; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityEnergySlicer createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityEnergySlicer( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + sliceWidth, sliceThickness, + resolved, combatData, homingData, lightningData, lifespanData + ); + } + + @Override + protected void fireEntity(EntityEnergySlicer slicer, EntityLivingBase target) { + if (isPreview()) { + slicer.startPreviewFiring(); + } else { + slicer.startMoving(target); + } + } + + @Override + protected void setupEntityCharging(EntityEnergySlicer slicer, ProjectileData projData, int index) { + slicer.setupSlicerCharging(projData.anchor, windUpTicks, sliceWidth, sliceThickness); + } + + @Override + protected void setupEntityPreview(EntityEnergySlicer slicer, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + slicer.setupPreview(caster, sliceWidth, sliceThickness, resolved, lightningData, projData.anchor, windUpTicks); + } + + @Override + protected EntityEnergySlicer[] createEntityArray(int size) { + return new EntityEnergySlicer[size]; + } + + @Override + protected float getProjectileTelegraphRadius() { + return sliceWidth * 0.75f; + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Slicer"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilitySlicer slicer = (AbilitySlicer) a; + a.setName("Double Slicer"); + slicer.setProjectileCount(2); + slicer.setFireDelay(5); + a.setWindUpAnimationName(""); + a.setActiveAnimationName(""); + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { + nbt.setFloat("sliceWidth", sliceWidth); + nbt.setFloat("sliceThickness", sliceThickness); + } + + @Override + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.sliceWidth = nbt.hasKey("sliceWidth") ? nbt.getFloat("sliceWidth") : 3.0f; + this.sliceThickness = nbt.hasKey("sliceThickness") ? nbt.getFloat("sliceThickness") : 0.15f; + } + + // ==================== TYPE-SPECIFIC GETTERS ==================== + + public float getSlicerSpeed() { + return homingData.speed; + } + + public void setSlicerSpeed(float speed) { + homingData.speed = speed; + } + + public float getSliceWidth() { + return sliceWidth; + } + + public void setSliceWidth(float width) { + this.sliceWidth = Math.max(0.5f, width); + } + + public float getSliceThickness() { + return sliceThickness; + } + + public void setSliceThickness(float thickness) { + this.sliceThickness = Math.max(0.05f, thickness); + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + 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::getSlicerSpeed, this::setSlicerSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.slicer")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.width", this::getSliceWidth, this::setSliceWidth).range(0.5f, 100.0f), + FieldDef.floatField("gui.thickness", this::getSliceThickness, this::setSliceThickness).range(0.05f, 100.0f) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) + )); + 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) + .range(0.0f, EnergyCombatData.MAX_EXPLOSION_RADIUS) + .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/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java similarity index 54% rename from src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java index 8638dd2a4..67c2d9c0d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -1,21 +1,19 @@ -package kamkeel.npcs.controllers.data.ability.type; +package kamkeel.npcs.controllers.data.ability.type.energy; 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.ability.data.EnergyDisplayData; -import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; 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.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergySweeper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; import noppes.npcs.api.ability.type.IAbilitySweeper; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; @@ -24,16 +22,16 @@ import java.util.List; * Sweeper ability: A low sweeping beam that rotates around the NPC. * Players can jump over it. The beam completes a set number of rotations before ending. * Telegraph shows a large circle on the ground indicating range. - * - * All damage logic is handled by the EntityAbilitySweeper entity to ensure + *

+ * All damage logic is handled by the EntityEnergySweeper entity to ensure * visual and damage hitbox alignment. */ -public class AbilitySweeper extends Ability implements IAbilitySweeper { +public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { // Type-specific parameters private float beamLength = 10.0f; private float beamWidth = 0.3f; // Thin like beam trail - private float beamHeight = 0.5f; // Height above ground (low enough to jump over) + private float beamHeight = 1.0f; // Beam vertical size in blocks (1 block tall, jumpable) private float damage = 5.0f; private int damageInterval = 5; private boolean piercing = true; @@ -41,24 +39,28 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { private int numberOfRotations = 2; // How many full rotations before ability ends private boolean lockOnTarget = false; - // Visual properties - private EnergyDisplayData colorData = new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f); - // Runtime state (transient) - private transient EntityAbilitySweeper activeEntity = null; + private transient EntityEnergySweeper activeEntity = null; public AbilitySweeper() { + super(new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f)); this.typeId = "ability.cnpc.sweeper"; this.name = "Sweeper"; this.targetingMode = TargetingMode.AGGRO_TARGET; this.maxRange = 15.0f; this.minRange = 0.0f; - this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; this.cooldownTicks = 0; this.windUpTicks = 60; // Circle telegraph to show range this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/sweeper.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/sweeper_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } @Override @@ -66,6 +68,21 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { return false; } + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + activeEntity = null; + } + @Override public boolean isTargetingModeLocked() { return true; @@ -77,38 +94,38 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - + 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(world, caster, target, + activeEntity = new EntityEnergySweeper(caster.worldObj, caster, target, beamLength, beamWidth, beamHeight, - colorData, + displayData, sweepSpeed, numberOfRotations, damage, damageInterval, piercing, lockOnTarget); + activeEntity.setIgnoreIFrames(this.isIgnoreIFrames()); + activeEntity.setSourceAbility(this); if (isPreview()) { activeEntity.setupPreview(caster); } - spawnAbilityEntity(world, activeEntity); - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class + spawnAbilityEntity(activeEntity); } @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; signalCompletion(); + return; + } + + // Free on Cast: complete immediately — sweeper lives independently + if (isFreeOnCast()) { + signalCompletion(); } } @@ -148,8 +165,9 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); telegraph.setHeightOffset(telegraphHeightOffset); - // Position at caster, not target - TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, caster.posY, caster.posZ, caster.rotationYaw); + // Position at caster ground level, not target + 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()); // Follow caster @@ -167,50 +185,98 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { nbt.setFloat("sweepSpeed", sweepSpeed); nbt.setInteger("numberOfRotations", numberOfRotations); nbt.setBoolean("lockOnTarget", lockOnTarget); - colorData.writeNBT(nbt); + writeEnergyNBT(nbt); } @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"); - colorData.readNBT(nbt); + 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"); + readEnergyNBT(nbt); } - // Getters & Setters - public float getBeamLength() { return beamLength; } - public void setBeamLength(float beamLength) { this.beamLength = beamLength; } - public float getBeamWidth() { return beamWidth; } - public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } - public float getBeamHeight() { return beamHeight; } - public void setBeamHeight(float beamHeight) { this.beamHeight = beamHeight; } - public float getDamage() { return damage; } - public void setDamage(float damage) { this.damage = damage; } - public int getDamageInterval() { return damageInterval; } - public void setDamageInterval(int damageInterval) { this.damageInterval = damageInterval; } - public boolean isPiercing() { return piercing; } - public void setPiercing(boolean piercing) { this.piercing = piercing; } - public float getSweepSpeed() { return sweepSpeed; } - public void setSweepSpeed(float sweepSpeed) { this.sweepSpeed = sweepSpeed; } - public int getNumberOfRotations() { return numberOfRotations; } - public void setNumberOfRotations(int numberOfRotations) { this.numberOfRotations = numberOfRotations; } - public boolean isLockOnTarget() { return lockOnTarget; } - public void setLockOnTarget(boolean lockOnTarget) { this.lockOnTarget = lockOnTarget; } - 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 boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } + // Getters & Setters (type-specific only; color/lightning inherited from AbilityEnergy) + public float getBeamLength() { + return beamLength; + } + + public void setBeamLength(float beamLength) { + this.beamLength = beamLength; + } + + public float getBeamWidth() { + return beamWidth; + } + + public void setBeamWidth(float beamWidth) { + this.beamWidth = beamWidth; + } + + public float getBeamHeight() { + return beamHeight; + } + + public void setBeamHeight(float beamHeight) { + this.beamHeight = beamHeight; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public int getDamageInterval() { + return damageInterval; + } + + public void setDamageInterval(int damageInterval) { + this.damageInterval = damageInterval; + } + + public boolean isPiercing() { + return piercing; + } + + public void setPiercing(boolean piercing) { + this.piercing = piercing; + } + + public float getSweepSpeed() { + return sweepSpeed; + } + + public void setSweepSpeed(float sweepSpeed) { + this.sweepSpeed = sweepSpeed; + } + + public int getNumberOfRotations() { + return numberOfRotations; + } + + public void setNumberOfRotations(int numberOfRotations) { + this.numberOfRotations = numberOfRotations; + } + + public boolean isLockOnTarget() { + return lockOnTarget; + } + + public void setLockOnTarget(boolean lockOnTarget) { + this.lockOnTarget = lockOnTarget; + } @Override public int getMaxPreviewDuration() { @@ -221,39 +287,30 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { @Override public void getAbilityDefinitions(List defs) { defs.addAll(Arrays.asList( - FieldDef.row( FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval) ), FieldDef.section("ability.section.beam"), FieldDef.row( - FieldDef.floatField("gui.length", this::getBeamLength, this::setBeamLength), - FieldDef.floatField("gui.width", this::getBeamWidth, this::setBeamWidth) + FieldDef.floatField("gui.length", this::getBeamLength, this::setBeamLength).range(0.5f, 100.0f), + FieldDef.floatField("gui.width", this::getBeamWidth, this::setBeamWidth).range(0.1f, 100.0f) ), FieldDef.row( - FieldDef.floatField("gui.height", this::getBeamHeight, this::setBeamHeight), - FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed) + FieldDef.floatField("gui.height", this::getBeamHeight, this::setBeamHeight).range(0.1f, 100.0f), + FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed).range(0.1f, 30.0f) ), - FieldDef.intField("ability.rotations", this::getNumberOfRotations, this::setNumberOfRotations), + FieldDef.intField("ability.rotations", this::getNumberOfRotations, this::setNumberOfRotations).range(1, 20), FieldDef.row( FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing) .hover("ability.hover.piercing"), FieldDef.boolField("ability.lockTarget", this::isLockOnTarget, this::setLockOnTarget) .hover("ability.hover.lockTarget") ), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - // Visual tab - 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.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled) + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); + + // Visual tab - colors + effects (from AbilityEnergy) + addEnergyVisualDefinitions(defs); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java new file mode 100644 index 000000000..bfe8c5b36 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java @@ -0,0 +1,236 @@ +package kamkeel.npcs.controllers.data.ability.type.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyPanel; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Energy Wall ability: Spawns a placeable flat energy barrier. + * Can float above ground (configurable height offset). + * Optional launching mode fires the wall forward with damage/knockback. + */ +public class AbilityWall extends AbilityBarrier { + + private final EnergyPanelData panelData; + + public AbilityWall() { + super( + new EnergyDisplayData(0x44FFCC, 0x22CCAA, true, 0.3f, 0.4f, 0.5f, 0.0f), + new EnergyBarrierData(80.0f, true, 160, true) + ); + this.panelData = new EnergyPanelData(4.0f, 3.0f, 0.0f); + this.typeId = "ability.cnpc.wall"; + this.name = "Wall"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 15.0f; + this.minRange = 2.0f; + this.cooldownTicks = 80; + this.windUpTicks = 20; + this.lockMovement = LockMode.WINDUP; + this.telegraphType = TelegraphType.LINE; + this.showTelegraph = true; + this.windUpAnimationName = ""; + this.activeAnimationName = ""; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/wall.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/wall_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; + } + + @Override + public boolean hasDamage() { + return panelData.launching; // Only has damage when launching + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + // Place wall between caster and target + double placeX, placeY, placeZ; + float yaw; + + if (target != null) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + double dist = Math.sqrt(dx * dx + dz * dz); + + if (dist < 0.01) { + // Target at same position — fall through to look-direction placement + float yawRad = (float) Math.toRadians(caster.rotationYaw); + placeX = caster.posX + (-Math.sin(yawRad) * 3.0); + placeY = caster.posY; + placeZ = caster.posZ + (Math.cos(yawRad) * 3.0); + yaw = caster.rotationYaw; + } else { + double placeDist = Math.min(dist * 0.5, 5.0); + placeX = caster.posX + (dx / dist) * placeDist; + placeY = caster.posY; + placeZ = caster.posZ + (dz / dist) * placeDist; + yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI); + } + } else { + float yawRad = (float) Math.toRadians(caster.rotationYaw); + placeX = caster.posX + (-Math.sin(yawRad) * 3.0); + placeY = caster.posY; + placeZ = caster.posZ + (Math.cos(yawRad) * 3.0); + yaw = caster.rotationYaw; + } + + placeX += offsetX; + placeY += offsetY; + placeZ += offsetZ; + + EntityEnergyPanel.PanelMode mode = panelData.launching + ? EntityEnergyPanel.PanelMode.LAUNCHED + : EntityEnergyPanel.PanelMode.PLACED; + + EnergyPanelData data = panelData.copy(); + data.heightOffset = 0.0f; // Y offset now handled by base class via placeY + + EntityEnergyPanel panel = new EntityEnergyPanel( + caster.worldObj, caster, + placeX, placeY, placeZ, yaw, mode, + displayData.copy(), lightningData.copy(), barrierData.copy(), data + ); + panel.setSourceAbility(this); + return panel; + } + + @Override + public float getTelegraphRadius() { + return Math.max(panelData.panelWidth, panelData.panelHeight) * 0.5f; + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.static", a -> { + a.setName("Static Wall"); + }), + new AbilityVariant("ability.variant.launched", a -> { + AbilityWall wall = (AbilityWall) a; + a.setName("Launched Wall"); + wall.panelData.launching = true; + wall.panelData.launchSpeed = 0.6f; + wall.panelData.launchDamage = 10.0f; + wall.panelData.launchKnockback = 3.0f; + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeBarrierTypeNBT(NBTTagCompound nbt) { + panelData.writeNBT(nbt); + } + + @Override + protected void readBarrierTypeNBT(NBTTagCompound nbt) { + panelData.readNBT(nbt); + // Migrate legacy heightOffset → base class offsetY + if (!nbt.hasKey("barrierOffsetY") && panelData.heightOffset != 0.0f) { + offsetY = panelData.heightOffset; + panelData.heightOffset = 0.0f; + } + } + + // ==================== GETTERS & SETTERS ==================== + + public EnergyPanelData getPanelData() { + return panelData; + } + + public float getPanelWidth() { + return panelData.panelWidth; + } + + public void setPanelWidth(float width) { + panelData.setPanelWidth(width); + } + + public float getPanelHeight() { + return panelData.panelHeight; + } + + public void setPanelHeight(float height) { + panelData.setPanelHeight(height); + } + + public boolean isLaunching() { + return panelData.launching; + } + + public void setLaunching(boolean launching) { + panelData.launching = launching; + } + + public float getLaunchSpeed() { + return panelData.launchSpeed; + } + + public void setLaunchSpeed(float speed) { + panelData.setLaunchSpeed(speed); + } + + public float getLaunchDamage() { + return panelData.launchDamage; + } + + public void setLaunchDamage(float damage) { + panelData.setLaunchDamage(damage); + } + + @Override + public float getDisplayDamage() { return panelData.launching ? panelData.launchDamage : 0; } + + public float getLaunchKnockback() { + return panelData.launchKnockback; + } + + public void setLaunchKnockback(float kb) { + panelData.setLaunchKnockback(kb); + } + + // ==================== TYPE-SPECIFIC GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + protected void addBarrierTypeDefinitions(List defs) { + defs.add(FieldDef.section("ability.section.panel")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.width", this::getPanelWidth, this::setPanelWidth).range(0.5f, 100.0f), + FieldDef.floatField("gui.height", this::getPanelHeight, this::setPanelHeight).range(0.5f, 100.0f) + )); + defs.add(FieldDef.section("ability.section.launch")); + defs.add(FieldDef.boolField("gui.enabled", this::isLaunching, this::setLaunching) + .hover("ability.hover.launching")); + defs.add(FieldDef.row( + FieldDef.floatField("stats.speed", this::getLaunchSpeed, this::setLaunchSpeed) + .visibleWhen(this::isLaunching), + FieldDef.floatField("enchantment.damage", this::getLaunchDamage, this::setLaunchDamage) + .visibleWhen(this::isLaunching) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getLaunchKnockback, this::setLaunchKnockback) + .visibleWhen(this::isLaunching)); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/util/AbilityTargetHelper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/util/AbilityTargetHelper.java new file mode 100644 index 000000000..3827f8691 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/util/AbilityTargetHelper.java @@ -0,0 +1,114 @@ +package kamkeel.npcs.controllers.data.ability.util; + +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.controllers.PartyController; +import noppes.npcs.controllers.data.Party; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.entity.EntityNPCInterface; + +/** + * Utility class for determining friend/foe relationships between entities. + * Extracted from EntityEnergyProjectile.shouldIgnoreEntity() for reuse + * across all AoE abilities and AbilityEffect targeting. + */ +public class AbilityTargetHelper { + + /** + * Determines if target is an ally of caster. + *

    + *
  • NPC vs NPC: same faction ID = ally
  • + *
  • NPC vs Player: faction friendly to player = ally
  • + *
  • Player vs NPC: NPC's faction friendly to player = ally
  • + *
  • Player vs Player: same party (if exists) = ally
  • + *
  • Passive NPCs are always considered allies (never enemies)
  • + *
+ */ + public static boolean isAlly(EntityLivingBase caster, Entity target) { + if (caster == null || target == null) return false; + if (target == caster) return true; + // Ally resolution relies on server-owned player/party/faction state. + if (caster.worldObj == null || caster.worldObj.isRemote) return false; + + // NPC target checks + if (target instanceof EntityNPCInterface) { + EntityNPCInterface targetNpc = (EntityNPCInterface) target; + + // Passive NPCs are always considered allies + if (targetNpc.faction.isPassive) return true; + + // NPC caster: same faction = ally + if (caster instanceof EntityNPCInterface) { + EntityNPCInterface casterNpc = (EntityNPCInterface) caster; + if (casterNpc.faction.id == targetNpc.faction.id) return true; + } + + // Player caster: friendly faction = ally + if (caster instanceof EntityPlayer) { + EntityPlayer casterPlayer = (EntityPlayer) caster; + if (PlayerData.get(casterPlayer) == null) return false; + if (targetNpc.faction.isFriendlyToPlayer(casterPlayer)) return true; + } + + return false; + } + + // Player target checks + if (target instanceof EntityPlayer && caster instanceof EntityNPCInterface) { + // NPC caster vs Player target: faction friendly to player = ally + EntityNPCInterface casterNpc = (EntityNPCInterface) caster; + EntityPlayer targetPlayer = (EntityPlayer) target; + if (PlayerData.get(targetPlayer) == null) return false; + return casterNpc.faction.isFriendlyToPlayer(targetPlayer); + } + + if (target instanceof EntityPlayer && caster instanceof EntityPlayer) { + // Player vs Player: same party = ally + EntityPlayer casterPlayer = (EntityPlayer) caster; + EntityPlayer targetPlayer = (EntityPlayer) target; + PlayerData casterData = PlayerData.get(casterPlayer); + PlayerData targetData = PlayerData.get(targetPlayer); + if (casterData == null || targetData == null) return false; + if (casterData.partyUUID != null && casterData.partyUUID.equals(targetData.partyUUID)) { + Party party = PartyController.Instance().getParty(casterData.partyUUID); + if (party != null && !party.friendlyFire()) return true; + } + return false; + } + + // Unknown entity types: not an ally + return false; + } + + /** + * Determines if a target should be affected by an ability, given the + * filter mode and includeSelf setting. + * + * @param caster The entity using the ability + * @param target The potential target entity + * @param filter ALLIES, ENEMIES, or ALL + * @param includeSelf Whether to include the caster themselves + * @return true if the target should be affected + */ + public static boolean shouldAffect(EntityLivingBase caster, Entity target, + TargetFilter filter, boolean includeSelf) { + if (caster == null || target == null || filter == null) return false; + if (caster.worldObj == null || caster.worldObj.isRemote) return false; + if (target == caster) return includeSelf; + if (!(target instanceof EntityLivingBase)) return false; + if (!target.isEntityAlive()) return false; + + switch (filter) { + case ALLIES: + return isAlly(caster, target); + case ENEMIES: + return !isAlly(caster, target); + case ALL: + return true; + default: + return false; + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/energy/IEnergyExtender.java b/src/main/java/kamkeel/npcs/controllers/data/energy/IEnergyExtender.java new file mode 100644 index 000000000..2dcd2fe43 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/energy/IEnergyExtender.java @@ -0,0 +1,49 @@ +package kamkeel.npcs.controllers.data.energy; + +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Extension point for handling energy entity damage without a sourceAbility. + * Registered with EnergyController. DBC Addon implements this to route + * script-created energy entity damage through the DBC damage pipeline. + */ +public interface IEnergyExtender { + + /** + * Handle damage for an energy entity with custom damage data. + * Chain of Responsibility — first handler returning true claims the damage. + * + * @param energyEntity The energy entity dealing damage + * @param owner The entity that owns/created the energy entity + * @param target The entity being damaged + * @param damage Base damage amount + * @param knockback Horizontal knockback strength + * @param knockbackUp Vertical knockback strength + * @param kbDirX Knockback direction X + * @param kbDirZ Knockback direction Z + * @param damageMultiplier Damage multiplier (e.g. falloff) + * @param damageData Custom damage configuration NBT (e.g. DBC stats) + * @return true if this handler processed the damage, false to pass to next handler + */ + boolean onEnergyDamage(Entity energyEntity, EntityLivingBase owner, + EntityLivingBase target, float damage, + float knockback, float knockbackUp, + double kbDirX, double kbDirZ, + float damageMultiplier, + NBTTagCompound damageData); + + /** + * Modify outgoing damage for an energy entity with custom damage data. + * Cumulative — each handler receives the previous handler's output. + * + * @param energyEntity The energy entity dealing damage + * @param owner The entity that owns/created the energy entity + * @param baseDamage Current damage value (after previous handlers) + * @param damageData Custom damage configuration NBT + * @return Modified damage value + */ + float modifyEnergyDamage(Entity energyEntity, EntityLivingBase owner, + float baseDamage, NBTTagCompound damageData); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/energycharge/EnergyChargePreviewManager.java b/src/main/java/kamkeel/npcs/controllers/data/energycharge/EnergyChargePreviewManager.java new file mode 100644 index 000000000..558399de1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/energycharge/EnergyChargePreviewManager.java @@ -0,0 +1,79 @@ +package kamkeel.npcs.controllers.data.energycharge; + +import kamkeel.npcs.entity.EntityEnergyProjectile; +import net.minecraft.world.World; + +import java.util.Collection; +import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Client-side manager for packet-driven charging preview entities. + * These entities are never spawned into the world; they are ticked and rendered manually. + */ +public class EnergyChargePreviewManager { + + /** Hard age cap for preview entities — last-resort safety net (60 seconds). */ + private static final int MAX_PREVIEW_AGE = 1200; + + public static EnergyChargePreviewManager ClientInstance; + + private final ConcurrentHashMap previews = new ConcurrentHashMap(); + + public static void initClient() { + ClientInstance = new EnergyChargePreviewManager(); + } + + public void addPreview(String instanceId, EntityEnergyProjectile entity) { + if (instanceId == null || entity == null) return; + previews.put(instanceId, entity); + } + + public void removePreview(String instanceId) { + if (instanceId == null) return; + previews.remove(instanceId); + } + + public Collection getPreviews() { + return previews.values(); + } + + public boolean hasPreviews() { + return !previews.isEmpty(); + } + + public void clear() { + previews.clear(); + } + + /** + * Tick all preview entities and remove invalid/expired entries. + */ + public void tick(World world) { + if (world == null) { + clear(); + return; + } + + Iterator iterator = previews.values().iterator(); + while (iterator.hasNext()) { + EntityEnergyProjectile entity = iterator.next(); + if (entity == null || entity.isDead || entity.worldObj != world) { + iterator.remove(); + continue; + } + + // Hard age cap: remove previews that have existed far too long + if (entity.ticksExisted > MAX_PREVIEW_AGE) { + entity.setDead(); + iterator.remove(); + continue; + } + + entity.onUpdate(); + if (entity.isDead) { + iterator.remove(); + } + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/energycharge/EnergyChargeTracker.java b/src/main/java/kamkeel/npcs/controllers/data/energycharge/EnergyChargeTracker.java new file mode 100644 index 000000000..606efb2fc --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/energycharge/EnergyChargeTracker.java @@ -0,0 +1,112 @@ +package kamkeel.npcs.controllers.data.energycharge; + +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.energycharge.EnergyChargeSpawnPacket; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * Server-side tracker for active charging preview visuals. + * Stores enough data to resend {@link EnergyChargeSpawnPacket} to late-joining players + * who enter tracking range after the initial broadcast. + *

+ * Keyed by caster entity ID so {@code PlayerEvent.StartTracking} can look up + * active charges for a newly tracked entity. + */ +public class EnergyChargeTracker { + public static final EnergyChargeTracker Instance = new EnergyChargeTracker(); + + public static class ChargeEntry { + public final String instanceId; + public final String entityClassName; + public final NBTTagCompound spawnNbt; + public final int casterEntityId; + public final int startTick; + + public ChargeEntry(String instanceId, String entityClassName, + NBTTagCompound spawnNbt, int casterEntityId, int startTick) { + this.instanceId = instanceId; + this.entityClassName = entityClassName; + this.spawnNbt = spawnNbt; + this.casterEntityId = casterEntityId; + this.startTick = startTick; + } + } + + private final Map> activeCharges = new HashMap<>(); + + public void add(ChargeEntry entry) { + List list = activeCharges.get(entry.casterEntityId); + if (list == null) { + list = new ArrayList<>(); + activeCharges.put(entry.casterEntityId, list); + } + list.add(entry); + } + + public void remove(String instanceId, int casterEntityId) { + List list = activeCharges.get(casterEntityId); + if (list == null) return; + Iterator it = list.iterator(); + while (it.hasNext()) { + if (it.next().instanceId.equals(instanceId)) { + it.remove(); + break; + } + } + if (list.isEmpty()) { + activeCharges.remove(casterEntityId); + } + } + + public void removeAllForCaster(int casterEntityId) { + activeCharges.remove(casterEntityId); + } + + /** + * Send all active charges for a caster to a specific player. + * Adjusts ChargeTick in the NBT to reflect elapsed time so the + * late-joining client starts at the correct visual progress. + */ + public void sendToPlayer(int casterEntityId, EntityPlayerMP player, int currentWorldTick) { + List entries = activeCharges.get(casterEntityId); + if (entries == null || entries.isEmpty()) return; + + for (ChargeEntry entry : entries) { + int elapsed = currentWorldTick - entry.startTick; + int chargeDuration = entry.spawnNbt.hasKey("ChargeDuration") + ? entry.spawnNbt.getInteger("ChargeDuration") : 0; + + // Charge already complete — server remove packet should follow shortly + if (chargeDuration > 0 && elapsed >= chargeDuration) { + continue; + } + + NBTTagCompound adjustedNbt = (NBTTagCompound) entry.spawnNbt.copy(); + if (elapsed > 0) { + adjustedNbt.setInteger("ChargeTick", elapsed); + } + + PacketHandler.Instance.sendToPlayer( + new EnergyChargeSpawnPacket(entry.instanceId, entry.entityClassName, adjustedNbt), + player + ); + } + } + + public boolean hasCharges(int casterEntityId) { + List list = activeCharges.get(casterEntityId); + return list != null && !list.isEmpty(); + } + + public void clear() { + activeCharges.clear(); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/profile/CNPCData.java b/src/main/java/kamkeel/npcs/controllers/data/profile/CNPCData.java index e4eb04dfe..ccf6ecac7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/profile/CNPCData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/profile/CNPCData.java @@ -1,6 +1,6 @@ package kamkeel.npcs.controllers.data.profile; -import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.sync.handlers.PlayerDataSyncHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; @@ -30,7 +30,7 @@ public class CNPCData implements IProfileData { public void save(EntityPlayer player) { PlayerData customNPCData = PlayerData.get(player); customNPCData.save(); - SyncController.syncPlayerData((EntityPlayerMP) player, false); + PlayerDataSyncHandler.syncPlayerData((EntityPlayerMP) player, false); } @Override @@ -63,6 +63,9 @@ public class CNPCData implements IProfileData { if (playerData.partyUUID != null) return ProfileOperation.error("Cannot switch while in Party"); + if (playerData.abilityData.isExecutingAbility()) + return ProfileOperation.error("Cannot switch while performing an Ability"); + return ProfileOperation.success(""); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java b/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java index 04ce9b66c..002fdb52f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java @@ -2,6 +2,7 @@ package kamkeel.npcs.controllers.data.profile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.handler.data.IProfile; @@ -15,6 +16,7 @@ public class Profile implements IProfile { public EntityPlayer player; public int currentSlotId; private final Map slots = new HashMap<>(); + public Map sharedQuestTimestamps = new HashMap<>(); private boolean locked = false; public Profile(EntityPlayer player, NBTTagCompound compound) { @@ -39,6 +41,14 @@ public class Profile implements IProfile { } } } + + if (compound.hasKey("SharedQuestTimestamps")) { + NBTTagList list = compound.getTagList("SharedQuestTimestamps", 10); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound entry = list.getCompoundTagAt(i); + sharedQuestTimestamps.put(entry.getInteger("Quest"), entry.getLong("Date")); + } + } } public Profile(EntityPlayer player) { @@ -88,6 +98,16 @@ public class Profile implements IProfile { slotsCompound.setTag(String.valueOf(entry.getKey()), entry.getValue().toNBT()); } compound.setTag("Slots", slotsCompound); + + NBTTagList questList = new NBTTagList(); + for (Map.Entry entry : sharedQuestTimestamps.entrySet()) { + NBTTagCompound questEntry = new NBTTagCompound(); + questEntry.setInteger("Quest", entry.getKey()); + questEntry.setLong("Date", entry.getValue()); + questList.appendTag(questEntry); + } + compound.setTag("SharedQuestTimestamps", questList); + return compound; } } 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..a12292263 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java @@ -28,6 +28,7 @@ public class Telegraph { private int warningStartTick = 10; private boolean animated = true; private float heightOffset = 0.1f; + private int groundSearchRange = 3; // Positioning private boolean atTarget = true; @@ -57,6 +58,7 @@ public class Telegraph { this.warningStartTick = other.warningStartTick; this.animated = other.animated; this.heightOffset = other.heightOffset; + this.groundSearchRange = other.groundSearchRange; this.atTarget = other.atTarget; this.followsTarget = other.followsTarget; this.followsCaster = other.followsCaster; @@ -82,6 +84,7 @@ public class Telegraph { nbt.setInteger("warningStartTick", warningStartTick); nbt.setBoolean("animated", animated); nbt.setFloat("heightOffset", heightOffset); + nbt.setInteger("groundSearchRange", groundSearchRange); nbt.setBoolean("atTarget", atTarget); nbt.setBoolean("followsTarget", followsTarget); nbt.setBoolean("followsCaster", followsCaster); @@ -109,6 +112,9 @@ public class Telegraph { this.warningStartTick = nbt.getInteger("warningStartTick"); this.animated = nbt.getBoolean("animated"); this.heightOffset = nbt.getFloat("heightOffset"); + if (nbt.hasKey("groundSearchRange")) { + this.groundSearchRange = nbt.getInteger("groundSearchRange"); + } this.atTarget = nbt.getBoolean("atTarget"); this.followsTarget = nbt.getBoolean("followsTarget"); this.followsCaster = nbt.getBoolean("followsCaster"); @@ -146,10 +152,24 @@ public class Telegraph { return t; } + public static Telegraph cone(float length, float angle, float innerRadius) { + Telegraph t = new Telegraph("", TelegraphType.CONE); + t.length = length; + t.angle = angle; + t.innerRadius = innerRadius; + return t; + } + public static Telegraph point() { return new Telegraph("", TelegraphType.POINT); } + public static Telegraph square(float radius) { + Telegraph t = new Telegraph("", TelegraphType.SQUARE); + t.radius = radius; + return t; + } + // ═══════════════════════════════════════════════════════════════════ // GETTERS & SETTERS // ═══════════════════════════════════════════════════════════════════ @@ -258,6 +278,14 @@ public class Telegraph { this.heightOffset = heightOffset; } + public int getGroundSearchRange() { + return groundSearchRange; + } + + public void setGroundSearchRange(int groundSearchRange) { + this.groundSearchRange = groundSearchRange; + } + public boolean isAtTarget() { return atTarget; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java index a5d2f0d95..a9ee8e4d7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java @@ -33,6 +33,7 @@ public class TelegraphInstance { private int entityIdToFollow = -1; private int casterEntityId = -1; private int targetEntityId = -1; // For LINE telegraphs: entity to face (yaw tracking) + private boolean trackFollowedEntityYaw = false; // Track followed entity's rotationYaw when no targetEntity // Timing private int remainingTicks; @@ -95,7 +96,13 @@ public class TelegraphInstance { this.x = entity.posX; this.z = entity.posZ; // Find ground level below the entity for proper telegraph placement - this.y = Ability.findGroundLevel(world, entity.posX, entity.posY, entity.posZ); + int searchRange = (telegraph != null) ? telegraph.getGroundSearchRange() : 3; + this.y = Ability.findGroundLevel(world, entity.posX, entity.posY, entity.posZ, searchRange); + + // Track followed entity's yaw for directional telegraphs (player casters) + if (trackFollowedEntityYaw && targetEntityId < 0) { + this.yaw = entity.rotationYaw; + } } } @@ -218,6 +225,7 @@ public class TelegraphInstance { nbt.setInteger("entityIdToFollow", entityIdToFollow); nbt.setInteger("casterEntityId", casterEntityId); nbt.setInteger("targetEntityId", targetEntityId); + nbt.setBoolean("trackFollowedYaw", trackFollowedEntityYaw); nbt.setInteger("remainingTicks", remainingTicks); nbt.setInteger("totalTicks", totalTicks); @@ -243,6 +251,7 @@ public class TelegraphInstance { this.entityIdToFollow = nbt.getInteger("entityIdToFollow"); this.casterEntityId = nbt.getInteger("casterEntityId"); this.targetEntityId = nbt.getInteger("targetEntityId"); + this.trackFollowedEntityYaw = nbt.hasKey("trackFollowedYaw") && nbt.getBoolean("trackFollowedYaw"); this.remainingTicks = nbt.getInteger("remainingTicks"); this.totalTicks = nbt.getInteger("totalTicks"); @@ -335,6 +344,14 @@ public class TelegraphInstance { this.targetEntityId = targetEntityId; } + public boolean isTrackFollowedEntityYaw() { + return trackFollowedEntityYaw; + } + + public void setTrackFollowedEntityYaw(boolean track) { + this.trackFollowedEntityYaw = track; + } + public int getRemainingTicks() { return remainingTicks; } 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/controllers/sync/SyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/SyncHandler.java new file mode 100644 index 000000000..35f863c35 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/SyncHandler.java @@ -0,0 +1,167 @@ +package kamkeel.npcs.controllers.sync; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.HashSet; +import java.util.Set; + +/** + * Contract for a synchronized data type. Implementors handle both + * server-side serialization and client-side deserialization for their + * specific data type. + * + *

Each handler is registered with {@link SyncRegistry} and covers + * all three sync actions: RELOAD (full), UPDATE (single entity), + * and REMOVE (delete entity).

+ * + *

Handlers that don't support UPDATE or REMOVE should use the + * default no-op implementations.

+ */ +public interface SyncHandler { + + // ========== SERVER-SIDE ========== + + /** + * Serialize ALL objects of this type into an NBTTagCompound. + * This is the supplier for the cache system. + * + *

Called lazily when the cache is dirty and a player needs data. + * The returned compound is cached and chunked for transmission.

+ * + * @return the serialized compound, or null if this type has no independent cache + */ + NBTTagCompound serializeAll(); + + + // ========== CLIENT-SIDE ========== + + /** + * Handle a RELOAD action on the client. Deserialize the full + * dataset and replace the client-side data. + * + *

Implementations should: + *

    + *
  1. Deserialize from the compound into a sync buffer
  2. + *
  3. Atomically swap the sync buffer to the primary map
  4. + *
  5. Reset the sync buffer for the next reload
  6. + *
+ * + * @param fullCompound the full serialized dataset from {@link #serializeAll()} + */ + @SideOnly(Side.CLIENT) + default void clientHandleReload(NBTTagCompound fullCompound){ + // No-op: type does not support individual updates + } + + /** + * Handle an UPDATE action on the client. + * Deserialize a single object and insert/replace it in the client-side data. + * + *

Default: no-op. Types that don't support individual updates + * use {@code syncAll()} for full reload instead.

+ * + * @param compound the serialized single object + */ + @SideOnly(Side.CLIENT) + default void clientHandleUpdate(NBTTagCompound compound) { + // No-op: type does not support individual updates + } + + /** + * Handle an UPDATE action on the client. + * Deserialize a single object and insert/replace it in the client-side data. + * + *

Default: no-op. Types that don't support individual updates + * use {@code syncAll()} for full reload instead.

+ * + * @param compound the serialized single object + * @param categoryKey the parent category key (null if not applicable) + */ + @SideOnly(Side.CLIENT) + default void clientHandleUpdate(NBTTagCompound compound, String categoryKey) { + // No-op: type does not support individual updates + } + + + /** + * Handle an UPDATE action on the client. Deserialize a single + * entity and insert/replace it in the client-side data. + * + *

Default: no-op. Types that don't support individual updates + * use {@code syncAll()} for full reload instead.

+ * + * @param compound the serialized single entity + * @param categoryId the parent category ID (-1 if not applicable) + */ + @SideOnly(Side.CLIENT) + default void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + // No-op: type does not support individual updates + } + + /** + * Removes a single object from client-side data. + * Full object NBTTagCompound sent finer query control + * Int-keyed handlers should override {@link #clientHandleRemove(int)} instead. + */ + @SideOnly(Side.CLIENT) + default void clientHandleRemove(String key) { + } + + /** + * Removes a single object with the given ID from client-side data. + * + * @param id the ID of the object to remove + */ + @SideOnly(Side.CLIENT) + default void clientHandleRemove(int id) { + } + + /** + * Whether this handler supports the UPDATE action. + * Used for validation and self-documentation. + */ + default boolean supportsUpdate() { + return false; + } + + /** + * Whether this handler supports the REMOVE action. + * Used for validation and self-documentation. + */ + default boolean supportsRemove() { + return false; + } + + /** + * Whether this type should be included in login sync. + * Types that return true will be sent to players on login + * and checked for revision deltas on reconnect. + * + *

Default: true. Override to false for types like PLAYERDATA + * that are synced through separate mechanisms, or child types + * (DIALOG, QUEST) that share their parent's cache.

+ */ + default boolean isCachedType() { + return true; + } + + /** + * Get the set of cache types that must be invalidated when + * this type changes. Used for cascade invalidation. + * + *

Most types return just themselves. Parent-child types + * (e.g. DIALOG maps to DIALOG_CATEGORY) point children + * to the parent's cache.

+ * + * @param self the SyncType this handler is registered under + * @return the set of types to invalidate + */ + default Set getInvalidationTargets(SyncType self) { + Set set = new HashSet<>(); + set.add(self); + return set; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/SyncRegistry.java b/src/main/java/kamkeel/npcs/controllers/sync/SyncRegistry.java new file mode 100644 index 000000000..1260d0ab1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/SyncRegistry.java @@ -0,0 +1,69 @@ +package kamkeel.npcs.controllers.sync; + +import kamkeel.npcs.network.enums.SyncType; +import noppes.npcs.LogWriter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public final class SyncRegistry { + + private static final LinkedHashMap handlers = new LinkedHashMap<>(); + + private static SyncType[] loginTypesCache = null; + + private SyncRegistry() {} + + public static void register(SyncType type, SyncHandler handler) { + if (type == null) throw new IllegalArgumentException("SyncType must not be null"); + if (handler == null) throw new IllegalArgumentException("SyncHandler must not be null for " + type); + if (handlers.containsKey(type)) throw new IllegalStateException("SyncHandler already registered for " + type); + + handlers.put(type, handler); + loginTypesCache = null; + } + + public static SyncHandler getHandler(SyncType type) { + return handlers.get(type); + } + + public static SyncType[] getLoginTypes() { + if (loginTypesCache == null) { + List list = new ArrayList<>(); + for (Map.Entry e : handlers.entrySet()) + if (e.getValue().isCachedType()) + list.add(e.getKey()); + + loginTypesCache = list.toArray(new SyncType[0]); + } + return loginTypesCache; + } + + public static Set getInvalidationTargets(SyncType type) { + SyncHandler handler = handlers.get(type); + if (handler == null) { + return Collections.emptySet(); + } + return handler.getInvalidationTargets(type); + } + + public static void clear() { + handlers.clear(); + loginTypesCache = null; + } + + + public static boolean isRegistered(SyncType type) { + return handlers.containsKey(type); + } + + public static Collection getRegisteredTypes() { + return Collections.unmodifiableCollection(handlers.keySet()); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/AnvilRecipeSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/AnvilRecipeSyncHandler.java new file mode 100644 index 000000000..caaad94d9 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/AnvilRecipeSyncHandler.java @@ -0,0 +1,56 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.RecipeController; +import noppes.npcs.controllers.data.RecipeAnvil; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#ANVIL_RECIPES}. + * RELOAD-only family — does not support individual UPDATE or REMOVE. + */ +public class AnvilRecipeSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + RecipeController controller = RecipeController.Instance; + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (RecipeAnvil recipe : controller.anvilRecipes.values()) { + list.appendTag(recipe.writeNBT(false)); + } + compound.setTag("recipes", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("recipes", 10); + if (list == null) + return; + + for (int i = 0; i < list.tagCount(); i++) { + RecipeAnvil recipe = new RecipeAnvil(); + recipe.readNBT(list.getCompoundTagAt(i)); + RecipeController.syncAnvilRecipes.put(recipe.id, recipe); + } + + RecipeController.Instance.anvilRecipes = RecipeController.syncAnvilRecipes; + RecipeController.syncAnvilRecipes = new HashMap<>(); + } + + // RELOAD-only: supportsUpdate() and supportsRemove() remain false (default) +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/CarpentryRecipeSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/CarpentryRecipeSyncHandler.java new file mode 100644 index 000000000..5213dc227 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/CarpentryRecipeSyncHandler.java @@ -0,0 +1,63 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.RecipeController; +import noppes.npcs.controllers.data.RecipeCarpentry; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#CARPENTRY_RECIPES}. + * RELOAD-only family — does not support individual UPDATE or REMOVE. + */ +public class CarpentryRecipeSyncHandler implements SyncHandler { + + private static final CarpentryRecipeSyncHandler INSTANCE = new CarpentryRecipeSyncHandler(); + + public static CarpentryRecipeSyncHandler getInstance() { + return INSTANCE; + } + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + RecipeController controller = RecipeController.Instance; + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (RecipeCarpentry recipe : controller.carpentryRecipes.values()) { + list.appendTag(recipe.writeNBT(false)); + } + compound.setTag("recipes", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("recipes", 10); + if (list == null) + return; + + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound recipeCompound = list.getCompoundTagAt(i); + RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound); + recipe.readNBT(recipeCompound); + RecipeController.syncRecipes.put(recipe.id, recipe); + } + + RecipeController.Instance.carpentryRecipes = RecipeController.syncRecipes; + RecipeController.syncRecipes = new HashMap<>(); + } + + // RELOAD-only: supportsUpdate() and supportsRemove() remain false (default) +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/ChainedAbilitySyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/ChainedAbilitySyncHandler.java new file mode 100644 index 000000000..59600770d --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/ChainedAbilitySyncHandler.java @@ -0,0 +1,58 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#CHAINED_ABILITY}. + * String-keyed family using ordered {@link LinkedHashMap} to preserve + * registration/reload order. Supports RELOAD only for global sync. + */ +public class ChainedAbilitySyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (Map.Entry entry : AbilityController.Instance.getChainedAbilities().entrySet()) { + NBTTagCompound chainNBT = entry.getValue().writeNBT(false); + chainNBT.setString("ChainedAbilityId", entry.getKey()); + list.appendTag(chainNBT); + } + compound.setTag("Data", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("Data", 10); + LinkedHashMap sync = new LinkedHashMap<>(); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound nbt = list.getCompoundTagAt(i); + String id = nbt.getString("ChainedAbilityId"); + ChainedAbility chain = new ChainedAbility(); + chain.readNBT(nbt); + chain.setName(id); + sync.put(id, chain); + } + AbilityController.Instance.setChainedAbilities(sync); + } + + // RELOAD-only for global sync: supportsUpdate() and supportsRemove() remain false (default) +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/CustomAbilitySyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/CustomAbilitySyncHandler.java new file mode 100644 index 000000000..16a808797 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/CustomAbilitySyncHandler.java @@ -0,0 +1,59 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#CUSTOM_ABILITY}. + * String-keyed family using ordered {@link LinkedHashMap} to preserve + * registration/reload order. Supports RELOAD only for global sync. + */ +public class CustomAbilitySyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (Map.Entry entry : AbilityController.Instance.getCustomAbilities().entrySet()) { + NBTTagCompound abilityNBT = entry.getValue().writeNBT(false); + abilityNBT.setString("CustomAbilityId", entry.getKey()); + list.appendTag(abilityNBT); + } + compound.setTag("Data", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("Data", 10); + LinkedHashMap sync = new LinkedHashMap<>(); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound nbt = list.getCompoundTagAt(i); + String name = nbt.getString("CustomAbilityId"); + Ability ability = AbilityController.Instance.fromNBT(nbt); + if (ability != null) { + ability.setName(name); + sync.put(name, ability); + } + } + AbilityController.Instance.setCustomAbilities(sync); + } + + // RELOAD-only for global sync: supportsUpdate() and supportsRemove() remain false (default) +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/CustomEffectSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/CustomEffectSyncHandler.java new file mode 100644 index 000000000..ed1d8012e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/CustomEffectSyncHandler.java @@ -0,0 +1,82 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#CUSTOM_EFFECTS}. + * Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support. + * Client-side RELOAD precaches effect icons via {@link ClientCacheHandler#getImageData}. + */ +public class CustomEffectSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (CustomEffect effect : CustomEffectController.getInstance().getCustomEffects().values()) { + list.appendTag(effect.writeToNBT(false)); + } + compound.setTag("Data", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("Data", 10); + CustomEffectController ce = CustomEffectController.getInstance(); + ce.customEffectsSync.clear(); + for (int i = 0; i < list.tagCount(); i++) { + CustomEffect effect = new CustomEffect(); + effect.readFromNBT(list.getCompoundTagAt(i)); + ClientCacheHandler.getImageData(effect.icon); + ce.customEffectsSync.put(effect.id, effect); + } + + ce.getCustomEffects().clear(); + ce.getCustomEffects().putAll(ce.customEffectsSync); + ce.customEffectsSync.clear(); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + CustomEffect effect = new CustomEffect(); + effect.readFromNBT(compound); + ClientCacheHandler.getImageData(effect.icon); + + CustomEffectController.Instance.getCustomEffects().put(effect.id, effect); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + CustomEffectController.Instance.getCustomEffects().remove(id); + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/DialogCategorySyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/DialogCategorySyncHandler.java new file mode 100644 index 000000000..45d8dcce8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/DialogCategorySyncHandler.java @@ -0,0 +1,140 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.DialogController; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.DialogCategory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#DIALOG_CATEGORY}. + * Parent-child category family. DIALOG children share this cache. + * Invalidation from DIALOG or DIALOG_CATEGORY both target this cache. + */ +public class DialogCategorySyncHandler implements SyncHandler { + + /** + * Serialize a single dialog category for UPDATE packets. + */ + public static NBTTagCompound serializeCategory(DialogCategory dialogCategory) { + NBTTagCompound dialogCompound = new NBTTagCompound(); + NBTTagList dialogList = new NBTTagList(); + for (int questID : dialogCategory.dialogs.keySet()) { + Dialog dialog = dialogCategory.dialogs.get(questID); + dialogList.appendTag(dialog.writeToNBT(new NBTTagCompound())); + } + dialogCompound.setTag("Data", dialogList); + dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound())); + return dialogCompound; + } + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList categoryList = new NBTTagList(); + for (DialogCategory category : DialogController.Instance.categories.values()) { + NBTTagCompound questCompound = new NBTTagCompound(); + NBTTagList dialogList = new NBTTagList(); + for (int dialogID : category.dialogs.keySet()) { + Dialog quest = category.dialogs.get(dialogID); + dialogList.appendTag(quest.writeToNBT(new NBTTagCompound())); + } + questCompound.setTag("Data", dialogList); + questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound())); + categoryList.appendTag(questCompound); + } + compound.setTag("DialogCategories", categoryList); + return compound; + } + + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + if (!fullCompound.hasNoTags()) { + NBTTagList categories = fullCompound.getTagList("DialogCategories", 10); + for (int j = 0; j < fullCompound.getTagList("DialogCategories", 10).tagCount(); j++) { + NBTTagCompound categoryCompound = categories.getCompoundTagAt(j); + if (categoryCompound.hasNoTags()) + continue; + + DialogCategory category = new DialogCategory(); + category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); + NBTTagList dialogList = categoryCompound.getTagList("Data", 10); + if (DialogController.Instance.categoriesSync.containsKey(category.id)) { + category = DialogController.Instance.categoriesSync.get(category.id); + category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); + } + for (int i = 0; i < dialogList.tagCount(); i++) { + Dialog dialog = new Dialog(); + dialog.readNBT(dialogList.getCompoundTagAt(i)); + dialog.category = category; + category.dialogs.put(dialog.id, dialog); + } + DialogController.Instance.categoriesSync.put(category.id, category); + } + } + + HashMap dialogs = new HashMap<>(); + for (DialogCategory category : DialogController.Instance.categoriesSync.values()) { + for (Dialog dialog : category.dialogs.values()) { + dialogs.put(dialog.id, dialog); + } + } + + DialogController.Instance.categories = DialogController.Instance.categoriesSync; + DialogController.Instance.dialogs = dialogs; + DialogController.Instance.categoriesSync = new HashMap<>(); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + DialogCategory category = new DialogCategory(); + category.readSmallNBT(compound.getCompoundTag("CatNBT")); + NBTTagList list = compound.getTagList("Data", 10); + if (DialogController.Instance.categoriesSync.containsKey(category.id)) { + category = DialogController.Instance.categoriesSync.get(category.id); + category.readSmallNBT(compound.getCompoundTag("CatNBT")); + } + for (int i = 0; i < list.tagCount(); i++) { + Dialog dialog = new Dialog(); + dialog.readNBT(list.getCompoundTagAt(i)); + dialog.category = category; + category.dialogs.put(dialog.id, dialog); + } + DialogController.Instance.categories.put(category.id, category); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + DialogCategory dialogCategory = DialogController.Instance.categories.remove(id); + if (dialogCategory != null) { + DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet()); + } + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/DialogSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/DialogSyncHandler.java new file mode 100644 index 000000000..df0b82259 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/DialogSyncHandler.java @@ -0,0 +1,89 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.DialogController; +import noppes.npcs.controllers.data.Dialog; +import noppes.npcs.controllers.data.DialogCategory; + +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#DIALOG}. + * Child family — does not have its own cache. UPDATE and REMOVE only. + * Invalidation targets the parent {@link SyncType#DIALOG_CATEGORY} cache. + */ +public class DialogSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + /** + * DIALOG does not have its own independent cache; it shares + * the DIALOG_CATEGORY parent cache. + */ + @Override + public NBTTagCompound serializeAll() { + return null; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + // DIALOG does not handle standalone RELOAD; it's part of DIALOG_CATEGORY + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + DialogCategory category = DialogController.Instance.categories.get(categoryId); + if (category == null) { + return; // Defensive: category may have been removed + } + Dialog dialog = new Dialog(); + dialog.category = category; + dialog.readNBT(compound); + DialogController.Instance.dialogs.put(dialog.id, dialog); + category.dialogs.put(dialog.id, dialog); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + Dialog dialog = DialogController.Instance.dialogs.remove(id); + if (dialog != null) { + dialog.category.dialogs.remove(id); + } + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + + /** + * Not a cached type — DIALOG shares the DIALOG_CATEGORY cache. + */ + @Override + public boolean isCachedType() { + return false; + } + + @Override + public Set getInvalidationTargets(SyncType self) { + // Child invalidates the parent cache + Set set = new HashSet<>(); + set.add(SyncType.DIALOG_CATEGORY); + return set; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/FactionSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/FactionSyncHandler.java new file mode 100644 index 000000000..2639567db --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/FactionSyncHandler.java @@ -0,0 +1,76 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.FactionController; +import noppes.npcs.controllers.data.Faction; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#FACTION}. + * Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support. + */ +public class FactionSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (Faction faction : FactionController.getInstance().factions.values()) { + NBTTagCompound factionNBT = new NBTTagCompound(); + faction.writeNBT(factionNBT); + list.appendTag(factionNBT); + } + compound.setTag("Factions", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("Factions", 10); + for (int i = 0; i < list.tagCount(); i++) { + Faction faction = new Faction(); + faction.readNBT(list.getCompoundTagAt(i)); + FactionController.getInstance().factionsSync.put(faction.id, faction); + } + FactionController.getInstance().factions = FactionController.getInstance().factionsSync; + FactionController.getInstance().factionsSync = new HashMap(); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + Faction faction = new Faction(); + faction.readNBT(compound); + FactionController.getInstance().factions.put(faction.id, faction); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + FactionController.getInstance().factions.remove(id); + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/MagicCycleSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/MagicCycleSyncHandler.java new file mode 100644 index 000000000..37cbb3091 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/MagicCycleSyncHandler.java @@ -0,0 +1,79 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.MagicController; +import noppes.npcs.controllers.data.MagicCycle; + +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#MAGIC_CYCLE}. + * Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support. + */ +public class MagicCycleSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (MagicCycle cycle : MagicController.getInstance().cycles.values()) { + NBTTagCompound cycleCompound = new NBTTagCompound(); + cycle.writeNBT(cycleCompound); + list.appendTag(cycleCompound); + } + compound.setTag("Data", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("Data", 10); + MagicController mc = MagicController.getInstance(); + mc.cyclesSync.clear(); + for (int i = 0; i < list.tagCount(); i++) { + MagicCycle cycle = new MagicCycle(); + cycle.readNBT(list.getCompoundTagAt(i)); + mc.cyclesSync.put(cycle.id, cycle); + } + + mc.cycles.clear(); + mc.cycles.putAll(mc.cyclesSync); + mc.cyclesSync.clear(); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + MagicCycle cycle = new MagicCycle(); + cycle.readNBT(compound); + MagicController.getInstance().cycles.put(cycle.id, cycle); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + MagicController.getInstance().cycles.remove(id); + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/MagicSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/MagicSyncHandler.java new file mode 100644 index 000000000..86d965cc4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/MagicSyncHandler.java @@ -0,0 +1,95 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.MagicController; +import noppes.npcs.controllers.data.Magic; +import noppes.npcs.controllers.data.MagicCycle; + +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#MAGIC}. + * Simple int-keyed map family. + * REMOVE dissociates cycle associations before removing the magic entry. + * + *

Note: The original code had a bug where MAGIC REMOVE incorrectly + * removed from {@code cycles} instead of {@code magics}. This handler + * fixes that by properly removing from {@code magics} after dissociating.

+ */ +public class MagicSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (Magic magic : MagicController.getInstance().magics.values()) { + NBTTagCompound magicCompound = new NBTTagCompound(); + magic.writeNBT(magicCompound); + list.appendTag(magicCompound); + } + compound.setTag("Data", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("Data", 10); + MagicController mc = MagicController.getInstance(); + mc.magicSync.clear(); + for (int i = 0; i < list.tagCount(); i++) { + Magic magic = new Magic(); + magic.readNBT(list.getCompoundTagAt(i)); + mc.magicSync.put(magic.id, magic); + } + + mc.magics.clear(); + mc.magics.putAll(mc.magicSync); + mc.magicSync.clear(); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + Magic magic = new Magic(); + magic.readNBT(compound); + MagicController.getInstance().magics.put(magic.id, magic); + } + + /** + * Removes a magic entry from the client. First dissociates cycle + * references, then removes from the magics map. + *

Bug fix: The original code incorrectly removed from {@code cycles} + * instead of {@code magics} after dissociating cycle associations.

+ */ + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + // First remove this magic's association from all cycles + for (MagicCycle cycle : MagicController.getInstance().cycles.values()) { + cycle.associations.remove(id); + } + // Then remove the magic itself (fixed: was cycles.remove(id)) + MagicController.getInstance().magics.remove(id); + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerAbilitySyncHelper.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerAbilitySyncHelper.java new file mode 100644 index 000000000..258b25edb --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerAbilitySyncHelper.java @@ -0,0 +1,47 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.controllers.data.PlayerData; + +/** + * Direct per-player sync helper for player ability state. + * This is NOT a cached global sync family — it operates outside the + * registry-driven reload/revision system. + * + *

Abilities are synced per-player on demand (e.g. ability unlock, + * entity reconstruction, periodic cooldown ticks).

+ */ +public final class PlayerAbilitySyncHelper { + + private PlayerAbilitySyncHelper() { + } + + /** + * Full sync of all player ability state to the client: unlocked abilities, + * selection, toggles, hotbar layout, and cooldowns. + * Used for entity reconstruction and other full-refresh scenarios. + */ + public static void syncAbilities(EntityPlayerMP playerMP) { + PlayerData playerData = PlayerData.get(playerMP); + if (playerData == null) return; + + PlayerAbilitySyncPacket.sendToPlayer(playerMP); + AbilityHotbarSyncPacket.sendToPlayer(playerMP); + AbilityCooldownSyncPacket.sendToPlayer(playerMP); + } + + /** + * Lightweight sync of cooldown state only (global + per-ability). + * Called periodically (every 10 ticks) to keep the client's cooldown + * display accurate. Cooldowns are transient and not part of NBT sync. + */ + public static void syncAbilityCooldowns(EntityPlayerMP playerMP) { + PlayerData playerData = PlayerData.get(playerMP); + if (playerData == null) return; + + AbilityCooldownSyncPacket.sendToPlayer(playerMP); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerDataSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerDataSyncHandler.java new file mode 100644 index 000000000..b92277c31 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerDataSyncHandler.java @@ -0,0 +1,55 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.data.PlayerData; + +/** + * Sync handler for {@link SyncType#PLAYERDATA}. + * Special non-cached per-player path. Not included in login cache iteration. + * RELOAD and UPDATE are sent as direct per-player packets. + */ +public class PlayerDataSyncHandler implements SyncHandler { + + public static void syncPlayerData(EntityPlayerMP player, boolean update) { + PlayerData data = PlayerData.get(player); + if (data != null) + SyncController.syncPlayerData(SyncType.PLAYERDATA, update ? data.getSyncNBTFull() : data.getSyncNBT(), update, player); + } + + // ========== SERVER-SIDE ========== + + /** + * PLAYERDATA is not a global cached type — it is per-player. + */ + @Override + public NBTTagCompound serializeAll() { + return null; + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + if (categoryId == 1) ClientCacheHandler.playerData.setSyncNBTFull(compound); + else ClientCacheHandler.playerData.setSyncNBT(compound); + } + + @Override + public boolean supportsUpdate() { + return true; + } + + /** + * Not a cached type — PLAYERDATA uses direct per-player sync. + */ + @Override + public boolean isCachedType() { + return false; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerEffectSyncHelper.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerEffectSyncHelper.java new file mode 100644 index 000000000..52244de44 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/PlayerEffectSyncHelper.java @@ -0,0 +1,54 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.large.SyncEffectPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.EffectKey; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.PlayerEffect; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * Direct per-player sync helper for player effects. + * This is NOT a cached global sync family — it operates outside the + * registry-driven reload/revision system. + * + *

Effects are synced per-player on demand (e.g. effect application, + * periodic ticks). The data mutates {@code playerData.effectData} + * before sending the packet.

+ */ +public final class PlayerEffectSyncHelper { + + private PlayerEffectSyncHelper() { + } + + /** + * Server-side: sync the player's active effects to their client. + * Mutates {@code playerData.effectData} before sending. + */ + public static void syncEffects(EntityPlayerMP playerMP) { + ConcurrentHashMap playerEffects = CustomEffectController.getInstance().getPlayerEffects(playerMP); + PlayerData playerData = PlayerData.get(playerMP); + playerData.effectData.setEffects(playerEffects); + + NBTTagCompound compound = playerData.getPlayerEffects(); + PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP); + } + + /** + * Client-side: apply incoming effect data to the local player. + */ + @SideOnly(Side.CLIENT) + public static void clientSyncEffects(NBTTagCompound compound) { + PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer); + if (playerData != null) { + playerData.setPlayerEffects(compound); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/QuestCategorySyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/QuestCategorySyncHandler.java new file mode 100644 index 000000000..91d1fc893 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/QuestCategorySyncHandler.java @@ -0,0 +1,141 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.QuestController; +import noppes.npcs.controllers.data.Quest; +import noppes.npcs.controllers.data.QuestCategory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#QUEST_CATEGORY}. + * Parent-child category family. QUEST children share this cache. + * Invalidation from QUEST or QUEST_CATEGORY both target this cache. + */ +public class QuestCategorySyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList categoryList = new NBTTagList(); + for (QuestCategory category : QuestController.Instance.categories.values()) { + NBTTagCompound questCompound = new NBTTagCompound(); + ; + NBTTagList questList = new NBTTagList(); + for (int questID : category.quests.keySet()) { + Quest quest = category.quests.get(questID); + questList.appendTag(quest.writeToNBT(new NBTTagCompound())); + } + questCompound.setTag("Data", questList); + questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound())); + categoryList.appendTag(questCompound); + } + compound.setTag("QuestCategories", categoryList); + return compound; + } + + /** + * Serialize a single quest category for UPDATE packets. + */ + public static NBTTagCompound serializeCategory(QuestCategory questCategory) { + NBTTagCompound questCompound = new NBTTagCompound(); + NBTTagList questList = new NBTTagList(); + for (int questID : questCategory.quests.keySet()) { + Quest quest = questCategory.quests.get(questID); + questList.appendTag(quest.writeToNBT(new NBTTagCompound())); + } + questCompound.setTag("Data", questList); + questCompound.setTag("CatNBT", questCategory.writeSmallNBT(new NBTTagCompound())); + return questCompound; + } + + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + if (!fullCompound.hasNoTags()) { + NBTTagList categories = fullCompound.getTagList("QuestCategories", 10); + for (int j = 0; j < fullCompound.getTagList("QuestCategories", 10).tagCount(); j++) { + NBTTagCompound categoryCompound = categories.getCompoundTagAt(j); + if (categoryCompound.hasNoTags()) + continue; + + QuestCategory category = new QuestCategory(); + category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); + NBTTagList questList = categoryCompound.getTagList("Data", 10); + if (QuestController.Instance.categoriesSync.containsKey(category.id)) { + category = QuestController.Instance.categoriesSync.get(category.id); + category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT")); + } + for (int i = 0; i < questList.tagCount(); i++) { + Quest quest = new Quest(); + quest.readNBT(questList.getCompoundTagAt(i)); + quest.category = category; + category.quests.put(quest.id, quest); + } + QuestController.Instance.categoriesSync.put(category.id, category); + } + } + + HashMap quests = new HashMap<>(); + for (QuestCategory category : QuestController.Instance.categoriesSync.values()) { + for (Quest quest : category.quests.values()) { + quests.put(quest.id, quest); + } + } + + QuestController.Instance.categories = QuestController.Instance.categoriesSync; + QuestController.Instance.quests = quests; + QuestController.Instance.categoriesSync = new HashMap<>(); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + QuestCategory category = new QuestCategory(); + category.readSmallNBT(compound.getCompoundTag("CatNBT")); + NBTTagList list = compound.getTagList("Data", 10); + if (QuestController.Instance.categoriesSync.containsKey(category.id)) { + category = QuestController.Instance.categoriesSync.get(category.id); + category.readSmallNBT(compound.getCompoundTag("CatNBT")); + } + for (int i = 0; i < list.tagCount(); i++) { + Quest quest = new Quest(); + quest.readNBT(list.getCompoundTagAt(i)); + quest.category = category; + category.quests.put(quest.id, quest); + } + QuestController.Instance.categories.put(category.id, category); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + QuestCategory questCategory = QuestController.Instance.categories.remove(id); + if (questCategory != null) { + QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet()); + } + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/QuestSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/QuestSyncHandler.java new file mode 100644 index 000000000..172bf5535 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/QuestSyncHandler.java @@ -0,0 +1,90 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.QuestController; +import noppes.npcs.controllers.data.Quest; +import noppes.npcs.controllers.data.QuestCategory; + +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#QUEST}. + * Child family — does not have its own cache. UPDATE and REMOVE only. + * Invalidation targets the parent {@link SyncType#QUEST_CATEGORY} cache. + */ +public class QuestSyncHandler implements SyncHandler { + + // ========== SERVER-SIDE ========== + + /** + * QUEST does not have its own independent cache; it shares + * the QUEST_CATEGORY parent cache. + */ + @Override + public NBTTagCompound serializeAll() { + return null; + } + + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + // QUEST does not handle standalone RELOAD; it's part of QUEST_CATEGORY + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleUpdate(NBTTagCompound compound, int categoryId) { + QuestCategory category = QuestController.Instance.categories.get(categoryId); + if (category == null) + return; // Defensive: category may have been removed + + Quest quest = new Quest(); + quest.category = category; + quest.readNBT(compound); + QuestController.Instance.quests.put(quest.id, quest); + category.quests.put(quest.id, quest); + } + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleRemove(int id) { + Quest quest = QuestController.Instance.quests.remove(id); + if (quest != null) + quest.category.quests.remove(id); + + } + + @Override + public boolean supportsUpdate() { + return true; + } + + @Override + public boolean supportsRemove() { + return true; + } + + /** + * Not a cached type — QUEST shares the QUEST_CATEGORY cache. + */ + @Override + public boolean isCachedType() { + return false; + } + + @Override + public Set getInvalidationTargets(SyncType self) { + // Child invalidates the parent cache + Set set = new HashSet<>(); + set.add(SyncType.QUEST_CATEGORY); + return set; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/sync/handlers/WorkbenchRecipeSyncHandler.java b/src/main/java/kamkeel/npcs/controllers/sync/handlers/WorkbenchRecipeSyncHandler.java new file mode 100644 index 000000000..02d52f25a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/sync/handlers/WorkbenchRecipeSyncHandler.java @@ -0,0 +1,70 @@ +package kamkeel.npcs.controllers.sync.handlers; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.sync.SyncHandler; +import kamkeel.npcs.network.enums.SyncType; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.RecipeController; +import noppes.npcs.controllers.data.RecipeCarpentry; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +/** + * Sync handler for {@link SyncType#WORKBENCH_RECIPES}. + * RELOAD-only family — does not support individual UPDATE or REMOVE. + * Client-side RELOAD routes through {@link RecipeController#reloadGlobalRecipes}. + */ +public class WorkbenchRecipeSyncHandler implements SyncHandler { + + private static final WorkbenchRecipeSyncHandler INSTANCE = new WorkbenchRecipeSyncHandler(); + + public static WorkbenchRecipeSyncHandler getInstance() { + return INSTANCE; + } + // ========== SERVER-SIDE ========== + + @Override + public NBTTagCompound serializeAll() { + RecipeController controller = RecipeController.Instance; + NBTTagList list = new NBTTagList(); + NBTTagCompound compound = new NBTTagCompound(); + for (RecipeCarpentry recipe : controller.globalRecipes.values()) { + list.appendTag(recipe.writeNBT(false)); + } + compound.setTag("recipes", list); + return compound; + } + + // ========== CLIENT-SIDE ========== + + @SideOnly(Side.CLIENT) + @Override + public void clientHandleReload(NBTTagCompound fullCompound) { + NBTTagList list = fullCompound.getTagList("recipes", 10); + if (list == null) + return; + + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound recipeCompound = list.getCompoundTagAt(i); + RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound); + recipe.readNBT(recipeCompound); + RecipeController.syncRecipes.put(recipe.id, recipe); + } + + RecipeController.reloadGlobalRecipes(RecipeController.syncRecipes); + RecipeController.syncRecipes = new HashMap<>(); + } + + @Override + public Set getInvalidationTargets(SyncType self) { + Set set = new HashSet<>(); + set.add(SyncType.WORKBENCH_RECIPES); + return set; + } + + // RELOAD-only: supportsUpdate() and supportsRemove() remain false (default) +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 1427b298f..646cbbd9a 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -1,101 +1,142 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.data.*; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; import kamkeel.npcs.util.AnchorPointHelper; 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.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.LogWriter; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** * Beam projectile - head with trailing path that curves with homing. * Stays attached to origin point, trail shows path of head. - * + *

* IMPORTANT: Trail points are stored RELATIVE to startX/Y/Z (origin). * This ensures rendering is stable regardless of entity position interpolation. - * + *

* Design inspired by LouisXIV's energy attack system. */ -public class EntityAbilityBeam extends EntityAbilityProjectile { +public class EntityAbilityBeam extends EntityEnergyProjectile { - // Beam shape properties + private enum BeamMode { + ANCHORED, + FREE_TRAIL + } + + // Beam shape properties (target values - set by sync packets/scripts) private float beamWidth = 0.3f; private float headSize = 0.5f; + // Lerp-smoothed render values (approach target each tick) + private float renderBeamWidth = 0.3f; + private float renderHeadSize = 0.5f; + private float prevRenderBeamWidth = 0.3f; + private float prevRenderHeadSize = 0.5f; + // Trail - list of points showing beam path (RELATIVE to origin!) private List trailPoints = new ArrayList<>(); private static final int MAX_TRAIL_POINTS = 200; private static final double MIN_POINT_DISTANCE = 0.2; + private static final int TRAIL_COMPACT_THRESHOLD = 128; + private int trailStartIndex = 0; // Head position relative to origin private double headOffsetX, headOffsetY, headOffsetZ; private double prevHeadOffsetX, prevHeadOffsetY, prevHeadOffsetZ; - // Origin stays fixed (or follows owner) - private boolean attachedToOwner = true; + // Beam behavior mode (single source of truth). + private BeamMode beamMode = BeamMode.ANCHORED; - // Whether to render tail orb (only when anchored) - private boolean renderTailOrb = true; + // Free Aim (players only) - steers beam toward player's look direction + private boolean freeAim = false; + private static final float FREE_AIM_STRENGTH = 0.15f; - // 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) - private boolean fadeTrail = false; 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; - public EntityAbilityBeam(World world) { super(world); } @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + // Beam can extend far from entity position (head); use a generous render distance + // that accounts for the full beam length (origin to head) + double headDist = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ); + double range = Math.max(128.0D, headDist * 2.0D + 64.0D); + return distance < range * range; } - /** - * 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; + private static BeamMode modeFromAnchored(boolean anchored) { + return anchored ? BeamMode.ANCHORED : BeamMode.FREE_TRAIL; } - /** - * 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)); + private boolean isAnchoredMode() { + return beamMode == BeamMode.ANCHORED; + } + + private boolean isFadingMode() { + return beamMode == BeamMode.FREE_TRAIL; + } + + private int getActiveTrailSize() { + return Math.max(0, trailPoints.size() - trailStartIndex); + } + + private void resetHeadOffsets() { + headOffsetX = 0; + headOffsetY = 0; + headOffsetZ = 0; + prevHeadOffsetX = 0; + prevHeadOffsetY = 0; + prevHeadOffsetZ = 0; + } + + private void resetTrailStorage() { + trailPoints.clear(); + trailPointAges.clear(); + trailStartIndex = 0; + } + + private void setBeamMode(BeamMode mode) { + beamMode = mode != null ? mode : BeamMode.ANCHORED; + if (isFadingMode()) { + while (trailPointAges.size() < trailPoints.size()) { + trailPointAges.add(0); + } + while (trailPointAges.size() > trailPoints.size()) { + trailPointAges.remove(trailPointAges.size() - 1); + } + } else { + if (trailStartIndex > 0 && trailStartIndex < trailPoints.size()) { + trailPoints = new ArrayList(trailPoints.subList(trailStartIndex, trailPoints.size())); + } + trailStartIndex = 0; + trailPointAges.clear(); } } /** * Full constructor with all parameters using data classes. + * * @param anchoredMode If true, origin follows owner and tail orb is rendered. * If false, beam is free-moving with trailing length (no tail orb). */ @@ -104,226 +145,86 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { float beamWidth, float headSize, EnergyDisplayData display, EnergyCombatData combat, EnergyHomingData homing, EnergyLightningData lightning, - EnergyLifespanData lifespan, EnergyTrajectoryData trajectory, + EnergyLifespanData lifespan, boolean anchoredMode) { super(world); // Initialize base properties via parent - initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan, trajectory); + initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan); // Beam-specific properties from homing data - this.homingData = homing; + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); this.beamWidth = beamWidth; this.headSize = headSize; - // Anchored mode controls whether origin follows owner and tail orb is rendered - this.attachedToOwner = anchoredMode; - this.renderTailOrb = anchoredMode; + // Beam mode controls tail attachment/orb/fading behavior. + setBeamMode(modeFromAnchored(anchoredMode)); // Initialize head offset at origin (0,0,0 relative) - this.headOffsetX = 0; - this.headOffsetY = 0; - this.headOffsetZ = 0; - this.prevHeadOffsetX = 0; - this.prevHeadOffsetY = 0; - this.prevHeadOffsetZ = 0; + resetHeadOffsets(); // Add initial trail point at origin (relative 0,0,0) trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); - if (DEBUG_LOGGING && !world.isRemote) { - LogWriter.info("[Beam] Created at origin " + x + ", " + y + ", " + z + " maxDist=" + lifespan.maxDistance); - } - // 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) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; + setupChargingState(anchor, chargeDuration); this.chargeOffsetDistance = chargeOffsetDistance; - this.anchorData = anchor; - this.fadeTrail = !attachedToOwner; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; + clearMotion(); } public void setupPreview(EntityLivingBase owner, float beamWidth, float headSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { - this.setPreviewMode(true); - this.setPreviewOwner(owner); + setupPreviewState(owner, display, lightning, anchor, chargeDuration); // Set visual properties this.beamWidth = beamWidth; this.headSize = headSize; - this.size = headSize; - this.displayData = display; - this.lightningData = lightning; + setVisualSize(headSize); - // Set charging state - this.setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; this.chargeOffsetDistance = chargeOffsetDistance; - this.anchorData = anchor; - - // Initial position at anchor point - Vec3 pos = AnchorPointHelper.calculateAnchorPosition(owner, anchorData, chargeOffsetDistance); - this.setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - this.prevPosX = pos.xCoord; - this.prevPosY = pos.yCoord; - this.prevPosZ = pos.zCoord; - this.startX = pos.xCoord; - this.startY = pos.yCoord; - this.startZ = pos.zCoord; + setChargeOriginFromAnchor(owner, anchorData, chargeOffsetDistance); // Initialize head offsets - this.headOffsetX = 0; - this.headOffsetY = 0; - this.headOffsetZ = 0; - this.prevHeadOffsetX = 0; - this.prevHeadOffsetY = 0; - this.prevHeadOffsetZ = 0; - - // Attach to owner for anchor following - this.attachedToOwner = true; - this.renderTailOrb = true; + resetHeadOffsets(); // Clear motion - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; + clearMotion(); } /** * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - - setCharging(false); - - // Origin (tail) stays at the charged position - startX = posX; - startY = posY; - startZ = posZ; + startPreviewFiringDefault(); // 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; + resetHeadOffsets(); // Reset trail - trailPoints.clear(); - trailPointAges.clear(); + resetTrailStorage(); 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); - motionX = -Math.sin(yaw) * getSpeed(); - motionY = 0; - motionZ = Math.cos(yaw) * getSpeed(); - } else { - motionX = getSpeed(); - motionY = 0; - motionZ = 0; - } + if (isFadingMode()) trailPointAges.add(0); } /** * Start the beam firing (exit charging mode). * Called by ability when windup ends. - * - * For anchored beams: origin follows owner, head starts at charged position - * For non-anchored beams: origin fixed at charged position, head starts there */ public void startFiring(EntityLivingBase target) { - if (!isCharging()) return; - - setCharging(false); - - // Origin (tail) stays at the charged position - where the orb was - // This is the same for both anchored and non-anchored modes - startX = posX; - startY = posY; - startZ = posZ; + startMovingTowardTargetFromStartDefault(target); // Head starts at the origin (tail position) - headOffsetX = 0; - headOffsetY = 0; - headOffsetZ = 0; - prevHeadOffsetX = 0; - prevHeadOffsetY = 0; - prevHeadOffsetZ = 0; - - // Origin no longer follows owner after firing starts - // (for anchored mode, tail is fixed in space; for non-anchored, there's no tail) - attachedToOwner = false; + resetHeadOffsets(); // Initialize trail with just the origin point - trailPoints.clear(); - trailPointAges.clear(); + resetTrailStorage(); trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); - if (fadeTrail) trailPointAges.add(0); + if (isFadingMode()) trailPointAges.add(0); - // Calculate velocity toward target (head starts at origin = startX/Y/Z) - Entity owner = getOwnerEntity(); - - if (target != null) { - double dx = target.posX - startX; - double dy = (target.posY + target.getEyeHeight()) - startY; - double dz = target.posZ - startZ; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - motionX = (dx / len) * getSpeed(); - motionY = (dy / len) * getSpeed(); - motionZ = (dz / len) * getSpeed(); - } - } else if (owner != null) { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - motionY = -Math.sin(pitch) * getSpeed(); - motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } - - if (DEBUG_LOGGING && !worldObj.isRemote) { - LogWriter.info("[Beam] startFiring: origin=(" + startX + "," + startY + "," + startZ + - ") headOffset=(" + headOffsetX + "," + headOffsetY + "," + headOffsetZ + - ") motion=(" + motionX + "," + motionY + "," + motionZ + ")"); - } } @Override @@ -331,31 +232,37 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Check distance using head offset (distance from origin) double distFromOrigin = Math.sqrt( headOffsetX * headOffsetX + - headOffsetY * headOffsetY + - headOffsetZ * headOffsetZ + headOffsetY * headOffsetY + + headOffsetZ * headOffsetZ ); - boolean exceeded = distFromOrigin >= getMaxDistance(); - if (exceeded && !worldObj.isRemote && DEBUG_LOGGING) { - LogWriter.info("[Beam] DEAD: Max distance exceeded. dist=" + distFromOrigin + " max=" + getMaxDistance()); - } - return exceeded; + return distFromOrigin >= getMaxDistance(); } @Override protected void updateProjectile() { + // Save previous render values for sub-tick interpolation + prevRenderBeamWidth = renderBeamWidth; + prevRenderHeadSize = renderHeadSize; + // Handle charging state (windup phase) - use isCharging() for synced value if (isCharging()) { + // During charging, snap render values to target (size grows smoothly already) + renderBeamWidth = beamWidth; + renderHeadSize = headSize; updateCharging(); return; } - // Store previous head offset for interpolation + // Lerp render values toward target (smooth out sync packet jumps) + renderBeamWidth += (beamWidth - renderBeamWidth) * 0.15f; + renderHeadSize += (headSize - renderHeadSize) * 0.15f; + prevHeadOffsetX = headOffsetX; prevHeadOffsetY = headOffsetY; prevHeadOffsetZ = headOffsetZ; // Age trail points for fading effect - if (fadeTrail) { + if (isFadingMode()) { ageTrailPoints(); } @@ -389,7 +296,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { headOffsetZ += motionZ; // Update origin if attached to owner - if (attachedToOwner) { + if (isAnchoredMode()) { Entity owner = getOwnerEntity(); if (owner != null) { startX = owner.posX; @@ -409,17 +316,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Add trail point addTrailPoint(); - // Debug log periodically - if (DEBUG_LOGGING && ticksExisted % 20 == 0) { - LogWriter.info("[Beam] Server tick=" + ticksExisted + " headOffset=(" + - String.format("%.2f", headOffsetX) + "," + - String.format("%.2f", headOffsetY) + "," + - String.format("%.2f", headOffsetZ) + ") origin=(" + - String.format("%.2f", startX) + "," + - String.format("%.2f", startY) + "," + - String.format("%.2f", startZ) + ") trail=" + trailPoints.size()); - } - // Skip collision checks on first few ticks if (ticksExisted > 2) { checkBlockCollision(headWorldX, headWorldY, headWorldZ); @@ -430,63 +326,76 @@ 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; } /** * Age trail points and remove old ones (for comet effect). */ private void ageTrailPoints() { - // Age all trail points - for (int i = 0; i < trailPointAges.size(); i++) { + if (trailStartIndex >= trailPoints.size()) { + resetTrailStorage(); + return; + } + + // Age all active trail points. + for (int i = trailStartIndex; i < trailPointAges.size(); i++) { trailPointAges.set(i, trailPointAges.get(i) + 1); } - // Remove trail points that have fully faded - while (!trailPointAges.isEmpty() && trailPointAges.get(0) >= trailFadeTime) { - trailPointAges.remove(0); - if (!trailPoints.isEmpty()) { - trailPoints.remove(0); - } + // Move logical start index forward for fully faded points. + while (trailStartIndex < trailPointAges.size() && trailPointAges.get(trailStartIndex) >= trailFadeTime) { + trailStartIndex++; + } + + if (trailStartIndex >= trailPoints.size()) { + resetTrailStorage(); + return; + } + + // Compact stale prefix to avoid unbounded growth of dead entries. + if (trailStartIndex >= TRAIL_COMPACT_THRESHOLD && trailStartIndex * 2 >= trailPoints.size()) { + trailPoints = new ArrayList(trailPoints.subList(trailStartIndex, trailPoints.size())); + trailPointAges = new ArrayList(trailPointAges.subList(trailStartIndex, trailPointAges.size())); + trailStartIndex = 0; } } private void addTrailPoint() { + if (trailStartIndex >= trailPoints.size()) { + resetTrailStorage(); + } + // Trail points are RELATIVE to origin if (trailPoints.isEmpty()) { trailPoints.add(Vec3.createVectorHelper(headOffsetX, headOffsetY, headOffsetZ)); - if (fadeTrail) { + if (isFadingMode()) { trailPointAges.add(0); } return; @@ -495,18 +404,18 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { Vec3 lastPoint = trailPoints.get(trailPoints.size() - 1); double dist = Math.sqrt( (headOffsetX - lastPoint.xCoord) * (headOffsetX - lastPoint.xCoord) + - (headOffsetY - lastPoint.yCoord) * (headOffsetY - lastPoint.yCoord) + - (headOffsetZ - lastPoint.zCoord) * (headOffsetZ - lastPoint.zCoord) + (headOffsetY - lastPoint.yCoord) * (headOffsetY - lastPoint.yCoord) + + (headOffsetZ - lastPoint.zCoord) * (headOffsetZ - lastPoint.zCoord) ); if (dist >= MIN_POINT_DISTANCE) { trailPoints.add(Vec3.createVectorHelper(headOffsetX, headOffsetY, headOffsetZ)); - if (fadeTrail) { + if (isFadingMode()) { trailPointAges.add(0); } // Limit trail length (only if not using fading - fading handles its own cleanup) - if (!fadeTrail) { + if (!isFadingMode()) { while (trailPoints.size() > MAX_TRAIL_POINTS) { trailPoints.remove(0); } @@ -524,7 +433,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { headOffsetZ += motionZ; // Update origin if attached to owner - if (attachedToOwner) { + if (isAnchoredMode()) { Entity owner = getOwnerEntity(); if (owner != null) { startX = owner.posX; @@ -545,7 +454,54 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { addTrailPoint(); } - private void updateHoming() { + /** + * Steer beam toward player's look direction (Free Aim mode). + * Blends the velocity DIRECTION toward the look vector each tick, producing + * a smooth arc. The turn radius scales naturally with speed (faster = wider arc). + *

+ * Previous approach projected a target point at headDist along the look line, + * which caused oscillation at high speeds (the position target kept shifting) + * and spiraling at large distances (cross-track error grew faster than correction). + */ + private void updateFreeAim() { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityPlayer)) return; + + Vec3 look = getOwnerLookVector(); + if (look == null) return; + + double speed = getSpeed(); + + // Desired velocity = look direction at current speed + double desiredVX = look.xCoord * speed; + double desiredVY = look.yCoord * speed; + double desiredVZ = look.zCoord * speed; + + // Blend current velocity toward desired direction + motionX += (desiredVX - motionX) * FREE_AIM_STRENGTH; + motionY += (desiredVY - motionY) * FREE_AIM_STRENGTH; + motionZ += (desiredVZ - motionZ) * FREE_AIM_STRENGTH; + + // Renormalize to constant speed + double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + if (vLen > 0) { + motionX = (motionX / vLen) * speed; + motionY = (motionY / vLen) * speed; + motionZ = (motionZ / vLen) * speed; + } + } + + @Override + protected void updateHoming() { + if (freeAim) { + Entity owner = getOwnerEntity(); + if (owner instanceof EntityPlayer) { + updateFreeAim(); + return; + } + // NPCs fall through to normal homing + } + if (!isHoming()) return; Entity target = getTargetEntity(); @@ -593,53 +549,45 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { double prevHeadWorldY = startY + prevHeadOffsetY; double prevHeadWorldZ = startZ + prevHeadOffsetZ; - Vec3 currentPos = Vec3.createVectorHelper(prevHeadWorldX, prevHeadWorldY, prevHeadWorldZ); - Vec3 nextPos = Vec3.createVectorHelper(headX, headY, headZ); - // Use full raytrace that doesn't stop at liquids and checks all blocks - MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); - - if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - hasHit = true; - if (isExplosive()) { - posX = blockHit.hitVec.xCoord; - posY = blockHit.hitVec.yCoord; - posZ = blockHit.hitVec.zCoord; - doExplosion(); - } - this.setDead(); - } + handleBlockImpact(rayTraceBlocks(prevHeadWorldX, prevHeadWorldY, prevHeadWorldZ, headX, headY, headZ), true); } private void checkEntityCollision(double headX, double headY, double headZ) { - double hitSize = headSize * 0.5; + // Swept head hitbox prevents misses when beam head moves quickly between ticks. + double prevHeadWorldX = startX + prevHeadOffsetX; + double prevHeadWorldY = startY + prevHeadOffsetY; + double prevHeadWorldZ = startZ + prevHeadOffsetZ; + double hitSize = Math.max(0.05, headSize * 0.5); AxisAlignedBB hitBox = AxisAlignedBB.getBoundingBox( - headX - hitSize, headY - hitSize, headZ - hitSize, - headX + hitSize, headY + hitSize, headZ + hitSize + Math.min(prevHeadWorldX, headX) - hitSize, + Math.min(prevHeadWorldY, headY) - hitSize, + Math.min(prevHeadWorldZ, headZ) - hitSize, + Math.max(prevHeadWorldX, headX) + hitSize, + Math.max(prevHeadWorldY, headY) + hitSize, + Math.max(prevHeadWorldZ, headZ) + hitSize ); - @SuppressWarnings("unchecked") - List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); + processEntitiesInHitBox(hitBox, headX, headY, headZ); + } - for (EntityLivingBase entity : entities) { - if (shouldIgnoreEntity(entity)) continue; + // ==================== DEBUG ==================== - if (DEBUG_LOGGING) { - LogWriter.info("[Beam] DEAD: Entity collision with " + entity.getClass().getSimpleName() + " at tick " + ticksExisted); - } - hasHit = true; - - if (isExplosive()) { - posX = headX; - posY = headY; - posZ = headZ; - doExplosion(); - } else { - applyDamage(entity); - } - - this.setDead(); - return; - } + @Override + protected String debugLogExtra() { + double headWorldX = startX + headOffsetX; + double headWorldY = startY + headOffsetY; + double headWorldZ = startZ + headOffsetZ; + return String.format("headOff=(%.2f,%.2f,%.2f) prevHead=(%.2f,%.2f,%.2f) " + + "origin=(%.2f,%.2f,%.2f) headWorld=(%.2f,%.2f,%.2f) " + + "trail=%d mode=%s anchored=%b beamW=%.2f headSz=%.2f " + + "motion=(%.3f,%.3f,%.3f)", + headOffsetX, headOffsetY, headOffsetZ, + prevHeadOffsetX, prevHeadOffsetY, prevHeadOffsetZ, + startX, startY, startZ, + headWorldX, headWorldY, headWorldZ, + getActiveTrailSize(), + beamMode.name(), isAnchoredMode(), beamWidth, headSize, + motionX, motionY, motionZ); } // ==================== GETTERS FOR RENDERER ==================== @@ -648,10 +596,38 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { return beamWidth; } + public float getInterpolatedBeamWidth(float partialTicks) { + return prevRenderBeamWidth + (renderBeamWidth - prevRenderBeamWidth) * partialTicks; + } + + public void setBeamWidth(float beamWidth) { + this.beamWidth = beamWidth; + } + public float getHeadSize() { return headSize; } + public float getInterpolatedHeadSize(float partialTicks) { + return prevRenderHeadSize + (renderHeadSize - prevRenderHeadSize) * partialTicks; + } + + public void setHeadSize(float headSize) { + this.headSize = headSize; + } + + public void setAttachedToOwner(boolean attached) { + setBeamMode(modeFromAnchored(attached)); + } + + public boolean isFreeAim() { + return freeAim; + } + + public void setFreeAim(boolean freeAim) { + this.freeAim = freeAim; + } + /** * Get interpolated head offset for smooth rendering. * Returns offset RELATIVE to origin. @@ -672,7 +648,13 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * Get trail points. These are RELATIVE to origin (startX/Y/Z). */ public List getTrailPoints() { - return trailPoints; + if (trailStartIndex <= 0) { + return trailPoints; + } + if (trailStartIndex >= trailPoints.size()) { + return Collections.emptyList(); + } + return trailPoints.subList(trailStartIndex, trailPoints.size()); } public double getOriginX() { @@ -691,46 +673,34 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * Whether the tail orb should be rendered (only true in anchored mode). */ public boolean shouldRenderTailOrb() { - return renderTailOrb; + return isAnchoredMode(); } /** * Whether the beam is attached to its owner (anchored mode). */ public boolean isAttachedToOwner() { - 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; + return isAnchoredMode(); } /** * Whether trail should fade (comet effect for non-anchored beams). */ public boolean hasFadingTrail() { - return fadeTrail; + return isFadingMode(); } /** * Get trail point ages for fading calculation. */ public List getTrailPointAges() { - return trailPointAges; + if (trailStartIndex <= 0) { + return trailPointAges; + } + if (trailStartIndex >= trailPointAges.size()) { + return Collections.emptyList(); + } + return trailPointAges.subList(trailStartIndex, trailPointAges.size()); } /** @@ -740,33 +710,109 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { return trailFadeTime; } + // ==================== REFLECTION ==================== + + @Override + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { + boolean reflected = super.reflectFromBarrier(barrier, reflectStrengthPct); + if (reflected) { + // Switch to FREE_TRAIL: detach from caster (tail-less), trail fades out. + setBeamMode(BeamMode.FREE_TRAIL); + + // Reset origin to the reflection point (current head position). + startX = posX; + startY = posY; + startZ = posZ; + resetHeadOffsets(); + resetTrailStorage(); + + // Free aim only works for the original caster + freeAim = false; + + // If targeting owner, keep homing so beam tracks back to caster + if (!barrier.getBarrierData().isTargetOwner()) { + homingData.setHoming(false); + setTargetEntityId(-1); + } + } + return reflected; + } + + @Override + protected void writeProjectileReflectionData(NBTTagCompound nbt) { + nbt.setByte("BeamMode", (byte) beamMode.ordinal()); + nbt.setDouble("StartX", startX); + nbt.setDouble("StartY", startY); + nbt.setDouble("StartZ", startZ); + } + + @Override + protected void applyProjectileReflectionData(NBTTagCompound nbt) { + int mode = nbt.getByte("BeamMode"); + setBeamMode(mode >= 0 && mode < BeamMode.values().length ? BeamMode.values()[mode] : BeamMode.FREE_TRAIL); + startX = nbt.getDouble("StartX"); + startY = nbt.getDouble("StartY"); + startZ = nbt.getDouble("StartZ"); + resetHeadOffsets(); + resetTrailStorage(); + homingData.setHoming(false); + freeAim = false; + setTargetEntityId(-1); + } + + // ==================== PROPERTY SYNC ==================== + + @Override + protected void writeProjectileClientSyncData(NBTTagCompound nbt) { + nbt.setFloat("BeamWidth", beamWidth); + nbt.setFloat("HeadSize", headSize); + nbt.setBoolean("AttachedToOwner", isAttachedToOwner()); + } + + @Override + protected void applyProjectileClientSyncData(NBTTagCompound nbt) { + beamWidth = nbt.getFloat("BeamWidth"); + headSize = nbt.getFloat("HeadSize"); + setAttachedToOwner(nbt.getBoolean("AttachedToOwner")); + } + // ==================== NBT ==================== @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f; - this.headSize = nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f; + this.beamWidth = sanitize(nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f, 0.3f, MAX_ENTITY_SIZE); + this.headSize = sanitize(nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f, 0.5f, MAX_ENTITY_SIZE); + this.renderBeamWidth = this.beamWidth; + this.renderHeadSize = this.headSize; + this.prevRenderBeamWidth = this.beamWidth; + this.prevRenderHeadSize = this.headSize; this.headOffsetX = nbt.hasKey("HeadOffsetX") ? nbt.getDouble("HeadOffsetX") : 0; this.headOffsetY = nbt.hasKey("HeadOffsetY") ? nbt.getDouble("HeadOffsetY") : 0; this.headOffsetZ = nbt.hasKey("HeadOffsetZ") ? nbt.getDouble("HeadOffsetZ") : 0; this.prevHeadOffsetX = this.headOffsetX; this.prevHeadOffsetY = this.headOffsetY; 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; + this.freeAim = nbt.getBoolean("FreeAim"); + boolean attachedLegacy = !nbt.hasKey("AttachedToOwner") || nbt.getBoolean("AttachedToOwner"); + BeamMode loadedMode = modeFromAnchored(attachedLegacy); + if (nbt.hasKey("BeamMode")) { + try { + loadedMode = BeamMode.valueOf(nbt.getString("BeamMode")); + } catch (IllegalArgumentException ignored) { + loadedMode = modeFromAnchored(attachedLegacy); + } + } else if (nbt.hasKey("FadeTrail")) { + loadedMode = nbt.getBoolean("FadeTrail") ? BeamMode.FREE_TRAIL : modeFromAnchored(attachedLegacy); + } // Read trail points (relative to origin) trailPoints.clear(); + trailPointAges.clear(); + trailStartIndex = 0; if (nbt.hasKey("Trail")) { NBTTagList trailList = nbt.getTagList("Trail", 10); for (int i = 0; i < trailList.tagCount(); i++) { @@ -778,6 +824,15 @@ 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); + } + } + setBeamMode(loadedMode); } @Override @@ -787,20 +842,18 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { nbt.setDouble("HeadOffsetX", headOffsetX); nbt.setDouble("HeadOffsetY", headOffsetY); nbt.setDouble("HeadOffsetZ", headOffsetZ); - nbt.setBoolean("AttachedToOwner", attachedToOwner); - nbt.setBoolean("RenderTailOrb", renderTailOrb); - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); + nbt.setBoolean("AttachedToOwner", isAnchoredMode()); + nbt.setString("BeamMode", beamMode.name()); + writeChargingNBT(nbt); nbt.setFloat("ChargeOffsetDistance", chargeOffsetDistance); - nbt.setBoolean("FadeTrail", fadeTrail); + nbt.setBoolean("FreeAim", freeAim); + nbt.setBoolean("FadeTrail", isFadingMode()); nbt.setInteger("TrailFadeTime", trailFadeTime); - this.anchorData.writeNBT(nbt); - // Write trail points NBTTagList trailList = new NBTTagList(); - for (Vec3 point : trailPoints) { + for (int i = trailStartIndex; i < trailPoints.size(); i++) { + Vec3 point = trailPoints.get(i); NBTTagCompound pointNbt = new NBTTagCompound(); pointNbt.setDouble("X", point.xCoord); pointNbt.setDouble("Y", point.yCoord); @@ -808,5 +861,14 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { trailList.appendTag(pointNbt); } nbt.setTag("Trail", trailList); + + // Write trail point ages for fading trail sync + int activeSize = isFadingMode() ? Math.max(0, trailPoints.size() - trailStartIndex) : 0; + int[] ages = new int[activeSize]; + for (int i = 0; i < activeSize; i++) { + int idx = trailStartIndex + i; + ages[i] = idx < trailPointAges.size() ? trailPointAges.get(idx) : 0; + } + 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 edd7b3dff..7edc1dae1 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -1,24 +1,26 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import java.util.List; - /** * Disc projectile - flat spinning disc with optional boomerang behavior. * Has a wider, thinner hitbox compared to Orb. - * + *

* Design inspired by LouisXIV's energy attack system. */ -public class EntityAbilityDisc extends EntityAbilityProjectile { +public class EntityAbilityDisc extends EntityEnergyProjectile { // Disc-specific movement propertie @@ -28,53 +30,31 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { private boolean returning = false; private int ticksSinceMiss = 0; - // Disc shape properties + // Disc shape properties (target values) private float discRadius = 1.0f; // Width of disc private float discThickness = 0.2f; // Height of disc + + // Lerp-smoothed render values + private float renderDiscRadius = 1.0f; + private float renderDiscThickness = 0.2f; + private float prevRenderDiscRadius = 1.0f; + private float prevRenderDiscThickness = 0.2f; + + // Boomerang owner-gone tracking + private int returnOwnerNullTicks = 0; 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; + // Cached travel direction for smooth rendering when motion is near zero + private float lastTravelYaw = 0.0f; + + // 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 - // 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. */ @@ -83,14 +63,14 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { float discRadius, float discThickness, EnergyDisplayData display, EnergyCombatData combat, EnergyHomingData homing, EnergyLightningData lightning, - EnergyLifespanData lifespan, EnergyTrajectoryData trajectory, + EnergyLifespanData lifespan, boolean boomerang, int boomerangDelay) { super(world); // Initialize base properties - initProjectile(owner, target, x, y, z, discRadius, display, combat, lightning, lifespan, trajectory); + initProjectile(owner, target, x, y, z, 1.0f, display, combat, lightning, lifespan); - this.homingData = homing; + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); this.boomerang = boomerang; this.boomerangDelay = boomerangDelay; @@ -99,23 +79,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); } /** @@ -124,21 +88,12 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Position follows the owner based on anchor point. */ public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; - this.vertical = 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; } /** @@ -147,18 +102,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * 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, boolean vertical) { - this.setPreviewMode(true); - this.setPreviewOwner(owner); - - // Set visual properties - this.displayData = display; - this.lightningData = lightning; - - // Set charging state - this.setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; + setupPreviewState(owner, display, lightning, anchor, chargeDuration); this.vertical = vertical; // Store target size and start at 0 for grow effect @@ -166,55 +110,16 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.targetDiscThickness = discThickness; this.discRadius = 0.01f; this.discThickness = 0.01f; - this.size = 0.01f; - - // Initial position at anchor point - Vec3 pos = AnchorPointHelper.calculateAnchorPosition(owner, anchorData); - this.setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - this.prevPosX = pos.xCoord; - this.prevPosY = pos.yCoord; - this.prevPosZ = pos.zCoord; - this.startX = pos.xCoord; - this.startY = pos.yCoord; - this.startZ = pos.zCoord; - - // Clear motion - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; + setVisualSize(0.01f); + setChargeOriginFromAnchor(owner, anchorData); + clearMotion(); } /** * 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 - startX = posX; - startY = posY; - startZ = posZ; - - // Sync prev position to prevent visual jump on first frame - prevPosX = posX; - prevPosY = posY; - prevPosZ = posZ; - - // 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(); - } else { - motionX = getSpeed(); - motionY = 0; - motionZ = 0; - } + startPreviewFiringDefault(); } /** @@ -222,35 +127,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Called by ability when windup ends. */ public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - - setCharging(false); - - // Update start position to current position - startX = posX; - startY = posY; - startZ = posZ; - - // Calculate velocity toward target - Entity owner = getOwnerEntity(); - - if (target != null) { - double dx = target.posX - posX; - double dy = (target.posY + target.getEyeHeight()) - posY; - double dz = target.posZ - posZ; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - motionX = (dx / len) * getSpeed(); - motionY = (dy / len) * getSpeed(); - motionZ = (dz / len) * getSpeed(); - } - } else if (owner != null) { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - motionY = -Math.sin(pitch) * getSpeed(); - motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } + startMovingTowardTargetDefault(target); } @Override @@ -263,12 +140,23 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { @Override protected void updateProjectile() { + // Save previous render values for sub-tick interpolation + prevRenderDiscRadius = renderDiscRadius; + prevRenderDiscThickness = renderDiscThickness; + // Handle charging state (windup phase) if (isCharging()) { + // During charging, snap render values to target (size grows smoothly already) + renderDiscRadius = discRadius; + renderDiscThickness = discThickness; updateCharging(); return; } + // Lerp render values toward target (smooth out sync packet jumps) + renderDiscRadius += (discRadius - renderDiscRadius) * 0.15f; + renderDiscThickness += (discThickness - renderDiscThickness) * 0.15f; + // In preview mode, run movement on client (no server) if (previewMode) { updatePreviewMovement(); @@ -296,23 +184,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { } // Check wall collision - if (this.isCollidedHorizontally || this.isCollidedVertically) { - if (!worldObj.isRemote) { - hasHit = true; - if (isExplosive()) { - doExplosion(); - } - } - this.setDead(); - } + handleSolidCollisionTermination(); } @Override protected boolean checkMaxDistance() { double distTraveled = Math.sqrt( (posX - startX) * (posX - startX) + - (posY - startY) * (posY - startY) + - (posZ - startZ) * (posZ - startZ) + (posY - startY) * (posY - startY) + + (posZ - startZ) * (posZ - startZ) ); if (boomerang) { @@ -327,15 +207,17 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { if (returning) { Entity owner = getOwnerEntity(); if (owner != null) { + returnOwnerNullTicks = 0; double distToOwner = Math.sqrt( (posX - owner.posX) * (posX - owner.posX) + - (posY - owner.posY) * (posY - owner.posY) + - (posZ - owner.posZ) * (posZ - owner.posZ) + (posY - owner.posY) * (posY - owner.posY) + + (posZ - owner.posZ) * (posZ - owner.posZ) ); return distToOwner < 1.5; } - // Owner gone but returning - keep going toward last known position - return false; + // Owner gone while returning - grace period then die + returnOwnerNullTicks++; + return returnOwnerNullTicks > 100; } // Not returning yet - don't die from distance (we'll trigger return above) @@ -356,43 +238,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(); @@ -435,70 +280,64 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { } private void checkBlockCollision() { - Vec3 currentPos = Vec3.createVectorHelper(posX, posY, posZ); - Vec3 nextPos = Vec3.createVectorHelper(posX + motionX, posY + motionY, posZ + motionZ); - // Use full raytrace that doesn't stop at liquids and checks all blocks - MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); - - if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - hasHit = true; - if (isExplosive()) { - posX = blockHit.hitVec.xCoord; - posY = blockHit.hitVec.yCoord; - posZ = blockHit.hitVec.zCoord; - doExplosion(); - } - this.setDead(); - } + handleBlockImpact(rayTraceBlocks(posX, posY, posZ, posX + motionX, posY + motionY, posZ + motionZ), true); } private void checkEntityCollision() { - // Disc hitbox: wider but thinner - double halfWidth = discRadius * 0.5; - double halfHeight = discThickness * 0.5; + // Swept disc hitbox to avoid miss-through at high speed. + double nextX = posX + motionX; + double nextY = posY + motionY; + double nextZ = posZ + motionZ; + + double halfRadius = Math.max(0.05, discRadius * 0.5); + double halfThickness = Math.max(0.03, discThickness * 0.5); + double halfX; + double halfY; + double halfZ; + + if (vertical) { + // Vertical disc: thin axis follows horizontal travel direction, tall on Y. + double horizLen = Math.sqrt(motionX * motionX + motionZ * motionZ); + if (horizLen > 1.0e-5) { + double nx = motionX / horizLen; + double nz = motionZ / horizLen; + halfX = Math.abs(nx) * halfThickness + Math.abs(nz) * halfRadius; + halfZ = Math.abs(nz) * halfThickness + Math.abs(nx) * halfRadius; + } else { + halfX = halfRadius; + halfZ = halfRadius; + } + halfY = halfRadius; + } else { + // Horizontal disc: wide on XZ, thin on Y. + halfX = halfRadius; + halfY = halfThickness; + halfZ = halfRadius; + } + AxisAlignedBB hitBox = AxisAlignedBB.getBoundingBox( - posX - halfWidth, posY - halfHeight, posZ - halfWidth, - posX + halfWidth, posY + halfHeight, posZ + halfWidth + Math.min(posX, nextX) - halfX, Math.min(posY, nextY) - halfY, Math.min(posZ, nextZ) - halfZ, + Math.max(posX, nextX) + halfX, Math.max(posY, nextY) + halfY, Math.max(posZ, nextZ) + halfZ ); - @SuppressWarnings("unchecked") - List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); - - for (EntityLivingBase entity : entities) { - if (shouldIgnoreEntity(entity)) continue; - - hasHit = true; - - if (isExplosive()) { - doExplosion(); - } else { - applyDamage(entity); - } - - this.setDead(); - return; - } + processEntitiesInHitBox(hitBox, nextX, nextY, nextZ); } /** * 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 + this.size = 1.0f; // Size acts as a scaling factor; discRadius handles actual dimensions - // 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); @@ -508,22 +347,15 @@ 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); - } + // ==================== DEBUG ==================== - /** - * 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; + @Override + protected String debugLogExtra() { + return String.format("motion=(%.3f,%.3f,%.3f) radius=%.2f thickness=%.2f " + + "boomerang=%b returning=%b vertical=%b ticksSinceMiss=%d", + motionX, motionY, motionZ, + discRadius, discThickness, + boomerang, returning, vertical, ticksSinceMiss); } // ==================== GETTERS ==================== @@ -532,14 +364,42 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { return discRadius; } + public float getInterpolatedDiscRadius(float partialTicks) { + return prevRenderDiscRadius + (renderDiscRadius - prevRenderDiscRadius) * partialTicks; + } + + public void setDiscRadius(float radius) { + this.discRadius = radius; + } + public float getDiscThickness() { return discThickness; } + public float getInterpolatedDiscThickness(float partialTicks) { + return prevRenderDiscThickness + (renderDiscThickness - prevRenderDiscThickness) * partialTicks; + } + + 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; } @@ -548,6 +408,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { 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. @@ -556,14 +420,57 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { if (isCharging()) { Entity owner = previewMode ? previewOwner : getOwnerEntity(); if (owner != null) { - return owner.rotationYaw; + lastTravelYaw = owner.rotationYaw; + return lastTravelYaw; } } double speed = Math.sqrt(motionX * motionX + motionZ * motionZ); if (speed > 0.001) { - return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI); + lastTravelYaw = (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI); } - return 0.0f; + return lastTravelYaw; + } + + // ==================== REFLECTION ==================== + + @Override + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { + boolean reflected = super.reflectFromBarrier(barrier, reflectStrengthPct); + if (reflected) { + // Disable boomerang on reflected discs — the original owner is no longer + // relevant and the return-to-owner logic causes erratic flight paths. + this.boomerang = false; + this.returning = false; + } + return reflected; + } + + @Override + protected void writeProjectileReflectionData(NBTTagCompound nbt) { + nbt.setBoolean("Boomerang", boomerang); + nbt.setBoolean("Returning", returning); + } + + @Override + protected void applyProjectileReflectionData(NBTTagCompound nbt) { + boomerang = nbt.getBoolean("Boomerang"); + returning = nbt.getBoolean("Returning"); + } + + // ==================== PROPERTY SYNC ==================== + + @Override + protected void writeProjectileClientSyncData(NBTTagCompound nbt) { + nbt.setFloat("DiscRadius", discRadius); + nbt.setFloat("DiscThickness", discThickness); + nbt.setBoolean("Vertical", vertical); + } + + @Override + protected void applyProjectileClientSyncData(NBTTagCompound nbt) { + discRadius = nbt.getFloat("DiscRadius"); + discThickness = nbt.getFloat("DiscThickness"); + vertical = nbt.getBoolean("Vertical"); } // ==================== NBT ==================== @@ -572,18 +479,24 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { protected void readProjectileNBT(NBTTagCompound nbt) { this.boomerang = nbt.hasKey("Boomerang") && nbt.getBoolean("Boomerang"); 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.discRadius = sanitize(nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f, 1.0f, MAX_ENTITY_SIZE); + this.discThickness = sanitize(nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f, 0.2f, MAX_ENTITY_SIZE); + this.renderDiscRadius = this.discRadius; + this.renderDiscThickness = this.discThickness; + this.prevRenderDiscRadius = this.discRadius; + this.prevRenderDiscThickness = this.discThickness; 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; + + // Normalize size to 1.0 (scaling factor) — discRadius handles actual dimensions. + // Old saves may have size = discRadius baked in from the quadratic scaling bug. + this.size = 1.0f; + this.renderCurrentSize = 1.0f; + this.prevRenderSize = 1.0f; } @Override @@ -594,10 +507,8 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { 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 8a1325a27..f8f5d44f5 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -1,7 +1,14 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityEnergyProjectile; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; import kamkeel.npcs.util.AnchorPointHelper; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -9,82 +16,57 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; +import noppes.npcs.EventHooks; +import noppes.npcs.entity.EntityNPCInterface; -import java.util.HashSet; import java.util.List; -import java.util.Set; /** - * Laser projectile - fast expanding thin line that pierces through multiple targets. - * No homing, travels in a straight line from origin to max distance. - * + * Laser entity - sweeping beam that follows the caster's look vector. + * Expands from origin at expansionSpeed until reaching maxLength, + * then stays active until maxLifetime expires. Always tracks the owner's + * look direction so the beam can be swept mid-shot. + *

* Design inspired by LouisXIV's energy attack system. */ -public class EntityAbilityLaser extends EntityAbilityProjectile { +public class EntityAbilityLaser extends EntityEnergyProjectile { - // Laser-specific properties + // Laser-specific properties (target value) private float laserWidth = 0.2f; + + // Lerp-smoothed render values + private float renderLaserWidth = 0.2f; + private float prevRenderLaserWidth = 0.2f; private float expansionSpeed = 2.0f; // Blocks per tick - private int lingerTicks = 10; // How long laser stays visible after reaching max + private float maxLength = 32.0f; // Maximum beam reach in blocks // State - private float currentLength = 0.0f; + private float desiredLength = 0.0f; // Intended beam reach (grows to maxLength) + private float currentLength = 0.0f; // Actual length after block truncation (visual + collision) private boolean fullyExtended = false; - private int ticksSinceFullExtension = 0; + private boolean trackOwnerOrigin = true; // When false, laser fires independently (fireAt mode) // 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 float targetSize = 1.0f; // Full size to grow to during charging + // Previous tick positions for partial tick interpolation + private double prevStartX, prevStartY, prevStartZ; + private double prevEndX, prevEndY, prevEndZ; - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; + // Block hit deduplication — prevents event/explosion spam every tick + private int lastBlockHitX = Integer.MIN_VALUE; + private int lastBlockHitY = Integer.MIN_VALUE; + private int lastBlockHitZ = Integer.MIN_VALUE; + private int lastExplosionTick = -100; + private static final int EXPLOSION_COOLDOWN = 10; // ticks between explosive impacts 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. */ @@ -93,17 +75,15 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { float laserWidth, EnergyDisplayData display, EnergyCombatData combat, EnergyLightningData lightning, EnergyLifespanData lifespan, - EnergyTrajectoryData trajectory, float expansionSpeed, int lingerTicks) { + float expansionSpeed, float maxLength) { super(world); - // Initialize base properties (laser doesn't rotate) - initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan, trajectory); - this.displayData.rotationSpeed = 0.0f; + initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan); // Laser-specific properties this.laserWidth = laserWidth; this.expansionSpeed = expansionSpeed; - this.lingerTicks = lingerTicks; + this.maxLength = maxLength; // Calculate direction toward target or forward if (target != null) { @@ -117,168 +97,222 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.dirZ = dz / len; } } else { - // Fire in NPC's facing direction - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.dirX = -Math.sin(yaw) * Math.cos(pitch); - this.dirY = -Math.sin(pitch); - this.dirZ = Math.cos(yaw) * Math.cos(pitch); + // Fall back to owner look direction so launch matches visual aim. + Vec3 look = owner == null ? null : owner.getLookVec(); + if (look != null) { + this.dirX = look.xCoord; + this.dirY = look.yCoord; + this.dirZ = look.zCoord; + } else if (owner != null) { + float yaw = (float) Math.toRadians(owner.rotationYaw); + float pitch = (float) Math.toRadians(owner.rotationPitch); + this.dirX = -Math.sin(yaw) * Math.cos(pitch); + this.dirY = -Math.sin(pitch); + this.dirZ = Math.cos(yaw) * Math.cos(pitch); + } else { + this.dirX = 1.0; + this.dirY = 0.0; + this.dirZ = 0.0; + } } - // Initialize end point + // Initialize end point and prev positions this.endX = x; this.endY = y; this.endZ = z; + this.prevStartX = x; + this.prevStartY = y; + this.prevStartZ = z; + this.prevEndX = x; + this.prevEndY = y; + this.prevEndZ = 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 + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + double range = Math.max(128.0D, currentLength * 2.0D + 64.0D); + return distance < range * range; } @Override protected void updateRotation() { - // Laser doesn't rotate + // Beam rotation is handled in the renderer via perpendicular vector rotation } @Override protected boolean checkMaxDistance() { - // Laser handles distance differently - it expands to max then lingers + // Laser handles distance via maxLength, not max distance return false; } @Override protected void updateProjectile() { + // Save previous render value for sub-tick interpolation + prevRenderLaserWidth = renderLaserWidth; + if (isCharging()) { + // During charging, snap render value to target + renderLaserWidth = laserWidth; updateCharging(); return; } - // Track owner's anchor position and rotation each tick - // so the laser follows the NPC's facing direction - updateLaserOriginAndDirection(); + // Lerp render value toward target (smooth out sync packet jumps) + renderLaserWidth += (laserWidth - renderLaserWidth) * 0.15f; + // Save previous positions for partial tick interpolation + prevStartX = startX; + prevStartY = startY; + prevStartZ = startZ; + prevEndX = endX; + prevEndY = endY; + prevEndZ = endZ; + + // Origin/direction tracking runs on BOTH sides so the client can render the beam. + // Once reflected, never resume owner-tracking — the laser flies in a fixed direction. + // When trackOwnerOrigin is false (fireAt mode), skip owner tracking entirely. + if (!reflected && trackOwnerOrigin) { + updateLaserOriginAndDirection(); + } + + // Expand the intended reach — runs on both sides for visual sync if (!fullyExtended) { - // Expand the laser - currentLength += expansionSpeed; - - if (currentLength >= getMaxDistance()) { - currentLength = getMaxDistance(); + desiredLength += expansionSpeed; + if (desiredLength >= maxLength) { + desiredLength = maxLength; fullyExtended = true; } + } - // Update end point - endX = startX + dirX * currentLength; - endY = startY + dirY * currentLength; - endZ = startZ + dirZ * currentLength; + // Start from full desired length, then truncate at block hits + currentLength = desiredLength; - // Check for block collision along the new segment - if (!worldObj.isRemote) { - checkBlockCollision(); - checkEntityCollisionAlongLine(); + // Block raytrace — truncate beam at first solid block (both sides) + checkBlockCollision(); + + // Update end point + updateEndPoint(); + + // Server-only: barrier collision, entity collision, death + if (!worldObj.isRemote) { + if (checkLaserBarrierCollision()) { + return; } - } 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) { - this.setDead(); - } + checkEntityCollisionAlongLine(); + // Death handled by base class deathWorldTime (from lifespanData.maxLifetime) } } /** - * 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. + * Update end point from current origin + direction * length. + */ + private void updateEndPoint() { + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + } + + /** + * Update laser origin and direction from the owner's current look rotation. + * Called each tick so the laser follows the caster's aim (sweeping beam). */ private void updateLaserOriginAndDirection() { Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) return; - if (!(owner instanceof EntityLivingBase)) return; - + if (owner == null || !(owner instanceof EntityLivingBase)) { + if (worldObj != null && worldObj.isRemote) { + handleClientInterpolation(); + } + 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 { + // Get owner look vector for direction + Vec3 look = livingOwner.getLookVec(); + if (look == null) { + float yaw = (float) Math.toRadians(owner.rotationYaw); 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); + look = Vec3.createVectorHelper( + -Math.sin(yaw) * Math.cos(pitch), + -Math.sin(pitch), + Math.cos(yaw) * Math.cos(pitch) + ); } - // Keep entity positioned at origin - prevPosX = startX; - prevPosY = startY; - prevPosZ = startZ; - setPosition(startX, startY, startZ); + // Set direction directly from look vector (no lockVerticalDirection split) + dirX = look.xCoord; + dirY = look.yCoord; + dirZ = look.zCoord; + + // Keep direction normalized + double dirLen = Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); + if (dirLen > 0.0001) { + dirX /= dirLen; + dirY /= dirLen; + dirZ /= dirLen; + } else { + dirX = 1.0; + dirY = 0.0; + dirZ = 0.0; + } + + // Position: use anchor if launchFromAnchor, otherwise use look vector position. + // When using an anchor point, recalculate direction from anchor toward the target + // so the beam aims at the target rather than shooting straight from the offset position. + if (anchorData.launchFromAnchor) { + Vec3 anchorPos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData); + setPosition(anchorPos.xCoord, anchorPos.yCoord, anchorPos.zCoord); + + // Converge on the point the owner is aiming at, not on the target itself. Aiming + // straight at the target would re-derive the direction every tick and ignore the + // rotation the owner is actually allowed to reach, which is what track speed and + // rotation lock constrain. + double aimX = livingOwner.posX + dirX * maxLength; + double aimY = livingOwner.posY + livingOwner.getEyeHeight() + dirY * maxLength; + double aimZ = livingOwner.posZ + dirZ * maxLength; + double dx = aimX - anchorPos.xCoord; + double dy = aimY - anchorPos.yCoord; + double dz = aimZ - anchorPos.zCoord; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0.0001) { + dirX = dx / len; + dirY = dy / len; + dirZ = dz / len; + } + } else { + Vec3 direction = Vec3.createVectorHelper(dirX, dirY, dirZ); + setLookVectorLaunchPosition(livingOwner, direction, false); + // Lower beam origin slightly so it doesn't obscure the player's crosshair + posY -= 0.15; + } + syncStartPositionToCurrent(); + syncPositionStateToCurrent(false); } public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; + beginLookVectorLaunch(false); - setCharging(false); + desiredLength = 0.0f; + currentLength = 0.0f; + fullyExtended = false; + lastBlockHitX = Integer.MIN_VALUE; + lastBlockHitY = Integer.MIN_VALUE; + lastBlockHitZ = Integer.MIN_VALUE; + lastExplosionTick = -100; - // Initialize from current anchor position - // updateLaserOriginAndDirection() will keep these updated each tick - startX = posX; - startY = posY; - startZ = posZ; - - // 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); - this.dirX = -Math.sin(yaw) * Math.cos(pitch); - this.dirY = -Math.sin(pitch); - this.dirZ = Math.cos(yaw) * Math.cos(pitch); - } else if (target != null) { - double dx = target.posX - startX; - double dy = (target.posY + target.getEyeHeight() - 0.4) - startY; - double dz = target.posZ - startZ; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.dirX = dx / len; - this.dirY = dy / len; - this.dirZ = dz / len; + // Set initial direction: aim toward target first (like Orb/Beam), + // fall back to owner look vector if no target is available. + if (!setDirectionTowardTarget(target, startX, startY, startZ)) { + Vec3 look = getOwnerLookVector(); + if (look != null) { + dirX = look.xCoord; + dirY = look.yCoord; + dirZ = look.zCoord; + } else { + dirX = 1.0; + dirY = 0.0; + dirZ = 0.0; } } @@ -286,81 +320,94 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endX = startX; this.endY = startY; this.endZ = startZ; + + // Initialize prev positions to current so first frame doesn't jump + this.prevStartX = startX; + this.prevStartY = startY; + this.prevStartZ = startZ; + this.prevEndX = startX; + this.prevEndY = startY; + this.prevEndZ = startZ; + } + + private boolean setDirectionTowardTarget(EntityLivingBase target, double sourceX, double sourceY, double sourceZ) { + if (target == null) return false; + double dx = target.posX - sourceX; + double dy = (target.posY + target.getEyeHeight() - 0.4) - sourceY; + double dz = target.posZ - sourceZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len <= 0.0001) return false; + + dirX = dx / len; + dirY = dy / len; + dirZ = dz / len; + return true; } private void checkBlockCollision() { - Vec3 start = Vec3.createVectorHelper(startX, startY, startZ); - Vec3 end = Vec3.createVectorHelper(endX, endY, endZ); - // Use full raytrace that doesn't stop at liquids and checks all blocks - MovingObjectPosition blockHit = worldObj.func_147447_a(start, end, false, true, false); + if (currentLength <= 0) return; + + double traceEndX = startX + dirX * currentLength; + double traceEndY = startY + dirY * currentLength; + double traceEndZ = startZ + dirZ * currentLength; + + MovingObjectPosition blockHit = rayTraceBlocks(startX, startY, startZ, traceEndX, traceEndY, traceEndZ); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - // Laser stops at block - currentLength = (float) Math.sqrt( + // Truncate beam at block hit + float hitDist = (float) Math.sqrt( (blockHit.hitVec.xCoord - startX) * (blockHit.hitVec.xCoord - startX) + - (blockHit.hitVec.yCoord - startY) * (blockHit.hitVec.yCoord - startY) + - (blockHit.hitVec.zCoord - startZ) * (blockHit.hitVec.zCoord - startZ) + (blockHit.hitVec.yCoord - startY) * (blockHit.hitVec.yCoord - startY) + + (blockHit.hitVec.zCoord - startZ) * (blockHit.hitVec.zCoord - startZ) ); - endX = blockHit.hitVec.xCoord; - endY = blockHit.hitVec.yCoord; - endZ = blockHit.hitVec.zCoord; - fullyExtended = true; - - if (isExplosive()) { - // Explode at hit point - double oldPosX = posX; - double oldPosY = posY; - double oldPosZ = posZ; - posX = endX; - posY = endY; - posZ = endZ; - doExplosion(); - posX = oldPosX; - posY = oldPosY; - posZ = oldPosZ; + if (hitDist < currentLength) { + currentLength = hitDist; + endX = blockHit.hitVec.xCoord; + endY = blockHit.hitVec.yCoord; + endZ = blockHit.hitVec.zCoord; } + + // Server-only: fire event and explosion only when block changes or cooldown expires + if (!worldObj.isRemote) { + int bx = blockHit.blockX; + int by = blockHit.blockY; + int bz = blockHit.blockZ; + boolean newBlock = (bx != lastBlockHitX || by != lastBlockHitY || bz != lastBlockHitZ); + + // Fire block impact event only when the beam hits a different block + if (newBlock) { + lastBlockHitX = bx; + lastBlockHitY = by; + lastBlockHitZ = bz; + EventHooks.onEnergyProjectileBlockImpact(this, bx, by, bz); + } + + // Explosive: fire on cooldown so sweeping doesn't explode every tick + if (isExplosive() && (ticksExisted - lastExplosionTick) >= EXPLOSION_COOLDOWN) { + lastExplosionTick = ticksExisted; + double oldPosX = posX; + double oldPosY = posY; + double oldPosZ = posZ; + posX = endX; + posY = endY; + posZ = endZ; + doExplosion(); + posX = oldPosX; + posY = oldPosY; + posZ = oldPosZ; + } + } + } else if (!worldObj.isRemote) { + // Beam is not hitting any block — reset tracking so next block contact triggers fresh + lastBlockHitX = Integer.MIN_VALUE; + lastBlockHitY = Integer.MIN_VALUE; + lastBlockHitZ = Integer.MIN_VALUE; } } - /** - * 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() { + if (currentLength <= 0) return; + // 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; @@ -377,81 +424,338 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { for (EntityLivingBase entity : entities) { if (shouldIgnoreEntity(entity)) continue; - if (hitEntities.contains(entity.getEntityId())) continue; + if (!canHitEntityNow(entity)) continue; // Check if entity's bounding box intersects with the laser line if (isEntityOnLine(entity)) { - hitEntities.add(entity.getEntityId()); - applyDamage(entity); - - // Piercing - don't stop, continue to next entity + if (processEntityHit(entity, entity.posX, entity.posY + entity.height * 0.5, entity.posZ)) { + // SINGLE hit or maxHits reached — truncate beam at impact and die + double dx = entity.posX - startX; + double dy = (entity.posY + entity.height * 0.5) - startY; + double dz = entity.posZ - startZ; + float impactDist = (float) Math.sqrt(dx * dx + dy * dy + dz * dz); + currentLength = Math.min(impactDist, currentLength); + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + return; + } + // MULTI/PIERCE continue through remaining entities } } } /** * 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. + * Uses a swept segment vs expanded AABB intercept test for reliable hits. */ private boolean isEntityOnLine(EntityLivingBase entity) { - double ex = entity.posX; - double ez = entity.posZ; + AxisAlignedBB bb = entity.boundingBox; + if (bb == null) return false; - // Project entity XZ position onto the laser line direction - double vx = ex - startX; - double vz = ez - startZ; - // 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; + // Minimum effective width keeps thin lasers from visually clipping targets without hitting. + double effectiveWidth = Math.max(laserWidth, 0.65); + double expand = effectiveWidth * 0.5; + AxisAlignedBB expanded = bb.expand(expand, expand, expand); + + Vec3 segmentStart = Vec3.createVectorHelper(startX, startY, startZ); + Vec3 segmentEnd = Vec3.createVectorHelper(endX, endY, endZ); + MovingObjectPosition intercept = expanded.calculateIntercept(segmentStart, segmentEnd); + if (intercept != null) return true; + + // Handle edge case where the segment starts or ends already inside the target volume. + return expanded.isVecInside(segmentStart) || expanded.isVecInside(segmentEnd); + } + + // ==================== BARRIER COLLISION ==================== + + /** + * Disable the base class barrier check — it uses position/velocity which doesn't work + * for lasers (posX/Y/Z stays at origin, motionX/Y/Z is zero). We handle barriers + * exclusively in updateProjectile() via checkLaserBarrierCollision(). + */ + @Override + protected boolean checkBarrierCollision() { + return false; + } + + /** + * Laser-specific barrier collision using line-segment intersection. + * Called from updateProjectile() every tick. + */ + @SuppressWarnings("unchecked") + private boolean checkLaserBarrierCollision() { + if (currentLength <= 0) return false; + + List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead || barrier.isCharging()) continue; + if (barrier.getOwnerEntityId() == this.ownerEntityId) continue; + + // Same-faction NPC check + Entity bOwner = barrier.getOwnerEntity(); + Entity lOwner = this.getOwnerEntity(); + if (bOwner instanceof EntityNPCInterface && lOwner instanceof EntityNPCInterface) { + if (((EntityNPCInterface) bOwner).faction.id == ((EntityNPCInterface) lOwner).faction.id) { + continue; + } + } + + if (barrier instanceof EntityEnergyDome) { + EntityEnergyDome dome = (EntityEnergyDome) barrier; + float intersectDist = getLineSphereIntersection(dome); + if (intersectDist >= 0) { + float damage = getModifiedDamage(); + EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = dome.onProjectileHitResolved(this, damage); + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { + continue; + } + + if (hitOutcome.result != EntityEnergyBarrier.ProjectileHitResult.BROKEN) { + currentLength = Math.max(0.0f, intersectDist); + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + } + + if (handleBarrierHitOutcome(dome, hitOutcome, damage)) { + return true; + } + return false; + } + } else { + // For line-based lasers, use a swept segment against generic barrier checks. + double segMotionX = endX - startX; + double segMotionY = endY - startY; + double segMotionZ = endZ - startZ; + boolean incoming = barrier.isIncomingGenericProjectile( + endX, endY, endZ, + segMotionX, segMotionY, segMotionZ, + startX, startY, startZ, + this.ownerEntityId + ); + + if (incoming) { + float damage = getModifiedDamage(); + EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage); + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { + continue; + } + + if (hitOutcome.result != EntityEnergyBarrier.ProjectileHitResult.BROKEN) { + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + } + + if (handleBarrierHitOutcome(barrier, hitOutcome, damage)) { + return true; + } + return false; + } + } } - dot = Math.max(0, Math.min(dot, currentLength)); + return false; + } - // Closest point on laser line at this parameter - double closestX = startX + dirX * dot; - double closestY = startY + dirY * dot; - double closestZ = startZ + dirZ * dot; + @Override + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { + if (barrier == null) { + return false; + } - // 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; + double vx = dirX; + double vy = dirY; + double vz = dirZ; + double vLenSq = vx * vx + vy * vy + vz * vz; + if (vLenSq < 1.0e-8) { + return false; + } - // 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; + double[] normal = getBarrierImpactNormal(barrier, vx, vy, vz); + if (normal == null) { + return false; + } - // 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; + double dot = vx * normal[0] + vy * normal[1] + vz * normal[2]; + if (dot > 0.0) { + normal[0] = -normal[0]; + normal[1] = -normal[1]; + normal[2] = -normal[2]; + dot = vx * normal[0] + vy * normal[1] + vz * normal[2]; + } + double rx = vx - 2.0 * dot * normal[0]; + double ry = vy - 2.0 * dot * normal[1]; + double rz = vz - 2.0 * dot * normal[2]; + if (ry < -0.06) { + ry = Math.max(0.08, Math.abs(ry) * 0.35); + } + double rLen = Math.sqrt(rx * rx + ry * ry + rz * rz); + if (rLen < 1.0e-8) { + rx = -vx; + ry = -vy; + rz = -vz; + rLen = Math.sqrt(rx * rx + ry * ry + rz * rz); + if (rLen < 1.0e-8) { + return false; + } + } + + dirX = rx / rLen; + dirY = ry / rLen; + dirZ = rz / rLen; + + // Start a fresh segment at the impact edge to make the rebound visible. + startX = endX; + startY = endY; + startZ = endZ; + setPosition(startX, startY, startZ); + syncPositionStateToCurrent(true); + + desiredLength = 0.0f; + currentLength = 0.0f; + fullyExtended = false; + endX = startX; + endY = startY; + endZ = startZ; + lastBlockHitX = Integer.MIN_VALUE; + lastBlockHitY = Integer.MIN_VALUE; + lastBlockHitZ = Integer.MIN_VALUE; + lastExplosionTick = -100; + + // Reset lifetime so reflected laser gets a fresh maxLifetime from the base class + deathWorldTime = -1; + + barrierImpactPauseTicks = 0; + barrierImpactDestroyOnResume = false; + + // Detach from source ability so the caster is freed from active-phase locks. + if (sourceAbility instanceof AbilityEnergyProjectile) { + ((AbilityEnergyProjectile) sourceAbility).detachEntity(this); + } + sourceAbility = null; + + // Save original owner before transfer for potential target retargeting + int originalOwnerId = ownerEntityId; + + Entity barrierOwner = barrier.getOwnerEntity(); + if (barrierOwner != null) { + setOwnerEntityId(barrierOwner.getEntityId()); + trackProjectile(this); + } + + // Target Owner: set the reflected projectile's target to the original caster + if (barrier.getBarrierData().isTargetOwner() && originalOwnerId != -1) { + setTargetEntityId(originalOwnerId); + } else { + setTargetEntityId(-1); + } + + setInnerColor(barrier.getInnerColor()); + setOuterColor(barrier.getOuterColor()); + + float clampedStrength = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct)); + float reducedDamage = getDamage() * (1.0f - clampedStrength / 100.0f); + setCombatDamage(Math.max(0.0f, reducedDamage)); + + hitOnceEntities.clear(); + lastHitTickByEntity.clear(); + reflected = true; return true; } - // ==================== GETTERS FOR RENDERER ==================== + /** + * Line-sphere intersection between the laser line segment and a dome. + * Returns the distance along the laser direction to the first entry point, + * or -1 if no intersection from outside. + */ + private float getLineSphereIntersection(EntityEnergyDome dome) { + double cx = dome.posX; + double cy = dome.posY; + double cz = dome.posZ; + float radius = dome.getDomeRadius(); - public void setLockVerticalDirection(boolean lock) { - this.lockVerticalDirection = lock; + // If laser origin is inside the dome, don't block (outgoing) + double ocX = startX - cx; + double ocY = startY - cy; + double ocZ = startZ - cz; + double originDistSq = ocX * ocX + ocY * ocY + ocZ * ocZ; + if (originDistSq < (double) radius * radius) return -1; + + // Solve: |start + t*dir - C|^2 = R^2 + double a = dirX * dirX + dirY * dirY + dirZ * dirZ; + double b = 2.0 * (dirX * ocX + dirY * ocY + dirZ * ocZ); + double c = originDistSq - (double) radius * radius; + + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0) return -1; + + double sqrtD = Math.sqrt(discriminant); + double t1 = (-b - sqrtD) / (2.0 * a); // Entry point + + if (t1 >= 0 && t1 <= currentLength) { + return (float) t1; + } + + return -1; } - public boolean isLockVerticalDirection() { - return lockVerticalDirection; + // ==================== DEBUG ==================== + + @Override + protected String debugLogExtra() { + return String.format("dir=(%.3f,%.3f,%.3f) desired=%.2f current=%.2f max=%.2f " + + "fullyExtended=%b end=(%.2f,%.2f,%.2f) width=%.2f expSpd=%.2f origin=(%.2f,%.2f,%.2f)", + dirX, dirY, dirZ, desiredLength, currentLength, maxLength, + fullyExtended, endX, endY, endZ, laserWidth, expansionSpeed, + startX, startY, startZ); } + // ==================== GETTERS / SETTERS ==================== + public float getLaserWidth() { return laserWidth; } + public float getInterpolatedLaserWidth(float partialTicks) { + return prevRenderLaserWidth + (renderLaserWidth - prevRenderLaserWidth) * partialTicks; + } + + public void setLaserWidth(float width) { + this.laserWidth = width; + } + + public float getExpansionSpeed() { + return expansionSpeed; + } + + public void setExpansionSpeed(float speed) { + this.expansionSpeed = speed; + } + + public float getMaxLength() { + return maxLength; + } + + public void setMaxLength(float maxLength) { + this.maxLength = maxLength; + } + + public void setDirection(double x, double y, double z) { + this.dirX = x; + this.dirY = y; + this.dirZ = z; + } + + public boolean isTrackOwnerOrigin() { + return trackOwnerOrigin; + } + + public void setTrackOwnerOrigin(boolean track) { + this.trackOwnerOrigin = track; + } + public float getCurrentLength() { return currentLength; } @@ -484,6 +788,30 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { return endZ; } + public double getInterpolatedStartX(float partialTicks) { + return prevStartX + (startX - prevStartX) * partialTicks; + } + + public double getInterpolatedStartY(float partialTicks) { + return prevStartY + (startY - prevStartY) * partialTicks; + } + + public double getInterpolatedStartZ(float partialTicks) { + return prevStartZ + (startZ - prevStartZ) * partialTicks; + } + + public double getInterpolatedEndX(float partialTicks) { + return prevEndX + (endX - prevEndX) * partialTicks; + } + + public double getInterpolatedEndY(float partialTicks) { + return prevEndY + (endY - prevEndY) * partialTicks; + } + + public double getInterpolatedEndZ(float partialTicks) { + return prevEndZ + (endZ - prevEndZ) * partialTicks; + } + public double getDirX() { return dirX; } @@ -496,98 +824,179 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { return dirZ; } - /** - * Get the alpha for fade-out effect during linger. - */ - public float getLingerAlpha() { - if (!fullyExtended) return 1.0f; - return 1.0f - ((float) ticksSinceFullExtension / lingerTicks); + @Override + protected float getLaunchClearanceRadius() { + return Math.max(0.1f, laserWidth * 0.5f); + } + + @Override + public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { + // Charge orb grows to half the beam width + this.size = laserWidth * 0.5f; + this.desiredLength = 0.0f; + this.currentLength = 0.0f; + this.fullyExtended = false; + super.setupCharging(anchor, chargeDuration); + this.endX = posX; + this.endY = posY; + this.endZ = posZ; + this.prevStartX = posX; + this.prevStartY = posY; + this.prevStartZ = posZ; + this.prevEndX = posX; + this.prevEndY = posY; + this.prevEndZ = posZ; + } + + // ==================== REFLECTION SYNC ==================== + + @Override + protected void writeProjectileReflectionData(NBTTagCompound nbt) { + nbt.setDouble("DirX", dirX); + nbt.setDouble("DirY", dirY); + nbt.setDouble("DirZ", dirZ); + nbt.setDouble("StartX", startX); + nbt.setDouble("StartY", startY); + nbt.setDouble("StartZ", startZ); + nbt.setFloat("DesiredLength", desiredLength); + nbt.setFloat("CurrentLength", currentLength); + nbt.setDouble("EndX", endX); + nbt.setDouble("EndY", endY); + nbt.setDouble("EndZ", endZ); + nbt.setBoolean("FullyExtended", fullyExtended); + nbt.setFloat("MaxLength", maxLength); + } + + @Override + protected void applyProjectileReflectionData(NBTTagCompound nbt) { + dirX = nbt.getDouble("DirX"); + dirY = nbt.getDouble("DirY"); + dirZ = nbt.getDouble("DirZ"); + startX = nbt.getDouble("StartX"); + startY = nbt.getDouble("StartY"); + startZ = nbt.getDouble("StartZ"); + desiredLength = nbt.getFloat("DesiredLength"); + currentLength = nbt.getFloat("CurrentLength"); + endX = nbt.getDouble("EndX"); + endY = nbt.getDouble("EndY"); + endZ = nbt.getDouble("EndZ"); + fullyExtended = nbt.getBoolean("FullyExtended"); + if (nbt.hasKey("MaxLength")) maxLength = nbt.getFloat("MaxLength"); + } + + // ==================== PROPERTY SYNC ==================== + + @Override + protected void writeProjectileClientSyncData(NBTTagCompound nbt) { + nbt.setFloat("LaserWidth", laserWidth); + nbt.setFloat("ExpansionSpeed", expansionSpeed); + nbt.setFloat("MaxLength", maxLength); + nbt.setDouble("DirX", dirX); + nbt.setDouble("DirY", dirY); + nbt.setDouble("DirZ", dirZ); + } + + @Override + protected void applyProjectileClientSyncData(NBTTagCompound nbt) { + laserWidth = nbt.getFloat("LaserWidth"); + expansionSpeed = nbt.getFloat("ExpansionSpeed"); + maxLength = nbt.getFloat("MaxLength"); + dirX = nbt.getDouble("DirX"); + dirY = nbt.getDouble("DirY"); + dirZ = nbt.getDouble("DirZ"); } // ==================== NBT ==================== @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.laserWidth = nbt.hasKey("LaserWidth") ? nbt.getFloat("LaserWidth") : 0.2f; - this.expansionSpeed = nbt.hasKey("ExpansionSpeed") ? nbt.getFloat("ExpansionSpeed") : 2.0f; - this.lingerTicks = nbt.hasKey("LingerTicks") ? nbt.getInteger("LingerTicks") : 10; + this.laserWidth = sanitize(nbt.hasKey("LaserWidth") ? nbt.getFloat("LaserWidth") : 0.2f, 0.2f, MAX_ENTITY_SIZE); + this.renderLaserWidth = this.laserWidth; + this.prevRenderLaserWidth = this.laserWidth; + this.expansionSpeed = sanitize(nbt.hasKey("ExpansionSpeed") ? nbt.getFloat("ExpansionSpeed") : 2.0f, 0.1f, MAX_ENTITY_SIZE); + this.maxLength = sanitize(nbt.hasKey("MaxLength") ? nbt.getFloat("MaxLength") : 32.0f, 1.0f, MAX_ENTITY_SIZE); this.dirX = nbt.getDouble("DirX"); this.dirY = nbt.getDouble("DirY"); this.dirZ = nbt.getDouble("DirZ"); + this.desiredLength = nbt.getFloat("DesiredLength"); this.currentLength = nbt.getFloat("CurrentLength"); this.fullyExtended = nbt.getBoolean("FullyExtended"); + this.trackOwnerOrigin = !nbt.hasKey("TrackOwnerOrigin") || nbt.getBoolean("TrackOwnerOrigin"); this.endX = nbt.getDouble("EndX"); this.endY = nbt.getDouble("EndY"); this.endZ = nbt.getDouble("EndZ"); - // 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) { nbt.setFloat("LaserWidth", laserWidth); nbt.setFloat("ExpansionSpeed", expansionSpeed); - nbt.setInteger("LingerTicks", lingerTicks); + nbt.setFloat("MaxLength", maxLength); nbt.setDouble("DirX", dirX); nbt.setDouble("DirY", dirY); nbt.setDouble("DirZ", dirZ); + nbt.setFloat("DesiredLength", desiredLength); nbt.setFloat("CurrentLength", currentLength); nbt.setBoolean("FullyExtended", fullyExtended); + nbt.setBoolean("TrackOwnerOrigin", trackOwnerOrigin); nbt.setDouble("EndX", endX); nbt.setDouble("EndY", endY); nbt.setDouble("EndZ", endZ); - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); - nbt.setFloat("TargetSize", targetSize); + writeChargingNBT(nbt); } /** * Setup this laser in preview mode for GUI display. - * Laser doesn't have charging state - spawns at active phase and fires immediately. + * Uses charging-orb visuals during windup before firing. */ public void setupPreview(EntityLivingBase owner, float laserWidth, EnergyDisplayData display, - EnergyLightningData lightning, float expansionSpeed, float maxDistance) { - this.setPreviewMode(true); - this.setPreviewOwner(owner); + EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, + float expansionSpeed, float maxLength) { + setupPreviewState(owner, display, lightning, anchor, chargeDuration); - // Set visual properties + // Laser-specific visual/behavior state. this.laserWidth = laserWidth; - this.size = laserWidth; - this.displayData = display; this.expansionSpeed = expansionSpeed; - this.lifespanData.maxDistance = Math.min(maxDistance, 5.0f); // Limit for GUI preview - this.lightningData = lightning; + this.maxLength = Math.min(maxLength, 5.0f); // Limit for GUI preview + this.desiredLength = 0.0f; + this.currentLength = 0.0f; + this.fullyExtended = false; - // Position at chest height - double x = owner.posX; - double y = owner.posY + owner.height * 0.7; - double z = owner.posZ; - this.setPosition(x, y, z); - this.prevPosX = x; - this.prevPosY = y; - this.prevPosZ = z; - this.startX = x; - this.startY = y; - this.startZ = z; + // Charge as an orb from tiny size to half laser width while anchored. + this.targetSize = laserWidth * 0.5f; + setVisualSize(0.01f); + setChargeOriginFromAnchor(owner, anchorData); + clearMotion(); + this.endX = posX; + this.endY = posY; + this.endZ = posZ; + this.prevStartX = posX; + this.prevStartY = posY; + this.prevStartZ = posZ; + this.prevEndX = posX; + this.prevEndY = posY; + this.prevEndZ = posZ; - // Fire in owner's facing direction - float yaw = (float) Math.toRadians(owner.rotationYaw); - this.dirX = -Math.sin(yaw); - this.dirY = 0; - this.dirZ = Math.cos(yaw); - - // Initialize end point (same as start, will expand) - this.endX = x; - this.endY = y; - this.endZ = z; + // Precompute initial direction from owner look for launch. + Vec3 look = owner == null ? null : owner.getLookVec(); + if (look == null) { + if (owner != null) { + float yaw = (float) Math.toRadians(owner.rotationYaw); + float pitch = (float) Math.toRadians(owner.rotationPitch); + look = Vec3.createVectorHelper( + -Math.sin(yaw) * Math.cos(pitch), + -Math.sin(pitch), + Math.cos(yaw) * Math.cos(pitch) + ); + } else { + look = Vec3.createVectorHelper(1.0, 0.0, 0.0); + } + } + this.dirX = look.xCoord; + this.dirY = look.yCoord; + this.dirZ = look.zCoord; } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java index 73e8c26f3..07e032829 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -1,66 +1,30 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.Vec3; import net.minecraft.world.World; -import java.util.List; - /** * Orb projectile - spherical homing energy ball. - * Extends EntityAbilityProjectile for shared functionality. - * + * Extends EntityEnergyAbility for shared functionality. + *

* Design inspired by LouisXIV's energy attack system. */ -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 class EntityAbilityOrb extends EntityEnergyProjectile { + private static final int HOMING_STARTUP_TICKS = 4; + private static final int HOMING_RAMP_TICKS = 8; 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. */ @@ -68,52 +32,16 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { double x, double y, double z, float orbSize, EnergyDisplayData display, EnergyCombatData combat, EnergyHomingData homing, EnergyLightningData lightning, - EnergyLifespanData lifespan, EnergyTrajectoryData trajectory) { + EnergyLifespanData lifespan) { super(world); // Initialize base properties - initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan, trajectory); + initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan); - this.homingData = homing; + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); // 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); } /** @@ -122,73 +50,20 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Can be fired when transitioning to active phase. */ public void setupPreview(EntityLivingBase owner, float orbSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { - this.setPreviewMode(true); - this.setPreviewOwner(owner); - - // Set visual properties - this.displayData = display; - this.lightningData = lightning; - - // Set charging state - this.setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; + setupPreviewState(owner, display, lightning, anchor, chargeDuration); // Store target size and start at 0 for grow effect this.targetSize = orbSize; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - - // Initial position at anchor point - Vec3 pos = AnchorPointHelper.calculateAnchorPosition(owner, anchorData); - this.setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - this.prevPosX = pos.xCoord; - this.prevPosY = pos.yCoord; - this.prevPosZ = pos.zCoord; - this.startX = pos.xCoord; - this.startY = pos.yCoord; - this.startZ = pos.zCoord; - - // Clear motion - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; + setVisualSize(0.01f); + setChargeOriginFromAnchor(owner, anchorData); + clearMotion(); } /** * 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 - startX = posX; - startY = posY; - startZ = posZ; - - // Sync prev position to prevent visual jump on first frame - prevPosX = posX; - prevPosY = posY; - prevPosZ = posZ; - - // Fire forward based on owner facing direction - Entity owner = getOwnerEntity(); - if (owner != null) { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(0); // Fire horizontally - motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - motionY = -Math.sin(pitch) * getSpeed(); - motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } else { - // Default: fire forward (positive X in model space) - motionX = getSpeed(); - motionY = 0; - motionZ = 0; - } + startPreviewFiringDefault(); } /** @@ -196,35 +71,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Called by ability when windup ends. */ public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - - setCharging(false); - - // Update start position to current position - startX = posX; - startY = posY; - startZ = posZ; - - // Calculate velocity toward target - Entity owner = getOwnerEntity(); - - if (target != null) { - double dx = target.posX - posX; - double dy = (target.posY + target.getEyeHeight()) - posY; - double dz = target.posZ - posZ; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - motionX = (dx / len) * getSpeed(); - motionY = (dy / len) * getSpeed(); - motionZ = (dz / len) * getSpeed(); - } - } else if (owner != null) { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - motionY = -Math.sin(pitch) * getSpeed(); - motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } + startMovingTowardTargetDefault(target); } @Override @@ -252,15 +99,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { } // Check wall collision - if (this.isCollidedHorizontally || this.isCollidedVertically) { - if (!worldObj.isRemote) { - hasHit = true; - if (isExplosive()) { - doExplosion(); - } - } - this.setDead(); - } + handleSolidCollisionTermination(); } /** @@ -274,155 +113,51 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { } private void updateMovement() { - if (!isTrajectoryConcluded()) { - updateTrajectory(); - } else { - updateHoming(); + if (ticksExisted > HOMING_STARTUP_TICKS) { + int homingTicks = ticksExisted - HOMING_STARTUP_TICKS; + if (homingTicks >= HOMING_RAMP_TICKS) { + updateHoming(); + } else { + float ramp = homingTicks / (float) HOMING_RAMP_TICKS; + updateHomingWithRamp(ramp); + } } } - private void updateTrajectory() { - if (isTrajectoryConcluded()) return; - // i really fucking hate math - - } - - private boolean isTrajectoryConcluded() { - if (trajectoryData.isEmpty()) return true; - - for (int i = 0; i < trajectoryData.size(); i++) { - if (!trajectoryData.getPath(i).isConcluded()) { - return false; - } - } - - 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 updateHomingWithRamp(float ramp) { + if (ramp <= 0.0f) return; + float originalStrength = homingData.homingStrength; + homingData.homingStrength = originalStrength * ramp; + updateHoming(); + homingData.homingStrength = originalStrength; } private void checkBlockCollision() { - Vec3 currentPos = Vec3.createVectorHelper(posX, posY, posZ); - Vec3 nextPos = Vec3.createVectorHelper(posX + motionX, posY + motionY, posZ + motionZ); - // Use full raytrace that doesn't stop at liquids and checks all blocks - MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); - - if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - hasHit = true; - if (isExplosive()) { - posX = blockHit.hitVec.xCoord; - posY = blockHit.hitVec.yCoord; - posZ = blockHit.hitVec.zCoord; - doExplosion(); - } - this.setDead(); - } + handleBlockImpact(rayTraceBlocks(posX, posY, posZ, posX + motionX, posY + motionY, posZ + motionZ), true); } private void checkEntityCollision() { - double hitSize = size * 0.5; + // Swept collision to avoid fast orbs skipping targets between ticks. + double nextX = posX + motionX; + double nextY = posY + motionY; + double nextZ = posZ + motionZ; + // Keep collision radius proportional to rendered orb size. + double hitSize = Math.max(0.05, size * 0.5); AxisAlignedBB hitBox = AxisAlignedBB.getBoundingBox( - posX - hitSize, posY - hitSize, posZ - hitSize, - posX + hitSize, posY + hitSize, posZ + hitSize + Math.min(posX, nextX) - hitSize, Math.min(posY, nextY) - hitSize, Math.min(posZ, nextZ) - hitSize, + Math.max(posX, nextX) + hitSize, Math.max(posY, nextY) + hitSize, Math.max(posZ, nextZ) + hitSize ); - - @SuppressWarnings("unchecked") - List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); - - for (EntityLivingBase entity : entities) { - if (shouldIgnoreEntity(entity)) continue; - - hasHit = true; - - if (isExplosive()) { - doExplosion(); - } else { - applyDamage(entity); - } - - this.setDead(); - return; - } + processEntitiesInHitBox(hitBox, nextX, nextY, nextZ); } - /** - * Update during charging state - follow owner based on anchor point. - */ - private void updateCharging() { - chargeTick++; + // ==================== DEBUG ==================== - 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; + @Override + protected String debugLogExtra() { + return String.format("motion=(%.3f,%.3f,%.3f) homing=%b start=(%.2f,%.2f,%.2f)", + motionX, motionY, motionZ, + homingData != null && homingData.isHoming(), + startX, startY, startZ); } // ==================== GETTERS ==================== @@ -436,22 +171,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 deleted file mode 100644 index 7080ce2ef..000000000 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ /dev/null @@ -1,837 +0,0 @@ -package kamkeel.npcs.entity; - -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.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 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.api.entity.IEnergyProjectile; -import noppes.npcs.api.entity.IEntity; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.scripted.NpcAPI; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Base class for all ability projectiles (Orb, Disc, Beam, Laser). - * Provides common functionality for visuals, combat, effects, and interpolation. - * - * Design inspired by LouisXIV's energy attack system. - */ -public abstract class EntityAbilityProjectile extends Entity implements IEnergyProjectile, IEntityAdditionalSpawnData { - - // ==================== VISUAL PROPERTIES ==================== - protected float size = 1.0f; - - // ==================== COMBAT PROPERTIES ==================== - protected EnergyCombatData combatData = new EnergyCombatData(); - - // ==================== EFFECT PROPERTIES ==================== - protected List effects = new ArrayList<>(); - - // ==================== LIGHTNING EFFECT PROPERTIES ==================== - protected EnergyLightningData lightningData = new EnergyLightningData(); - - // Client-side lightning state (not saved to NBT) - @cpw.mods.fml.relauncher.SideOnly(cpw.mods.fml.relauncher.Side.CLIENT) - public transient Object lightningState; // Actually AttachedLightningRenderer.LightningState - - // ==================== DISPLAY PROPERTIES ==================== - protected EnergyDisplayData displayData = new EnergyDisplayData(); - - // ==================== ANCHOR PROPERTIES ==================== - protected EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); - - // ==================== LIFESPAN PROPERTIES ==================== - protected EnergyLifespanData lifespanData = new EnergyLifespanData(); - protected long deathWorldTime = -1; // World time when entity should die (-1 = not set) - - // ==================== HOMING PROPERTIES ==================== - protected EnergyHomingData homingData = new EnergyHomingData(); - - // ==================== TRAJECTORY PROPERTIES ==================== - protected EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - protected Map pathDelays; - - // ==================== TRACKING ==================== - protected double startX, startY, startZ; - protected int ownerEntityId = -1; - protected int targetEntityId = -1; - protected int siblingEntityId = -1; - - // ==================== STATE ==================== - protected boolean hasHit = false; - protected boolean previewMode = false; // Client-side preview mode (no damage/effects) - protected EntityLivingBase previewOwner = null; // Direct reference for GUI preview (no world lookup) - - /** The ability that spawned this projectile. Transient, not saved to NBT. */ - protected transient Ability sourceAbility = null; - - // ==================== ROTATION INTERPOLATION ==================== - public float prevRotationValX, prevRotationValY, prevRotationValZ; - public float rotationValX, rotationValY, rotationValZ; - - // ==================== SIZE INTERPOLATION ==================== - protected float renderCurrentSize; - protected float prevRenderSize; - - // ==================== POSITION INTERPOLATION ==================== - protected double interpTargetX, interpTargetY, interpTargetZ; - protected double interpTargetMotionX, interpTargetMotionY, interpTargetMotionZ; - protected int interpSteps; - - public EntityAbilityProjectile(World world) { - super(world); - this.setSize(0.5f, 0.5f); - this.noClip = false; - this.isImmuneToFire = true; - this.ignoreFrustumCheck = true; - } - - /** - * Initialize common properties using data classes. Call from subclass constructors. - */ - protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, EntityAbilityProjectile sibling, - double x, double y, double z, float size, - EnergyDisplayData display, EnergyCombatData combat, - EnergyLightningData lightning, EnergyLifespanData lifespan, - EnergyTrajectoryData trajectory) { - this.setPosition(x, y, z); - this.startX = x; - this.startY = y; - this.startZ = z; - - this.ownerEntityId = owner.getEntityId(); - this.targetEntityId = target != null ? target.getEntityId() : -1; - this.siblingEntityId = sibling != null ? sibling.getEntityId() : -1; - - // Visual - this.size = size; - - this.displayData = display; - this.combatData = combat; - this.lifespanData = lifespan; // deathWorldTime will be set on first tick when world is available - this.lightningData = lightning; - this.trajectoryData = trajectory; - - // Initialize render size - this.renderCurrentSize = size; - 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 - } - - @Override - @SideOnly(Side.CLIENT) - public boolean isInRangeToRenderDist(double distance) { - double d1 = this.boundingBox.getAverageEdgeLength() * 4.0D; - d1 *= 128.0D; - return distance < d1 * d1; - } - - @Override - public boolean shouldRenderInPass(int pass) { - return pass == 1; // Translucent pass - } - - @Override - public void onUpdate() { - // Store previous values for interpolation - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.prevRotationValX = this.rotationValX; - this.prevRotationValY = this.rotationValY; - this.prevRotationValZ = this.rotationValZ; - this.prevRenderSize = this.renderCurrentSize; - - // Skip super.onUpdate() in preview mode to avoid world checks - if (!previewMode) { - super.onUpdate(); - } - - // Update rotation - updateRotation(); - - // Lerp render size toward actual size - this.renderCurrentSize = this.renderCurrentSize + (this.size - this.renderCurrentSize) * 0.15f; - - // Skip lifetime/distance checks in preview mode - if (!previewMode) { - // Failsafe: if owner entity is gone, dead, or NPC was killed/reset, self-destruct - 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; - } - } - - // Set death time on first tick if not already set (handles chunk load/unload) - if (deathWorldTime < 0 && worldObj != null) { - deathWorldTime = worldObj.getTotalWorldTime() + getMaxLifetime(); - } - - // Check lifespan using world time (survives chunk unload/reload) - if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { - this.setDead(); - return; - } - - // Check max distance (subclass can override if needed) - if (checkMaxDistance()) { - this.setDead(); - return; - } - - if (hasHit) { - this.setDead(); - return; - } - } - - // Subclass-specific update - updateProjectile(); - } - - /** - * Update rotation values. Override for custom rotation behavior. - */ - protected void updateRotation() { - this.rotationValX += getRotationSpeed() * 0.7f; - this.rotationValY += getRotationSpeed(); - this.rotationValZ += getRotationSpeed() * 0.5f; - - if (this.rotationValX > 360.0f) this.rotationValX -= 360.0f; - if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f; - if (this.rotationValZ > 360.0f) this.rotationValZ -= 360.0f; - } - - /** - * Check if projectile has exceeded max distance. - * @return true if should die - */ - protected boolean checkMaxDistance() { - double distTraveled = Math.sqrt( - (posX - startX) * (posX - startX) + - (posY - startY) * (posY - startY) + - (posZ - startZ) * (posZ - startZ) - ); - return distTraveled >= getMaxDistance(); - } - - /** - * Subclass-specific update logic. Called every tick. - */ - protected abstract void updateProjectile(); - - // ==================== POSITION INTERPOLATION ==================== - - @Override - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements) { - this.interpTargetX = x; - this.interpTargetY = y; - this.interpTargetZ = z; - this.interpSteps = posRotationIncrements; - } - - @Override - public void setVelocity(double motionX, double motionY, double motionZ) { - this.interpTargetMotionX = motionX; - this.interpTargetMotionY = motionY; - this.interpTargetMotionZ = motionZ; - this.motionX = motionX; - this.motionY = motionY; - this.motionZ = motionZ; - } - - /** - * Handle client-side position interpolation. - */ - protected void handleClientInterpolation() { - if (this.interpSteps > 0) { - double newX = this.posX + (this.interpTargetX - this.posX) / this.interpSteps; - double newY = this.posY + (this.interpTargetY - this.posY) / this.interpSteps; - double newZ = this.posZ + (this.interpTargetZ - this.posZ) / this.interpSteps; - - this.motionX = this.motionX + (this.interpTargetMotionX - this.motionX) / this.interpSteps; - this.motionY = this.motionY + (this.interpTargetMotionY - this.motionY) / this.interpSteps; - this.motionZ = this.motionZ + (this.interpTargetMotionZ - this.motionZ) / this.interpSteps; - - this.setPosition(newX, newY, newZ); - this.interpSteps--; - } else { - this.posX += this.motionX; - this.posY += this.motionY; - this.posZ += this.motionZ; - this.setPosition(this.posX, this.posY, this.posZ); - } - } - - // ==================== PREVIEW MODE ==================== - - /** - * Set preview mode for GUI display. - * In preview mode, no damage or world effects are applied. - */ - public void setPreviewMode(boolean preview) { - this.previewMode = preview; - } - - /** - * Check if entity is in preview mode. - */ - public boolean isPreviewMode() { - return previewMode; - } - - // ==================== DAMAGE & EFFECTS ==================== - - protected void applyDamage(EntityLivingBase target) { - if (previewMode) return; // Skip damage in preview mode - applyDamage(target, this.getDamage(), this.getKnockback()); - } - - protected void applyDamage(EntityLivingBase target, float dmg, float kb) { - if (previewMode) return; // Skip damage in preview mode - Entity owner = getOwnerEntity(); - - // Check for external damage handler (e.g., DBC Addon) - 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); - } - } - - if (!handled) { - // Default damage path - if (owner instanceof EntityNPCInterface) { - target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg); - } else if (owner instanceof EntityPlayer) { - target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg); - } else if (owner instanceof EntityLivingBase) { - target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg); - } else { - target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg); - } - } - - if (kb > 0) { - double dx = target.posX - posX; - double dz = target.posZ - posZ; - double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - double kbX = (dx / len) * kb * 0.5; - double kbZ = (dz / len) * kb * 0.5; - double kbY = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1; - target.addVelocity(kbX, kbY, kbZ); - target.velocityChanged = true; - } - } - - applyEffects(target); - } - - protected void applyEffects(EntityLivingBase target) { - for (AbilityEffect effect : effects) { - effect.apply(target); - } - } - - /** - * Set the effects list from the ability's configured effects. - */ - public void setEffects(List effects) { - this.effects = effects != null ? effects : new ArrayList<>(); - } - - /** - * Set the source ability that spawned this projectile. - * Used by external damage handlers to access ability-specific data. - */ - public void setSourceAbility(Ability ability) { - this.sourceAbility = ability; - } - - /** - * Get the source ability that spawned this projectile. - */ - public Ability getSourceAbility() { - return sourceAbility; - } - - protected void doExplosion() { - if (previewMode) return; // Skip explosion in preview mode - worldObj.playSoundEffect(posX, posY, posZ, "random.explode", 1.0f, 1.0f); - - Entity owner = getOwnerEntity(); - - AxisAlignedBB explosionBox = AxisAlignedBB.getBoundingBox( - posX - getExplosionRadius(), posY - getExplosionRadius(), posZ - getExplosionRadius(), - posX + getExplosionRadius(), posY + getExplosionRadius(), posZ + getExplosionRadius() - ); - - @SuppressWarnings("unchecked") - List targets = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, explosionBox); - - for (EntityLivingBase target : targets) { - if (target == owner) continue; - - double dist = Math.sqrt( - Math.pow(target.posX - posX, 2) + - Math.pow(target.posY - posY, 2) + - Math.pow(target.posZ - posZ, 2) - ); - - if (dist <= getExplosionRadius()) { - float falloff = 1.0f - (float) (dist / getExplosionRadius()) * getExplosionDamageFalloff(); - applyDamage(target, getDamage() * falloff, getKnockback() * falloff); - } - } - } - - // ==================== ENTITY HELPERS ==================== - - public Entity getOwnerEntity() { - // In preview mode, use direct reference (no world lookup) - if (previewMode && previewOwner != null) { - return previewOwner; - } - if (ownerEntityId == -1) return null; - return worldObj.getEntityByID(ownerEntityId); - } - - @Override - public int getOwnerEntityId() { - return ownerEntityId; - } - - @Override - public IEntity getOwner() { - if (previewMode) return null; - if (getOwnerEntity() == null) return null; - return NpcAPI.Instance().getIEntity(getOwnerEntity()); - } - - /** - * Set the preview owner for GUI preview mode. - * This allows anchor point calculations without world entity lookup. - */ - public void setPreviewOwner(EntityLivingBase owner) { - this.previewOwner = owner; - } - - @Override - public int getTargetEntityId() { - return targetEntityId; - } - - 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. - */ - protected boolean shouldIgnoreEntity(Entity entity) { - Entity owner = getOwnerEntity(); - if (entity == owner) return true; - - if (owner instanceof EntityNPCInterface && entity instanceof EntityNPCInterface) { - EntityNPCInterface ownerNpc = (EntityNPCInterface) owner; - EntityNPCInterface targetNpc = (EntityNPCInterface) entity; - if (ownerNpc.faction.id == targetNpc.faction.id) return true; - } - - if (entity.getEntityId() == getSiblingEntityId()) - return true; - - return false; - } - - // ==================== VISUAL GETTERS ==================== - - @Override - public float getSize() { - return size; - } - - @Override - public int getInnerColor() { - return displayData.getInnerColor(); - } - - @Override - public int getOuterColor() { - return displayData.getOuterColor(); - } - - @Override - public boolean isOuterColorEnabled() { - return displayData.isOuterColorEnabled(); - } - - @Override - public float getOuterColorWidth() { - return displayData.getOuterColorWidth(); - } - - @Override - public float getOuterColorAlpha() { - return displayData.getOuterColorAlpha(); - } - - @Override - public float getRotationSpeed() { - return displayData.getRotationSpeed(); - } - - // ==================== 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 ==================== - - @Override - public boolean hasLightningEffect() { - return lightningData.isLightningEffect(); - } - - @Override - public float getLightningDensity() { - return lightningData.getLightningDensity(); - } - - @Override - public float getLightningRadius() { - return lightningData.getLightningRadius(); - } - - @Override - public int getLightningFadeTime() { - return lightningData.getLightningFadeTime(); - } - - // ==================== LIFESPAN GETTERS ==================== - - @Override - public float getMaxDistance() { return lifespanData.getMaxDistance(); } - - @Override - public int getMaxLifetime() { return lifespanData.getMaxLifetime(); } - - // ==================== COMBAT GETTERS ==================== - - @Override - public float getDamage() { return combatData.getDamage(); } - - @Override - public float getKnockback() { return combatData.knockback; } - - @Override - public float getKnockbackUp() { return combatData.knockbackUp; } - - @Override - public boolean isExplosive() { return combatData.isExplosive(); } - - @Override - public float getExplosionRadius() { return combatData.explosionRadius; } - - @Override - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - - // ==================== HOMING GETTERS ==================== - - @Override - public boolean isHoming() { return homingData.isHoming(); } - - @Override - public float getHomingStrength() { return homingData.getHomingStrength(); } - - @Override - public float getHomingRange() { return homingData.getHomingRange(); } - - // ==================== TRAJECTORY GETTERS ==================== - - - - // ==================== ANCHOR GETTERS ==================== - - @Override - public float getSpeed() { return homingData.getSpeed(); } - - 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; } - - @Override public double getStartY() { return startY; } - - @Override public double getStartZ() { return startZ; } - - @Override public double getMotionX() { return motionX; } - - @Override public double getMotionY() { return motionY; } - - @Override public double getMotionZ() { return motionZ; } - - // ==================== BRIGHTNESS ==================== - - @Override - public float getBrightness(float partialTicks) { - return 1.0f; - } - - @Override - @SideOnly(Side.CLIENT) - public int getBrightnessForRender(float partialTicks) { - return 0xF000F0; - } - - // ==================== NBT ==================== - - @Override - protected void readEntityFromNBT(NBTTagCompound nbt) { - readBaseNBT(nbt); - readProjectileNBT(nbt); - } - - @Override - protected void writeEntityToNBT(NBTTagCompound nbt) { - writeBaseNBT(nbt); - writeProjectileNBT(nbt); - } - - /** - * Read base projectile properties from NBT. - */ - protected void readBaseNBT(NBTTagCompound nbt) { - this.size = nbt.getFloat("Size"); - - // Read effects list - this.effects.clear(); - if (nbt.hasKey("Effects")) { - NBTTagList effectsList = nbt.getTagList("Effects", 10); // 10 = compound tag - for (int i = 0; i < effectsList.tagCount(); i++) { - effects.add(AbilityEffect.fromNBT(effectsList.getCompoundTagAt(i))); - } - } - - this.deathWorldTime = nbt.hasKey("DeathWorldTime") ? nbt.getLong("DeathWorldTime") : -1; - - this.startX = nbt.getDouble("StartX"); - this.startY = nbt.getDouble("StartY"); - this.startZ = nbt.getDouble("StartZ"); - - 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; - } - - anchorData.readNBT(nbt); - combatData.readNBT(nbt); - displayData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - lightningData.readNBT(nbt); - trajectoryData.readNBT(nbt); - } - - /** - * Write base projectile properties to NBT. - */ - protected void writeBaseNBT(NBTTagCompound nbt) { - nbt.setFloat("Size", size); - - // Write effects list - if (!effects.isEmpty()) { - NBTTagList effectsList = new NBTTagList(); - for (AbilityEffect effect : effects) { - effectsList.appendTag(effect.writeNBT()); - } - nbt.setTag("Effects", effectsList); - } - - nbt.setLong("DeathWorldTime", deathWorldTime); - - nbt.setDouble("StartX", startX); - nbt.setDouble("StartY", startY); - nbt.setDouble("StartZ", startZ); - - nbt.setInteger("OwnerId", ownerEntityId); - nbt.setInteger("TargetId", targetEntityId); - nbt.setInteger("SiblingId", targetEntityId); - - nbt.setDouble("MotionX", motionX); - nbt.setDouble("MotionY", motionY); - nbt.setDouble("MotionZ", motionZ); - - anchorData.writeNBT(nbt); - combatData.writeNBT(nbt); - displayData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - lightningData.writeNBT(nbt); - trajectoryData.writeNBT(nbt); - } - - /** - * Subclass-specific NBT reading. - */ - protected abstract void readProjectileNBT(NBTTagCompound nbt); - - /** - * Subclass-specific NBT writing. - */ - protected abstract void writeProjectileNBT(NBTTagCompound nbt); - - // ==================== SPAWN DATA ==================== - - @Override - public void writeSpawnData(ByteBuf buffer) { - try { - NBTTagCompound compound = new NBTTagCompound(); - this.writeEntityToNBT(compound); - cpw.mods.fml.common.network.ByteBufUtils.writeTag(buffer, compound); - } catch (Exception ignored) {} - } - - @Override - public void readSpawnData(ByteBuf buffer) { - try { - NBTTagCompound compound = cpw.mods.fml.common.network.ByteBufUtils.readTag(buffer); - if (compound != null) { - this.readEntityFromNBT(compound); - } - } catch (Exception ignored) {} - } - - // ==================== COLLISION SETTINGS ==================== - - @Override - public boolean canBeCollidedWith() { - return false; - } - - @Override - public boolean canBePushed() { - return false; - } - - @Override - protected boolean canTriggerWalking() { - return false; - } - - @Override - public boolean isBurning() { - return false; - } - - @SideOnly(Side.CLIENT) - public float getShadowSize() { - return 0.0f; - } -} 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..529d59d74 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -0,0 +1,988 @@ +package kamkeel.npcs.entity; + +import kamkeel.npcs.util.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.AbilityController; +import kamkeel.npcs.controllers.EnergyController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.enums.TargetFilter; +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; + +/** + * 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 + // ═══════════════════════════════════════════════════════════════════ + + /** Floor on how often a hazard pulses, so a small interval cannot turn into a per-tick scan. */ + public static final int MIN_DAMAGE_INTERVAL = 5; + + private float damagePerSecond = 1.0f; + private int damageInterval = 20; + private boolean ignoreIFrames = 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 transient Ability sourceAbility = null; + + /** + * Custom damage data for script-created zones that don't have a sourceAbility. + * Used by EnergyController handlers (e.g. DBC Addon) to carry damage configuration + * directly on the entity. Synced via spawn data for client sync. + */ + private NBTTagCompound customDamageData = null; + + 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 != null ? owner.getEntityId() : -1; + // 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); + } + + /** + * Initialize as a hazard zone with default values. Used by EnergyController factory. + * Scripts can then configure properties before calling spawn(). + */ + public void initAsHazard(Entity owner, double x, double y, double z) { + this.zoneType = ZoneType.HAZARD; + this.ownerEntityId = owner != null ? owner.getEntityId() : -1; + double groundY = Ability.findGroundLevel(worldObj, x, y, z) + GROUND_OFFSET; + this.setPosition(x, groundY, z); + this.ticksSinceDamage = damageInterval; + } + + /** + * Initialize as a trap zone with default values. Used by EnergyController factory. + * Scripts can then configure properties before calling spawn(). + */ + public void initAsTrap(Entity owner, double x, double y, double z) { + this.zoneType = ZoneType.TRAP; + this.ownerEntityId = owner != null ? owner.getEntityId() : -1; + double groundY = Ability.findGroundLevel(worldObj, x, y, z) + GROUND_OFFSET; + this.setPosition(x, groundY, z); + this.ticksSinceLastTrigger = triggerCooldown; + } + + 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, + boolean ignoreIFrames, + 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.ignoreIFrames = ignoreIFrames; + 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 (AbilityPotionEffect 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 ignoreIFrames, 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 = Math.max(MIN_DAMAGE_INTERVAL, damageInterval); + zone.ignoreIFrames = ignoreIFrames; + 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 (AbilityPotionEffect e : effects) { + zone.effects.add(e.copy()); + } + } + return zone; + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTITY LIFECYCLE + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void entityInit() { + } + + @Override + protected void readEntityFromNBT(NBTTagCompound nbt) { + this.setDead(); + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @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.getEntityId())) continue; + if (owner instanceof EntityLivingBase && !AbilityTargetHelper.shouldAffect((EntityLivingBase) owner, entity, TargetFilter.ENEMIES, false)) 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; + if (owner instanceof EntityLivingBase && !AbilityTargetHelper.shouldAffect((EntityLivingBase) owner, entity, TargetFilter.ENEMIES, false)) 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.getEntityId()); + 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 (entity != owner && owner instanceof EntityLivingBase && !AbilityTargetHelper.shouldAffect((EntityLivingBase) owner, entity, TargetFilter.ENEMIES, false)) continue; + if (!isInZone(entity)) continue; + + if (damagePerSecond > 0) { + // The configured value is damage per second, so a pulse deals the share of a + // second it covers. Applying it whole made the real rate depend on the interval. + applyDamage(entity, owner, damagePerSecond * (damageInterval / 20.0f)); + } + + 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; + + int previousHurtResistantTime = Ability.clearHurtResistanceIfNeeded(target, ignoreIFrames); + try { + // Route through ability extender (e.g. DBC Addon damage scaling) + boolean handled = false; + if (sourceAbility != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + handled = AbilityController.Instance.fireOnAbilityDamage( + sourceAbility, (EntityLivingBase) owner, target, + dmg, 0.0f, 0.0f, dx, dz, 1.0f); + } + // Fallback: route through EnergyController for script-created entities with custom damage data + if (!handled && customDamageData != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + handled = EnergyController.Instance.fireOnEnergyDamage( + this, (EntityLivingBase) owner, target, + dmg, 0.0f, 0.0f, dx, dz, 1.0f, customDamageData); + } + + if (!handled) { + 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); + } + } + return true; + } finally { + Ability.restoreHurtResistanceIfNeeded(target, ignoreIFrames, previousHurtResistantTime); + } + } + + private void applyEffects(EntityLivingBase entity) { + if (entity == null || effects.isEmpty()) return; + for (AbilityPotionEffect 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; + } + + public Ability getSourceAbility() { + return sourceAbility; + } + + public void setSourceAbility(Ability ability) { + this.sourceAbility = ability; + } + + public NBTTagCompound getCustomDamageData() { + return customDamageData; + } + + public void setCustomDamageData(NBTTagCompound data) { + this.customDamageData = data; + } + + // ═══════════════════════════════════════════════════════════════════ + // 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; + } + + // ═══════════════════════════════════════════════════════════════════ + // PUBLIC SETTERS (for EnergyController / scripting API) + // ═══════════════════════════════════════════════════════════════════ + + public void setShape(ZoneShape shape) { this.shape = shape; } + public void setRadius(float radius) { this.radius = radius; } + public void setZoneHeight(float height) { this.zoneHeight = height; } + public void setDurationTicks(int ticks) { this.durationTicks = ticks; this.maxTicks = ticks; } + public void setInnerColor(int color) { this.innerColor = color; } + public void setOuterColor(int color) { this.outerColor = color; } + public void setOuterColorEnabled(boolean enabled) { this.outerColorEnabled = enabled; } + public void setParticleDensity(float density) { this.particleDensity = density; } + public void setParticleScale(float scale) { this.particleScale = scale; } + public void setAnimSpeed(float speed) { this.animSpeed = speed; } + public void setIgnoreIFrames(boolean ignore) { this.ignoreIFrames = ignore; } + + // Hazard-specific + public float getDamagePerSecond() { return damagePerSecond; } + public void setDamagePerSecond(float dps) { this.damagePerSecond = dps; } + public int getDamageInterval() { return damageInterval; } + public void setDamageInterval(int ticks) { this.damageInterval = Math.max(MIN_DAMAGE_INTERVAL, ticks); } + public boolean isAffectsCaster() { return affectsCaster; } + public void setAffectsCaster(boolean affects) { this.affectsCaster = affects; } + + // Trap-specific + public float getTriggerRadius() { return triggerRadius; } + public void setTriggerRadius(float radius) { this.triggerRadius = radius; } + public int getArmTime() { return armTime; } + public void setArmTime(int ticks) { this.armTime = ticks; } + public int getMaxTriggers() { return maxTriggers; } + public void setMaxTriggers(int max) { this.maxTriggers = max; } + public int getTriggerCooldown() { return triggerCooldown; } + public void setTriggerCooldown(int ticks) { this.triggerCooldown = ticks; } + public float getDamage() { return damage; } + public void setDamage(float damage) { this.damage = damage; } + public float getDamageRadius() { return damageRadius; } + public void setDamageRadius(float radius) { this.damageRadius = radius; } + public float getKnockback() { return knockback; } + public void setKnockback(float knockback) { this.knockback = knockback; } + public void setVisible(boolean visible) { this.visible = visible; } + + public boolean isIgnoreIFrames() { return ignoreIFrames; } + + public int getOwnerEntityId() { return ownerEntityId; } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + + // ═══════════════════════════════════════════════════════════════════ + // SPAWN DATA (ByteBuf for client sync) + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void writeSpawnData(ByteBuf buffer) { + buffer.writeInt(zoneType.ordinal()); + ByteBufUtils.writeString(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.writeString(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 (AbilityPotionEffect effect : effects) { + effectList.appendTag(effect.writeNBT()); + } + effectsNbt.setTag("Effects", effectList); + try { + ByteBufUtils.writeNBT(buffer, effectsNbt); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error writing zone effects spawn data", e); + } + + // Custom damage data + boolean hasDamageData = customDamageData != null; + buffer.writeBoolean(hasDamageData); + if (hasDamageData) { + try { + ByteBufUtils.writeNBT(buffer, customDamageData); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error writing zone custom damage data", e); + } + } + } + + @Override + public void readSpawnData(ByteBuf buffer) { + int zoneTypeOrd = buffer.readInt(); + this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; + String shapeName = ByteBufUtils.readString(buffer); + try { + this.shape = ZoneShape.valueOf(shapeName); + } catch (Exception e) { + this.shape = ZoneShape.CIRCLE; + } + this.ownerEntityId = buffer.readInt(); + this.radius = Math.max(0.1f, Math.min(100.0f, buffer.readFloat())); + if (Float.isNaN(radius) || Float.isInfinite(radius)) radius = 5.0f; + 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.readString(buffer); + this.particleSize = buffer.readInt(); + this.particleGlow = buffer.readBoolean(); + + this.armTime = buffer.readInt(); + this.visible = buffer.readBoolean(); + + // Effects + NBTTagCompound effectsNbt = null; + try { + effectsNbt = ByteBufUtils.readNBT(buffer); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error reading zone effects spawn data", e); + } + effects.clear(); + if (effectsNbt != null && effectsNbt.hasKey("Effects")) { + NBTTagList effectList = effectsNbt.getTagList("Effects", 10); + for (int i = 0; i < effectList.tagCount(); i++) { + AbilityPotionEffect effect = AbilityPotionEffect.fromNBT(effectList.getCompoundTagAt(i)); + if (effect != null && effect.isValid()) { + effects.add(effect); + } + } + } + + // Custom damage data + if (buffer.readableBytes() > 0 && buffer.readBoolean()) { + try { + this.customDamageData = ByteBufUtils.readNBT(buffer); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error reading zone custom damage data", e); + } + } + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java new file mode 100644 index 000000000..9d6e8ab88 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java @@ -0,0 +1,455 @@ +package kamkeel.npcs.entity; + +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.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import noppes.npcs.controllers.data.MagicData; + +/** + * Universal base class for all energy ability entities (Projectiles, Barriers, Sweeper). + * Provides shared visual data, owner tracking, charging state, and common entity properties. + */ +public abstract class EntityEnergyAbility extends Entity implements IEntityAdditionalSpawnData { + + // ==================== SAFETY CONSTANTS ==================== + protected static final int CHARGE_TIMEOUT_GRACE = 60; // Ticks of grace after charge should have ended + protected static final int PREVIEW_CHARGE_GRACE = 3; // Ticks of grace for client-only charge previews + protected static final int HARD_LIFETIME_CAP = 1200; // 60 seconds absolute max for projectiles/sweepers + protected static final int BARRIER_HARD_LIFETIME_CAP = 12000; // 10 minutes absolute max for barriers + protected static final float MAX_ENTITY_SIZE = 100.0f; // Max size/width/length for any energy entity + protected static final float MAX_ENTITY_RADIUS = 50.0f; // Max radius for dome barriers + + // ==================== VISUAL PROPERTIES ==================== + protected EnergyDisplayData displayData = new EnergyDisplayData(); + protected EnergyLightningData lightningData = new EnergyLightningData(); + + // Client-side lightning state (not saved to NBT) + @SideOnly(Side.CLIENT) + public transient Object lightningState; // Actually AttachedLightningRenderer.LightningState + + // ==================== TRACKING ==================== + protected int ownerEntityId = -1; + + // ==================== STATE ==================== + /** + * The ability that spawned this entity. Transient, not saved to NBT. + */ + protected transient Ability sourceAbility = null; + + /** + * Custom damage data for script-created entities that don't have a sourceAbility. + * Used by EnergyController handlers (e.g. DBC Addon) to carry damage configuration + * directly on the entity. Persistent — saved to spawn data for client sync. + */ + protected NBTTagCompound customDamageData = null; + + /** Magic data for this entity — defines magic types for outgoing damage or barrier defense. */ + protected MagicData magicData = new MagicData(); + + protected boolean ignoreIFrames = false; + protected boolean previewMode = false; + protected EntityLivingBase previewOwner = null; + + // ==================== CHARGING STATE ==================== + protected boolean charging = false; + protected int chargeDuration = 0; + protected int chargeTick = 0; + protected static final int DW_CHARGING = 20; + + public EntityEnergyAbility(World world) { + super(world); + this.isImmuneToFire = true; + this.ignoreFrustumCheck = true; + } + + @Override + protected void entityInit() { + this.dataWatcher.addObject(DW_CHARGING, (byte) 0); + } + + // ==================== CHARGING ==================== + + /** + * 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). + */ + public void setCharging(boolean value) { + this.charging = value; + if (!worldObj.isRemote) { + this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); + } + } + + public void setChargeDuration(int duration) { + this.chargeDuration = duration; + } + + /** + * Reset chargeTick back to chargeDuration so the charging timeout + * grace period restarts. Used by items that let the player hold + * a fully-charged orb indefinitely. + */ + public void resetChargeTick() { + this.chargeTick = this.chargeDuration; + } + + 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.min(1.0f, Math.max(0, (float) (chargeTick - 1) / chargeDuration)); + float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); + return prevProgress + (currProgress - prevProgress) * partialTicks; + } + + // ==================== OWNER ==================== + + /** + * Get the owner entity. In preview mode, returns the preview owner directly. + */ + public Entity getOwnerEntity() { + if (previewMode && previewOwner != null) { + return previewOwner; + } + if (ownerEntityId == -1) return null; + return worldObj.getEntityByID(ownerEntityId); + } + + public int getOwnerEntityId() { + return ownerEntityId; + } + + public void setOwnerEntityId(int id) { + this.ownerEntityId = id; + } + + // ==================== SOURCE ABILITY ==================== + + public Ability getSourceAbility() { + return sourceAbility; + } + + public void setSourceAbility(Ability ability) { + this.sourceAbility = ability; + } + + // ==================== CUSTOM DAMAGE DATA ==================== + + public NBTTagCompound getCustomDamageData() { + return customDamageData; + } + + public void setCustomDamageData(NBTTagCompound data) { + this.customDamageData = data; + } + + public MagicData getMagicData() { + return magicData; + } + + public void setMagicData(MagicData data) { + this.magicData = data != null ? data : new MagicData(); + } + + public boolean isIgnoreIFrames() { + return ignoreIFrames; + } + + public void setIgnoreIFrames(boolean ignoreIFrames) { + this.ignoreIFrames = ignoreIFrames; + } + + // ==================== PREVIEW MODE ==================== + + public boolean isPreviewMode() { + return previewMode; + } + + public void setPreviewMode(boolean preview) { + this.previewMode = preview; + } + + public void setPreviewOwner(EntityLivingBase owner) { + this.previewOwner = owner; + } + + // ==================== DISPLAY GETTERS & SETTERS ==================== + + public EnergyDisplayData getDisplayData() { + return displayData; + } + + public EnergyLightningData getLightningData() { + return lightningData; + } + + public int getInnerColor() { + return displayData.getInnerColor(); + } + + public void setInnerColor(int color) { + displayData.setInnerColor(color); + } + + public float getInnerAlpha() { + return displayData.getInnerAlpha(); + } + + public void setInnerAlpha(float alpha) { + displayData.setInnerAlpha(alpha); + } + + public int getOuterColor() { + return displayData.getOuterColor(); + } + + public void setOuterColor(int color) { + displayData.setOuterColor(color); + } + + public boolean isOuterColorEnabled() { + return displayData.isOuterColorEnabled(); + } + + public void setOuterColorEnabled(boolean enabled) { + displayData.setOuterColorEnabled(enabled); + } + + public float getOuterColorWidth() { + return displayData.getOuterColorWidth(); + } + + public void setOuterColorWidth(float width) { + displayData.setOuterColorWidth(width); + } + + 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); + } + + // ==================== LIGHTNING GETTERS & SETTERS ==================== + + public boolean hasLightningEffect() { + return lightningData.isLightningEffect(); + } + + public void setLightningEffect(boolean enabled) { + lightningData.setLightningEffect(enabled); + } + + public float getLightningDensity() { + return lightningData.getLightningDensity(); + } + + public void setLightningDensity(float density) { + lightningData.setLightningDensity(density); + } + + public float getLightningRadius() { + return lightningData.getLightningRadius(); + } + + public void setLightningRadius(float radius) { + lightningData.setLightningRadius(radius); + } + + public int getLightningFadeTime() { + return lightningData.getLightningFadeTime(); + } + + public void setLightningFadeTime(int ticks) { + lightningData.setLightningFadeTime(ticks); + } + + // ==================== BRIGHTNESS ==================== + + @Override + public float getBrightness(float partialTicks) { + return 1.0f; + } + + @Override + @SideOnly(Side.CLIENT) + public int getBrightnessForRender(float partialTicks) { + return 0xF000F0; + } + + @Override + public boolean shouldRenderInPass(int pass) { + return pass == 1; // Translucent pass + } + + // ==================== COLLISION SETTINGS ==================== + + @Override + public boolean canBePushed() { + return false; + } + + @Override + protected boolean canTriggerWalking() { + return false; + } + + @Override + public boolean isBurning() { + return false; + } + + @SideOnly(Side.CLIENT) + public float getShadowSize() { + return 0.0f; + } + + // ==================== SAFETY HELPERS ==================== + + /** + * Sanitize a float value loaded from NBT or external sources. + * Guards against NaN, Infinity, negative values, and values exceeding a max. + */ + protected static float sanitize(float value, float fallback, float max) { + if (Float.isNaN(value) || Float.isInfinite(value) || value < 0) return fallback; + return Math.min(value, max); + } + + // ==================== NBT HELPERS ==================== + + /** + * Write shared energy base fields to NBT (owner, display, lightning). + * Call from subclass NBT writers before writing type-specific fields. + */ + protected void writeEnergyBaseNBT(NBTTagCompound nbt) { + nbt.setInteger("OwnerId", ownerEntityId); + nbt.setBoolean("IgnoreIFrames", ignoreIFrames); + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + if (customDamageData != null) { + nbt.setTag("CustomDamageData", customDamageData); + } + magicData.writeToNBT(nbt); + } + + /** + * Read shared energy base fields from NBT (owner, display, lightning). + * Call from subclass NBT readers before reading type-specific fields. + */ + protected void readEnergyBaseNBT(NBTTagCompound nbt) { + this.ownerEntityId = nbt.getInteger("OwnerId"); + this.ignoreIFrames = nbt.getBoolean("IgnoreIFrames"); + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + if (nbt.hasKey("CustomDamageData")) { + this.customDamageData = nbt.getCompoundTag("CustomDamageData"); + } + magicData.readToNBT(nbt); + } + + // ==================== WORLD NBT (INTENTIONALLY EMPTY) ==================== + + /** + * Ability entities are transient — they must not survive world saves. + * If Minecraft deserializes one from a chunk, kill it immediately. + */ + @Override + protected void readEntityFromNBT(NBTTagCompound nbt) { + this.setDead(); + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + // ==================== SPAWN DATA ==================== + + /** + * Write entity data for client sync. Subclasses override this + * to serialize their fields. Separate from writeEntityToNBT + * which is intentionally empty (entities are transient, not saved to world). + */ + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + } + + /** + * Read entity data from client sync. Subclasses override this + * to deserialize their fields. Separate from readEntityFromNBT + * which is intentionally empty (entities are transient, not saved to world). + */ + protected void readSpawnNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + } + + /** + * Export spawn NBT for non-world preview rendering sync. + */ + public final NBTTagCompound exportSpawnNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + writeSpawnNBT(nbt); + return nbt; + } + + /** + * Import spawn NBT for non-world preview rendering sync. + */ + public final void importSpawnNBT(NBTTagCompound nbt) { + if (nbt != null) { + readSpawnNBT(nbt); + } + } + + @Override + public void writeSpawnData(ByteBuf buffer) { + try { + NBTTagCompound compound = new NBTTagCompound(); + this.writeSpawnNBT(compound); + ByteBufUtils.writeNBT(buffer, compound); + } catch (Exception e) { + noppes.npcs.LogWriter.error("Error writing energy ability spawn data", e); + } + } + + @Override + public void readSpawnData(ByteBuf buffer) { + try { + NBTTagCompound compound = ByteBufUtils.readNBT(buffer); + if (compound != null) { + this.readSpawnNBT(compound); + } + } catch (Exception e) { + noppes.npcs.LogWriter.error("Error reading energy ability spawn data", e); + } + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java new file mode 100644 index 000000000..da9edb676 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -0,0 +1,936 @@ +package kamkeel.npcs.entity; + +import kamkeel.npcs.addon.DBCAddon; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.network.packets.data.energy.BarrierClientSyncPacket; +import kamkeel.npcs.util.AttributeAttackUtil; +import kamkeel.npcs.util.CNPCDebug; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.world.World; +import noppes.npcs.CustomNpcs; +import noppes.npcs.EventHooks; +import noppes.npcs.config.ConfigMain; +import noppes.npcs.controllers.data.MagicData; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.entity.EntityNPCInterface; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Base class for energy barrier entities (Dome, Panel). + * Provides shared health, damage, hit flash, knockback target, + * and barrier lifecycle management. + * Extends EntityEnergyAbility for shared visual/owner/charging state. + */ +public abstract class EntityEnergyBarrier extends EntityEnergyAbility { + + /** + * Outcome of a projectile vs barrier interaction. + */ + public enum ProjectileHitResult { + PASS, + BLOCKED, + BROKEN; + + public boolean isAbsorbed() { + return this == BLOCKED || this == BROKEN; + } + } + + /** + * Full result of a projectile vs barrier hit after multiplier/event processing. + */ + public static class ProjectileHitOutcome { + public final ProjectileHitResult result; + public final float barrierHealthBefore; + public final float barrierHealthAfter; + public final float appliedBarrierDamage; + public final float remainingProjectileDamage; + public final boolean reflectEnabled; + public final float reflectStrengthPct; + public final boolean useHealth; + + public ProjectileHitOutcome(ProjectileHitResult result, + float barrierHealthBefore, + float barrierHealthAfter, + float appliedBarrierDamage, + float remainingProjectileDamage, + boolean reflectEnabled, + float reflectStrengthPct, + boolean useHealth) { + this.result = result; + this.barrierHealthBefore = barrierHealthBefore; + this.barrierHealthAfter = barrierHealthAfter; + this.appliedBarrierDamage = appliedBarrierDamage; + this.remainingProjectileDamage = remainingProjectileDamage; + this.reflectEnabled = reflectEnabled; + this.reflectStrengthPct = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct)); + this.useHealth = useHealth; + } + + public boolean shouldReflect() { + return reflectEnabled && result == ProjectileHitResult.BLOCKED; + } + } + + // ==================== ACTIVE BARRIER REGISTRY ==================== + private static final List> activeBarriers = new ArrayList<>(); + private boolean tracked = false; + + public static void trackBarrier(EntityEnergyBarrier barrier) { + activeBarriers.add(new WeakReference<>(barrier)); + } + + /** + * Get all living barriers in the given world. Auto-cleans dead refs. + */ + public static List getActiveBarriers(World world) { + List result = new ArrayList<>(); + Iterator> it = activeBarriers.iterator(); + while (it.hasNext()) { + EntityEnergyBarrier b = it.next().get(); + if (b == null || b.isDead) { + it.remove(); + } else if (b.worldObj == world) { + result.add(b); + } + } + return result; + } + + public static void clearAllBarriers() { + activeBarriers.clear(); + } + + // ==================== BARRIER PROPERTIES ==================== + protected EnergyBarrierData barrierData = new EnergyBarrierData(); + protected float currentHealth; + protected int ticksAlive = 0; + /** Absolute world time the barrier expires at, so ticks it misses cannot extend it. */ + protected long barrierDeathTime = -1; + + // ==================== DATA WATCHER INDICES ==================== + protected static final int DW_HEALTH_PERCENT = 21; + protected static final int DW_HIT_FLASH = 22; + + public EntityEnergyBarrier(World world) { + super(world); + this.noClip = true; + } + + @Override + protected void entityInit() { + super.entityInit(); // DW_CHARGING = 20 + this.dataWatcher.addObject(DW_HEALTH_PERCENT, 1.0f); + this.dataWatcher.addObject(DW_HIT_FLASH, (byte) 0); + } + + // ==================== ABSTRACT METHODS ==================== + + /** + * Check if a projectile is incoming toward this barrier. + * Dome uses spherical check, Panel uses planar check. + */ + public abstract boolean isIncomingProjectile(EntityEnergyProjectile projectile); + + /** + * Setup charging state. Called during windup phase. + */ + public abstract void setupCharging(int duration); + + /** + * Finish charging — snap to full size and become active. + */ + public abstract void finishCharging(); + + /** + * Process entity physics for this barrier. + * Handles solid wall (entity repositioning) and knockback (repulsion force). + */ + protected abstract void processEntityPhysics(); + + /** + * Get the maximum extent of this barrier for distance pre-filtering. + * Dome returns radius, Panel returns max(width, height) / 2. + */ + public abstract float getMaxExtent(); + + /** + * Check if a generic (non-CNPC+) projectile is incoming toward this barrier. + * Uses the same geometric logic as isIncomingProjectile but with raw position data. + * + * @param posX, posY, posZ Current (or predicted) position of the projectile + * @param motionX, motionY, motionZ Current velocity of the projectile + * @param prevPosX, prevPosY, prevPosZ Previous position of the projectile + * @param ownerEntityId Entity ID of the projectile's shooter + */ + public abstract boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId); + + /** + * Compute the outward surface normal at a given hit point on this barrier. + * Used by external systems (e.g., mixin-based projectile reflection) that cannot + * access barrier-subtype internals. + * + * @param hitX, hitY, hitZ Position near the barrier surface + * @param velX, velY, velZ Incoming velocity (used as fallback direction) + * @return double[3] normalized surface normal pointing outward from the barrier + */ + public abstract double[] getSurfaceNormal(double hitX, double hitY, double hitZ, + double velX, double velY, double velZ); + + /** + * Compute a position just outside the barrier surface, along the outward normal + * from the given position. Used to snap paused/reflected projectiles outside + * the collision zone. + * + * @param px, py, pz Current projectile position + * @param velX, velY, velZ Current velocity (used as fallback for direction) + * @param bias Distance outside the surface to snap to + * @return double[3] position outside the barrier surface + */ + public abstract double[] getOutsideSurfacePoint(double px, double py, double pz, + double velX, double velY, double velZ, + float bias); + + // ==================== GENERIC PROJECTILE HIT ==================== + + /** + * Apply damage from a generic (non-CNPC+) projectile to this barrier. + * Uses the typeId for damage multiplier lookup (e.g. "dbc.ki_attack"). + * + * @param projectileEntity The entity that hit the barrier (for context) + * @param damage Base damage to apply + * @param typeId Type identifier for damage multiplier lookup + * @return true if the barrier absorbed the hit (projectile should be destroyed) + */ + public boolean onGenericProjectileHit(Entity projectileEntity, float damage, String typeId) { + float multiplier = barrierData.getMultiplier(typeId); + float finalDamage = damage * multiplier; + + if (!worldObj.isRemote) { + float eventDamage = EventHooks.onEnergyBarrierHit(this, ownerEntityId, null, finalDamage); + if (eventDamage < 0) return false; + finalDamage = eventDamage; + } + + triggerHitFlash(); + + if (!barrierData.useHealth) { + return true; + } + + currentHealth -= finalDamage; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + + return true; + } + + /** + * Apply damage from a generic (non-CNPC+) projectile and return full hit context. + * Same logic as onProjectileHitResolved() but for raw Entity + typeId. + * + * @param projectileEntity The entity that hit the barrier (for event context) + * @param damage Base damage to apply + * @param typeId Type identifier for damage multiplier lookup (e.g., "dbc.ki_attack") + * @return Full ProjectileHitOutcome with result, reflect data, remaining damage + */ + public ProjectileHitOutcome onGenericProjectileHitResolved(Entity projectileEntity, float damage, String typeId) { + float multiplier = barrierData.getMultiplier(typeId); + float finalDamage = damage * multiplier; + + // Apply magic interactions if projectile is a CNPC+ energy entity + if (projectileEntity instanceof EntityEnergyAbility) { + float magicMultiplier = AttributeAttackUtil.calculateMagicInteractionMultiplier( + ((EntityEnergyAbility) projectileEntity).getMagicData(), this.magicData); + finalDamage *= magicMultiplier; + } + + if (!worldObj.isRemote) { + float eventDamage = EventHooks.onEnergyBarrierHit(this, ownerEntityId, null, finalDamage); + if (eventDamage < 0) { + return new ProjectileHitOutcome( + ProjectileHitResult.PASS, + currentHealth, currentHealth, + 0.0f, 0.0f, + barrierData.reflect, barrierData.reflectStrengthPct, + barrierData.useHealth + ); + } + finalDamage = eventDamage; + } + + triggerHitFlash(); + float healthBefore = currentHealth; + + if (!barrierData.useHealth) { + return new ProjectileHitOutcome( + ProjectileHitResult.BLOCKED, + healthBefore, healthBefore, + 0.0f, 0.0f, + barrierData.reflect, barrierData.reflectStrengthPct, + false + ); + } + + currentHealth -= finalDamage; + syncHealthPercent(); + + if (currentHealth <= 0) { + float remaining = Math.max(0.0f, finalDamage - healthBefore); + onBarrierDestroyed(); + this.setDead(); + return new ProjectileHitOutcome( + ProjectileHitResult.BROKEN, + healthBefore, 0.0f, + finalDamage, remaining, + barrierData.reflect, barrierData.reflectStrengthPct, + true + ); + } + + return new ProjectileHitOutcome( + ProjectileHitResult.BLOCKED, + healthBefore, currentHealth, + finalDamage, 0.0f, + barrierData.reflect, barrierData.reflectStrengthPct, + true + ); + } + + // ==================== PROJECTILE HIT ==================== + + /** + * Apply damage to this barrier from a projectile. + * Returns true if the barrier absorbed the hit (projectile should be destroyed). + */ + public boolean onProjectileHit(EntityEnergyProjectile projectile, float baseDamage) { + return onProjectileHitDetailed(projectile, baseDamage).isAbsorbed(); + } + + /** + * Apply damage to this barrier from a projectile and return detailed outcome. + */ + public ProjectileHitResult onProjectileHitDetailed(EntityEnergyProjectile projectile, float baseDamage) { + return onProjectileHitResolved(projectile, baseDamage).result; + } + + /** + * Apply damage to this barrier from a projectile and return full hit context. + */ + public ProjectileHitOutcome onProjectileHitResolved(EntityEnergyProjectile projectile, float baseDamage) { + // Get damage multiplier for this projectile type + String typeId = ""; + if (projectile.getSourceAbility() != null) { + typeId = projectile.getSourceAbility().getTypeId(); + } + float multiplier = barrierData.getMultiplier(typeId); + float damage = baseDamage * multiplier; + + // Apply magic interactions (e.g., Water projectile vs Fire barrier) + float magicMultiplier = AttributeAttackUtil.calculateMagicInteractionMultiplier( + projectile.getMagicData(), this.magicData); + damage *= magicMultiplier; + + // Fire hit event (may cancel or modify damage) + if (!worldObj.isRemote) { + float eventDamage = EventHooks.onEnergyBarrierHit(this, ownerEntityId, projectile, damage); + if (eventDamage < 0) { + return new ProjectileHitOutcome( + ProjectileHitResult.PASS, + currentHealth, + currentHealth, + 0.0f, + 0.0f, + barrierData.reflect, + barrierData.reflectStrengthPct, + barrierData.useHealth + ); + } + damage = eventDamage; + } + + triggerHitFlash(); + + float healthBefore = currentHealth; + + if (!barrierData.useHealth) { + return new ProjectileHitOutcome( + ProjectileHitResult.BLOCKED, + healthBefore, + healthBefore, + 0.0f, + 0.0f, + barrierData.reflect, + barrierData.reflectStrengthPct, + false + ); + } + + currentHealth -= damage; + syncHealthPercent(); + + if (currentHealth <= 0) { + float remaining = Math.max(0.0f, damage - healthBefore); + onBarrierDestroyed(); + this.setDead(); + return new ProjectileHitOutcome( + ProjectileHitResult.BROKEN, + healthBefore, + 0.0f, + damage, + remaining, + barrierData.reflect, + barrierData.reflectStrengthPct, + true + ); + } + + return new ProjectileHitOutcome( + ProjectileHitResult.BLOCKED, + healthBefore, + currentHealth, + damage, + 0.0f, + barrierData.reflect, + barrierData.reflectStrengthPct, + true + ); + } + + // ==================== MELEE DAMAGE ==================== + + @Override + public boolean canBeCollidedWith() { + return barrierData.meleeEnabled; + } + + @Override + public boolean isEntityInsideOpaqueBlock() { + return false; + } + + @Override + protected boolean func_145771_j(double x, double y, double z) { + return false; + } + + @Override + public boolean attackEntityFrom(DamageSource source, float amount) { + if (worldObj.isRemote || !barrierData.meleeEnabled) return false; + if (isCharging()) return false; + + float damage = amount * barrierData.meleeDamageMultiplier; + + Entity attacker = source.getEntity(); + + // A barrier is a plain Entity, so no LivingHurtEvent fires for it and nothing scales the + // hit the way it would against a living target - vanilla hands us the bare attackDamage + // attribute. Run the scaling here instead, or the barrier only ever takes a point of it. + if (attacker instanceof EntityLivingBase) { + damage = AbilityController.Instance.fireModifyBarrierMeleeDamage(this, (EntityLivingBase) attacker, damage); + } + if (attacker instanceof EntityPlayer && ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable()) { + damage = AttributeAttackUtil.calculateOutgoing((EntityPlayer) attacker, damage); + } + + // Apply magic interactions from attacker's magic vs barrier's magic + if (attacker != null) { + MagicData attackerMagic = null; + if (attacker instanceof EntityPlayer) { + PlayerData data = PlayerData.get((EntityPlayer) attacker); + if (data != null) attackerMagic = data.magicData; + } else if (attacker instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) attacker; + if (npc.stats != null) attackerMagic = npc.stats.magicData; + } + if (attackerMagic != null) { + float magicMultiplier = AttributeAttackUtil.calculateMagicInteractionMultiplier( + attackerMagic, this.magicData); + damage *= magicMultiplier; + } + } + + // Fire hit event with null projectile (melee hit) + float eventDamage = EventHooks.onEnergyBarrierHit(this, ownerEntityId, null, damage); + if (eventDamage < 0) return false; + damage = eventDamage; + + triggerHitFlash(); + + if (!barrierData.useHealth) return true; + + currentHealth -= damage; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + return true; + } + + // ==================== SHARED UPDATE LOGIC ==================== + + /** + * Shared barrier tick logic for onUpdate(). Handles spawned event, owner death, + * duration check, hit flash decay, and tick event. + * Call this after incrementing ticksAlive in subclass onUpdate(). + * + * @return true if barrier died this tick (caller should return early) + */ + protected boolean updateBarrierTick() { + if (!worldObj.isRemote) { + // Track barrier and fire spawned event on first tick + if (ticksAlive == 1) { + if (!tracked) { + trackBarrier(this); + tracked = true; + } + EventHooks.onEnergyBarrierSpawned(this, ownerEntityId); + } + + // Check owner death + if (ownerEntityId >= 0 && ticksAlive > 5) { + Entity owner = worldObj.getEntityByID(ownerEntityId); + if (owner != null) { + if (owner.isDead) { + onBarrierDestroyed(); + this.setDead(); + return true; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + onBarrierDestroyed(); + this.setDead(); + return true; + } + } + } + + // Set the deadline on the first tick after charging, so lifetime starts when the + // barrier is actually up. Counting elapsed ticks instead would let any tick the + // entity misses - chunk unload, for one - extend it past its configured duration. + if (barrierDeathTime < 0 && !isCharging()) { + barrierDeathTime = worldObj.getTotalWorldTime() + + (barrierData.useDuration ? barrierData.durationTicks : BARRIER_HARD_LIFETIME_CAP); + } + + // Duration check, and the hard lifetime cap for barriers with no duration + if (barrierDeathTime >= 0 && worldObj.getTotalWorldTime() >= barrierDeathTime) { + onBarrierDestroyed(); + this.setDead(); + return true; + } + + // Reset hit flash + if (getHitFlash() > 0) { + setHitFlash((byte) (getHitFlash() - 1)); + } + + // Fire tick event + EventHooks.onEnergyBarrierTick(this, ownerEntityId); + } + return false; + } + + // ==================== HELPERS ==================== + + protected void onBarrierDestroyed() { + EventHooks.onEnergyBarrierDestroyed(this, ownerEntityId); + } + + protected void syncHealthPercent() { + float percent = barrierData.useHealth && barrierData.maxHealth > 0 + ? Math.max(0, currentHealth / barrierData.maxHealth) + : 1.0f; + if (!worldObj.isRemote) { + this.dataWatcher.updateObject(DW_HEALTH_PERCENT, percent); + } + } + + protected void triggerHitFlash() { + if (!worldObj.isRemote) { + setHitFlash((byte) 4); + } + } + + protected void setHitFlash(byte value) { + this.dataWatcher.updateObject(DW_HIT_FLASH, value); + } + + public byte getHitFlash() { + return this.dataWatcher.getWatchableObjectByte(DW_HIT_FLASH); + } + + public float getHealthPercent() { + return this.dataWatcher.getWatchableObjectFloat(DW_HEALTH_PERCENT); + } + + /** + * Client prediction only runs for the local player. + */ + protected EntityPlayer getClientPredictionPlayer() { + return worldObj != null && worldObj.isRemote ? CustomNpcs.proxy.getPlayer() : null; + } + + /** + * Shared target filter used by Dome/Panel physics loops. + */ + protected boolean shouldSkipBarrierPhysicsTarget(EntityLivingBase entity, EntityPlayer clientPredictionPlayer) { + if (entity == null || !entity.isEntityAlive()) return true; + if (entity.getEntityId() == ownerEntityId) return true; + if (worldObj.isRemote && (clientPredictionPlayer == null || entity != clientPredictionPlayer)) return true; + return isAllyOfOwner(entity); + } + + /** + * Check if an entity is an ally of this barrier's owner. + * Server uses full relationship logic; client uses a lightweight safe approximation. + */ + protected boolean isAllyOfOwner(EntityLivingBase entity) { + Entity owner = getOwnerEntity(); + if (owner == null || !(owner instanceof EntityLivingBase)) return false; + if (worldObj != null && worldObj.isRemote) { + return isClientPredictedAlly((EntityLivingBase) owner, entity); + } + return AbilityTargetHelper.isAlly((EntityLivingBase) owner, entity); + } + + /** + * Client-safe ally approximation used only for movement prediction. + * Avoids PlayerData/Party/Faction point lookups that are server-owned. + */ + protected boolean isClientPredictedAlly(EntityLivingBase owner, EntityLivingBase target) { + if (owner == null || target == null) return false; + if (owner == target) return true; + + if (target instanceof EntityNPCInterface) { + EntityNPCInterface targetNpc = (EntityNPCInterface) target; + if (targetNpc.faction.isPassive) return true; + if (owner instanceof EntityNPCInterface) { + EntityNPCInterface ownerNpc = (EntityNPCInterface) owner; + return ownerNpc.faction.id == targetNpc.faction.id; + } + } + + return false; + } + + // ==================== CONTAINMENT & ABSORBING ==================== + + /** + * Check if an entity is geometrically inside this barrier's protected zone. + * Override in subclasses (dome checks sphere containment). + */ + public boolean isEntityInside(Entity entity) { + return false; + } + + /** + * Find a barrier that would absorb damage for the given entity (its caster). + * Returns the barrier if: absorbing is enabled, entity is the barrier's owner, + * and entity is within the barrier's absorb radius of the barrier's current position. + * + * Absorb radius behavior: + * -1 = no limit (absorb regardless of distance) + * 0 = uses the barrier's extent as the radius (dome radius, panel half-size, etc.) + * >0 = owner must be within this many blocks of the barrier entity + */ + public static EntityEnergyBarrier getAbsorbingBarrier(Entity entity) { + if (entity == null || entity.worldObj == null) return null; + List barriers = getActiveBarriers(entity.worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead) continue; + if (!barrier.barrierData.absorbing) continue; + if (barrier.ownerEntityId != entity.getEntityId()) continue; + + float absorbRadius = barrier.barrierData.absorbRadius; + + // -1 = unlimited range + if (absorbRadius < 0) { + return barrier; + } + + // 0 = use barrier's own extent as the effective radius + // Domes: dome radius. Panels: max(width, height) * 0.5 + 1.0, doubled. + float effectiveRadius; + if (absorbRadius > 0) { + effectiveRadius = absorbRadius; + } else if (barrier instanceof EntityEnergyDome) { + effectiveRadius = barrier.getMaxExtent(); + } else { + effectiveRadius = barrier.getMaxExtent() * 3.0f; + } + + // Distance check from barrier's current position to the owner + double dx = entity.posX - barrier.posX; + double dy = (entity.posY + entity.height * 0.5) - barrier.posY; + double dz = entity.posZ - barrier.posZ; + double distSq = dx * dx + dy * dy + dz * dz; + + if (distSq <= (double) effectiveRadius * effectiveRadius) { + return barrier; + } + } + return null; + } + + /** + * Absorb damage from an external source. Reduces barrier health directly. + * Used by damage protection to redirect attacks on inside entities to the barrier. + * + * @param amount The damage amount to absorb + * @return true if damage was absorbed (barrier still alive or just destroyed) + */ + public boolean absorbDamage(float amount) { + if (worldObj.isRemote) return false; + + triggerHitFlash(); + + if (!barrierData.useHealth) { + return true; // Duration-only: absorb but no health loss + } + + currentHealth -= amount; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + return true; + } + + /** + * Teleport an entity to a position. Uses network handler for players + * to ensure reliable client synchronization. + * Skips teleport if destination intersects solid blocks. + */ + protected void teleportEntity(EntityLivingBase ent, double x, double y, double z) { + if (!isPositionClear(ent, x, y, z)) return; + + if (ent instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) ent; + player.playerNetServerHandler.setPlayerLocation(x, y, z, player.rotationYaw, player.rotationPitch); + } else { + ent.setPosition(x, y, z); + } + } + + /** + * Returns true if placing the entity at (x, y, z) would not intersect solid blocks. + */ + protected boolean isPositionClear(EntityLivingBase ent, double x, double y, double z) { + double halfW = ent.width * 0.5; + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + x - halfW, y, z - halfW, + x + halfW, y + ent.height, z + halfW + ); + return worldObj.getCollidingBoundingBoxes(ent, box).isEmpty(); + } + + /** + * Returns true if the entity can be pushed in the given direction without hitting solid blocks. + * Probes a small distance (0.3 blocks) ahead in the push direction. + */ + protected boolean canPushInDirection(EntityLivingBase ent, double dirX, double dirY, double dirZ) { + double probe = 0.3; + double halfW = ent.width * 0.5; + double px = ent.posX + dirX * probe; + double py = ent.posY + dirY * probe; + double pz = ent.posZ + dirZ * probe; + // Never probe below the entity's feet — a downward probe always detects the + // block the entity is already standing/hovering above (false positive). + // MC's own collision system prevents entities from falling through floors, + // so the downward check is redundant. Upward probes (ceiling detection) still work. + if (py < ent.posY) { + py = ent.posY; + } + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + px - halfW, py, pz - halfW, + px + halfW, py + ent.height, pz + halfW + ); + return worldObj.getCollidingBoundingBoxes(ent, box).isEmpty(); + } + + // ==================== GETTERS ==================== + + public EnergyBarrierData getBarrierData() { + return barrierData; + } + + public float getCurrentHealth() { + return currentHealth; + } + + public void setCurrentHealth(float health) { + this.currentHealth = health; + syncHealthPercent(); + } + + /** + * Override the barrier's max health and set current health to match. + * Used by extenders (e.g., DBC scaling) to dynamically set barrier HP at spawn time. + */ + public void setBarrierMaxHealth(float maxHealth) { + this.barrierData.setMaxHealth(maxHealth); + this.currentHealth = maxHealth; + syncHealthPercent(); + } + + public int getTicksAlive() { + return ticksAlive; + } + + // ==================== CLIENT SYNC ==================== + + /** + * Write all client-relevant barrier state for sync. + * Subclasses should override writeBarrierClientSyncData for type-specific fields. + */ + public NBTTagCompound writeClientSyncData() { + NBTTagCompound nbt = new NBTTagCompound(); + // Position + nbt.setDouble("PosX", posX); + nbt.setDouble("PosY", posY); + nbt.setDouble("PosZ", posZ); + // Display + nbt.setInteger("InnerColor", getInnerColor()); + nbt.setFloat("InnerAlpha", getInnerAlpha()); + nbt.setInteger("OuterColor", getOuterColor()); + nbt.setBoolean("OuterColorEnabled", isOuterColorEnabled()); + nbt.setFloat("OuterColorWidth", getOuterColorWidth()); + nbt.setFloat("OuterColorAlpha", getOuterColorAlpha()); + nbt.setFloat("RotationSpeed", getRotationSpeed()); + // Lightning + nbt.setBoolean("LightningEffect", hasLightningEffect()); + nbt.setFloat("LightningDensity", getLightningDensity()); + nbt.setFloat("LightningRadius", getLightningRadius()); + nbt.setInteger("LightningFadeTime", getLightningFadeTime()); + writeBarrierClientSyncData(nbt); + return nbt; + } + + /** + * Apply client sync data from server. + * Subclasses should override applyBarrierClientSyncData for type-specific fields. + */ + public void applyClientSyncData(NBTTagCompound nbt) { + // Position + setPosition(nbt.getDouble("PosX"), nbt.getDouble("PosY"), nbt.getDouble("PosZ")); + // Display + displayData.setInnerColor(nbt.getInteger("InnerColor")); + displayData.setInnerAlpha(nbt.getFloat("InnerAlpha")); + displayData.setOuterColor(nbt.getInteger("OuterColor")); + displayData.setOuterColorEnabled(nbt.getBoolean("OuterColorEnabled")); + displayData.setOuterColorWidth(nbt.getFloat("OuterColorWidth")); + displayData.setOuterColorAlpha(nbt.getFloat("OuterColorAlpha")); + displayData.setRotationSpeed(nbt.getFloat("RotationSpeed")); + // Lightning + setLightningEffect(nbt.getBoolean("LightningEffect")); + setLightningDensity(nbt.getFloat("LightningDensity")); + setLightningRadius(nbt.getFloat("LightningRadius")); + setLightningFadeTime(nbt.getInteger("LightningFadeTime")); + applyBarrierClientSyncData(nbt); + } + + /** + * Subclass hook: write type-specific client sync data (dome radius, panel dimensions, etc.). + */ + protected void writeBarrierClientSyncData(NBTTagCompound nbt) { + } + + /** + * Subclass hook: apply type-specific client sync data on client. + */ + protected void applyBarrierClientSyncData(NBTTagCompound nbt) { + } + + /** + * Send full client sync to all tracking clients. + */ + public void sendClientSync() { + if (worldObj == null || worldObj.isRemote) return; + BarrierClientSyncPacket.sendToTracking(this, writeClientSyncData()); + } + + // ==================== NBT HELPERS ==================== + + /** + * Write shared barrier base fields to NBT. + * Call from subclass writeEntityToNBT() before writing type-specific fields. + */ + protected void writeBarrierBaseNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + nbt.setInteger("TicksAlive", ticksAlive); + nbt.setLong("BarrierDeathTime", barrierDeathTime); + nbt.setFloat("CurrentHealth", currentHealth); + nbt.setBoolean("Charging", charging); + nbt.setInteger("ChargeTick", chargeTick); + nbt.setInteger("ChargeDuration", chargeDuration); + barrierData.writeNBT(nbt); + } + + /** + * Read shared barrier base fields from NBT. + * Call from subclass readEntityFromNBT() before reading type-specific fields. + */ + protected void readBarrierBaseNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + this.ticksAlive = nbt.getInteger("TicksAlive"); + this.barrierDeathTime = nbt.hasKey("BarrierDeathTime") ? nbt.getLong("BarrierDeathTime") : -1; + this.currentHealth = nbt.getFloat("CurrentHealth"); + if (Float.isNaN(currentHealth) || Float.isInfinite(currentHealth) || currentHealth < 0) currentHealth = barrierData.maxHealth; + this.charging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); + this.chargeTick = nbt.getInteger("ChargeTick"); + this.chargeDuration = nbt.getInteger("ChargeDuration"); + this.dataWatcher.updateObject(DW_CHARGING, (byte) (charging ? 1 : 0)); + barrierData.readNBT(nbt); + } + + // ==================== DEBUG LOGGING ==================== + + /** + * Debug log called every tick for barriers. Subclasses override debugLogBarrierExtra(). + */ + protected void debugLogBarrierTick() { + boolean isClient = worldObj.isRemote; + if (isClient ? !CNPCDebug.isClientEnabled("energy") : !CNPCDebug.isServerEnabled("energy")) + return; + + String className = getClass().getSimpleName(); + String base = String.format("[%s id=%d tick=%d] pos=(%.2f,%.2f,%.2f) charging=%b health=%.1f", + className, getEntityId(), ticksAlive, + posX, posY, posZ, isCharging(), currentHealth); + + String extra = debugLogBarrierExtra(); + String full = extra.isEmpty() ? base : base + " " + extra; + CNPCDebug.log("energy", isClient, full); + } + + /** + * Subclass hook for barrier-specific debug data. + */ + protected String debugLogBarrierExtra() { + return ""; + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java new file mode 100644 index 000000000..697fa4c16 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -0,0 +1,726 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +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.CustomNpcs; + +import java.util.HashSet; +import java.util.List; + +/** + * Energy Dome entity - a spherical barrier that blocks incoming energy projectiles. + * Centered on the caster's position at time of casting. + * Only blocks incoming attacks (not outgoing from allies inside). + * Extends EntityEnergyBarrier for shared barrier logic. + */ +public class EntityEnergyDome extends EntityEnergyBarrier { + + // ==================== DOME-SPECIFIC PROPERTIES ==================== + protected float domeRadius = 5.0f; + protected float targetDomeRadius = 5.0f; + protected boolean followCaster = false; + protected float offsetX = 0.0f; + protected float offsetY = 0.0f; + protected float offsetZ = 0.0f; + + // Server-side melee detection state + private boolean inTickMelee = false; + private final HashSet processedMeleeSwings = new HashSet<>(); + + public EntityEnergyDome(World world) { + super(world); + this.noClip = true; + this.stepHeight = 0.0F; + this.setSize(1.0f, 1.0f); + } + + public EntityEnergyDome(World world, EntityLivingBase owner, double x, double y, double z, + float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier) { + this(world); + this.noClip = true; + this.stepHeight = 0.0F; + this.ownerEntityId = owner != null ? owner.getEntityId() : -1; + this.setDomeRadius(domeRadius); + // Defensive copy: entities must never share data objects with the source ability. + this.displayData = display != null ? display.copy() : new EnergyDisplayData(); + this.lightningData = lightning != null ? lightning.copy() : new EnergyLightningData(); + this.barrierData = barrier != null ? barrier.copy() : new EnergyBarrierData(); + this.currentHealth = this.barrierData.maxHealth; + this.setPosition(x, y, z); + } + + // ==================== POSITION / BOUNDING BOX ==================== + + @Override + protected void setSize(float width, float height) { + super.setSize(width, height); + } + + @Override + public void applyEntityCollision(Entity entityIn) { + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + super.onUpdate(); + + // Follow caster: both sides for smooth interpolated rendering + if (followCaster) { + Entity owner = ownerEntityId >= 0 ? worldObj.getEntityByID(ownerEntityId) : null; + if (owner != null) { + this.setPosition(owner.posX + offsetX, owner.posY + offsetY, owner.posZ + offsetZ); + // Sync prevPos with owner's prevPos for smooth interpolation + this.prevPosX = owner.prevPosX + offsetX; + this.prevPosY = owner.prevPosY + offsetY; + this.prevPosZ = owner.prevPosZ + offsetZ; + } + } + + // Handle charging animation (both sides for smooth rendering) + if (isCharging()) { + chargeTick++; + float progress = getChargeProgress(); + this.setDomeRadius(targetDomeRadius * progress); + // Refresh BB for current charge radius + this.setPosition(posX, posY, posZ); + return; // Don't tick duration/death during charging + } + + ticksAlive++; + + if (updateBarrierTick()) return; + + // Server-side: detect and apply melee hits from nearby players. + // Bypasses MC's processUseEntity reach check (which uses center-to-center + // distance and fails for domes with radius > 5). + if (!worldObj.isRemote && barrierData.meleeEnabled) { + processMeleeHits(); + } + + // Process entity physics every tick + // Server: solid + knockback for all entities + // Client: solid prediction for local player only (smooth movement blocking) + if (barrierData.solid || barrierData.knockbackEnabled) { + processEntityPhysics(); + } + + // Client-side: adjust BB for accurate melee targeting at all approach angles. + // Must run AFTER all position/BB updates and BEFORE getMouseOver() in the render phase. + if (worldObj.isRemote && barrierData.meleeEnabled && !isCharging()) { + adjustMeleeBoundingBox(); + } + + debugLogBarrierTick(); + } + + // ==================== INCOMING CHECK ==================== + + /** + * Swept ray-sphere intersection test. + * Tests if the line segment from prevPos to currPos crosses the dome sphere boundary + * from outside. Handles fast projectiles that skip through in a single tick. + * + * @return true if the segment enters the sphere from outside + */ + private boolean isIncomingRay( + double currX, double currY, double currZ, + double prevX, double prevY, double prevZ, + int projOwnerEntityId) + { + if (isCharging()) return false; + if (projOwnerEntityId == this.ownerEntityId) return false; + + // Ray: P(t) = prev + t * (curr - prev), t in [0, 1] + double rayDirX = currX - prevX; + double rayDirY = currY - prevY; + double rayDirZ = currZ - prevZ; + + // Vector from dome center to ray origin (prevPos) + double ocX = prevX - this.posX; + double ocY = prevY - this.posY; + double ocZ = prevZ - this.posZ; + + double r = domeRadius; + + // Quadratic: a*t^2 + b*t + c = 0 + double a = rayDirX * rayDirX + rayDirY * rayDirY + rayDirZ * rayDirZ; + double b = 2.0 * (ocX * rayDirX + ocY * rayDirY + ocZ * rayDirZ); + double c = (ocX * ocX + ocY * ocY + ocZ * ocZ) - r * r; + + // c > 0: prevPos is outside sphere; c <= 0: inside (don't block) + if (c <= 0) return false; + + if (a < 1e-10) return false; // No movement + + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0) return false; // Ray misses sphere entirely + + double sqrtDisc = Math.sqrt(discriminant); + double t1 = (-b - sqrtDisc) / (2.0 * a); // Entry point (first intersection) + + // Entry must be within this tick's movement segment [0, 1] + return t1 >= 0.0 && t1 <= 1.0; + } + + @Override + public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { + // Faction check: don't block same-faction NPC projectiles + Entity owner = getOwnerEntity(); + Entity projOwner = projectile.getOwnerEntity(); + if (owner instanceof noppes.npcs.entity.EntityNPCInterface && projOwner instanceof noppes.npcs.entity.EntityNPCInterface) { + if (((noppes.npcs.entity.EntityNPCInterface) owner).faction.id == ((noppes.npcs.entity.EntityNPCInterface) projOwner).faction.id) { + return false; + } + } + + // Test the UPCOMING movement (this tick) so the barrier intercepts before + // entity collision runs in updateProjectile(). Using the previous tick's + // segment caused small domes to miss fast projectiles that could cross the + // dome and hit the player in a single tick. + double nextX = projectile.posX + projectile.motionX; + double nextY = projectile.posY + projectile.motionY; + double nextZ = projectile.posZ + projectile.motionZ; + + return isIncomingRay( + nextX, nextY, nextZ, + projectile.posX, projectile.posY, projectile.posZ, + projectile.getOwnerEntityId()); + } + + @Override + public boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId) + { + return isIncomingRay(posX, posY, posZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } + + @Override + public double[] getSurfaceNormal(double hitX, double hitY, double hitZ, + double velX, double velY, double velZ) { + double nx = hitX - this.posX; + double ny = hitY - this.posY; + double nz = hitZ - this.posZ; + double lenSq = nx * nx + ny * ny + nz * nz; + if (lenSq > 1.0e-8) { + double invLen = 1.0 / Math.sqrt(lenSq); + return new double[]{nx * invLen, ny * invLen, nz * invLen}; + } + // Fallback: use negative velocity direction + double vLenSq = velX * velX + velY * velY + velZ * velZ; + if (vLenSq > 1.0e-8) { + double invVLen = 1.0 / Math.sqrt(vLenSq); + return new double[]{-velX * invVLen, -velY * invVLen, -velZ * invVLen}; + } + return new double[]{0.0, 1.0, 0.0}; + } + + @Override + public double[] getOutsideSurfacePoint(double px, double py, double pz, + double velX, double velY, double velZ, + float bias) { + double nx = px - this.posX; + double ny = py - this.posY; + double nz = pz - this.posZ; + double len = Math.sqrt(nx * nx + ny * ny + nz * nz); + + if (len < 1.0e-5) { + double vLen = Math.sqrt(velX * velX + velY * velY + velZ * velZ); + if (vLen > 1.0e-5) { + nx = -velX / vLen; + ny = -velY / vLen; + nz = -velZ / vLen; + } else { + nx = 0.0; ny = 1.0; nz = 0.0; + } + len = 1.0; + } + + double invLen = 1.0 / len; + double target = domeRadius + bias; + return new double[]{ + this.posX + nx * invLen * target, + this.posY + ny * invLen * target, + this.posZ + nz * invLen * target + }; + } + + @Override + public float getMaxExtent() { + return domeRadius; + } + + // ==================== CHARGING ==================== + + @Override + public void setupCharging(int duration) { + this.targetDomeRadius = this.domeRadius; + this.setDomeRadius(0.01f); + this.chargeDuration = duration; + this.chargeTick = 0; + setCharging(true); + } + + @Override + public void finishCharging() { + this.setDomeRadius(this.targetDomeRadius); + setCharging(false); + } + + // ==================== ENTITY PHYSICS (Solid + Knockback) ==================== + + /** + * Processes entity physics for the dome barrier. Two independent systems: + *

+ * SOLID: Hard wall — entities cannot cross the dome boundary in either direction. + * Uses reactive crossing detection: compares current position to previous tick + * to detect boundary crossings, then teleports back and applies velocity correction. + * Also preemptively cancels inward velocity when near the surface. + *

+ * KNOCKBACK: Repulsion force — entities near the dome surface get pushed away. + * This is a push effect only; entities can still pass through with enough effort. + * Does NOT prevent passthrough — use solid for that. + *

+ * For moving domes (followCaster), dome velocity is accounted for by using + * the dome's previous position for previous-tick distance calculations. + */ + @Override + @SuppressWarnings("unchecked") + protected void processEntityPhysics() { + float r = domeRadius; + boolean solid = barrierData.solid; + boolean knockback = barrierData.knockbackEnabled; + float strength = barrierData.knockbackStrength; + + float solidMargin = 1.5f; // Zone around surface for preemptive velocity correction + float knockbackMargin = 2.0f; // Zone around surface for knockback push + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - r - knockbackMargin, posY - r - knockbackMargin, posZ - r - knockbackMargin, + posX + r + knockbackMargin, posY + r + knockbackMargin, posZ + r + knockbackMargin + ); + + EntityPlayer localPlayer = getClientPredictionPlayer(); + + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + for (EntityLivingBase ent : entities) { + if (shouldSkipBarrierPhysicsTarget(ent, localPlayer)) continue; + + // Current position relative to dome center + double dx = ent.posX - posX; + double dy = (ent.posY + ent.height * 0.5) - posY; + double dz = ent.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (dist < 0.01) continue; + + // Normalized direction from dome center toward entity (outward) + double nx = dx / dist; + double ny = dy / dist; + double nz = dz / dist; + + boolean isInside = dist < r; + + // --- SOLID: hard wall preventing boundary crossing --- + if (solid) { + // Previous tick: entity position relative to dome's previous position + double prevDx = ent.prevPosX - prevPosX; + double prevDy = (ent.prevPosY + ent.height * 0.5) - prevPosY; + double prevDz = ent.prevPosZ - prevPosZ; + double prevDist = Math.sqrt(prevDx * prevDx + prevDy * prevDy + prevDz * prevDz); + boolean wasInside = prevDist < r; + + // Radial velocity (positive = moving outward from dome center) + double radialVel = ent.motionX * nx + ent.motionY * ny + ent.motionZ * nz; + + if (wasInside != isInside) { + // Entity crossed the boundary this tick — push back to original side. + // Use a larger buffer (1.0) to prevent flying entities from crossing + // again in a single tick (their AI hard-sets motionY every tick). + double pushDist = wasInside ? (r - 1.0) : (r + 0.3); + double surfaceX = posX + nx * pushDist; + double surfaceY = posY + ny * pushDist - ent.height * 0.5; + double surfaceZ = posZ + nz * pushDist; + + // Prevent grounded entities from being teleported below the floor. + // The spherical surface calculation can produce a Y below ground level + // near the dome's equator, and setPosition bypasses collision detection. + if (ent.onGround && surfaceY < ent.posY) { + surfaceY = ent.posY; + } + + teleportEntity(ent, surfaceX, surfaceY, surfaceZ); + + // Cancel radial velocity and add corrective push (all 3 axes). + // The Y component is critical for the dome top where nx/nz ≈ 0: + // without it, flying entities get no inward push at the apex. + ent.motionX -= radialVel * nx; + ent.motionY -= radialVel * ny; + ent.motionZ -= radialVel * nz; + double pushForce = wasInside ? -0.15 : 0.15; + if (canPushInDirection(ent, nx * pushForce, ny * pushForce, nz * pushForce)) { + ent.motionX += nx * pushForce; + ent.motionY += ny * pushForce; + ent.motionZ += nz * pushForce; + } + ent.velocityChanged = true; + } else { + // Preemptive: near surface and moving toward it — cancel radial velocity + double surfaceDist = Math.abs(dist - r); + if (surfaceDist < solidMargin) { + boolean movingTowardSurface = (!isInside && radialVel < -0.01) + || (isInside && radialVel > 0.01); + if (movingTowardSurface) { + ent.motionX -= radialVel * nx; + ent.motionY -= radialVel * ny; + ent.motionZ -= radialVel * nz; + double pushForce = isInside ? -0.05 : 0.05; + if (canPushInDirection(ent, nx * pushForce, ny * pushForce, nz * pushForce)) { + ent.motionX += nx * pushForce; + ent.motionY += ny * pushForce; + ent.motionZ += nz * pushForce; + } + ent.velocityChanged = true; + } + } + } + } + + // --- KNOCKBACK: repulsion push (server only, synced via velocityChanged) --- + if (!worldObj.isRemote && knockback) { + double surfaceDist = Math.abs(dist - r); + if (surfaceDist < knockbackMargin) { + double proximity = 1.0 - (surfaceDist / knockbackMargin); + double force = proximity * strength * 0.06; + + double pushX, pushY, pushZ; + if (isInside) { + pushX = -nx * force; + pushY = -ny * force * 0.5; + pushZ = -nz * force; + } else { + pushX = nx * force; + pushY = ny * force * 0.5; + pushZ = nz * force; + } + + if (canPushInDirection(ent, pushX, pushY, pushZ)) { + ent.motionX += pushX; + ent.motionY += pushY; + ent.motionZ += pushZ; + } + ent.velocityChanged = true; + } + } + } + } + + // ==================== CONTAINMENT CHECK ==================== + + @Override + public boolean isEntityInside(Entity entity) { + if (entity == null) return false; + double dx = entity.posX - posX; + double dy = (entity.posY + entity.height * 0.5) - posY; + double dz = entity.posZ - posZ; + return dx * dx + dy * dy + dz * dz < domeRadius * domeRadius; + } + + // ==================== MELEE (spherical check) ==================== + + /** + * Controls whether MC's entity picking (crosshair raycast) can target this dome. + * Returns false when melee is disabled or the dome is still charging. + *

+ * Inside players CAN target the dome because adjustMeleeBoundingBox places a small BB + * at the nearest surface point, allowing mobs in other directions to still be targeted. + */ + @Override + public boolean canBeCollidedWith() { + if (!barrierData.meleeEnabled) return false; + if (isCharging()) return false; + return true; + } + + /** + * Client-side: Repositions the bounding box to a small cube at the nearest sphere surface + * point toward the player. This fixes melee targeting at diagonal approach angles where the + * player would otherwise be inside the dome-sized cubic BB but outside the actual sphere, + * causing MC's AABB raycast to return the far exit point (beyond reach distance). + *

+ * With a small BB (2x2x2) at the surface point, even if the player is inside it at close + * range, the exit point is at most ~1.7 blocks away — well within melee reach. + */ + private void adjustMeleeBoundingBox() { + EntityPlayer player = CustomNpcs.proxy.getPlayer(); + if (player == null) { + updateBoundingBox(); + return; + } + + double dx = player.posX - posX; + double dy = (player.posY + player.getEyeHeight()) - posY; + double dz = player.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + // Only adjust when player is within reasonable melee range of dome surface + if (dist < 0.01 || dist > domeRadius + 6.0) { + updateBoundingBox(); + return; + } + + // Nearest point on sphere surface toward player + double nx = dx / dist; + double ny = dy / dist; + double nz = dz / dist; + double surfX = posX + nx * domeRadius; + double surfY = posY + ny * domeRadius; + double surfZ = posZ + nz * domeRadius; + + float s = 1.0f; + this.boundingBox.setBounds( + surfX - s, surfY - s, surfZ - s, + surfX + s, surfY + s, surfZ + s + ); + } + + /** + * Player melee is handled by processMeleeHits (server-side tick detection) to bypass + * MC's processUseEntity reach check which uses center-to-center distance. + * Direct player melee ("player" damage type) is rejected unless inTickMelee is set, + * preventing double-hits when both the C02 path and tick detection fire. + * Non-player melee (mobs) and all other damage sources pass through with sphere validation. + */ + @Override + public boolean attackEntityFrom(DamageSource source, float amount) { + // Player melee: only allow from tick-based detection + if (!inTickMelee && "player".equals(source.damageType)) { + return false; + } + if (source.getEntity() != null) { + Entity attacker = source.getEntity(); + double dx = attacker.posX - this.posX; + double dy = (attacker.posY + attacker.height * 0.5) - this.posY; + double dz = attacker.posZ - this.posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + double surfaceDist = Math.abs(dist - domeRadius); + if (surfaceDist > 5.0) return false; + } + return super.attackEntityFrom(source, amount); + } + + /** + * Server-side melee detection. Each tick, finds players near the dome surface who are + * swinging and looking at the dome, then applies the attack via attackTargetEntityWithCurrentItem + * (preserving enchantments, crits, fire aspect, etc.). This bypasses MC's processUseEntity + * reach check which uses center-to-center distance and fails for large domes. + */ + @SuppressWarnings("unchecked") + private void processMeleeHits() { + float r = domeRadius; + float maxReach = 6.0f; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - r - maxReach, posY - r - maxReach, posZ - r - maxReach, + posX + r + maxReach, posY + r + maxReach, posZ + r + maxReach + ); + + List players = worldObj.getEntitiesWithinAABB(EntityPlayer.class, searchBox); + for (EntityPlayer player : players) { + if (player.getEntityId() == ownerEntityId) continue; + if (isAllyOfOwner(player)) continue; + + int playerId = player.getEntityId(); + + if (!player.isSwingInProgress) { + processedMeleeSwings.remove(playerId); + continue; + } + + if (processedMeleeSwings.contains(playerId)) continue; + + // Check surface distance + double dx = player.posX - posX; + double dy = (player.posY + 1.62) - posY; + double dz = player.posZ - posZ; + double distSq = dx * dx + dy * dy + dz * dz; + double dist = Math.sqrt(distSq); + double surfaceDist = Math.abs(dist - r); + if (surfaceDist > maxReach) continue; + + // Ray-sphere intersection: check if look direction hits the dome + Vec3 look = player.getLook(1.0f); + double b = 2.0 * (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord); + double c = distSq - (double)(r * r); + double discriminant = b * b - 4.0 * c; + if (discriminant < 0) continue; + + double sqrtDisc = Math.sqrt(discriminant); + double t1 = (-b - sqrtDisc) / 2.0; + double t2 = (-b + sqrtDisc) / 2.0; + + // Outside: t1 is entry distance. Inside: t1 < 0, t2 is exit distance. + double hitDist = t1 >= 0 ? t1 : t2; + if (hitDist < 0 || hitDist > maxReach) continue; + + // Apply the attack with full MC damage calculation + processedMeleeSwings.add(playerId); + inTickMelee = true; + player.attackTargetEntityWithCurrentItem(this); + inTickMelee = false; + } + } + + // ==================== BOUNDING BOX ==================== + + /** + * No expansion needed — the bounding box is already dome-sized. + * Returning 0 ensures players outside the dome sphere are also outside the + * ray-testing BB, so MC's raycast returns the near-face hit (within reach) + * rather than the far exit point (beyond reach). + */ + @Override + public float getCollisionBorderSize() { + return 0.0f; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + double d = domeRadius * 8.0D; + d *= 64.0D; + return distance < d * d; + } + + // ==================== DISTANCE (for render sorting) ==================== + + /** + * Returns squared distance from the given point to the nearest point on the dome sphere surface. + * Uses absolute distance to surface: |centerDist - radius|. + *

+ * Inside: nearest surface is (radius - centerDist) away. + * Outside: nearest surface is (centerDist - radius) away. + * This ensures entities inside the dome sort correctly relative to the dome shell. + */ + @Override + public double getDistanceSq(double x, double y, double z) { + double dx = this.posX - x; + double dy = this.posY - y; + double dz = this.posZ - z; + double centerDist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + double surfaceDist = Math.abs(centerDist - domeRadius); + return surfaceDist * surfaceDist; + } + + // ==================== DEBUG ==================== + + @Override + protected String debugLogBarrierExtra() { + return String.format("radius=%.2f targetRadius=%.2f follow=%b", + domeRadius, targetDomeRadius, followCaster); + } + + // ==================== GETTERS ==================== + + public float getDomeRadius() { + return domeRadius; + } + + public void setDomeRadius(float radius) { + this.domeRadius = Math.max(0.1f, radius); + this.setPosition(this.posX, this.posY, this.posZ); + } + + public boolean isFollowCaster() { + return followCaster; + } + + public void setFollowCaster(boolean follow) { + this.followCaster = follow; + } + + public void setOffsets(float x, float y, float z) { + this.offsetX = x; + this.offsetY = y; + this.offsetZ = z; + } + + @Override + @SideOnly(Side.CLIENT) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int increments) { + // Don't do the vanilla "push up out of blocks" logic. + this.setPosition(x, y, z); + this.setRotation(yaw, pitch); + } + + @Override + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + updateBoundingBox(); + } + + protected void updateBoundingBox() { + float r = this.domeRadius; + this.boundingBox.setBounds( + this.posX - r, this.posY - r, this.posZ - r, + this.posX + r, this.posY + r, this.posZ + r + ); + } + + // ==================== CLIENT SYNC ==================== + + @Override + protected void writeBarrierClientSyncData(NBTTagCompound nbt) { + nbt.setFloat("DomeRadius", domeRadius); + } + + @Override + protected void applyBarrierClientSyncData(NBTTagCompound nbt) { + setDomeRadius(nbt.getFloat("DomeRadius")); + } + + // ==================== NBT ==================== + + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBarrierBaseNBT(nbt); + nbt.setFloat("DomeRadius", domeRadius); + nbt.setFloat("TargetDomeRadius", targetDomeRadius); + nbt.setBoolean("FollowCaster", followCaster); + nbt.setFloat("OffsetX", offsetX); + nbt.setFloat("OffsetY", offsetY); + nbt.setFloat("OffsetZ", offsetZ); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBarrierBaseNBT(nbt); + this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS)); + this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); + this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); + this.offsetX = nbt.hasKey("OffsetX") ? nbt.getFloat("OffsetX") : 0.0f; + this.offsetY = nbt.hasKey("OffsetY") ? nbt.getFloat("OffsetY") : 0.0f; + this.offsetZ = nbt.hasKey("OffsetZ") ? nbt.getFloat("OffsetZ") : 0.0f; + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyExplosion.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyExplosion.java new file mode 100644 index 000000000..8c69b6aa0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyExplosion.java @@ -0,0 +1,337 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.EnergyController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +import kamkeel.npcs.util.AttributeAttackUtil; +import kamkeel.npcs.util.CNPCDebug; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import noppes.npcs.NpcDamageSource; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +/** + * Short-lived explosion entity for energy projectile impacts and standalone API use. + * Renders an expanding voxel shell. When damage is enabled, applies area damage on the first tick. + */ +public class EntityEnergyExplosion extends EntityEnergyAbility { + + private float maxRadius = 2.0f; + private int durationTicks = 10; + private float prevRenderRadius = 0.0f; + private float renderRadius = 0.0f; + private long renderSeed = 0L; + + // ==================== DAMAGE (for standalone API use) ==================== + private float damage = 0f; + private float knockback = 0f; + private float knockbackUp = 0.1f; + private float damageFalloff = 0.5f; + private boolean damageEnabled = false; + private boolean hasDamaged = false; + + public EntityEnergyExplosion(World world) { + super(world); + this.noClip = true; + this.setSize(0.1f, 0.1f); + } + + /** + * Constructor for projectile-spawned explosions (render-only, no damage). + */ + public EntityEnergyExplosion(World world, EntityEnergyProjectile source, float radius) { + this(world); + + if (source != null) { + this.ownerEntityId = source.getOwnerEntityId(); + EnergyDisplayData sourceDisplay = source.getDisplayData(); + this.displayData = sourceDisplay != null ? sourceDisplay.copy() : new EnergyDisplayData(); + EnergyLightningData sourceLightning = source.getLightningData(); + this.lightningData = sourceLightning != null ? sourceLightning.copy() : new EnergyLightningData(); + this.setPosition(source.posX, source.posY, source.posZ); + } + + setExplosionRadius(radius); + this.renderSeed = world != null ? world.rand.nextLong() : 0L; + } + + /** + * Constructor for standalone API-spawned explosions. + */ + public EntityEnergyExplosion(World world, Entity owner, double x, double y, double z, float radius) { + this(world); + if (owner != null) { + this.ownerEntityId = owner.getEntityId(); + } + this.setPosition(x, y, z); + setExplosionRadius(radius); + this.renderSeed = world != null ? world.rand.nextLong() : 0L; + } + + @Override + protected void entityInit() { + super.entityInit(); + } + + @Override + public void onUpdate() { + this.prevRenderRadius = this.renderRadius; + + super.onUpdate(); + + float progress = getLifeProgress(0.0f); + float eased = 1.0f - (1.0f - progress) * (1.0f - progress); + this.renderRadius = maxRadius * eased; + + // Apply damage on first server tick + if (damageEnabled && !hasDamaged && !worldObj.isRemote && ticksExisted >= 1) { + applyExplosionDamage(); + hasDamaged = true; + } + + // Debug logging + { + boolean isClient = worldObj.isRemote; + if (isClient ? CNPCDebug.isClientEnabled("energy") : CNPCDebug.isServerEnabled("energy")) { + CNPCDebug.log("energy", isClient, String.format( + "[Explosion id=%d tick=%d] pos=(%.2f,%.2f,%.2f) renderRadius=%.2f maxRadius=%.2f progress=%.2f", + getEntityId(), ticksExisted, posX, posY, posZ, + renderRadius, maxRadius, getLifeProgress(0f))); + } + } + + if (ticksExisted >= durationTicks) { + setDead(); + } + } + + // ==================== DAMAGE LOGIC ==================== + + private void applyExplosionDamage() { + if (damage <= 0 || maxRadius <= 0) return; + + Entity owner = getOwnerEntity(); + double explosionRadSq = maxRadius * maxRadius; + + AxisAlignedBB explosionBox = AxisAlignedBB.getBoundingBox( + posX - maxRadius, posY - maxRadius, posZ - maxRadius, + posX + maxRadius, posY + maxRadius, posZ + maxRadius + ); + + @SuppressWarnings("unchecked") + List targets = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, explosionBox); + + for (EntityLivingBase target : targets) { + if (target == owner) continue; + if (target.boundingBox == null) continue; + + double closestX = Math.max(target.boundingBox.minX, Math.min(posX, target.boundingBox.maxX)); + double closestY = Math.max(target.boundingBox.minY, Math.min(posY, target.boundingBox.maxY)); + double closestZ = Math.max(target.boundingBox.minZ, Math.min(posZ, target.boundingBox.maxZ)); + double dx = closestX - posX; + double dy = closestY - posY; + double dz = closestZ - posZ; + double distSq = dx * dx + dy * dy + dz * dz; + if (distSq > explosionRadSq) continue; + + float falloff = 1.0f; + if (damageFalloff != 0.0f && distSq > 0.0D) { + float dist = (float) Math.sqrt(distSq); + falloff = 1.0f - (dist / maxRadius) * damageFalloff; + } + + float finalDmg = damage * falloff; + float finalKb = knockback * falloff; + + // Route through EnergyController for addon integration (e.g. DBC) + boolean handled = false; + if (customDamageData != null && owner instanceof EntityLivingBase) { + double kbDirX = target.posX - posX; + double kbDirZ = target.posZ - posZ; + handled = EnergyController.Instance.fireOnEnergyDamage( + this, (EntityLivingBase) owner, target, + finalDmg, finalKb, knockbackUp, kbDirX, kbDirZ, 1.0f, customDamageData); + } + + int prevHurtResist = Ability.clearHurtResistanceIfNeeded(target, ignoreIFrames); + try { + if (!handled) { + float dmgToApply = finalDmg; + + // Magic pipeline + if (this.magicData != null && !this.magicData.isEmpty() && owner instanceof EntityLivingBase) { + dmgToApply = AttributeAttackUtil.calculateAbilityDamage( + (EntityLivingBase) owner, target, finalDmg, this.magicData); + } + + if (owner instanceof EntityNPCInterface) { + target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmgToApply); + } else if (owner instanceof EntityPlayer) { + target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmgToApply); + } else if (owner instanceof EntityLivingBase) { + target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmgToApply); + } else { + target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmgToApply); + } + } + } finally { + Ability.restoreHurtResistanceIfNeeded(target, ignoreIFrames, prevHurtResist); + } + + // Apply knockback + if (finalKb > 0) { + double kbDx = target.posX - posX; + double kbDz = target.posZ - posZ; + double len = Math.sqrt(kbDx * kbDx + kbDz * kbDz); + if (len > 0) { + target.addVelocity((kbDx / len) * finalKb * 0.5, knockbackUp, (kbDz / len) * finalKb * 0.5); + target.velocityChanged = true; + } + } + } + + worldObj.playSoundEffect(posX, posY, posZ, "random.explode", 1.0f, 1.0f); + } + + // ==================== RADIUS / DURATION ==================== + + public void setExplosionRadius(float radius) { + this.maxRadius = Math.max(0.5f, sanitize(radius, 2.0f, MAX_ENTITY_RADIUS)); + this.durationTicks = Math.max(6, Math.min(18, (int) (6 + this.maxRadius * 1.8f))); + this.setSize(this.maxRadius * 2.0f, this.maxRadius * 2.0f); + } + + public float getExplosionRadius() { + return maxRadius; + } + + public int getDurationTicks() { + return durationTicks; + } + + public float getInterpolatedRadius(float partialTicks) { + return this.prevRenderRadius + (this.renderRadius - this.prevRenderRadius) * partialTicks; + } + + public float getLifeProgress(float partialTicks) { + if (durationTicks <= 0) return 1.0f; + float age = (ticksExisted + partialTicks) / durationTicks; + return MathHelper.clamp_float(age, 0.0f, 1.0f); + } + + public long getRenderSeed() { + return renderSeed; + } + + // ==================== DAMAGE GETTERS/SETTERS ==================== + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = Math.max(0, damage); + this.damageEnabled = this.damage > 0; + } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = Math.max(0, knockback); + } + + public float getKnockbackUp() { + return knockbackUp; + } + + public void setKnockbackUp(float knockbackUp) { + this.knockbackUp = knockbackUp; + } + + public float getDamageFalloff() { + return damageFalloff; + } + + public void setDamageFalloff(float falloff) { + this.damageFalloff = MathHelper.clamp_float(falloff, 0.0f, 1.0f); + } + + public boolean isDamageEnabled() { + return damageEnabled; + } + + // ==================== RENDER / COLLISION ==================== + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + double d = Math.max(16.0D, maxRadius * 64.0D); + return distance < d * d; + } + + @Override + public boolean canBeCollidedWith() { + return false; + } + + // ==================== NBT ==================== + + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + nbt.setDouble("PosX", this.posX); + nbt.setDouble("PosY", this.posY); + nbt.setDouble("PosZ", this.posZ); + nbt.setFloat("ExplosionRadius", maxRadius); + nbt.setInteger("ExplosionDuration", durationTicks); + nbt.setLong("ExplosionSeed", renderSeed); + if (damageEnabled) { + nbt.setFloat("Damage", damage); + nbt.setFloat("Knockback", knockback); + nbt.setFloat("KnockbackUp", knockbackUp); + nbt.setFloat("DamageFalloff", damageFalloff); + } + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + double x = nbt.hasKey("PosX") ? nbt.getDouble("PosX") : this.posX; + double y = nbt.hasKey("PosY") ? nbt.getDouble("PosY") : this.posY; + double z = nbt.hasKey("PosZ") ? nbt.getDouble("PosZ") : this.posZ; + this.setPosition(x, y, z); + this.prevPosX = x; + this.prevPosY = y; + this.prevPosZ = z; + this.lastTickPosX = x; + this.lastTickPosY = y; + this.lastTickPosZ = z; + setExplosionRadius(nbt.hasKey("ExplosionRadius") ? nbt.getFloat("ExplosionRadius") : 2.0f); + this.durationTicks = nbt.hasKey("ExplosionDuration") ? nbt.getInteger("ExplosionDuration") : durationTicks; + if (durationTicks <= 0) durationTicks = 10; + this.renderSeed = nbt.hasKey("ExplosionSeed") ? nbt.getLong("ExplosionSeed") : 0L; + this.renderRadius = 0.0f; + this.prevRenderRadius = 0.0f; + if (nbt.hasKey("Damage")) { + this.damage = nbt.getFloat("Damage"); + this.knockback = nbt.getFloat("Knockback"); + this.knockbackUp = nbt.getFloat("KnockbackUp"); + this.damageFalloff = nbt.getFloat("DamageFalloff"); + this.damageEnabled = this.damage > 0; + } + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java new file mode 100644 index 000000000..96949bbd4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -0,0 +1,757 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.EnergyController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +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.List; + +/** + * Energy Panel entity - a flat rectangular barrier used by Wall and Shield abilities. + * Supports three modes: PLACED (stationary), HELD (tracks caster), LAUNCHED (moves forward). + * Extends EntityEnergyBarrier for shared barrier logic. + */ +public class EntityEnergyPanel extends EntityEnergyBarrier { + + public enum PanelMode { + PLACED, // Stationary wall + HELD, // Follows caster, rotates with caster look + LAUNCHED // Moves forward, deals damage/knockback on contact + } + + // ==================== PANEL-SPECIFIC PROPERTIES ==================== + protected EnergyPanelData panelData = new EnergyPanelData(); + protected PanelMode mode = PanelMode.PLACED; + protected float panelYaw = 0.0f; // Rotation of the panel face (degrees) + protected float prevPanelYaw = 0.0f; // Previous tick yaw for smooth interpolation + + // ==================== CHARGING (panel-specific targets) ==================== + protected float targetPanelWidth; + protected float targetPanelHeight; + + public EntityEnergyPanel(World world) { + super(world); + this.setSize(0.5f, 0.5f); + } + + public EntityEnergyPanel(World world, EntityLivingBase owner, double x, double y, double z, + float yaw, PanelMode mode, + EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier, EnergyPanelData panel) { + this(world); + this.setPosition(x, y + panel.heightOffset, z); + this.ownerEntityId = owner != null ? owner.getEntityId() : -1; + this.panelYaw = yaw; + this.prevPanelYaw = yaw; + this.mode = mode; + // Defensive copy: entities must never share data objects with the source ability. + this.displayData = display != null ? display.copy() : new EnergyDisplayData(); + this.lightningData = lightning != null ? lightning.copy() : new EnergyLightningData(); + this.barrierData = barrier != null ? barrier.copy() : new EnergyBarrierData(); + this.panelData = panel != null ? panel.copy() : new EnergyPanelData(); + this.currentHealth = this.barrierData.maxHealth; + + // For launched panels, set initial velocity + if (mode == PanelMode.LAUNCHED) { + float yawRad = (float) Math.toRadians(yaw); + this.motionX = -Math.sin(yawRad) * panel.launchSpeed; + this.motionY = 0; + this.motionZ = Math.cos(yawRad) * panel.launchSpeed; + } + } + + // ==================== POSITION / BOUNDING BOX ==================== + + /** + * Override setPosition to maintain panel-sized bounding box. + * MC's default setPosition() resets BB based on width/height fields. + * Network sync calls setPosition(), which would shrink the BB. + * This ensures melee targeting always works against the full panel surface. + */ + @Override + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + if (panelData != null) { + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float extent = Math.max(halfW, 0.5f); + this.boundingBox.setBounds(x - extent, y - halfH, z - extent, x + extent, y + halfH, z + extent); + } else { + float f = this.width / 2.0F; + this.boundingBox.setBounds(x - f, y, z - f, x + f, y + this.height, z + f); + } + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.prevPanelYaw = this.panelYaw; + + super.onUpdate(); + + // Handle charging animation (both sides for smooth rendering) + if (isCharging()) { + chargeTick++; + float progress = getChargeProgress(); + panelData.panelWidth = targetPanelWidth * progress; + panelData.panelHeight = targetPanelHeight * progress; + + // During charging, held panels still track owner + if (mode == PanelMode.HELD) { + updateHeld(); + } + return; // Don't tick duration/death during charging + } + + ticksAlive++; + + if (updateBarrierTick()) return; + + // Process entity physics every tick (not during launched mode) + // Server: solid + knockback for all entities + // Client: solid prediction for local player only (smooth movement blocking) + if ((barrierData.solid || barrierData.knockbackEnabled) && mode != PanelMode.LAUNCHED) { + processEntityPhysics(); + } + + // Mode-specific updates + switch (mode) { + case HELD: + updateHeld(); + break; + case LAUNCHED: + updateLaunched(); + break; + case PLACED: + default: + // Stationary, no update needed + break; + } + + debugLogBarrierTick(); + } + + private void updateHeld() { + Entity owner = getOwnerEntity(); + if (owner == null) return; + + // Update yaw BEFORE position calc to avoid 1-tick lag + this.panelYaw = owner.rotationYaw; + + // Follow owner position + float frontDist = 1.5f; + float yawRad = (float) Math.toRadians(panelYaw); + double newX = owner.posX + (-Math.sin(yawRad) * frontDist) + panelData.offsetX; + double newY = owner.posY + panelData.heightOffset + (owner.height * 0.5f); + double newZ = owner.posZ + (Math.cos(yawRad) * frontDist) + panelData.offsetZ; + + this.setPosition(newX, newY, newZ); + + // Sync prevPos with owner's prevPos for smooth interpolation + float prevYawRad = (float) Math.toRadians(owner.prevRotationYaw); + this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist) + panelData.offsetX; + this.prevPosY = owner.prevPosY + panelData.heightOffset + (owner.height * 0.5f); + this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist) + panelData.offsetZ; + } + + @Override + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements) { + // HELD panels are fully owner-driven each tick via updateHeld(). + // Applying network position lerp on top of owner-following causes visible jitter/stutter + // when the caster is moving, so ignore remote corrections in this mode. + if (worldObj != null && worldObj.isRemote && mode == PanelMode.HELD && getOwnerEntity() != null) { + return; + } + // Bypass vanilla's lerp + push-out-of-blocks logic which causes + // large-BB entities (PLACED/LAUNCHED panels) to shift into the sky. + this.setPosition(x, y, z); + this.setRotation(yaw, pitch); + } + + private void updateLaunched() { + // Move forward on both sides for smooth client rendering + this.posX += motionX; + this.posY += motionY; + this.posZ += motionZ; + this.setPosition(posX, posY, posZ); + + // Damage and knockback are server-only + if (!worldObj.isRemote) { + // Check entity collision for damage + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float halfD = 0.5f; // Panel collision depth + float searchRadius = Math.max(halfW, halfD); + AxisAlignedBB hitBox = AxisAlignedBB.getBoundingBox( + posX - searchRadius, posY - halfH, posZ - searchRadius, + posX + searchRadius, posY + halfH, posZ + searchRadius + ); + + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); + Entity owner = getOwnerEntity(); + boolean ignoreIFrames = sourceAbility != null && sourceAbility.isIgnoreIFrames(); + + for (EntityLivingBase target : entities) { + if (target.getEntityId() == ownerEntityId) continue; + if (isAllyOfOwner(target)) continue; + + // Apply damage + if (panelData.launchDamage > 0) { + int previousHurtResistantTime = Ability.clearHurtResistanceIfNeeded(target, ignoreIFrames); + try { + // Route through ability extender (e.g. DBC Addon damage scaling) + boolean handled = false; + if (sourceAbility != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + handled = AbilityController.Instance.fireOnAbilityDamage( + sourceAbility, (EntityLivingBase) owner, target, + panelData.launchDamage, panelData.launchKnockback, 0.0f, dx, dz, 1.0f); + } + // Fallback: route through EnergyController for script-created entities with custom damage data + if (!handled && customDamageData != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + handled = EnergyController.Instance.fireOnEnergyDamage( + this, (EntityLivingBase) owner, target, + panelData.launchDamage, panelData.launchKnockback, 0.0f, dx, dz, 1.0f, customDamageData); + } + + if (!handled) { + if (owner instanceof EntityNPCInterface) { + target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), panelData.launchDamage); + } else if (owner instanceof EntityPlayer) { + target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), panelData.launchDamage); + } else { + target.attackEntityFrom(DamageSource.generic, panelData.launchDamage); + } + } + } finally { + Ability.restoreHurtResistanceIfNeeded(target, ignoreIFrames, previousHurtResistantTime); + } + } + + // Apply knockback + if (panelData.launchKnockback > 0) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + double len = Math.sqrt(dx * dx + dz * dz); + if (len > 0) { + double kbX = (dx / len) * panelData.launchKnockback * 0.5; + double kbZ = (dz / len) * panelData.launchKnockback * 0.5; + if (canPushInDirection(target, kbX, 0.1, kbZ)) { + target.addVelocity(kbX, 0.1, kbZ); + target.velocityChanged = true; + } + } + } + } + + // Max lifetime check + if (ticksAlive > 200) { + onBarrierDestroyed(); + this.setDead(); + } + } + } + + // ==================== INCOMING CHECK ==================== + + /** + * Swept ray-plane intersection test for the panel. + * Tests if the line segment from prevPos to currPos crosses the panel plane + * within its width/height bounds. Handles fast projectiles that skip through + * the thin panel in a single tick. + * + * @return true if the segment crosses the panel from either side + */ + private boolean isIncomingRay( + double currX, double currY, double currZ, + double prevX, double prevY, double prevZ, + int projOwnerEntityId) + { + if (isCharging()) return false; + if (projOwnerEntityId == this.ownerEntityId) return false; + + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float panelThickness = 0.5f; + + float yawRad = (float) Math.toRadians(panelYaw); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + + // Signed distance from prevPos and currPos to panel plane + double relPrevX = prevX - this.posX; + double relPrevY = prevY - this.posY; + double relPrevZ = prevZ - this.posZ; + double prevDist = relPrevX * normalX + relPrevZ * normalZ; + + double relCurrX = currX - this.posX; + double relCurrY = currY - this.posY; + double relCurrZ = currZ - this.posZ; + double currDist = relCurrX * normalX + relCurrZ * normalZ; + + // Check if segment crosses the plane (sign change) + if (prevDist * currDist > 0) { + // Both on same side — check if within thickness (slow projectile fallback) + if (Math.abs(currDist) <= panelThickness) { + double localRight = relCurrX * cos + relCurrZ * sin; + if (Math.abs(localRight) > halfW) return false; + if (Math.abs(relCurrY) > halfH) return false; + // Check incoming direction + double motX = currX - prevX; + double motZ = currZ - prevZ; + double dot = motX * normalX + motZ * normalZ; + if (currDist > 0 && dot >= 0) return false; + if (currDist < 0 && dot <= 0) return false; + return true; + } + return false; + } + + // Segment crosses plane — compute intersection parameter t + double rayDirX = currX - prevX; + double rayDirZ = currZ - prevZ; + double denom = rayDirX * normalX + rayDirZ * normalZ; + if (Math.abs(denom) < 1e-10) return false; // Parallel to plane + + double t = -prevDist / denom; + if (t < 0.0 || t > 1.0) return false; + + // Compute intersection point + double hitX = prevX + (currX - prevX) * t; + double hitY = prevY + (currY - prevY) * t; + double hitZ = prevZ + (currZ - prevZ) * t; + + // Transform hit point to panel-local space and check bounds + double relHitX = hitX - this.posX; + double relHitY = hitY - this.posY; + double relHitZ = hitZ - this.posZ; + + double localRight = relHitX * cos + relHitZ * sin; + if (Math.abs(localRight) > halfW) return false; + if (Math.abs(relHitY) > halfH) return false; + + return true; + } + + @Override + public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { + // Faction check: don't block same-faction NPC projectiles + Entity owner = getOwnerEntity(); + Entity projOwner = projectile.getOwnerEntity(); + if (owner instanceof EntityNPCInterface && projOwner instanceof EntityNPCInterface) { + if (((EntityNPCInterface) owner).faction.id == ((EntityNPCInterface) projOwner).faction.id) { + return false; + } + } + + if (mode == PanelMode.LAUNCHED) { + // For moving panels, use RELATIVE motion in the panel's reference frame. + // This correctly captures the combined closing speed when both objects + // are moving toward each other, preventing phase-through at high speeds. + double relMotionX = projectile.motionX - this.motionX; + double relMotionY = projectile.motionY - this.motionY; + double relMotionZ = projectile.motionZ - this.motionZ; + + double nextX = projectile.posX + relMotionX; + double nextY = projectile.posY + relMotionY; + double nextZ = projectile.posZ + relMotionZ; + + return isIncomingRay( + nextX, nextY, nextZ, + projectile.posX, projectile.posY, projectile.posZ, + projectile.getOwnerEntityId()); + } + + // Non-moving panels: standard test using projectile's absolute motion + double nextX = projectile.posX + projectile.motionX; + double nextY = projectile.posY + projectile.motionY; + double nextZ = projectile.posZ + projectile.motionZ; + + return isIncomingRay( + nextX, nextY, nextZ, + projectile.posX, projectile.posY, projectile.posZ, + projectile.getOwnerEntityId()); + } + + @Override + public boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId) + { + if (mode == PanelMode.LAUNCHED) { + // Use relative motion for moving panels + double relMotionX = motionX - this.motionX; + double relMotionY = motionY - this.motionY; + double relMotionZ = motionZ - this.motionZ; + double adjX = prevPosX + relMotionX; + double adjY = prevPosY + relMotionY; + double adjZ = prevPosZ + relMotionZ; + return isIncomingRay(adjX, adjY, adjZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } + return isIncomingRay(posX, posY, posZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } + + @Override + public double[] getSurfaceNormal(double hitX, double hitY, double hitZ, + double velX, double velY, double velZ) { + float yawRad = (float) Math.toRadians(panelYaw); + double nx = -Math.sin(yawRad); + double nz = Math.cos(yawRad); + + // Determine which side the hit is on + double relX = hitX - this.posX; + double relZ = hitZ - this.posZ; + double side = relX * nx + relZ * nz; + if (Math.abs(side) < 1.0e-5) { + // Near the plane: use incoming velocity to determine side + side = velX * nx + velZ * nz; + } + if (side < 0.0) { + nx = -nx; + nz = -nz; + } + + return new double[]{nx, 0.0, nz}; + } + + @Override + public double[] getOutsideSurfacePoint(double px, double py, double pz, + double velX, double velY, double velZ, + float bias) { + float yawRad = (float) Math.toRadians(panelYaw); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + + double relX = px - this.posX; + double relZ = pz - this.posZ; + double signedDist = relX * normalX + relZ * normalZ; + + double halfThickness = 0.25; + double side; + if (Math.abs(signedDist) > 0.035) { + side = signedDist >= 0 ? 1.0 : -1.0; + } else { + double vDot = velX * normalX + velZ * normalZ; + if (Math.abs(vDot) > 1.0e-5) { + side = vDot < 0 ? 1.0 : -1.0; + } else { + side = signedDist >= 0 ? 1.0 : -1.0; + } + } + + double targetDist = side * (halfThickness + bias); + double delta = targetDist - signedDist; + return new double[]{ + px + normalX * delta, + py, + pz + normalZ * delta + }; + } + + @Override + public float getMaxExtent() { + return Math.max(panelData.panelWidth, panelData.panelHeight) * 0.5f + 1.0f; + } + + // ==================== CHARGING ==================== + + @Override + public void setupCharging(int duration) { + this.targetPanelWidth = panelData.panelWidth; + this.targetPanelHeight = panelData.panelHeight; + panelData.panelWidth = 0.01f; + panelData.panelHeight = 0.01f; + this.chargeDuration = duration; + this.chargeTick = 0; + setCharging(true); + } + + @Override + public void finishCharging() { + panelData.panelWidth = targetPanelWidth; + panelData.panelHeight = targetPanelHeight; + setCharging(false); + } + + // ==================== ENTITY PHYSICS (Solid + Knockback) ==================== + + /** + * Processes entity physics for the panel barrier. Two independent systems: + *

+ * SOLID: Hard wall — entities cannot cross the panel plane within its bounds. + * Uses reactive crossing detection: compares current side to previous tick + * to detect plane crossings, then teleports back and applies velocity correction. + * Also preemptively cancels normal velocity when near the plane. + *

+ * KNOCKBACK: Repulsion force — entities near the panel surface get pushed away. + * This is a push effect only; entities can still pass through with enough effort. + * Does NOT prevent passthrough — use solid for that. + */ + @Override + @SuppressWarnings("unchecked") + protected void processEntityPhysics() { + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float searchExtension = 3.0f; + boolean solid = barrierData.solid; + boolean knockback = barrierData.knockbackEnabled; + float strength = barrierData.knockbackStrength; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - halfW - searchExtension, posY - halfH - searchExtension, posZ - halfW - searchExtension, + posX + halfW + searchExtension, posY + halfH + searchExtension, posZ + halfW + searchExtension + ); + + EntityPlayer localPlayer = getClientPredictionPlayer(); + + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + float yawRad = (float) Math.toRadians(panelYaw); + float normalX = -(float) Math.sin(yawRad); + float normalZ = (float) Math.cos(yawRad); + + for (EntityLivingBase ent : entities) { + if (shouldSkipBarrierPhysicsTarget(ent, localPlayer)) continue; + + // Current position relative to panel center + double dx = ent.posX - posX; + double dy = (ent.posY + ent.height * 0.5) - posY; + double dz = ent.posZ - posZ; + + // Panel-local coordinates + float localForward = (float) (dx * normalX + dz * normalZ); + float localRight = (float) (dx * (-normalZ) + dz * normalX); + + // Skip if outside panel bounds (with margin) + if (Math.abs(localRight) > halfW + 1.0f) continue; + if (Math.abs(dy) > halfH + 1.0f) continue; + if (Math.abs(localForward) > searchExtension) continue; + + // Determine which side the entity is on + float side = localForward >= 0 ? 1.0f : -1.0f; + + // Check if within panel width/height bounds + boolean inBounds = Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH; + + // --- SOLID: hard wall preventing plane crossing --- + if (solid && inBounds) { + // Previous tick: entity position relative to panel + double prevDx = ent.prevPosX - prevPosX; + double prevDz = ent.prevPosZ - prevPosZ; + float prevLocalForward = (float) (prevDx * normalX + prevDz * normalZ); + float prevSide = prevLocalForward >= 0 ? 1.0f : -1.0f; + + // Normal velocity component (positive = moving in normal direction) + double normalVel = ent.motionX * normalX + ent.motionZ * normalZ; + + if (prevSide != side) { + // Entity crossed the panel plane this tick — push back to original side + double pushDist = 0.3; + double newX = posX + normalX * prevSide * pushDist + (localRight * (-normalZ)); + double newZ = posZ + normalZ * prevSide * pushDist + (localRight * normalX); + teleportEntity(ent, newX, ent.posY, newZ); + + // Cancel normal velocity and add corrective push + ent.motionX -= normalVel * normalX; + ent.motionZ -= normalVel * normalZ; + double pushX = normalX * prevSide * 0.15; + double pushZ = normalZ * prevSide * 0.15; + if (canPushInDirection(ent, pushX, 0, pushZ)) { + ent.motionX += pushX; + ent.motionZ += pushZ; + } + ent.velocityChanged = true; + } else { + // Preemptive: near the plane and moving toward it — cancel normal velocity + double absDist = Math.abs(localForward); + if (absDist < 1.5) { + boolean movingToward = (side > 0 && normalVel < -0.01) + || (side < 0 && normalVel > 0.01); + if (movingToward) { + ent.motionX -= normalVel * normalX; + ent.motionZ -= normalVel * normalZ; + double pushX = normalX * side * 0.05; + double pushZ = normalZ * side * 0.05; + if (canPushInDirection(ent, pushX, 0, pushZ)) { + ent.motionX += pushX; + ent.motionZ += pushZ; + } + ent.velocityChanged = true; + } + } + } + } + + // --- KNOCKBACK: repulsion push (server only, synced via velocityChanged) --- + if (!worldObj.isRemote && knockback && inBounds) { + double absDist = Math.abs(localForward); + if (absDist < searchExtension) { + double proximity = 1.0 - (absDist / searchExtension); + double force = proximity * strength * 0.06; + double pushX = normalX * side * force; + double pushZ = normalZ * side * force; + if (canPushInDirection(ent, pushX, 0, pushZ)) { + ent.motionX += pushX; + ent.motionZ += pushZ; + } + ent.velocityChanged = true; + } + } + } + } + + // ==================== RENDER ==================== + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + double d = Math.max(panelData.panelWidth, panelData.panelHeight) * 8.0D; + d *= 64.0D; + return distance < d * d; + } + + // ==================== DISTANCE (for render sorting) ==================== + + /** + * Returns squared distance from the given point to the closest point on the panel surface. + * Accounts for panel rotation (panelYaw), width, height, and thickness. + * This ensures correct transparency render ordering when the camera is near or behind the panel. + */ + @Override + public double getDistanceSq(double x, double y, double z) { + double dx = x - this.posX; + double dy = y - this.posY; + double dz = z - this.posZ; + + float yawRad = (float) Math.toRadians(panelYaw); + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + + // Transform to panel-local space + // Panel normal (forward): (-sin, 0, cos) + // Panel right (width axis): (cos, 0, sin) + double localForward = dx * (-sin) + dz * cos; + double localRight = dx * cos + dz * sin; + double localUp = dy; + + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float halfThickness = 0.25f; + + // Clamp to panel bounds to find closest point on the panel volume + double clampedForward = Math.max(-halfThickness, Math.min(halfThickness, localForward)); + double clampedRight = Math.max(-halfW, Math.min(halfW, localRight)); + double clampedUp = Math.max(-halfH, Math.min(halfH, localUp)); + + // Distance from point to closest point on panel + double df = localForward - clampedForward; + double dr = localRight - clampedRight; + double du = localUp - clampedUp; + + return df * df + dr * dr + du * du; + } + + // ==================== DEBUG ==================== + + @Override + protected String debugLogBarrierExtra() { + return String.format("mode=%s yaw=%.1f w=%.2f h=%.2f", + mode.name(), panelYaw, panelData.panelWidth, panelData.panelHeight); + } + + // ==================== GETTERS ==================== + + public PanelMode getMode() { + return mode; + } + + public float getPanelYaw() { + return panelYaw; + } + + public float getPrevPanelYaw() { + return prevPanelYaw; + } + + public EnergyPanelData getPanelData() { + return panelData; + } + + public void setPanelYaw(float yaw) { + this.panelYaw = yaw; + this.prevPanelYaw = yaw; + } + + public void setMode(PanelMode mode) { + this.mode = mode; + } + + // ==================== CLIENT SYNC ==================== + + @Override + protected void writeBarrierClientSyncData(NBTTagCompound nbt) { + nbt.setFloat("PanelWidth", panelData.panelWidth); + nbt.setFloat("PanelHeight", panelData.panelHeight); + nbt.setFloat("PanelYaw", panelYaw); + } + + @Override + protected void applyBarrierClientSyncData(NBTTagCompound nbt) { + panelData.panelWidth = nbt.getFloat("PanelWidth"); + panelData.panelHeight = nbt.getFloat("PanelHeight"); + panelYaw = nbt.getFloat("PanelYaw"); + } + + // ==================== NBT ==================== + + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBarrierBaseNBT(nbt); + nbt.setFloat("PanelYaw", panelYaw); + nbt.setInteger("PanelMode", mode.ordinal()); + nbt.setFloat("TargetPanelWidth", targetPanelWidth); + nbt.setFloat("TargetPanelHeight", targetPanelHeight); + panelData.writeNBT(nbt); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBarrierBaseNBT(nbt); + this.panelYaw = nbt.getFloat("PanelYaw"); + int modeOrdinal = nbt.getInteger("PanelMode"); + this.mode = (modeOrdinal >= 0 && modeOrdinal < PanelMode.values().length) + ? PanelMode.values()[modeOrdinal] : PanelMode.PLACED; + panelData.readNBT(nbt); + panelData.panelWidth = sanitize(panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); + panelData.panelHeight = sanitize(panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); + this.targetPanelWidth = sanitize(nbt.hasKey("TargetPanelWidth") ? nbt.getFloat("TargetPanelWidth") : panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); + this.targetPanelHeight = sanitize(nbt.hasKey("TargetPanelHeight") ? nbt.getFloat("TargetPanelHeight") : panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java new file mode 100644 index 000000000..702c62c4d --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -0,0 +1,2538 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.EnergyController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.type.energy.AbilityEnergyProjectile; +import kamkeel.npcs.controllers.data.ability.data.effect.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.enums.HitType; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +import kamkeel.npcs.network.packets.data.energy.ProjectileClientSyncPacket; +import kamkeel.npcs.network.packets.data.energy.ProjectileReflectPacket; +import kamkeel.npcs.network.packets.data.energyexplosion.EnergyExplosionSpawnPacket; +import kamkeel.npcs.util.AnchorPointHelper; +import kamkeel.npcs.util.AttributeAttackUtil; +import kamkeel.npcs.util.CNPCDebug; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.Explosion; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; +import noppes.npcs.EventHooks; +import noppes.npcs.NpcDamageSource; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.config.ConfigEnergy; +import noppes.npcs.config.ConfigMain; +import noppes.npcs.controllers.PartyController; +import noppes.npcs.controllers.data.Party; +import noppes.npcs.controllers.data.PlayerData; +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.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * Base class for all ability projectiles (Orb, Disc, Beam, Laser, Slicer). + * Provides common functionality for combat, effects, homing, and interpolation. + * Extends EntityEnergyAbility for shared visual/owner/charging state. + *

+ * Design inspired by LouisXIV's energy attack system. + */ +public abstract class EntityEnergyProjectile extends EntityEnergyAbility { + // ==================== ACTIVE PROJECTILE TRACKING ==================== + private static final Map>> activeProjectiles = new HashMap<>(); + + public static void trackProjectile(EntityEnergyProjectile 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 void clearAllProjectiles() { + activeProjectiles.clear(); + } + + 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()) { + EntityEnergyProjectile 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; + + // ==================== COMBAT PROPERTIES ==================== + protected EnergyCombatData combatData = new EnergyCombatData(); + + // ==================== EFFECT PROPERTIES ==================== + protected List effects = new ArrayList<>(); + + // ==================== ANCHOR PROPERTIES ==================== + protected EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); + + // ==================== LIFESPAN PROPERTIES ==================== + protected EnergyLifespanData lifespanData = new EnergyLifespanData(); + protected long deathWorldTime = -1; // World time when entity should die (-1 = not set) + + // ==================== HOMING PROPERTIES ==================== + protected EnergyHomingData homingData = new EnergyHomingData(); + + // ==================== TRACKING ==================== + protected double startX, startY, startZ; + protected int targetEntityId = -1; + + // ==================== STATE ==================== + protected boolean reflected = false; // Set after barrier reflection; prevents owner-tracking on reflected projectiles + protected boolean hasHit = false; + protected int hitCount = 0; + protected final Set hitOnceEntities = new HashSet(); + protected final Map lastHitTickByEntity = new HashMap(); + protected static final int BARRIER_IMPACT_PAUSE_TICKS = 10; + protected static final int BARRIER_BREAK_SPARK_TICKS = 10; + protected static final int DW_BARRIER_SPARK_TICKS = 21; + protected static final int DW_SYNC_INNER_COLOR = 22; + protected static final int DW_SYNC_OUTER_COLOR = 23; + protected int barrierImpactPauseTicks = 0; + protected boolean barrierImpactDestroyOnResume = false; + protected double pausedMotionX, pausedMotionY, pausedMotionZ; + + // ==================== CHARGING STATE (projectile-specific) ==================== + protected float targetSize = 1.0f; + + // ==================== ROTATION INTERPOLATION ==================== + public float prevRotationValX, prevRotationValY, prevRotationValZ; + public float rotationValX, rotationValY, rotationValZ; + + // ==================== SIZE INTERPOLATION ==================== + protected float renderCurrentSize; + protected float prevRenderSize; + + // ==================== POSITION INTERPOLATION ==================== + protected double interpTargetX, interpTargetY, interpTargetZ; + protected double interpTargetMotionX, interpTargetMotionY, interpTargetMotionZ; + protected int interpSteps; + + public EntityEnergyProjectile(World world) { + super(world); + this.setSize(0.5f, 0.5f); + this.yOffset = this.height / 2.0f; + this.noClip = false; + } + + @Override + protected void entityInit() { + super.entityInit(); // DW_CHARGING = 20 + this.dataWatcher.addObject(DW_BARRIER_SPARK_TICKS, 0); + // displayData is not guaranteed to be initialized yet during Entity construction. + this.dataWatcher.addObject(DW_SYNC_INNER_COLOR, 0xFFFFFF); + this.dataWatcher.addObject(DW_SYNC_OUTER_COLOR, 0xFFFFFF); + } + + /** + * Initialize common properties using data classes. Call from subclass constructors. + */ + protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, float size, + EnergyDisplayData display, EnergyCombatData combat, + EnergyLightningData lightning, EnergyLifespanData lifespan) { + this.setPosition(x, y, z); + this.startX = x; + this.startY = y; + this.startZ = z; + + this.ownerEntityId = owner != null ? owner.getEntityId() : -1; + this.targetEntityId = target != null ? target.getEntityId() : -1; + + // Visual + this.size = size; + + // Defensive copy: entities must never share data objects with the source ability. + // Without copies, runtime mutations (e.g. barrier reflection changing colors/damage) + // bleed back into the ability template and corrupt future projectiles. + this.displayData = display != null ? display.copy() : new EnergyDisplayData(); + this.combatData = combat != null ? combat.copy() : new EnergyCombatData(); + this.lifespanData = lifespan != null ? lifespan.copy() : new EnergyLifespanData(); + this.lightningData = lightning != null ? lightning.copy() : new EnergyLightningData(); + syncProjectileColorWatchers(); + + // Initialize render size + this.renderCurrentSize = size; + this.prevRenderSize = size; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + double d1 = this.boundingBox.getAverageEdgeLength() * 4.0D; + d1 *= 128.0D; + return distance < d1 * d1; + } + + @Override + public void onUpdate() { + // Store previous values for interpolation + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.prevRotationValX = this.rotationValX; + this.prevRotationValY = this.rotationValY; + this.prevRotationValZ = this.rotationValZ; + this.prevRenderSize = this.renderCurrentSize; + + // 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); + } + } else { + // Preview entities skip super.onUpdate() but still need ticksExisted + // for renderer pulsing effects (e.g., sin(ticksExisted + partialTicks)). + this.ticksExisted++; + + // Preview-specific safety: self-destruct if charging has exceeded duration + grace + if (isCharging() && chargeDuration > 0 && chargeTick > chargeDuration + PREVIEW_CHARGE_GRACE) { + this.setDead(); + return; + } + + // Preview hard lifetime cap (mirrors real entity HARD_LIFETIME_CAP) + if (ticksExisted > HARD_LIFETIME_CAP) { + this.setDead(); + return; + } + } + + if (!previewMode) { + syncDisplayColorsFromWatchers(); + } + + // Update rotation + updateRotation(); + + // Update render size: during charging, track directly (size already grows smoothly). + // Post-charging, lerp for smooth visual transitions. + if (isCharging()) { + this.renderCurrentSize = this.size; + } else { + this.renderCurrentSize = this.renderCurrentSize + (this.size - this.renderCurrentSize) * 0.15f; + } + + // Server-synced visual timer used for brief barrier impact lightning. + if (!previewMode && !worldObj.isRemote) { + tickBarrierSparkTimer(); + } + + // Skip lifetime/distance checks in preview mode + if (!previewMode) { + // 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) { + if (owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + this.setDead(); + return; + } + } + } + + // Charging timeout - if charge phase exceeded with grace period, force kill + if (isCharging() && chargeTick > chargeDuration + CHARGE_TIMEOUT_GRACE) { + this.setDead(); + return; + } + + // Absolute hard lifetime cap (safety net for any stuck state) + if (ticksExisted > HARD_LIFETIME_CAP) { + this.setDead(); + return; + } + + // Set death time on first tick if not already set (handles chunk load/unload) + // Skip during charging phase - lifetime starts when the entity actually fires + if (deathWorldTime < 0 && worldObj != null && !isCharging()) { + deathWorldTime = worldObj.getTotalWorldTime() + getMaxLifetime(); + } + + // 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; + } + + if (hasHit) { + this.setDead(); + return; + } + } + + if (!previewMode && !worldObj.isRemote && !isCharging()) { + if (tickBarrierImpactPause()) { + return; + } + } + + // Check barrier collisions (server-side, non-preview, non-charging) + if (!previewMode && !worldObj.isRemote && !isCharging()) { + if (checkBarrierCollision()) { + return; // Barrier interaction handled (pause + destroy/continue) + } + } + + // Subclass-specific update + updateProjectile(); + + // Fire tick event (server-side, non-preview only) + if (!previewMode && !worldObj.isRemote) { + EventHooks.onEnergyProjectileTick(this, ticksExisted); + } + + debugLogTick(); + } + + /** + * Update rotation values. Override for custom rotation behavior. + */ + protected void updateRotation() { + this.rotationValX += getRotationSpeed() * 0.7f; + this.rotationValY += getRotationSpeed(); + this.rotationValZ += getRotationSpeed() * 0.5f; + + if (this.rotationValX > 360.0f) this.rotationValX -= 360.0f; + if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f; + if (this.rotationValZ > 360.0f) this.rotationValZ -= 360.0f; + } + + // ==================== DEBUG LOGGING ==================== + + /** + * Debug log called every tick. Logs position/size/charging state. + * Subclasses override debugLogExtra() for type-specific data. + */ + protected void debugLogTick() { + boolean isClient = worldObj.isRemote; + if (isClient ? !CNPCDebug.isClientEnabled("energy") : !CNPCDebug.isServerEnabled("energy")) + return; + + String className = getClass().getSimpleName(); + boolean dwCharging = isCharging(); // DataWatcher value (what client sees) + boolean localCharging = this.charging; // Local field (server truth) + + String base = String.format("[%s id=%d tick=%d] pos=(%.2f,%.2f,%.2f) prev=(%.2f,%.2f,%.2f) " + + "size=%.3f renderSize=%.3f prevRenderSize=%.3f " + + "charging(dw)=%b charging(local)=%b chargeTick=%d/%d chargeProgress=%.3f", + className, getEntityId(), ticksExisted, + posX, posY, posZ, prevPosX, prevPosY, prevPosZ, + size, renderCurrentSize, prevRenderSize, + dwCharging, localCharging, chargeTick, chargeDuration, getChargeProgress()); + + // Flag mismatch between DataWatcher and local field + if (dwCharging != localCharging) { + base += " !!CHARGE_MISMATCH!!"; + } + + // Client interpolation state (only meaningful on client) + if (isClient) { + base += String.format(" interp(steps=%d target=(%.2f,%.2f,%.2f))", + interpSteps, interpTargetX, interpTargetY, interpTargetZ); + } + + String extra = debugLogExtra(); + String full = extra.isEmpty() ? base : base + " " + extra; + CNPCDebug.log("energy", isClient, full); + } + + /** + * Subclass hook for type-specific debug data. + * Return empty string if nothing extra to log. + */ + protected String debugLogExtra() { + return ""; + } + + /** + * Check if projectile has exceeded max distance. + * + * @return true if should die + */ + protected boolean checkMaxDistance() { + double distTraveled = Math.sqrt( + (posX - startX) * (posX - startX) + + (posY - startY) * (posY - startY) + + (posZ - startZ) * (posZ - startZ) + ); + return distTraveled >= getMaxDistance(); + } + + /** + * Subclass-specific update logic. Called every tick. + */ + protected abstract void updateProjectile(); + + // ==================== BARRIER COLLISION ==================== + + /** + * Check for collision with energy barrier entities. + * Barriers only block incoming projectiles from enemies. + * + * @return true if barrier interaction was handled (caller should stop processing this tick) + */ + protected boolean checkBarrierCollision() { + List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead) continue; + + // Quick distance pre-filter + double dx = barrier.posX - this.posX; + double dy = barrier.posY - this.posY; + double dz = barrier.posZ - this.posZ; + double distSq = dx * dx + dy * dy + dz * dz; + double maxRange = barrier.getMaxExtent() + 5.0; + if (distSq > maxRange * maxRange) continue; + + if (barrier.isIncomingProjectile(this)) { + float damage = getModifiedDamage(); + EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage); + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { + continue; + } + if (handleBarrierHitOutcome(barrier, hitOutcome, damage)) { + return true; + } + return false; + } + } + + return false; + } + + /** + * Handle the result of a projectile/barrier interaction. + * + * @param fullDamage The DBC-scaled damage that was passed to the barrier (from getModifiedDamage). + * @return true if caller should stop processing this tick. + */ + protected boolean handleBarrierHitOutcome(EntityEnergyBarrier barrier, EntityEnergyBarrier.ProjectileHitOutcome hitOutcome, float fullDamage) { + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { + return false; + } + + if (hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.BROKEN) { + if (hitOutcome.remainingProjectileDamage <= 0.0f) { + damageMultiplier = 0.0f; + setBarrierSparkTicks(Math.max(getBarrierSparkTicks(), BARRIER_BREAK_SPARK_TICKS)); + hasHit = true; + return true; + } + + // Accumulate barrier pass-through ratio for extender damage scaling. + // fullDamage is the DBC-scaled damage the barrier saw; remainingProjectileDamage + // is what survived. Multiply into the running ratio so multiple barriers stack. + if (fullDamage > 0.0f) { + damageMultiplier *= (hitOutcome.remainingProjectileDamage / fullDamage); + } + + setCombatDamage(hitOutcome.remainingProjectileDamage); + setBarrierSparkTicks(Math.max(getBarrierSparkTicks(), BARRIER_BREAK_SPARK_TICKS)); + return false; + } + + if (hitOutcome.shouldReflect()) { + if (!reflectFromBarrier(barrier, hitOutcome.reflectStrengthPct)) { + beginBarrierImpactPause(true, barrier); + } else { + sendReflectionSync(); + } + return true; + } + + beginBarrierImpactPause(true, barrier); + return true; + } + + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { + if (barrier == null) { + return false; + } + + double vx = motionX; + double vy = motionY; + double vz = motionZ; + double vLenSq = vx * vx + vy * vy + vz * vz; + if (vLenSq < 1.0e-8) { + return false; + } + + double[] normal = getBarrierImpactNormal(barrier, vx, vy, vz); + if (normal == null) { + return false; + } + + double dot = vx * normal[0] + vy * normal[1] + vz * normal[2]; + if (dot > 0.0) { + normal[0] = -normal[0]; + normal[1] = -normal[1]; + normal[2] = -normal[2]; + dot = vx * normal[0] + vy * normal[1] + vz * normal[2]; + } + + double rx = vx - 2.0 * dot * normal[0]; + double ry = vy - 2.0 * dot * normal[1]; + double rz = vz - 2.0 * dot * normal[2]; + double rLenSq = rx * rx + ry * ry + rz * rz; + if (rLenSq < 1.0e-8) { + rx = -vx; + ry = -vy; + rz = -vz; + rLenSq = rx * rx + ry * ry + rz * rz; + } + + // Prefer rebounding out and away from ground instead of immediately diving downward. + if (ry < -0.06) { + double speed = Math.sqrt(Math.max(rLenSq, 1.0e-8)); + ry = Math.max(0.08, Math.abs(ry) * 0.35); + double newLen = Math.sqrt(rx * rx + ry * ry + rz * rz); + if (newLen > 1.0e-8) { + double scale = speed / newLen; + rx *= scale; + ry *= scale; + rz *= scale; + } + } + + // Push slightly outside the collision boundary so the reflected motion + // starts cleanly from the barrier surface instead of re-colliding in place. + snapOutsideBarrierForPause(barrier); + + motionX = rx; + motionY = ry; + motionZ = rz; + pausedMotionX = rx; + pausedMotionY = ry; + pausedMotionZ = rz; + barrierImpactPauseTicks = 0; + barrierImpactDestroyOnResume = false; + + // Reset start position and lifetime so the reflected projectile gets a fresh + // max-distance budget and lifetime. Without this, re-reflection fails because + // the projectile expires from the original launch's distance/time limits. + startX = posX; + startY = posY; + startZ = posZ; + deathWorldTime = -1; + + // Detach from source ability BEFORE changing ownership. + // This lets the ability see the projectile as gone and free the caster + // (e.g., release movement/rotation locks on the player). + if (sourceAbility instanceof AbilityEnergyProjectile) { + ((AbilityEnergyProjectile) sourceAbility).detachEntity(this); + } + sourceAbility = null; + + // Save original owner before transfer for potential target retargeting + int originalOwnerId = ownerEntityId; + + Entity barrierOwner = barrier.getOwnerEntity(); + if (barrierOwner != null) { + setOwnerEntityId(barrierOwner.getEntityId()); + // Ensure ownership-sensitive systems can query this projectile under the new owner. + trackProjectile(this); + } + + // Target Owner: set the reflected projectile's target to the original caster + if (barrier.getBarrierData().isTargetOwner() && originalOwnerId != -1) { + setTargetEntityId(originalOwnerId); + } else { + setTargetEntityId(-1); + } + + setInnerColor(barrier.getInnerColor()); + setOuterColor(barrier.getOuterColor()); + + float clampedStrength = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct)); + float reductionFactor = 1.0f - clampedStrength / 100.0f; + float reducedDamage = getDamage() * reductionFactor; + setCombatDamage(Math.max(0.0f, reducedDamage)); + damageMultiplier *= reductionFactor; + + hitOnceEntities.clear(); + lastHitTickByEntity.clear(); + hitCount = 0; + reflected = true; + return true; + } + + // ==================== REFLECTION SYNC ==================== + + /** + * Write reflection state for client sync. + * Subclasses should override writeProjectileReflectionData for type-specific fields. + */ + public NBTTagCompound writeReflectionData() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("OwnerId", ownerEntityId); + nbt.setDouble("PosX", posX); + nbt.setDouble("PosY", posY); + nbt.setDouble("PosZ", posZ); + nbt.setDouble("MotionX", motionX); + nbt.setDouble("MotionY", motionY); + nbt.setDouble("MotionZ", motionZ); + nbt.setInteger("InnerColor", getInnerColor()); + nbt.setInteger("OuterColor", getOuterColor()); + nbt.setBoolean("Reflected", reflected); + writeProjectileReflectionData(nbt); + return nbt; + } + + /** + * Apply reflection state from server sync. + * Subclasses should override applyProjectileReflectionData for type-specific fields. + */ + public void applyReflectionData(NBTTagCompound nbt) { + ownerEntityId = nbt.getInteger("OwnerId"); + double px = nbt.getDouble("PosX"); + double py = nbt.getDouble("PosY"); + double pz = nbt.getDouble("PosZ"); + setPosition(px, py, pz); + motionX = nbt.getDouble("MotionX"); + motionY = nbt.getDouble("MotionY"); + motionZ = nbt.getDouble("MotionZ"); + setInnerColor(nbt.getInteger("InnerColor")); + setOuterColor(nbt.getInteger("OuterColor")); + reflected = nbt.getBoolean("Reflected"); + syncPositionStateToCurrent(true); + hitOnceEntities.clear(); + lastHitTickByEntity.clear(); + hitCount = 0; + applyProjectileReflectionData(nbt); + } + + /** + * Subclass hook: write type-specific reflection data. + */ + protected void writeProjectileReflectionData(NBTTagCompound nbt) { + } + + /** + * Subclass hook: apply type-specific reflection data on client. + */ + protected void applyProjectileReflectionData(NBTTagCompound nbt) { + } + + /** + * Send reflection state to all tracking clients. + */ + protected void sendReflectionSync() { + if (worldObj == null || worldObj.isRemote) return; + ProjectileReflectPacket.sendToTracking(this, writeReflectionData()); + } + + // ==================== CLIENT SYNC ==================== + + /** + * Write all client-relevant state: position, motion, visual, and movement properties. + * Subclasses should override writeProjectileClientSyncData for type-specific fields. + */ + public NBTTagCompound writeClientSyncData() { + NBTTagCompound nbt = new NBTTagCompound(); + // Position & motion + nbt.setDouble("PosX", posX); + nbt.setDouble("PosY", posY); + nbt.setDouble("PosZ", posZ); + nbt.setDouble("MotionX", motionX); + nbt.setDouble("MotionY", motionY); + nbt.setDouble("MotionZ", motionZ); + // Size & visual + nbt.setFloat("Size", size); + nbt.setFloat("RotationSpeed", displayData.getRotationSpeed()); + nbt.setFloat("InnerAlpha", displayData.getInnerAlpha()); + nbt.setBoolean("OuterColorEnabled", displayData.isOuterColorEnabled()); + nbt.setFloat("OuterColorWidth", displayData.getOuterColorWidth()); + nbt.setFloat("OuterColorAlpha", displayData.getOuterColorAlpha()); + // Lightning + nbt.setBoolean("LightningEffect", hasLightningEffect()); + nbt.setFloat("LightningDensity", getLightningDensity()); + nbt.setFloat("LightningRadius", getLightningRadius()); + nbt.setInteger("LightningFadeTime", getLightningFadeTime()); + // Movement + nbt.setFloat("Speed", getSpeed()); + nbt.setBoolean("Homing", isHoming()); + nbt.setFloat("HomingStrength", getHomingStrength()); + nbt.setFloat("HomingRange", getHomingRange()); + writeProjectileClientSyncData(nbt); + return nbt; + } + + /** + * Apply client sync data from server. + * Subclasses should override applyProjectileClientSyncData for type-specific fields. + */ + public void applyClientSyncData(NBTTagCompound nbt) { + // Position & motion + setPosition(nbt.getDouble("PosX"), nbt.getDouble("PosY"), nbt.getDouble("PosZ")); + motionX = nbt.getDouble("MotionX"); + motionY = nbt.getDouble("MotionY"); + motionZ = nbt.getDouble("MotionZ"); + syncPositionStateToCurrent(true); + // Size & visual (set target only - let the lerp in onUpdate smooth the transition) + this.size = nbt.getFloat("Size"); + displayData.setRotationSpeed(nbt.getFloat("RotationSpeed")); + displayData.setInnerAlpha(nbt.getFloat("InnerAlpha")); + displayData.setOuterColorEnabled(nbt.getBoolean("OuterColorEnabled")); + displayData.setOuterColorWidth(nbt.getFloat("OuterColorWidth")); + displayData.setOuterColorAlpha(nbt.getFloat("OuterColorAlpha")); + // Lightning + setLightningEffect(nbt.getBoolean("LightningEffect")); + setLightningDensity(nbt.getFloat("LightningDensity")); + setLightningRadius(nbt.getFloat("LightningRadius")); + setLightningFadeTime(nbt.getInteger("LightningFadeTime")); + // Movement + setSpeed(nbt.getFloat("Speed")); + setHomingEnabled(nbt.getBoolean("Homing")); + setHomingStrength(nbt.getFloat("HomingStrength")); + setHomingRange(nbt.getFloat("HomingRange")); + applyProjectileClientSyncData(nbt); + } + + /** + * Subclass hook: write type-specific client sync data. + */ + protected void writeProjectileClientSyncData(NBTTagCompound nbt) { + } + + /** + * Subclass hook: apply type-specific client sync data on client. + */ + protected void applyProjectileClientSyncData(NBTTagCompound nbt) { + } + + /** + * Send full client sync to all tracking clients. + */ + public void sendClientSync() { + if (worldObj == null || worldObj.isRemote) return; + ProjectileClientSyncPacket.sendToTracking(this, writeClientSyncData()); + } + + protected double[] getBarrierImpactNormal(EntityEnergyBarrier barrier, double velocityX, double velocityY, double velocityZ) { + return barrier.getSurfaceNormal(posX, posY, posZ, velocityX, velocityY, velocityZ); + } + + protected void beginBarrierImpactPause(boolean destroyOnResume, EntityEnergyBarrier barrier) { + if (barrierImpactPauseTicks <= 0) { + pausedMotionX = motionX; + pausedMotionY = motionY; + pausedMotionZ = motionZ; + } + + barrierImpactDestroyOnResume = destroyOnResume; + barrierImpactPauseTicks = BARRIER_IMPACT_PAUSE_TICKS; + motionX = 0; + motionY = 0; + motionZ = 0; + + int sparkTicks = getBarrierSparkTicks(); + if (sparkTicks < BARRIER_IMPACT_PAUSE_TICKS) { + setBarrierSparkTicks(BARRIER_IMPACT_PAUSE_TICKS); + } + } + + protected float getBarrierPauseOutsideDistance() { + // Keep the paused projectile just outside the surface without a visible "fling". + return Math.max(0.06f, Math.min(0.22f, size * 0.18f + 0.03f)); + } + + protected void snapOutsideBarrierForPause(EntityEnergyBarrier barrier) { + if (barrier == null) return; + + float bias = getBarrierPauseOutsideDistance(); + double[] point = barrier.getOutsideSurfacePoint(posX, posY, posZ, motionX, motionY, motionZ, bias); + setPosition(point[0], point[1], point[2]); + } + + protected boolean tickBarrierImpactPause() { + if (barrierImpactPauseTicks <= 0) { + return false; + } + + motionX = 0; + motionY = 0; + motionZ = 0; + barrierImpactPauseTicks--; + + if (barrierImpactPauseTicks <= 0) { + if (barrierImpactDestroyOnResume) { + hasHit = true; + this.setDead(); + } else { + motionX = pausedMotionX; + motionY = pausedMotionY; + motionZ = pausedMotionZ; + } + barrierImpactDestroyOnResume = false; + } + + return true; + } + + protected void tickBarrierSparkTimer() { + int sparkTicks = getBarrierSparkTicks(); + if (sparkTicks > 0) { + setBarrierSparkTicks(sparkTicks - 1); + } + } + + protected void setBarrierSparkTicks(int ticks) { + if (!worldObj.isRemote) { + this.dataWatcher.updateObject(DW_BARRIER_SPARK_TICKS, Math.max(0, ticks)); + } + } + + public int getBarrierSparkTicks() { + if (this.dataWatcher == null) { + return 0; + } + return Math.max(0, this.dataWatcher.getWatchableObjectInt(DW_BARRIER_SPARK_TICKS)); + } + + protected void syncProjectileColorWatchers() { + if (this.dataWatcher == null) { + return; + } + this.dataWatcher.updateObject(DW_SYNC_INNER_COLOR, this.displayData.getInnerColor()); + this.dataWatcher.updateObject(DW_SYNC_OUTER_COLOR, this.displayData.getOuterColor()); + } + + protected void syncDisplayColorsFromWatchers() { + if (this.dataWatcher == null) { + return; + } + this.displayData.setInnerColor(this.dataWatcher.getWatchableObjectInt(DW_SYNC_INNER_COLOR)); + this.displayData.setOuterColor(this.dataWatcher.getWatchableObjectInt(DW_SYNC_OUTER_COLOR)); + } + + @Override + public void setInnerColor(int color) { + super.setInnerColor(color); + if (!previewMode) { + syncProjectileColorWatchers(); + } + } + + @Override + public void setOuterColor(int color) { + super.setOuterColor(color); + if (!previewMode) { + syncProjectileColorWatchers(); + } + } + + /** + * Get the projectile damage modified by extenders (e.g. DBC damage scaling). + * Falls back to base getDamage() when no sourceAbility or no extenders modify it. + */ + protected float getModifiedDamage() { + float damage = getDamage(); + if (sourceAbility != null) { + Entity owner = getOwnerEntity(); + if (owner instanceof EntityLivingBase) { + damage = AbilityController.Instance.fireModifyProjectileDamage( + sourceAbility, (EntityLivingBase) owner, damage); + } + } + return damage; + } + + // ==================== POSITION INTERPOLATION ==================== + + @Override + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements) { + int steps = Math.max(1, posRotationIncrements); + double dx = x - this.posX; + double dy = y - this.posY; + double dz = z - this.posZ; + double dotToCurrentMotion = dx * this.motionX + dy * this.motionY + dz * this.motionZ; + + // Spawn-time and large correction snaps: avoid visible startup rubber-banding. + if (worldObj != null && worldObj.isRemote) { + double distSq = dx * dx + dy * dy + dz * dz; + // Launch-time stale tracker packets can arrive one update late and point behind + // an already-predicted projectile. Skipping these avoids visible backward "bounce". + if (ticksExisted <= 24 && distSq <= 4.0D && dotToCurrentMotion < -0.0025D) { + return; + } + if (ticksExisted <= 2 || distSq > 16.0D) { + this.setPosition(x, y, z); + syncPositionState(x, y, z, true); + return; + } + } + + this.interpTargetX = x; + this.interpTargetY = y; + this.interpTargetZ = z; + if (worldObj != null && worldObj.isRemote && ticksExisted <= 24 && dotToCurrentMotion < 0.0D) { + // Keep existing velocity when correction points opposite current travel + // to prevent launch-time reverse lerp. + this.interpTargetMotionX = this.motionX; + this.interpTargetMotionY = this.motionY; + this.interpTargetMotionZ = this.motionZ; + } else { + this.interpTargetMotionX = dx / steps; + this.interpTargetMotionY = dy / steps; + this.interpTargetMotionZ = dz / steps; + } + this.interpSteps = steps; + } + + @Override + public void setVelocity(double motionX, double motionY, double motionZ) { + this.interpTargetMotionX = motionX; + this.interpTargetMotionY = motionY; + this.interpTargetMotionZ = motionZ; + this.motionX = motionX; + this.motionY = motionY; + this.motionZ = motionZ; + } + + /** + * Handle client-side position interpolation. + * Only moves position during active interpolation (interpSteps > 0). + * Does NOT predict/drift between server updates — the motion values are + * derived from correction deltas, not actual entity velocity, so applying + * them between updates causes entities to fly off in wrong directions. + * This matches vanilla Minecraft behavior for non-player entities. + */ + protected void handleClientInterpolation() { + if (this.interpSteps > 0) { + double dx = this.interpTargetX - this.posX; + double dy = this.interpTargetY - this.posY; + double dz = this.interpTargetZ - this.posZ; + double distSq = dx * dx + dy * dy + dz * dz; + + if (distSq < 0.0001) { + this.setPosition(this.interpTargetX, this.interpTargetY, this.interpTargetZ); + this.interpSteps = 0; + return; + } + + double newX = this.posX + dx / this.interpSteps; + double newY = this.posY + dy / this.interpSteps; + double newZ = this.posZ + dz / this.interpSteps; + + this.motionX = this.motionX + (this.interpTargetMotionX - this.motionX) / this.interpSteps; + this.motionY = this.motionY + (this.interpTargetMotionY - this.motionY) / this.interpSteps; + this.motionZ = this.motionZ + (this.interpTargetMotionZ - this.motionZ) / this.interpSteps; + + this.setPosition(newX, newY, newZ); + this.interpSteps--; + } + } + + // ==================== DAMAGE & EFFECTS ==================== + + protected boolean applyDamage(EntityLivingBase target) { + if (previewMode) return false; // Skip damage in preview mode + return applyDamage(target, this.getDamage(), this.getKnockback()); + } + + protected boolean applyDamage(EntityLivingBase target, float dmg, float kb) { + if (previewMode) return false; // Skip damage in preview mode + if (target == null || shouldIgnoreEntity(target)) return false; + + // Fire entity impact event (may cancel or modify damage) + if (!worldObj.isRemote) { + float result = EventHooks.onEnergyProjectileEntityImpact(this, target, dmg); + if (result < 0) return false; // Event was cancelled + dmg = result; + } + + Entity owner = getOwnerEntity(); + boolean ignoreIFrames = isIgnoreIFrames(); + + // Check for ability extenders (e.g., DBC Addon damage routing) + boolean handled = false; + boolean defaultDamageApplied = false; + if (sourceAbility != null && owner instanceof EntityLivingBase) { + 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, damageMultiplier); + } + // Fallback: route through EnergyController for script-created entities with custom damage data + if (!handled && customDamageData != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f; + handled = EnergyController.Instance.fireOnEnergyDamage( + this, (EntityLivingBase) owner, target, + dmg, kb, kbUp, dx, dz, damageMultiplier, customDamageData); + } + + int previousHurtResistantTime = Ability.clearHurtResistanceIfNeeded(target, ignoreIFrames); + try { + if (!handled) { + float finalDmg = dmg; + + // Apply magic pipeline for player and NPC casters + if (this.magicData != null && !this.magicData.isEmpty() && owner instanceof EntityLivingBase) { + finalDmg = AttributeAttackUtil.calculateAbilityDamage( + (EntityLivingBase) owner, target, dmg, this.magicData); + } + + // Default damage path + if (owner instanceof EntityNPCInterface) { + defaultDamageApplied = target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), finalDmg); + } else if (owner instanceof EntityPlayer) { + defaultDamageApplied = target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), finalDmg); + } else if (owner instanceof EntityLivingBase) { + defaultDamageApplied = target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), finalDmg); + } else { + defaultDamageApplied = target.attackEntityFrom(new NpcDamageSource("npc_ability", null), finalDmg); + } + } + } finally { + Ability.restoreHurtResistanceIfNeeded(target, ignoreIFrames, previousHurtResistantTime); + } + + boolean allowSecondaryEffects = handled || dmg <= 0 || defaultDamageApplied; + if (!allowSecondaryEffects) return false; + + if (kb > 0) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + double len = Math.sqrt(dx * dx + dz * dz); + if (len > 0) { + double kbX = (dx / len) * kb * 0.5; + double kbZ = (dz / len) * kb * 0.5; + double kbY = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1; + target.addVelocity(kbX, kbY, kbZ); + target.velocityChanged = true; + } + } + + applyEffects(target); + return true; + } + + protected void applyEffects(EntityLivingBase target) { + for (AbilityPotionEffect effect : effects) { + effect.apply(target); + } + } + + /** + * Set the effects list from the ability's configured effects. + */ + public void setAnchorData(EnergyAnchorData anchor) { + this.anchorData = anchor != null ? anchor.copy() : new EnergyAnchorData(AnchorPoint.FRONT); + } + + public void setEffects(List effects) { + if (effects == null || effects.isEmpty()) { + this.effects = new ArrayList<>(); + } else { + // Deep copy: entity must not share the ability's effects list or its entries. + this.effects = new ArrayList<>(effects.size()); + for (AbilityPotionEffect effect : effects) { + this.effects.add(effect.copy()); + } + } + } + + protected boolean doExplosion() { + if (previewMode) return false; // Skip explosion in preview mode + if (worldObj.isRemote) return false; // Explosions are server-side only + float explosionRad = getExplosionRadius(); + if (Float.isNaN(explosionRad) || explosionRad <= 0) return false; + final double explosionRadSq = explosionRad * explosionRad; + final float baseDamage = getDamage(); + final float baseKnockback = getKnockback(); + final float damageFalloff = getExplosionDamageFalloff(); + spawnExplosionRenderEntity(explosionRad); + spawnExplosionVisuals(explosionRad); + worldObj.playSoundEffect(posX, posY, posZ, "random.explode", 1.0f, 1.0f); + + Entity owner = getOwnerEntity(); + + AxisAlignedBB explosionBox = AxisAlignedBB.getBoundingBox( + posX - explosionRad, posY - explosionRad, posZ - explosionRad, + posX + explosionRad, posY + explosionRad, posZ + explosionRad + ); + + @SuppressWarnings("unchecked") + List targets = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, explosionBox); + boolean anyDamaged = false; + + for (EntityLivingBase target : targets) { + if (target == owner) continue; + if (shouldIgnoreExplosionTarget(target)) continue; + + // Measure distance to nearest point on entity's bounding box, not feet position. + // Using feet position (target.posY) causes explosions at impact height to miss + // entities standing below — e.g. a projectile hitting at eye height (~1.62 above feet) + // would measure dist=1.62, failing a radius<=1.6 check despite a direct hit. + if (target.boundingBox == null) continue; + double closestX = Math.max(target.boundingBox.minX, Math.min(posX, target.boundingBox.maxX)); + double closestY = Math.max(target.boundingBox.minY, Math.min(posY, target.boundingBox.maxY)); + double closestZ = Math.max(target.boundingBox.minZ, Math.min(posZ, target.boundingBox.maxZ)); + double dx = closestX - posX; + double dy = closestY - posY; + double dz = closestZ - posZ; + double distSq = dx * dx + dy * dy + dz * dz; + if (distSq > explosionRadSq) continue; + + float falloff = 1.0f; + if (damageFalloff != 0.0f && distSq > 0.0D) { + float dist = (float) Math.sqrt(distSq); + falloff = 1.0f - (dist / explosionRad) * damageFalloff; + } + if (applyDamage(target, baseDamage * falloff, baseKnockback * falloff)) { + anyDamaged = true; + } + } + + tryDestroyTerrain(explosionRad); + return anyDamaged; + } + + /** + * Explosion safety filter. + * Reuses standard projectile-friendly checks (owner, faction, party). + */ + protected boolean shouldIgnoreExplosionTarget(EntityLivingBase target) { + if (target == null) return true; + return shouldIgnoreEntity(target); + } + + /** + * Clamp a point to the nearest point inside the provided AABB. + */ + protected Vec3 closestPointOnBoundingBox(AxisAlignedBB box, double x, double y, double z) { + if (box == null) return null; + double closestX = Math.max(box.minX, Math.min(x, box.maxX)); + double closestY = Math.max(box.minY, Math.min(y, box.maxY)); + double closestZ = Math.max(box.minZ, Math.min(z, box.maxZ)); + return Vec3.createVectorHelper(closestX, closestY, closestZ); + } + + /** + * Spawn a packet-driven client preview so explosions are visible as geometry, + * not only as particles. + */ + protected void spawnExplosionRenderEntity(float explosionRad) { + if (worldObj == null || worldObj.isRemote) return; + float renderRad = Math.max(0.75f, Math.min(explosionRad, EnergyCombatData.MAX_EXPLOSION_RADIUS)); + EntityEnergyExplosion fx = new EntityEnergyExplosion(worldObj, this, renderRad); + EnergyExplosionSpawnPacket.sendToTracking(getExplosionVisualInstanceId(), fx, this); + } + + protected String getExplosionVisualInstanceId() { + return "energy_explosion_" + UUID.randomUUID(); + } + + /** + * Shared voxel-style explosion VFX for all energy projectile abilities. + */ + protected void spawnExplosionVisuals(float explosionRad) { + if (worldObj == null) return; + + float visualRad = Math.max(0.75f, Math.min(explosionRad, EnergyCombatData.MAX_EXPLOSION_RADIUS)); + int coreBursts = Math.max(1, Math.min(4, Math.round(visualRad * 0.35f))); + int shellCount = Math.max(1, Math.min(3, Math.round(visualRad / 3.5f) + 1)); + + // Core flash. + emitRandomBurstParticle("largeexplode", coreBursts, visualRad * 0.10, visualRad * 0.08, visualRad * 0.10, 0.01); + + // Expanding voxel shells. + for (int i = 1; i <= shellCount; i++) { + double frac = i / (double) shellCount; + double shellRadius = visualRad * (0.35D + 0.65D * frac); + spawnVoxelShell(shellRadius, i, visualRad); + } + + // Residual smoke volume. + int smokeCount = Math.max(6, Math.min(40, Math.round(visualRad * 4.5f))); + emitRandomBurstParticle("smoke", smokeCount, visualRad * 0.45, visualRad * 0.30, visualRad * 0.45, 0.01); + + // Pull block fragments for stronger voxel feel. + spawnVoxelDebris(visualRad); + } + + /** + * Emit random burst particles centered around this explosion. + */ + protected void emitRandomBurstParticle(String particle, int count, + double spreadX, double spreadY, double spreadZ, + double speed) { + if (worldObj == null || count <= 0 || particle == null || particle.isEmpty()) return; + + if (worldObj.isRemote) { + for (int i = 0; i < count; i++) { + double px = posX + (rand.nextDouble() - 0.5D) * 2.0D * spreadX; + double py = posY + (rand.nextDouble() - 0.5D) * 2.0D * spreadY; + double pz = posZ + (rand.nextDouble() - 0.5D) * 2.0D * spreadZ; + double mx = rand.nextGaussian() * speed; + double my = rand.nextGaussian() * speed; + double mz = rand.nextGaussian() * speed; + worldObj.spawnParticle(particle, px, py, pz, mx, my, mz); + } + return; + } + + if (worldObj instanceof WorldServer) { + ((WorldServer) worldObj).func_147487_a(particle, posX, posY, posZ, count, spreadX, spreadY, spreadZ, speed); + } + } + + /** + * Emits a single directed voxel particle. + * Uses count=0 packet mode on server so motion values are preserved. + */ + protected void emitVoxelParticle(String particle, double x, double y, double z, + double motionX, double motionY, double motionZ) { + if (worldObj == null || particle == null || particle.isEmpty()) return; + + if (worldObj.isRemote) { + worldObj.spawnParticle(particle, x, y, z, motionX, motionY, motionZ); + return; + } + + if (worldObj instanceof WorldServer) { + ((WorldServer) worldObj).func_147487_a(particle, x, y, z, 0, motionX, motionY, motionZ, 1.0D); + } + } + + /** + * Spawn one cubic shell of explosion particles to get a blocky/voxel silhouette. + */ + protected void spawnVoxelShell(double shellRadius, int shellIndex, float visualRad) { + int steps = Math.max(2, Math.min(4, (int) Math.ceil(shellRadius * 0.55D))); + double cell = shellRadius / steps; + double jitter = Math.min(0.15D, cell * 0.20D); + double shellSpeed = 0.03D + (shellRadius / Math.max(1.0D, visualRad)) * 0.05D; + + for (int ix = -steps; ix <= steps; ix++) { + for (int iy = -steps; iy <= steps; iy++) { + for (int iz = -steps; iz <= steps; iz++) { + int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz))); + if (edge != steps) continue; + if (((ix + iy + iz + shellIndex) & 1) != 0) continue; + + double px = posX + ix * cell + (rand.nextDouble() - 0.5D) * jitter; + double py = posY + iy * cell + (rand.nextDouble() - 0.5D) * jitter; + double pz = posZ + iz * cell + (rand.nextDouble() - 0.5D) * jitter; + + double nx = ix; + double ny = iy; + double nz = iz; + double len = Math.sqrt(nx * nx + ny * ny + nz * nz); + if (len < 0.001D) { + ny = 1.0D; + len = 1.0D; + } + nx /= len; + ny /= len; + nz /= len; + + emitVoxelParticle("explode", px, py, pz, nx * shellSpeed, ny * shellSpeed, nz * shellSpeed); + + if (((ix + iy + iz + shellIndex) % 3) == 0) { + emitVoxelParticle("smoke", px, py, pz, nx * shellSpeed * 0.35D, ny * shellSpeed * 0.35D, nz * shellSpeed * 0.35D); + } + } + } + } + } + + /** + * Spawn debris particles using nearby block textures. + */ + protected void spawnVoxelDebris(float visualRad) { + if (worldObj == null) return; + + int count = Math.max(4, Math.min(24, Math.round(visualRad * 2.5f))); + for (int i = 0; i < count; i++) { + double ox = (rand.nextDouble() - 0.5D) * visualRad * 1.2D; + double oy = (rand.nextDouble() - 0.35D) * visualRad * 0.9D; + double oz = (rand.nextDouble() - 0.5D) * visualRad * 1.2D; + + int bx = MathHelper.floor_double(posX + ox); + int by = MathHelper.floor_double(posY + oy); + int bz = MathHelper.floor_double(posZ + oz); + + Block block = worldObj.getBlock(bx, by, bz); + if (block == null || block == Blocks.air) continue; + + int blockId = Block.getIdFromBlock(block); + if (blockId <= 0) continue; + int meta = worldObj.getBlockMetadata(bx, by, bz); + + String particle = "blockcrack_" + blockId + "_" + Math.max(0, meta); + emitVoxelParticle( + particle, + posX + ox * 0.55D, + posY + oy * 0.55D, + posZ + oz * 0.55D, + ox * 0.03D, oy * 0.03D, oz * 0.03D + ); + } + } + + /** + * Optional terrain damage for energy explosions. + * Controlled server-side by ConfigEnergy.EnableEnergyExplosionBlockDamage. + */ + protected void tryDestroyTerrain(float explosionRad) { + if (worldObj == null || worldObj.isRemote) return; + if (!ConfigEnergy.EnableEnergyExplosionBlockDamage) return; + if (!worldObj.getGameRules().getGameRuleBooleanValue("mobGriefing")) return; + + float terrainRad = Math.max(0.5f, Math.min(explosionRad, EnergyCombatData.MAX_EXPLOSION_RADIUS)); + int minX = MathHelper.floor_double(posX - terrainRad); + int maxX = MathHelper.floor_double(posX + terrainRad); + int minY = MathHelper.floor_double(posY - terrainRad); + int maxY = MathHelper.floor_double(posY + terrainRad); + int minZ = MathHelper.floor_double(posZ - terrainRad); + int maxZ = MathHelper.floor_double(posZ + terrainRad); + int worldMaxY = Math.max(0, worldObj.getActualHeight() - 1); + if (maxY < 0 || minY > worldMaxY) return; + float resistanceCutoff = Math.max(4.0f, terrainRad * 6.0f); + + Explosion context = new Explosion(worldObj, this, posX, posY, posZ, terrainRad); + context.isFlaming = false; + context.isSmoking = true; + int lastChunkX = Integer.MIN_VALUE; + int lastChunkZ = Integer.MIN_VALUE; + boolean lastChunkLoaded = false; + + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + double cx = x + 0.5D - posX; + double cy = y + 0.5D - posY; + double cz = z + 0.5D - posZ; + + // Chebyshev metric yields a voxel/cubic blast shape. + double chebyshev = Math.max(Math.abs(cx), Math.max(Math.abs(cy), Math.abs(cz))); + if (chebyshev > terrainRad) continue; + + // Soften cube corners a bit for a less artificial crater edge. + double normalized = chebyshev / terrainRad; + if (normalized > 0.72D && rand.nextDouble() < (normalized - 0.72D) * 1.4D) continue; + if (y < 0 || y > worldMaxY) continue; + + int chunkX = x >> 4; + int chunkZ = z >> 4; + if (chunkX != lastChunkX || chunkZ != lastChunkZ) { + lastChunkX = chunkX; + lastChunkZ = chunkZ; + lastChunkLoaded = worldObj.getChunkProvider().chunkExists(chunkX, chunkZ); + } + if (!lastChunkLoaded) continue; + + Block block = worldObj.getBlock(x, y, z); + if (block == null || block == Blocks.air || block == Blocks.bedrock) continue; + Material material = block.getMaterial(); + if (material == null || material == Material.air) continue; + + float resistance = block.getExplosionResistance(this, worldObj, x, y, z, posX, posY, posZ); + if (resistance > resistanceCutoff) continue; + + try { + block.onBlockExploded(worldObj, x, y, z, context); + } catch (Exception ignored) { + } + } + } + } + } + + // ==================== LAUNCH HELPERS ==================== + + /** + * Snaps the projectile position to the owner's look vector on launch. + * This ensures projectiles launch aligned with the owner's facing direction + * rather than from the last anchor point position. + * Should be called in startMoving/startFiring BEFORE setting startX/Y/Z. + */ + protected void snapToLookVector() { + setLookVectorLaunchPosition(true); + } + + /** + * Shared launch transition: exit charging, snap to look-vector launch origin, + * sync start position, and optionally reset interpolation state. + * + * @param resetInterpolationState true to reset prev/lastTick/interp state to launch origin. + * @return true when look-vector launch origin was resolved from owner/look data. + */ + protected boolean beginLookVectorLaunch(boolean resetInterpolationState) { + setCharging(false); + Entity owner = getOwnerEntity(); + boolean positioned = false; + if (owner instanceof EntityLivingBase && shouldSnapLaunchToLookVector((EntityLivingBase) owner)) { + positioned = setLookVectorLaunchPosition((EntityLivingBase) owner, getOwnerLookVector(), true); + } + syncStartPositionToCurrent(); + if (resetInterpolationState) { + syncPositionStateToCurrent(true); + } + return positioned; + } + + /** + * Shared launch transition with explicit owner/look vector data. + */ + protected boolean beginLookVectorLaunch(EntityLivingBase owner, Vec3 look, boolean resetInterpolationState) { + setCharging(false); + boolean positioned = shouldSnapLaunchToLookVector(owner) && setLookVectorLaunchPosition(owner, look, true); + syncStartPositionToCurrent(); + if (resetInterpolationState) { + syncPositionStateToCurrent(true); + } + return positioned; + } + + /** + * Determines whether the projectile should snap to the look-vector launch origin on fire. + * By default, player-cast projectiles snap (launch from eye position along crosshair), + * and NPC projectiles keep their anchor charge origin. + * When {@code anchorData.launchFromAnchor} is true, snapping is disabled so the + * projectile launches from its configured anchor position instead. + */ + protected boolean shouldSnapLaunchToLookVector(EntityLivingBase owner) { + if (anchorData.launchFromAnchor) { + return false; + } + return owner instanceof EntityPlayer; + } + + /** + * Default preview launch: snap to look-vector origin and fire along look. + */ + protected void startPreviewFiringDefault() { + beginLookVectorLaunch(true); + setMotionAlongLookVectorOrFallback(getSpeed(), getSpeed(), 0, 0); + } + + /** + * Default active launch: snap to look-vector origin and fire toward target when available. + */ + protected void startMovingTowardTargetDefault(EntityLivingBase target) { + beginLookVectorLaunch(false); + setMotionTowardTargetOrLookVector(target, posX, posY, posZ, getSpeed(), getSpeed(), 0, 0); + } + + /** + * Default active launch from fixed origin fields (used by beam-like projectiles). + */ + protected void startMovingTowardTargetFromStartDefault(EntityLivingBase target) { + beginLookVectorLaunch(false); + setMotionTowardTargetOrLookVector(target, startX, startY, startZ, getSpeed(), getSpeed(), 0, 0); + } + + /** + * Default active launch strictly along look vector. + */ + protected void startMovingAlongLookVectorDefault() { + beginLookVectorLaunch(false); + setMotionAlongLookVectorOrFallback(getSpeed(), getSpeed(), 0, 0); + } + + /** + * Resolve the owner's look vector. + * Falls back to yaw/pitch math if look vector is unavailable. + */ + protected Vec3 getOwnerLookVector() { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityLivingBase)) return null; + + Vec3 look = owner.getLookVec(); + if (look != null) return look; + + float yaw = (float) Math.toRadians(owner.rotationYaw); + float pitch = (float) Math.toRadians(owner.rotationPitch); + return Vec3.createVectorHelper( + -Math.sin(yaw) * Math.cos(pitch), + -Math.sin(pitch), + Math.cos(yaw) * Math.cos(pitch) + ); + } + + /** + * Shared launch origin: owner eye position + look-vector offset. + * + * @param syncPositionState When true, sync prev/lastTick/interp targets to this position. + */ + protected boolean setLookVectorLaunchPosition(boolean syncPositionState) { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityLivingBase)) return false; + Vec3 look = getOwnerLookVector(); + if (look == null) return false; + return setLookVectorLaunchPosition((EntityLivingBase) owner, look, syncPositionState); + } + + /** + * Shared launch origin using provided owner/look data. + */ + protected boolean setLookVectorLaunchPosition(EntityLivingBase owner, Vec3 look, boolean syncPositionState) { + if (owner == null || look == null) return false; + + double originX = owner.posX; + double originY = owner.posY + owner.getEyeHeight(); + double originZ = owner.posZ; + + float frontDist = computeLaunchFrontDistance(owner, look, originX, originY, originZ); + double newX = originX + look.xCoord * frontDist; + double newY = originY + look.yCoord * frontDist; + double newZ = originZ + look.zCoord * frontDist; + + setPosition(newX, newY, newZ); + if (syncPositionState) { + syncPositionState(newX, newY, newZ, true); + } + return true; + } + + /** + * Radius used to clear the caster hitbox on launch. + * Subclasses may override if their effective launch footprint differs from {@code size}. + */ + protected float getLaunchClearanceRadius() { + return Math.max(0.1f, size * 0.5f); + } + + private float computeLaunchFrontDistance(EntityLivingBase owner, Vec3 look, double originX, double originY, double originZ) { + // Legacy baseline offset retained as lower bound. + float baseline = size * 0.4f; + float clearance = getLaunchClearanceRadius() + 0.05f; + + AxisAlignedBB bb = owner.boundingBox; + if (bb == null) { + return Math.max(baseline, owner.width * 0.5f + clearance); + } + + double dx = look.xCoord; + double dy = look.yCoord; + double dz = look.zCoord; + + double tx = computeRayExitT(originX, dx, bb.minX, bb.maxX); + double ty = computeRayExitT(originY, dy, bb.minY, bb.maxY); + double tz = computeRayExitT(originZ, dz, bb.minZ, bb.maxZ); + + double tExit = Math.min(tx, Math.min(ty, tz)); + if (Double.isInfinite(tExit) || tExit < 0) { + return Math.max(baseline, owner.width * 0.5f + clearance); + } + + return (float) Math.max(baseline, tExit + clearance); + } + + private double computeRayExitT(double origin, double dir, double min, double max) { + final double EPS = 1.0e-6; + if (dir > EPS) { + return (max - origin) / dir; + } else if (dir < -EPS) { + return (min - origin) / dir; + } + return Double.POSITIVE_INFINITY; + } + + /** + * Set projectile motion along owner look vector. + * + * @return true if owner/look were available. + */ + protected boolean setMotionAlongLookVector(float speed) { + Vec3 look = getOwnerLookVector(); + if (look == null) return false; + + motionX = look.xCoord * speed; + motionY = look.yCoord * speed; + motionZ = look.zCoord * speed; + return true; + } + + /** + * Set motion along owner look vector or apply explicit fallback values. + * When {@code launchFromAnchor} is true, ray-casts from the owner's eye to find the + * crosshair target point and aims from the projectile's anchor position toward it. + */ + protected void setMotionAlongLookVectorOrFallback(float speed, double fallbackX, double fallbackY, double fallbackZ) { + if (anchorData.launchFromAnchor && setMotionTowardLookTarget(speed)) { + return; + } + if (!setMotionAlongLookVector(speed)) { + motionX = fallbackX; + motionY = fallbackY; + motionZ = fallbackZ; + } + } + + /** + * Ray-cast from the owner's eye along the look vector to find the crosshair target point, + * then set motion from the projectile's current position toward that point. + * Used when {@code launchFromAnchor} is true so projectiles fired from offset anchor + * positions converge to the crosshair rather than flying parallel to the look direction. + */ + protected boolean setMotionTowardLookTarget(float speed) { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityLivingBase)) return false; + Vec3 look = getOwnerLookVector(); + if (look == null) return false; + + EntityLivingBase livingOwner = (EntityLivingBase) owner; + double eyeX = livingOwner.posX; + double eyeY = livingOwner.posY + livingOwner.getEyeHeight(); + double eyeZ = livingOwner.posZ; + + double maxDist = 200.0; + Vec3 start = Vec3.createVectorHelper(eyeX, eyeY, eyeZ); + Vec3 end = Vec3.createVectorHelper( + eyeX + look.xCoord * maxDist, + eyeY + look.yCoord * maxDist, + eyeZ + look.zCoord * maxDist + ); + + double targetX, targetY, targetZ; + MovingObjectPosition hit = worldObj.rayTraceBlocks(start, end); + if (hit != null && hit.hitVec != null) { + targetX = hit.hitVec.xCoord; + targetY = hit.hitVec.yCoord; + targetZ = hit.hitVec.zCoord; + } else { + targetX = eyeX + look.xCoord * maxDist; + targetY = eyeY + look.yCoord * maxDist; + targetZ = eyeZ + look.zCoord * maxDist; + } + + double dx = targetX - posX; + double dy = targetY - posY; + double dz = targetZ - posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len <= 0.0001) return false; + + motionX = (dx / len) * speed; + motionY = (dy / len) * speed; + motionZ = (dz / len) * speed; + return true; + } + + /** + * Set projectile motion toward a target from a given source point. + * + * @return true if target was valid and motion was updated. + */ + protected boolean setMotionTowardTarget(EntityLivingBase target, double sourceX, double sourceY, double sourceZ, float speed) { + if (target == null) return false; + + double dx = target.posX - sourceX; + double dy = (target.posY + target.getEyeHeight()) - sourceY; + double dz = target.posZ - sourceZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len <= 0.0001) return false; + + motionX = (dx / len) * speed; + motionY = (dy / len) * speed; + motionZ = (dz / len) * speed; + return true; + } + + /** + * Set motion toward target from source point; when target is unavailable, + * fall back to owner look vector, then explicit fallback values. + */ + protected void setMotionTowardTargetOrLookVector(EntityLivingBase target, double sourceX, double sourceY, double sourceZ, float speed, + double fallbackX, double fallbackY, double fallbackZ) { + if (!setMotionTowardTarget(target, sourceX, sourceY, sourceZ, speed)) { + setMotionAlongLookVectorOrFallback(speed, fallbackX, fallbackY, fallbackZ); + } + } + + /** + * Sync start position (distance origin) to the current entity position. + */ + protected void syncStartPositionToCurrent() { + startX = posX; + startY = posY; + startZ = posZ; + } + + /** + * Sync prev/lastTick and optional interpolation state to an explicit position. + */ + protected void syncPositionState(double x, double y, double z, boolean resetInterpolation) { + prevPosX = x; + prevPosY = y; + prevPosZ = z; + lastTickPosX = x; + lastTickPosY = y; + lastTickPosZ = z; + + if (resetInterpolation) { + interpTargetX = x; + interpTargetY = y; + interpTargetZ = z; + interpTargetMotionX = motionX; + interpTargetMotionY = motionY; + interpTargetMotionZ = motionZ; + interpSteps = 0; + } + } + + /** + * Sync prev/lastTick and optional interpolation state to current entity position. + */ + public void syncPositionStateToCurrent(boolean resetInterpolation) { + syncPositionState(posX, posY, posZ, resetInterpolation); + } + + // ==================== CHARGING METHODS (projectile-specific) ==================== + + /** + * Shared charging-state bootstrap used by both world and preview setup paths. + */ + protected void setupChargingState(EnergyAnchorData anchor, int chargeDuration) { + setCharging(true); + this.chargeDuration = chargeDuration; + this.chargeTick = 0; + this.anchorData = anchor; + } + + /** + * Shared preview bootstrap used by projectile preview setup methods. + */ + protected void setupPreviewState(EntityLivingBase owner, EnergyDisplayData display, + EnergyLightningData lightning, EnergyAnchorData anchor, + int chargeDuration) { + this.setPreviewMode(true); + this.setPreviewOwner(owner); + this.displayData = display != null ? display.copy() : new EnergyDisplayData(); + this.lightningData = lightning != null ? lightning.copy() : new EnergyLightningData(); + setupChargingState(anchor, chargeDuration); + } + + /** + * Set size and render-size state to a single value. + */ + protected void setVisualSize(float value) { + this.size = value; + this.renderCurrentSize = value; + this.prevRenderSize = value; + } + + /** + * Set entity/start state to a fixed position used as charging/launch origin. + */ + protected void setChargeOrigin(Vec3 pos) { + if (pos == null) return; + this.setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + syncPositionState(pos.xCoord, pos.yCoord, pos.zCoord, true); + this.startX = pos.xCoord; + this.startY = pos.yCoord; + this.startZ = pos.zCoord; + } + + /** + * Resolve and apply charging/launch origin from anchor position. + */ + protected void setChargeOriginFromAnchor(EntityLivingBase owner, EnergyAnchorData anchor) { + if (owner == null || anchor == null) return; + setChargeOrigin(AnchorPointHelper.calculateAnchorPosition(owner, anchor)); + } + + /** + * Resolve and apply charging/launch origin from anchor position with forward offset. + */ + protected void setChargeOriginFromAnchor(EntityLivingBase owner, EnergyAnchorData anchor, float offsetDistance) { + if (owner == null || anchor == null) return; + setChargeOrigin(AnchorPointHelper.calculateAnchorPosition(owner, anchor, offsetDistance)); + } + + /** + * Zero current motion. + */ + protected void clearMotion() { + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + } + + /** + * 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) { + setupChargingState(anchor, chargeDuration); + this.targetSize = this.size; + setVisualSize(0.01f); + clearMotion(); + } + + /** + * 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 IEntity getOwner() { + if (previewMode) return null; + if (getOwnerEntity() == null) return null; + return NpcAPI.Instance().getIEntity(getOwnerEntity()); + } + + 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); + } + + public IEntity getTarget() { + if (getTargetEntity() == null) return null; + return NpcAPI.Instance().getIEntity(getTargetEntity()); + } + + /** + * Check if an entity should be ignored for collision. + * Ignores: the owner, same-faction NPCs, passive NPCs, NPCs friendly to player owner, + * party members (if friendly fire is off), and other projectiles from the same caster. + */ + protected boolean shouldIgnoreEntity(Entity entity) { + Entity owner = getOwnerEntity(); + if (entity == owner) return true; + + // Ignore other projectiles from the same caster (e.g. multi-projectile abilities) + if (entity instanceof EntityEnergyProjectile) { + EntityEnergyProjectile other = (EntityEnergyProjectile) entity; + if (other.ownerEntityId == this.ownerEntityId) return true; + } + + // NPC target checks + if (entity instanceof EntityNPCInterface) { + EntityNPCInterface targetNpc = (EntityNPCInterface) entity; + + // Ignore passive NPCs + if (targetNpc.faction.isPassive) return true; + + // NPC owner: ignore same-faction NPCs + if (owner instanceof EntityNPCInterface) { + EntityNPCInterface ownerNpc = (EntityNPCInterface) owner; + if (ownerNpc.faction.id == targetNpc.faction.id) return true; + } + + // Player owner: ignore NPCs whose faction is friendly to the player + if (owner instanceof EntityPlayer) { + if (targetNpc.faction.isFriendlyToPlayer((EntityPlayer) owner)) return true; + } + } + + // Party friendly fire check: player owner hitting another player + if (owner instanceof EntityPlayer && entity instanceof EntityPlayer) { + EntityPlayer ownerPlayer = (EntityPlayer) owner; + EntityPlayer targetPlayer = (EntityPlayer) entity; + PlayerData ownerData = PlayerData.get(ownerPlayer); + PlayerData targetData = PlayerData.get(targetPlayer); + if (ownerData.partyUUID != null && ownerData.partyUUID.equals(targetData.partyUUID)) { + Party party = PartyController.Instance().getParty(ownerData.partyUUID); + if (party != null && !party.friendlyFire()) return true; + } + } + + return false; + } + + // ==================== VISUAL GETTERS & SETTERS ==================== + + public float getSize() { + return size; + } + + public void setProjectileSize(float size) { + this.size = size; + this.renderCurrentSize = size; + this.prevRenderSize = size; + } + + /** + * 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; + } + + // ==================== ROTATION GETTERS ==================== + + public float getInterpolatedRotationX(float partialTicks) { + return this.prevRotationValX + (this.rotationValX - this.prevRotationValX) * partialTicks; + } + + public float getInterpolatedRotationY(float partialTicks) { + return this.prevRotationValY + (this.rotationValY - this.prevRotationValY) * partialTicks; + } + + public float getInterpolatedRotationZ(float partialTicks) { + return this.prevRotationValZ + (this.rotationValZ - this.prevRotationValZ) * partialTicks; + } + + public float getInterpolatedSize(float partialTicks) { + return this.prevRenderSize + (this.renderCurrentSize - this.prevRenderSize) * partialTicks; + } + + // ==================== LIFESPAN GETTERS & SETTERS ==================== + + public float getMaxDistance() { + return lifespanData.getMaxDistance(); + } + + public void setMaxDistance(float distance) { + lifespanData.setMaxDistance(distance); + } + + public int getMaxLifetime() { + return lifespanData.getMaxLifetime(); + } + + public void setMaxLifetime(int ticks) { + lifespanData.setMaxLifetime(ticks); + } + + // ==================== COMBAT GETTERS & SETTERS ==================== + + /** + * Accumulated proportional damage multiplier (0.0-1.0). + * Accumulates multiplicatively when the projectile breaks through barriers, is reflected, + * or any other system reduces its effective damage. Used by ability extenders to scale + * recalculated damage proportionally. + */ + private float damageMultiplier = 1.0f; + + public float getDamageMultiplier() { + return damageMultiplier; + } + + public float getDamage() { + return combatData.getDamage(); + } + + public void setCombatDamage(float damage) { + combatData.setDamage(damage); + } + + public float getKnockback() { + return combatData.knockback; + } + + public void setCombatKnockback(float knockback) { + combatData.setKnockback(knockback); + } + + public float getKnockbackUp() { + return combatData.knockbackUp; + } + + public void setCombatKnockbackUp(float knockbackUp) { + combatData.setKnockbackUp(knockbackUp); + } + + public boolean isExplosive() { + return combatData.isExplosive(); + } + + public void setExplosive(boolean explosive) { + combatData.setExplosive(explosive); + } + + public float getExplosionRadius() { + return combatData.getExplosionRadius(); + } + + public void setExplosionRadius(float radius) { + combatData.setExplosionRadius(radius); + } + + public float getExplosionDamageFalloff() { + return combatData.explosionDamageFalloff; + } + + public void setExplosionDamageFalloff(float falloff) { + combatData.setExplosionDamageFalloff(falloff); + } + + public int getHitType() { + return combatData.hitType.ordinal(); + } + + public void setHitType(int hitType) { + combatData.hitType = HitType.fromOrdinal(hitType); + } + + public int getMultiHitDelayTicks() { + return combatData.multiHitDelayTicks; + } + + public void setMultiHitDelayTicks(int delayTicks) { + combatData.multiHitDelayTicks = Math.max(1, delayTicks); + } + + public int getMaxHits() { + return combatData.getMaxHits(); + } + + public void setMaxHits(int maxHits) { + combatData.setMaxHits(maxHits); + } + + protected boolean canHitEntityNow(EntityLivingBase entity) { + if (entity == null) return false; + if (combatData.hitType != HitType.SINGLE && hasReachedMaxHits()) return false; + + int entityId = entity.getEntityId(); + switch (combatData.hitType) { + case PIERCE: + return !hitOnceEntities.contains(entityId); + case MULTI: + Integer lastHitTick = lastHitTickByEntity.get(entityId); + if (lastHitTick == null) return true; + int delay = Math.max(1, combatData.multiHitDelayTicks); + return ticksExisted - lastHitTick >= delay; + case SINGLE: + default: + return !hasHit; + } + } + + protected void recordEntityHit(EntityLivingBase entity) { + if (entity == null) return; + int entityId = entity.getEntityId(); + hitOnceEntities.add(entityId); + lastHitTickByEntity.put(entityId, ticksExisted); + hitCount++; + } + + protected boolean hasReachedMaxHits() { + if (combatData.hitType == HitType.SINGLE) return false; + return hitCount >= combatData.getMaxHits(); + } + + protected boolean shouldTerminateAfterHit() { + if (combatData.hitType == HitType.SINGLE) return true; + return hasReachedMaxHits(); + } + + /** + * Shared block raytrace helper used by most projectile types. + */ + protected MovingObjectPosition rayTraceBlocks(double fromX, double fromY, double fromZ, double toX, double toY, double toZ) { + Vec3 currentPos = Vec3.createVectorHelper(fromX, fromY, fromZ); + Vec3 nextPos = Vec3.createVectorHelper(toX, toY, toZ); + return worldObj.func_147447_a(currentPos, nextPos, false, true, false); + } + + /** + * Shared block-hit handling: fires block impact hook, optional explosion, and kills projectile. + */ + protected boolean handleBlockImpact(MovingObjectPosition blockHit, boolean explodeAtHitPoint) { + if (blockHit == null || blockHit.typeOfHit != MovingObjectPosition.MovingObjectType.BLOCK) return false; + + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } + hasHit = true; + + if (isExplosive()) { + if (explodeAtHitPoint && blockHit.hitVec != null) { + posX = blockHit.hitVec.xCoord; + posY = blockHit.hitVec.yCoord; + posZ = blockHit.hitVec.zCoord; + } + doExplosion(); + } + + this.setDead(); + return true; + } + + /** + * Apply projectile hit behavior to a target and return true if the projectile terminated. + */ + protected boolean processEntityHit(EntityLivingBase entity, double impactX, double impactY, double impactZ) { + if (entity == null || shouldIgnoreEntity(entity) || !canHitEntityNow(entity)) return false; + + boolean successfulHit; + if (isExplosive()) { + Vec3 impactPoint = resolveEntityImpactPoint(entity, impactX, impactY, impactZ); + double oldX = posX; + double oldY = posY; + double oldZ = posZ; + posX = impactPoint.xCoord; + posY = impactPoint.yCoord; + posZ = impactPoint.zCoord; + successfulHit = doExplosion(); + posX = oldX; + posY = oldY; + posZ = oldZ; + } else { + successfulHit = applyDamage(entity); + } + + if (successfulHit) { + recordEntityHit(entity); + } + + if ((successfulHit && shouldTerminateAfterHit()) || (!successfulHit && combatData.hitType == HitType.SINGLE)) { + hasHit = true; + this.setDead(); + return true; + } + + return false; + } + + /** + * Resolve a stable impact point on the target so explosive collisions use actual contact. + */ + protected Vec3 resolveEntityImpactPoint(EntityLivingBase entity, double impactX, double impactY, double impactZ) { + if (entity == null || entity.boundingBox == null) { + return Vec3.createVectorHelper(impactX, impactY, impactZ); + } + + Vec3 segmentStart = Vec3.createVectorHelper(posX, posY, posZ); + Vec3 segmentEnd = Vec3.createVectorHelper(impactX, impactY, impactZ); + AxisAlignedBB expandedBox = entity.boundingBox.expand(1.0e-4, 1.0e-4, 1.0e-4); + MovingObjectPosition intercept = expandedBox.calculateIntercept(segmentStart, segmentEnd); + if (intercept != null && intercept.hitVec != null) { + return intercept.hitVec; + } + + Vec3 closest = closestPointOnBoundingBox(entity.boundingBox, impactX, impactY, impactZ); + return closest != null ? closest : Vec3.createVectorHelper(impactX, impactY, impactZ); + } + + /** + * Scan entities in a hitbox and process the first/each valid hit based on hit mode. + */ + protected boolean processEntitiesInHitBox(AxisAlignedBB hitBox, double impactX, double impactY, double impactZ) { + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); + for (EntityLivingBase entity : entities) { + if (processEntityHit(entity, impactX, impactY, impactZ)) { + return true; + } + } + return false; + } + + protected boolean handleSolidCollisionTermination() { + if (!this.isCollidedHorizontally && !this.isCollidedVertically) return false; + + if (!worldObj.isRemote) { + hasHit = true; + if (isExplosive()) { + doExplosion(); + } + } + this.setDead(); + return true; + } + + // ==================== HOMING GETTERS & SETTERS ==================== + + public boolean isHoming() { + return homingData.isHoming(); + } + + public void setHomingEnabled(boolean homing) { + homingData.setHoming(homing); + } + + public float getHomingStrength() { + return homingData.getHomingStrength(); + } + + public void setHomingStrength(float strength) { + homingData.setHomingStrength(strength); + } + + public float getHomingRange() { + return homingData.getHomingRange(); + } + + public void setHomingRange(float range) { + homingData.setHomingRange(range); + } + + // ==================== SPEED & ANCHOR GETTERS & SETTERS ==================== + + public float getSpeed() { + return homingData.getSpeed(); + } + + public void setSpeed(float speed) { + float oldSpeed = homingData.getSpeed(); + homingData.setSpeed(speed); + // Rescale current motion vector to match new speed + if (addedToChunk && !worldObj.isRemote) { + double len = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + if (len > 0) { + double scale = speed / len; + motionX *= scale; + motionY *= scale; + motionZ *= scale; + } + } + } + + public AnchorPoint getAnchorPoint() { + return anchorData.getAnchorPoint(); + } + + public int getAnchor() { + return anchorData.getAnchor(); + } + + public float getAnchorOffsetX() { + return anchorData.getAnchorOffsetX(); + } + + public float getAnchorOffsetY() { + return anchorData.getAnchorOffsetY(); + } + + public float getAnchorOffsetZ() { + return anchorData.getAnchorOffsetZ(); + } + + // ==================== MOVEMENT GETTERS ==================== + + public double getStartX() { + return startX; + } + + public double getStartY() { + return startY; + } + + public double getStartZ() { + return startZ; + } + + // ==================== STATE GETTERS ==================== + + public boolean getHasHit() { + return hasHit; + } + + @Override + public boolean hasLightningEffect() { + return super.hasLightningEffect() || getBarrierSparkTicks() > 0; + } + + // ==================== NBT ==================== + + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBaseNBT(nbt); + writeProjectileNBT(nbt); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBaseNBT(nbt); + readProjectileNBT(nbt); + } + + /** + * Read base projectile properties from NBT. + */ + protected void readBaseNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + + this.size = sanitize(nbt.getFloat("Size"), 1.0f, MAX_ENTITY_SIZE); + + // Read effects list + this.effects.clear(); + if (nbt.hasKey("Effects")) { + NBTTagList effectsList = nbt.getTagList("Effects", 10); // 10 = compound tag + for (int i = 0; i < effectsList.tagCount(); i++) { + effects.add(AbilityPotionEffect.fromNBT(effectsList.getCompoundTagAt(i))); + } + } + + this.deathWorldTime = nbt.hasKey("DeathWorldTime") ? nbt.getLong("DeathWorldTime") : -1; + + this.startX = nbt.getDouble("StartX"); + this.startY = nbt.getDouble("StartY"); + this.startZ = nbt.getDouble("StartZ"); + + this.targetEntityId = nbt.getInteger("TargetId"); + this.reflected = nbt.getBoolean("Reflected"); + + this.motionX = nbt.getDouble("MotionX"); + this.motionY = nbt.getDouble("MotionY"); + this.motionZ = nbt.getDouble("MotionZ"); + + // Authoritative launch origin comes from spawn NBT (set during fire/startMoving). + // Sync full client position state to this origin to avoid first-tick spawn/interp pops. + this.setPosition(this.startX, this.startY, this.startZ); + this.prevPosX = this.startX; + this.prevPosY = this.startY; + this.prevPosZ = this.startZ; + this.lastTickPosX = this.startX; + this.lastTickPosY = this.startY; + this.lastTickPosZ = this.startZ; + this.interpTargetX = this.startX; + this.interpTargetY = this.startY; + this.interpTargetZ = this.startZ; + this.interpTargetMotionX = this.motionX; + this.interpTargetMotionY = this.motionY; + this.interpTargetMotionZ = this.motionZ; + this.interpSteps = 0; + + // 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); + homingData.readNBT(nbt); + lifespanData.readNBT(nbt); + syncProjectileColorWatchers(); + } + + /** + * Write base projectile properties to NBT. + */ + protected void writeBaseNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + + nbt.setFloat("Size", size); + + // Write effects list (always write, even if empty, so readBaseNBT finds the key) + NBTTagList effectsList = new NBTTagList(); + for (AbilityPotionEffect effect : effects) { + effectsList.appendTag(effect.writeNBT()); + } + nbt.setTag("Effects", effectsList); + + nbt.setLong("DeathWorldTime", deathWorldTime); + + nbt.setDouble("StartX", startX); + nbt.setDouble("StartY", startY); + nbt.setDouble("StartZ", startZ); + + nbt.setInteger("TargetId", targetEntityId); + nbt.setBoolean("Reflected", reflected); + + nbt.setDouble("MotionX", motionX); + nbt.setDouble("MotionY", motionY); + nbt.setDouble("MotionZ", motionZ); + + anchorData.writeNBT(nbt); + combatData.writeNBT(nbt); + homingData.writeNBT(nbt); + lifespanData.writeNBT(nbt); + } + + /** + * Subclass-specific NBT reading. + */ + protected abstract void readProjectileNBT(NBTTagCompound nbt); + + /** + * Subclass-specific NBT writing. + */ + protected abstract void writeProjectileNBT(NBTTagCompound nbt); + + // ==================== COLLISION SETTINGS ==================== + + @Override + public boolean canBeCollidedWith() { + return false; + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java b/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java new file mode 100644 index 000000000..02b93d57e --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java @@ -0,0 +1,254 @@ +package kamkeel.npcs.entity; + +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; +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; + +/** + * Energy Slicer entity - a thin, wide blade projectile that flies in a straight line. + * JJK Cleave/Dismantle inspired. + * Extends EntityEnergyAbility to leverage the existing projectile infrastructure. + */ +public class EntityEnergySlicer extends EntityEnergyProjectile { + + private float sliceWidth = 3.0f; + private float sliceThickness = 0.15f; + + // Cached travel direction for smooth rendering when motion is near zero + private float lastTravelYaw = 0.0f; + private float lastTravelPitch = 0.0f; + + public EntityEnergySlicer(World world) { + super(world); + } + + /** + * Full constructor with all parameters. + */ + public EntityEnergySlicer(World world, EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, + float sliceWidth, float sliceThickness, + EnergyDisplayData display, EnergyCombatData combat, + EnergyHomingData homing, EnergyLightningData lightning, + EnergyLifespanData lifespan) { + super(world); + + initProjectile(owner, target, x, y, z, sliceWidth, display, combat, lightning, lifespan); + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); + this.sliceWidth = sliceWidth; + this.sliceThickness = sliceThickness; + + calculateInitialVelocity(owner, target, x, y, z); + } + + // Targets stored during charging for grow animation + private float targetSliceWidth = 3.0f; + private float targetSliceThickness = 0.15f; + + /** + * Setup charging with full target dimensions. + */ + public void setupSlicerCharging(EnergyAnchorData anchor, int chargeDuration, float width, float thickness) { + this.targetSliceWidth = width; + this.targetSliceThickness = thickness; + this.sliceWidth = 0.01f; + this.sliceThickness = 0.01f; + super.setupCharging(anchor, chargeDuration); + } + + /** + * Setup preview mode. + */ + public void setupPreview(EntityLivingBase owner, float width, float thickness, + EnergyDisplayData display, EnergyLightningData lightning, + EnergyAnchorData anchor, int chargeDuration) { + setupPreviewState(owner, display, lightning, anchor, chargeDuration); + + this.targetSliceWidth = width; + this.targetSliceThickness = thickness; + this.sliceWidth = 0.01f; + this.sliceThickness = 0.01f; + setVisualSize(0.01f); + setChargeOriginFromAnchor(owner, anchorData); + clearMotion(); + } + + /** + * Start preview firing. + */ + public void startPreviewFiring() { + startPreviewFiringDefault(); + } + + /** + * Start the slicer moving (exit charging mode). + */ + public void startMoving(EntityLivingBase target) { + startMovingTowardTargetDefault(target); + } + + @Override + protected void updateRotation() { + // Slicer doesn't spin - it stays oriented perpendicular to travel direction + // No rotation update needed + } + + @Override + protected void updateProjectile() { + if (isCharging()) { + updateCharging(); + return; + } + + if (previewMode) { + posX += motionX; + posY += motionY; + posZ += motionZ; + return; + } + + if (worldObj.isRemote) { + handleClientInterpolation(); + } else { + // No homing by default for slicer (straight line flight) + if (homingData.isHoming()) { + updateHoming(); + } + + checkBlockCollision(); + checkEntityCollision(); + this.moveEntity(motionX, motionY, motionZ); + } + + // Wall collision + handleSolidCollisionTermination(); + } + + @Override + protected void updateCharging() { + chargeTick++; + float progress = getChargeProgress(); + this.sliceWidth = targetSliceWidth * progress; + this.sliceThickness = targetSliceThickness * progress; + this.size = this.sliceWidth; + + Entity owner = getOwnerEntity(); + if (owner instanceof EntityLivingBase) { + Vec3 pos = kamkeel.npcs.util.AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + } + } + + private void checkBlockCollision() { + handleBlockImpact(rayTraceBlocks(posX, posY, posZ, posX + motionX, posY + motionY, posZ + motionZ), false); + } + + private void checkEntityCollision() { + float halfW = sliceWidth * 0.5f; + float halfH = sliceThickness * 0.5f; + AxisAlignedBB hitBox = AxisAlignedBB.getBoundingBox( + posX - halfW, posY - halfH, posZ - halfW, + posX + halfW, posY + halfH, posZ + halfW + ); + + processEntitiesInHitBox(hitBox, posX, posY, posZ); + } + + /** + * Get the yaw angle from motion vector for orientation. + */ + public float getTravelYaw() { + if (isCharging()) { + Entity owner = previewMode ? previewOwner : getOwnerEntity(); + if (owner != null) { + lastTravelYaw = owner.rotationYaw; + return lastTravelYaw; + } + } + double speed = Math.sqrt(motionX * motionX + motionZ * motionZ); + if (speed > 0.001) { + lastTravelYaw = (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI); + } + return lastTravelYaw; + } + + /** + * Get the pitch angle from motion vector. + */ + public float getTravelPitch() { + double horizSpeed = Math.sqrt(motionX * motionX + motionZ * motionZ); + if (horizSpeed > 0.001 || Math.abs(motionY) > 0.001) { + lastTravelPitch = (float) (-Math.atan2(motionY, horizSpeed) * 180.0 / Math.PI); + } + return lastTravelPitch; + } + + // ==================== DEBUG ==================== + + @Override + protected String debugLogExtra() { + return String.format("motion=(%.3f,%.3f,%.3f) sliceW=%.2f sliceT=%.2f", + motionX, motionY, motionZ, sliceWidth, sliceThickness); + } + + // ==================== GETTERS ==================== + + public float getSliceWidth() { + return sliceWidth; + } + + public void setSliceWidth(float width) { + this.sliceWidth = width; + } + + public float getSliceThickness() { + return sliceThickness; + } + + public void setSliceThickness(float thickness) { + this.sliceThickness = thickness; + } + + // ==================== PROPERTY SYNC ==================== + + @Override + protected void writeProjectileClientSyncData(NBTTagCompound nbt) { + nbt.setFloat("SliceWidth", sliceWidth); + nbt.setFloat("SliceThickness", sliceThickness); + } + + @Override + protected void applyProjectileClientSyncData(NBTTagCompound nbt) { + sliceWidth = nbt.getFloat("SliceWidth"); + sliceThickness = nbt.getFloat("SliceThickness"); + } + + // ==================== NBT ==================== + + @Override + protected void readProjectileNBT(NBTTagCompound nbt) { + readChargingNBT(nbt); + this.sliceWidth = sanitize(nbt.hasKey("SliceWidth") ? nbt.getFloat("SliceWidth") : 3.0f, 3.0f, MAX_ENTITY_SIZE); + this.sliceThickness = sanitize(nbt.hasKey("SliceThickness") ? nbt.getFloat("SliceThickness") : 0.15f, 0.15f, MAX_ENTITY_SIZE); + this.targetSliceWidth = sanitize(nbt.hasKey("TargetSliceWidth") ? nbt.getFloat("TargetSliceWidth") : sliceWidth, sliceWidth, MAX_ENTITY_SIZE); + this.targetSliceThickness = sanitize(nbt.hasKey("TargetSliceThickness") ? nbt.getFloat("TargetSliceThickness") : sliceThickness, sliceThickness, MAX_ENTITY_SIZE); + } + + @Override + protected void writeProjectileNBT(NBTTagCompound nbt) { + writeChargingNBT(nbt); + nbt.setFloat("SliceWidth", sliceWidth); + nbt.setFloat("SliceThickness", sliceThickness); + nbt.setFloat("TargetSliceWidth", targetSliceWidth); + nbt.setFloat("TargetSliceThickness", targetSliceThickness); + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java similarity index 50% rename from src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java rename to src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java index 4d072090e..263ecd36c 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java @@ -1,10 +1,12 @@ package kamkeel.npcs.entity; -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.data.EnergyDisplayData; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.EnergyController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.util.CNPCDebug; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -12,8 +14,10 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.LogWriter; import noppes.npcs.NpcDamageSource; +import noppes.npcs.controllers.PartyController; +import noppes.npcs.controllers.data.Party; +import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; import java.util.HashSet; @@ -24,19 +28,16 @@ import java.util.Set; * Sweeper ability entity - a rotating beam attached to the NPC. * Unlike other projectiles, this handles its own damage logic since it's * attached to and rotates around the caster. - * + * Extends EntityEnergyAbility for shared visual/owner/charging state. + *

* Design: Similar to Beam trail visuals but rotating around origin. */ -public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpawnData { +public class EntityEnergySweeper extends EntityEnergyAbility { // Beam properties private float beamLength = 10.0f; private float beamWidth = 0.3f; // Thin like beam trail - private float beamHeight = 0.8f; - private int innerColor = 0xFF6600; - private int outerColor = 0xFF0000; - private boolean outerColorEnabled = true; - private float outerColorWidth = 1.8f; + private float beamHeight = 1.0f; // Combat properties private float damage = 5.0f; @@ -52,47 +53,37 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa private float baseYaw = 0; // Starting yaw direction private boolean lockOnTarget = false; - // Owner tracking - private int ownerEntityId = -1; + // Target tracking private int targetEntityId = -1; // Lifetime 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<>(); - public EntityAbilitySweeper(World world) { + public EntityEnergySweeper(World world) { super(world); this.setSize(0.1f, 0.1f); this.noClip = true; - this.isImmuneToFire = true; - this.ignoreFrustumCheck = true; } - public EntityAbilitySweeper(World world, EntityLivingBase owner, EntityLivingBase target, - float beamLength, float beamWidth, float beamHeight, - EnergyDisplayData displayData, - float sweepSpeed, int numberOfRotations, - float damage, int damageInterval, boolean piercing, - boolean lockOnTarget) { + public EntityEnergySweeper(World world, EntityLivingBase owner, EntityLivingBase target, + float beamLength, float beamWidth, float beamHeight, + EnergyDisplayData displayData, + float sweepSpeed, int numberOfRotations, + float damage, int damageInterval, boolean piercing, + boolean lockOnTarget) { this(world); - this.ownerEntityId = owner.getEntityId(); + this.ownerEntityId = owner != null ? owner.getEntityId() : -1; this.targetEntityId = target != null ? target.getEntityId() : -1; this.beamLength = beamLength; this.beamWidth = beamWidth; this.beamHeight = beamHeight; - this.innerColor = displayData.innerColor; - this.outerColor = displayData.outerColor; - this.outerColorEnabled = displayData.outerColorEnabled; - this.outerColorWidth = displayData.outerColorWidth; + this.displayData = displayData != null ? displayData.copy() : new EnergyDisplayData(); this.sweepSpeed = sweepSpeed; this.numberOfRotations = numberOfRotations; this.damage = damage; @@ -104,16 +95,18 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa this.maxTicks = (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10; // Calculate base yaw - if (lockOnTarget && target != null) { + if (lockOnTarget && target != null && owner != null) { double dx = target.posX - owner.posX; double dz = target.posZ - owner.posZ; this.baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); - } else { + } else if (owner != null) { this.baseYaw = owner.rotationYaw; } - // Position at owner - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + // Position at beam center (bottom at feet, top at feet + beamHeight) + if (owner != null) { + this.setPosition(owner.posX, owner.posY + beamHeight / 2.0, owner.posZ); + } // Ready to deal damage immediately this.ticksSinceDamage = damageInterval; @@ -121,7 +114,7 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa @Override protected void entityInit() { - // No DataWatcher needed + super.entityInit(); } @Override @@ -144,15 +137,25 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return; } - // Follow owner - Entity owner = getOwner(); - if (owner == null) { + // Absolute hard lifetime cap (safety net) + if (ticksExisted > HARD_LIFETIME_CAP) { this.setDead(); return; } - // Update position to follow owner - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + Entity owner = getOwnerEntity(); + if (owner != null && owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + this.setDead(); + return; + } + + if (owner != null) { + this.setPosition(owner.posX, owner.posY + beamHeight / 2.0, owner.posZ); + } // Check if sweep is done if (completedRotations >= numberOfRotations) { @@ -162,18 +165,28 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa // Update rotation currentAngle += sweepSpeed; - if (currentAngle >= 360) { + while (currentAngle >= 360) { currentAngle -= 360; completedRotations++; - if (!worldObj.isRemote) { - LogWriter.info("[Sweeper] Completed rotation " + completedRotations + "/" + numberOfRotations); - } } // Server handles damage if (!worldObj.isRemote) { handleDamage(owner); } + + // Debug logging + { + boolean isClient = worldObj.isRemote; + if (isClient ? CNPCDebug.isClientEnabled("energy") : CNPCDebug.isServerEnabled("energy")) { + CNPCDebug.log("energy", isClient, String.format( + "[Sweeper id=%d tick=%d] pos=(%.2f,%.2f,%.2f) angle=%.1f prevAngle=%.1f " + + "speed=%.1f rotations=%d/%d length=%.2f width=%.2f", + getEntityId(), ticksExisted, posX, posY, posZ, + currentAngle, prevAngle, sweepSpeed, + completedRotations, numberOfRotations, beamLength, beamWidth)); + } + } } /** @@ -208,10 +221,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa double checkY = startY; double checkZ = startZ + dirZ * beamLength * progress; - // Narrow hitbox for thin beam + // Hitbox: beam center ± half-height vertically, generous width for thin beams AxisAlignedBB checkBox = AxisAlignedBB.getBoundingBox( - checkX - beamWidth * 2, checkY - 0.5, checkZ - beamWidth * 2, - checkX + beamWidth * 2, checkY + 1.0, checkZ + beamWidth * 2 + checkX - beamWidth * 2, checkY - beamHeight / 2.0, checkZ - beamWidth * 2, + checkX + beamWidth * 2, checkY + beamHeight / 2.0, checkZ + beamWidth * 2 ); @SuppressWarnings("unchecked") @@ -221,6 +234,7 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa if (!(entity instanceof EntityLivingBase)) continue; if (entity == owner) continue; if (hitThisTick.contains(entity.getEntityId())) continue; + if (shouldIgnoreEntity((EntityLivingBase) entity, owner)) continue; EntityLivingBase livingEntity = (EntityLivingBase) entity; @@ -262,22 +276,77 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return false; } - // Height check - entity's feet must be below beam top (allows jumping over) + // Height check - entity must overlap beam vertically + double beamTopY = startY + beamHeight / 2.0; + double beamBottomY = startY - beamHeight / 2.0; double entityFeetY = entity.posY; - double beamTopY = startY + 0.5; + double entityTopY = entity.posY + entity.height; - return entityFeetY < beamTopY; + // Entity feet must be below beam top AND entity top must be above beam bottom + return entityFeetY < beamTopY && entityTopY > beamBottomY; + } + + /** + * Check if an entity should be ignored for sweep damage. + * Same logic as EntityEnergyProjectile.shouldIgnoreEntity but adapted for sweeper. + */ + private boolean shouldIgnoreEntity(EntityLivingBase entity, Entity owner) { + if (entity instanceof EntityNPCInterface) { + EntityNPCInterface targetNpc = (EntityNPCInterface) entity; + if (targetNpc.faction.isPassive) return true; + if (owner instanceof EntityNPCInterface) { + if (((EntityNPCInterface) owner).faction.id == targetNpc.faction.id) return true; + } + if (owner instanceof EntityPlayer) { + if (targetNpc.faction.isFriendlyToPlayer((EntityPlayer) owner)) return true; + } + } + if (owner instanceof EntityPlayer && entity instanceof EntityPlayer) { + PlayerData ownerData = PlayerData.get((EntityPlayer) owner); + PlayerData targetData = PlayerData.get((EntityPlayer) entity); + if (ownerData.partyUUID != null && ownerData.partyUUID.equals(targetData.partyUUID)) { + Party party = PartyController.Instance().getParty(ownerData.partyUUID); + if (party != null && !party.friendlyFire()) return true; + } + } + return false; } private void applyDamage(EntityLivingBase target, Entity owner) { - if (owner instanceof EntityNPCInterface) { - target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), damage); - } else if (owner instanceof EntityPlayer) { - target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), damage); - } else if (owner instanceof EntityLivingBase) { - target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), damage); - } else { - target.attackEntityFrom(new NpcDamageSource("npc_ability", null), damage); + boolean ignoreIFrames = isIgnoreIFrames(); + int previousHurtResistantTime = Ability.clearHurtResistanceIfNeeded(target, ignoreIFrames); + try { + // Route through ability extender (e.g. DBC Addon damage scaling) + boolean handled = false; + if (sourceAbility != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + handled = AbilityController.Instance.fireOnAbilityDamage( + sourceAbility, (EntityLivingBase) owner, target, + damage, 0.0f, 0.2f, dx, dz, 1.0f); + } + // Fallback: route through EnergyController for script-created entities with custom damage data + if (!handled && customDamageData != null && owner instanceof EntityLivingBase) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + handled = EnergyController.Instance.fireOnEnergyDamage( + this, (EntityLivingBase) owner, target, + damage, 0.0f, 0.2f, dx, dz, 1.0f, customDamageData); + } + + if (!handled) { + if (owner instanceof EntityNPCInterface) { + target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), damage); + } else if (owner instanceof EntityPlayer) { + target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), damage); + } else if (owner instanceof EntityLivingBase) { + target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), damage); + } else { + target.attackEntityFrom(new NpcDamageSource("npc_ability", null), damage); + } + } + } finally { + Ability.restoreHurtResistanceIfNeeded(target, ignoreIFrames, previousHurtResistantTime); } // Small upward knockback to help escape @@ -293,12 +362,6 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa this.previewOwner = owner; } - private Entity getOwner() { - if (previewMode && previewOwner != null) return previewOwner; - if (ownerEntityId == -1) return null; - return worldObj.getEntityByID(ownerEntityId); - } - // ==================== RENDERING ==================== @Override @@ -307,22 +370,6 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return distance < 16384.0D; // 128 blocks squared } - @Override - public boolean shouldRenderInPass(int pass) { - return pass == 1; // Translucent pass - } - - @Override - public float getBrightness(float partialTicks) { - return 1.0f; - } - - @Override - @SideOnly(Side.CLIENT) - public int getBrightnessForRender(float partialTicks) { - return 0xF000F0; - } - // ==================== GETTERS FOR RENDERER ==================== public float getBeamLength() { @@ -337,22 +384,6 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return beamHeight; } - public int getInnerColor() { - return innerColor; - } - - public int getOuterColor() { - return outerColor; - } - - public boolean isOuterColorEnabled() { - return outerColorEnabled; - } - - public float getOuterColorWidth() { - return outerColorWidth; - } - /** * Get the full interpolated angle INCLUDING base yaw for rendering. */ @@ -374,46 +405,37 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return baseYaw; } + // ==================== PUBLIC SETTERS (for EnergyController / scripting API) ==================== + + public void setBeamLength(float length) { this.beamLength = length; } + public void setBeamWidth(float width) { this.beamWidth = width; } + public void setBeamHeight(float height) { this.beamHeight = height; } + public float getDamage() { return damage; } + public void setDamage(float damage) { this.damage = damage; } + public int getDamageInterval() { return damageInterval; } + public void setDamageInterval(int interval) { this.damageInterval = interval; } + public boolean isPiercing() { return piercing; } + public void setPiercing(boolean piercing) { this.piercing = piercing; } + public float getSweepSpeed() { return sweepSpeed; } + public void setSweepSpeed(float speed) { this.sweepSpeed = speed; } + public int getNumberOfRotations() { return numberOfRotations; } + public void setNumberOfRotations(int rotations) { this.numberOfRotations = rotations; } + public boolean isLockOnTarget() { return lockOnTarget; } + public void setLockOnTarget(boolean lock) { this.lockOnTarget = lock; } + // ==================== NBT ==================== - @Override - protected void readEntityFromNBT(NBTTagCompound nbt) { - this.beamLength = nbt.getFloat("BeamLength"); - this.beamWidth = nbt.getFloat("BeamWidth"); - this.beamHeight = nbt.getFloat("BeamHeight"); - this.innerColor = nbt.getInteger("InnerColor"); - this.outerColor = nbt.getInteger("OuterColor"); - this.outerColorEnabled = !nbt.hasKey("OuterColorEnabled") || nbt.getBoolean("OuterColorEnabled"); - this.outerColorWidth = nbt.hasKey("OuterColorWidth") ? nbt.getFloat("OuterColorWidth") : 1.8f; - this.sweepSpeed = nbt.getFloat("SweepSpeed"); - this.numberOfRotations = nbt.getInteger("NumRotations"); - this.completedRotations = nbt.getInteger("CompletedRotations"); - this.maxTicks = nbt.getInteger("MaxTicks"); - this.ownerEntityId = nbt.getInteger("OwnerId"); - this.targetEntityId = nbt.getInteger("TargetId"); - this.currentAngle = nbt.getFloat("CurrentAngle"); - this.baseYaw = nbt.getFloat("BaseYaw"); - this.deathWorldTime = nbt.getLong("DeathWorldTime"); - this.damage = nbt.getFloat("Damage"); - this.damageInterval = nbt.getInteger("DamageInterval"); - this.piercing = nbt.getBoolean("Piercing"); - this.lockOnTarget = nbt.getBoolean("LockOnTarget"); - } @Override - protected void writeEntityToNBT(NBTTagCompound nbt) { + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); nbt.setFloat("BeamLength", beamLength); nbt.setFloat("BeamWidth", beamWidth); nbt.setFloat("BeamHeight", beamHeight); - nbt.setInteger("InnerColor", innerColor); - nbt.setInteger("OuterColor", outerColor); - nbt.setBoolean("OuterColorEnabled", outerColorEnabled); - nbt.setFloat("OuterColorWidth", outerColorWidth); nbt.setFloat("SweepSpeed", sweepSpeed); nbt.setInteger("NumRotations", numberOfRotations); nbt.setInteger("CompletedRotations", completedRotations); nbt.setInteger("MaxTicks", maxTicks); - nbt.setInteger("OwnerId", ownerEntityId); nbt.setInteger("TargetId", targetEntityId); nbt.setFloat("CurrentAngle", currentAngle); nbt.setFloat("BaseYaw", baseYaw); @@ -424,52 +446,29 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa nbt.setBoolean("LockOnTarget", lockOnTarget); } - // ==================== SPAWN DATA ==================== - @Override - public void writeSpawnData(ByteBuf buffer) { - buffer.writeFloat(beamLength); - buffer.writeFloat(beamWidth); - buffer.writeFloat(beamHeight); - buffer.writeInt(innerColor); - buffer.writeInt(outerColor); - buffer.writeBoolean(outerColorEnabled); - buffer.writeFloat(outerColorWidth); - buffer.writeFloat(sweepSpeed); - buffer.writeInt(numberOfRotations); - buffer.writeInt(completedRotations); - buffer.writeInt(maxTicks); - buffer.writeInt(ownerEntityId); - buffer.writeInt(targetEntityId); - buffer.writeFloat(currentAngle); - buffer.writeFloat(baseYaw); - buffer.writeFloat(damage); - buffer.writeInt(damageInterval); - buffer.writeBoolean(piercing); - buffer.writeBoolean(lockOnTarget); - } - - @Override - public void readSpawnData(ByteBuf buffer) { - this.beamLength = buffer.readFloat(); - this.beamWidth = buffer.readFloat(); - this.beamHeight = buffer.readFloat(); - this.innerColor = buffer.readInt(); - this.outerColor = buffer.readInt(); - this.outerColorEnabled = buffer.readBoolean(); - this.outerColorWidth = buffer.readFloat(); - this.sweepSpeed = buffer.readFloat(); - this.numberOfRotations = buffer.readInt(); - this.completedRotations = buffer.readInt(); - this.maxTicks = buffer.readInt(); - this.ownerEntityId = buffer.readInt(); - this.targetEntityId = buffer.readInt(); - this.currentAngle = buffer.readFloat(); - this.baseYaw = buffer.readFloat(); - this.damage = buffer.readFloat(); - this.damageInterval = buffer.readInt(); - this.piercing = buffer.readBoolean(); - this.lockOnTarget = buffer.readBoolean(); - this.prevAngle = this.currentAngle; + protected void readSpawnNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + this.beamLength = sanitize(nbt.getFloat("BeamLength"), 10.0f, MAX_ENTITY_SIZE); + this.beamWidth = sanitize(nbt.getFloat("BeamWidth"), 0.3f, MAX_ENTITY_SIZE); + this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 1.0f, MAX_ENTITY_SIZE); + this.sweepSpeed = nbt.hasKey("SweepSpeed") ? nbt.getFloat("SweepSpeed") : 3.0f; + if (Float.isNaN(sweepSpeed) || Float.isInfinite(sweepSpeed) || sweepSpeed <= 0) sweepSpeed = 3.0f; + this.numberOfRotations = nbt.hasKey("NumRotations") ? nbt.getInteger("NumRotations") : 2; + if (numberOfRotations <= 0) numberOfRotations = 1; + this.completedRotations = nbt.getInteger("CompletedRotations"); + this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 400; + if (maxTicks <= 0) maxTicks = 400; + this.targetEntityId = nbt.getInteger("TargetId"); + this.currentAngle = nbt.getFloat("CurrentAngle"); + this.prevAngle = currentAngle; + this.baseYaw = nbt.getFloat("BaseYaw"); + this.deathWorldTime = nbt.getLong("DeathWorldTime"); + this.damage = nbt.hasKey("Damage") ? nbt.getFloat("Damage") : 5.0f; + if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 5.0f; + this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 5; + if (damageInterval <= 0) damageInterval = 1; + this.piercing = !nbt.hasKey("Piercing") || nbt.getBoolean("Piercing"); + this.lockOnTarget = nbt.getBoolean("LockOnTarget"); } } diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index bcfd18abd..06bffe6a7 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -8,27 +8,11 @@ import cpw.mods.fml.common.network.internal.FMLProxyPacket; import cpw.mods.fml.relauncher.Side; import io.netty.buffer.ByteBuf; import kamkeel.npcs.network.enums.EnumChannelType; -import kamkeel.npcs.network.packets.data.AchievementPacket; -import kamkeel.npcs.network.packets.data.ChatAlertPacket; -import kamkeel.npcs.network.packets.data.ChatBubblePacket; -import kamkeel.npcs.network.packets.data.ClonerPacket; -import kamkeel.npcs.network.packets.data.ConfigCommandPacket; -import kamkeel.npcs.network.packets.data.DisableMouseInputPacket; -import kamkeel.npcs.network.packets.data.LoginPacket; -import kamkeel.npcs.network.packets.data.MarkDataPacket; -import kamkeel.npcs.network.packets.data.OverlayQuestTrackingPacket; -import kamkeel.npcs.network.packets.data.ParticlePacket; -import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket; -import kamkeel.npcs.network.packets.data.PlayerUpdateSkinOverlaysPacket; -import kamkeel.npcs.network.packets.data.QuestCompletionPacket; -import kamkeel.npcs.network.packets.data.ScrollSelectedPacket; -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.*; +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +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; import kamkeel.npcs.network.packets.data.gui.GuiClosePacket; import kamkeel.npcs.network.packets.data.gui.GuiErrorPacket; import kamkeel.npcs.network.packets.data.gui.GuiOpenBookPacket; @@ -52,6 +36,18 @@ import kamkeel.npcs.network.packets.data.npc.WeaponNpcPacket; import kamkeel.npcs.network.packets.data.script.ScriptOverlayClosePacket; import kamkeel.npcs.network.packets.data.script.ScriptOverlayDataPacket; import kamkeel.npcs.network.packets.data.script.ScriptedParticlePacket; +import kamkeel.npcs.network.packets.data.energycharge.EnergyChargeRemovePacket; +import kamkeel.npcs.network.packets.data.energycharge.EnergyChargeSpawnPacket; +import kamkeel.npcs.network.packets.data.energyexplosion.EnergyExplosionSpawnPacket; +import kamkeel.npcs.network.packets.data.energy.BarrierClientSyncPacket; +import kamkeel.npcs.network.packets.data.energy.ProjectileClientSyncPacket; +import kamkeel.npcs.network.packets.data.energy.ProjectileReflectPacket; +import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; +import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityTogglePacket; import kamkeel.npcs.network.packets.player.BankActionPacket; import kamkeel.npcs.network.packets.player.CheckPlayerValue; import kamkeel.npcs.network.packets.player.CompanionActionPacket; @@ -60,7 +56,6 @@ import kamkeel.npcs.network.packets.player.FollowerPacket; import kamkeel.npcs.network.packets.player.GetNPCRole; import kamkeel.npcs.network.packets.player.GetTraderData; import kamkeel.npcs.network.packets.player.InputDevicePacket; -import kamkeel.npcs.network.packets.player.AuctionActionPacket; import kamkeel.npcs.network.packets.player.MailActionPacket; import kamkeel.npcs.network.packets.player.SaveBookPacket; import kamkeel.npcs.network.packets.player.SaveSignPacket; @@ -93,15 +88,31 @@ import kamkeel.npcs.network.packets.request.TraderMarketSavePacket; 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.BuiltInAbilityGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilitiesGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityClonePacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityRemovePacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilitySavePacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; +import kamkeel.npcs.network.packets.request.category.AbilityCategoryMovePacket; +import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket; +import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket; +import kamkeel.npcs.network.packets.request.category.CategorySavePacket; +import kamkeel.npcs.network.packets.request.ability.CopyAbilityScriptsPacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilityClonePacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket; import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket; +import kamkeel.npcs.network.packets.request.animation.AnimationClonePacket; import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket; import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket; import kamkeel.npcs.network.packets.request.animation.BuiltInAnimationGetPacket; +import kamkeel.npcs.network.packets.request.auction.ManageAuctionPacket; import kamkeel.npcs.network.packets.request.bank.BankGetPacket; import kamkeel.npcs.network.packets.request.bank.BankRemovePacket; import kamkeel.npcs.network.packets.request.bank.BankSavePacket; @@ -110,8 +121,8 @@ import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket; import kamkeel.npcs.network.packets.request.clone.CloneFolderCrudPacket; import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; -import kamkeel.npcs.network.packets.request.clone.CloneMovePacket; import kamkeel.npcs.network.packets.request.clone.CloneListPacket; +import kamkeel.npcs.network.packets.request.clone.CloneMovePacket; import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket; import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket; import kamkeel.npcs.network.packets.request.clone.CloneSavePacket; @@ -129,6 +140,7 @@ import kamkeel.npcs.network.packets.request.dialog.DialogNpcSetPacket; import kamkeel.npcs.network.packets.request.dialog.DialogRemovePacket; import kamkeel.npcs.network.packets.request.dialog.DialogSavePacket; import kamkeel.npcs.network.packets.request.dialog.DialogsGetPacket; +import kamkeel.npcs.network.packets.request.effects.EffectClonePacket; import kamkeel.npcs.network.packets.request.effects.EffectGetPacket; import kamkeel.npcs.network.packets.request.effects.EffectRemovePacket; import kamkeel.npcs.network.packets.request.effects.EffectSavePacket; @@ -149,6 +161,7 @@ import kamkeel.npcs.network.packets.request.jobs.JobSpawnerRemovePacket; import kamkeel.npcs.network.packets.request.linked.LinkedGetAllPacket; import kamkeel.npcs.network.packets.request.linked.LinkedGetPacket; import kamkeel.npcs.network.packets.request.linked.LinkedItemBuildPacket; +import kamkeel.npcs.network.packets.request.linked.LinkedItemClonePacket; import kamkeel.npcs.network.packets.request.linked.LinkedItemRemovePacket; import kamkeel.npcs.network.packets.request.linked.LinkedItemSavePacket; import kamkeel.npcs.network.packets.request.linked.LinkedNPCAddPacket; @@ -227,6 +240,8 @@ import kamkeel.npcs.network.packets.request.role.RoleCompanionUpdatePacket; import kamkeel.npcs.network.packets.request.role.RoleGetPacket; import kamkeel.npcs.network.packets.request.role.RoleSavePacket; import kamkeel.npcs.network.packets.request.script.BlockScriptPacket; +import kamkeel.npcs.network.packets.request.script.AbilityScriptPacket; +import kamkeel.npcs.network.packets.request.script.ChainedAbilityScriptPacket; import kamkeel.npcs.network.packets.request.script.EffectScriptPacket; import kamkeel.npcs.network.packets.request.script.EventScriptPacket; import kamkeel.npcs.network.packets.request.script.ForgeScriptPacket; @@ -317,6 +332,8 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new ScriptInfoPacket()); REQUEST_PACKET.registerPacket(new ScriptFilesPacket()); REQUEST_PACKET.registerPacket(new EffectScriptPacket()); + REQUEST_PACKET.registerPacket(new AbilityScriptPacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilityScriptPacket()); // Cloner Packets REQUEST_PACKET.registerPacket(new CloneListPacket()); @@ -342,6 +359,7 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new LinkedItemSavePacket()); REQUEST_PACKET.registerPacket(new LinkedItemRemovePacket()); REQUEST_PACKET.registerPacket(new LinkedItemBuildPacket()); + REQUEST_PACKET.registerPacket(new LinkedItemClonePacket()); // Bank Packets @@ -473,6 +491,7 @@ public class PacketHandler { // Trader Packets REQUEST_PACKET.registerPacket(new TraderMarketSavePacket()); + REQUEST_PACKET.registerPacket(new ManageAuctionPacket()); // Party Packets moved to player channel @@ -481,6 +500,7 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new AnimationGetPacket()); REQUEST_PACKET.registerPacket(new AnimationRemovePacket()); REQUEST_PACKET.registerPacket(new AnimationSavePacket()); + REQUEST_PACKET.registerPacket(new AnimationClonePacket()); REQUEST_PACKET.registerPacket(new BuiltInAnimationGetPacket()); // Moving Path @@ -497,6 +517,7 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new EffectsGetPacket()); REQUEST_PACKET.registerPacket(new EffectSavePacket()); REQUEST_PACKET.registerPacket(new EffectRemovePacket()); + REQUEST_PACKET.registerPacket(new EffectClonePacket()); // Magic Packets REQUEST_PACKET.registerPacket(new MagicCycleRemovePacket()); @@ -516,6 +537,22 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new CustomAbilityGetPacket()); REQUEST_PACKET.registerPacket(new CustomAbilityRemovePacket()); REQUEST_PACKET.registerPacket(new CustomAbilitySavePacket()); + REQUEST_PACKET.registerPacket(new BuiltInAbilityGetPacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilitiesGetPacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilityGetPacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilitySavePacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilityRemovePacket()); + REQUEST_PACKET.registerPacket(new CustomAbilityClonePacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilityClonePacket()); + REQUEST_PACKET.registerPacket(new CopyAbilityScriptsPacket()); + + // Category Packets + REQUEST_PACKET.registerPacket(new CategorySavePacket()); + REQUEST_PACKET.registerPacket(new CategoryRemovePacket()); + REQUEST_PACKET.registerPacket(new CategoryMoveItemPacket()); + REQUEST_PACKET.registerPacket(new CategoryListRequestPacket()); + REQUEST_PACKET.registerPacket(new CategoryItemsRequestPacket()); + REQUEST_PACKET.registerPacket(new AbilityCategoryMovePacket()); // Other Packets REQUEST_PACKET.registerPacket(new IsGuiOpenInform()); @@ -549,6 +586,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new UpdateAnimationsPacket()); DATA_PACKET.registerPacket(new VillagerListPacket()); DATA_PACKET.registerPacket(new PlayerDataInfoPacket()); + DATA_PACKET.registerPacket(new ProfileSharedQuestPacket()); // Data | GUI Packets DATA_PACKET.registerPacket(new GuiClosePacket()); @@ -585,7 +623,16 @@ public class PacketHandler { // Data | Ability Packets DATA_PACKET.registerPacket(new TelegraphSpawnPacket()); DATA_PACKET.registerPacket(new TelegraphRemovePacket()); + DATA_PACKET.registerPacket(new EnergyChargeSpawnPacket()); + DATA_PACKET.registerPacket(new EnergyChargeRemovePacket()); + DATA_PACKET.registerPacket(new EnergyExplosionSpawnPacket()); + DATA_PACKET.registerPacket(new ProjectileReflectPacket()); + DATA_PACKET.registerPacket(new ProjectileClientSyncPacket()); + DATA_PACKET.registerPacket(new BarrierClientSyncPacket()); DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); + DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); + DATA_PACKET.registerPacket(new AbilityHotbarSyncPacket()); + DATA_PACKET.registerPacket(new AbilityCooldownSyncPacket()); } public void registerPlayerPackets() { @@ -651,6 +698,11 @@ public class PacketHandler { PLAYER_PACKET.registerPacket(new PartyAcceptInvitePacket()); PLAYER_PACKET.registerPacket(new PartyIgnoreInvitePacket()); PLAYER_PACKET.registerPacket(new PartyLogToServerPacket()); + + // Ability Hotbar Packets + PLAYER_PACKET.registerPacket(new AbilityHotbarSavePacket()); + PLAYER_PACKET.registerPacket(new AbilityHotbarSelectPacket()); + PLAYER_PACKET.registerPacket(new AbilityTogglePacket()); } public void registerChannels() { diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index 18321d0a4..598126a2d 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -63,7 +63,29 @@ public enum EnumDataPacket { TELEGRAPH_SPAWN, TELEGRAPH_REMOVE, PLAYER_ABILITY_SYNC, + PLAYER_ABILITY_STATE, + ABILITY_HOTBAR_SYNC, + ABILITY_COOLDOWN_SYNC, + + // Profile System + PROFILE_SHARED_QUEST, // Auction System AUCTION_DATA, + + // Energy Charge Preview + ENERGY_CHARGE_SPAWN, + ENERGY_CHARGE_REMOVE, + + // Energy Explosion Preview + ENERGY_EXPLOSION_SPAWN, + + // Energy Projectile Reflection Sync + PROJECTILE_REFLECT, + + // Energy Projectile Client Sync (position, motion, visual, and movement properties) + PROJECTILE_CLIENT_SYNC, + + // Energy Barrier Client Sync (visual properties and barrier-specific data) + BARRIER_CLIENT_SYNC, } diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java index 48f400fb2..e1587467b 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java @@ -37,4 +37,9 @@ public enum EnumPlayerPacket { // Auction AuctionAction, + + // Ability Hotbar + AbilityHotbarSave, + AbilityHotbarSelect, + AbilityToggle, } diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java index 2f3e6ea94..27a319abd 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java @@ -93,6 +93,7 @@ public enum EnumRequestPacket { AnimationGet, AnimationRemove, AnimationSave, + AnimationClone, BuiltInAnimationGet, RemoteNpcsGet, @@ -205,7 +206,28 @@ public enum EnumRequestPacket { CustomAbilityGet, CustomAbilityRemove, CustomAbilitySave, + BuiltInAbilityGet, + ChainedAbilitiesGet, + ChainedAbilityGet, + ChainedAbilitySave, + ChainedAbilityRemove, Hammer, RecipeScript, + ManageAuctionAction, + AbilityScript, + ChainedAbilityScript, + + CategorySave, + CategoryRemove, + CategoryMoveItem, + CategoryListRequest, + CategoryItemsRequest, + AbilityCategoryMoveItem, + + CustomAbilityClone, + ChainedAbilityClone, + CopyAbilityScripts, + LinkedItemClone, + EffectClone, } diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java b/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java deleted file mode 100644 index 1ac0ec828..000000000 --- a/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java +++ /dev/null @@ -1,17 +0,0 @@ -package kamkeel.npcs.network.enums; - -public enum EnumSyncType { - FACTION, - DIALOG, - DIALOG_CATEGORY, - QUEST, - QUEST_CATEGORY, - PLAYERDATA, - MAGIC, - MAGIC_CYCLE, - WORKBENCH_RECIPES, - CARPENTRY_RECIPES, - ANVIL_RECIPES, - CUSTOM_EFFECTS, - CUSTOM_ABILITY -} diff --git a/src/main/java/kamkeel/npcs/network/enums/SyncType.java b/src/main/java/kamkeel/npcs/network/enums/SyncType.java new file mode 100644 index 000000000..82d5639ae --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/enums/SyncType.java @@ -0,0 +1,142 @@ +package kamkeel.npcs.network.enums; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Immutable, object-based sync-type identity for the CNPC+ sync backend. + * + *

Each {@code SyncType} has a canonical namespaced string ID ({@code modid:path}) + * and is registered via the static {@link #register} factory. Built-in CNPC+ + * families are exposed as {@code public static final} constants.

+ * + *

Identity is based on the canonical {@link #id} string, which is unique + * across all registered types. Two references with the same {@code id} + * are always the same object (identity == equality for registered types).

+ * + *

The {@code ordinal} field provides a stable integer identity for + * wire encoding during the migration period. It is assigned at registration + * time in declaration order and must NOT be used as a protocol identifier + * once string-on-wire migration is complete.

+ */ +public final class SyncType { + + // ──────────────────── Registry ──────────────────── + private static final Map REGISTRY = new LinkedHashMap<>(); + private static int nextOrdinal = 0; + + // ──────────────────── CNPC+ families ──────────────────── + public static final SyncType FACTION = register("cnpc:faction"); + public static final SyncType DIALOG = register("cnpc:dialog"); + public static final SyncType DIALOG_CATEGORY = register("cnpc:dialog_category"); + public static final SyncType QUEST = register("cnpc:quest"); + public static final SyncType QUEST_CATEGORY = register("cnpc:quest_category"); + public static final SyncType PLAYERDATA = register("cnpc:playerdata"); + public static final SyncType MAGIC = register("cnpc:magic"); + public static final SyncType MAGIC_CYCLE = register("cnpc:magic_cycle"); + public static final SyncType WORKBENCH_RECIPES = register("cnpc:workbench_recipes"); + public static final SyncType CARPENTRY_RECIPES = register("cnpc:carpentry_recipes"); + public static final SyncType ANVIL_RECIPES = register("cnpc:anvil_recipes"); + public static final SyncType CUSTOM_EFFECTS = register("cnpc:custom_effects"); + public static final SyncType CUSTOM_ABILITY = register("cnpc:custom_ability"); + public static final SyncType CHAINED_ABILITY = register("cnpc:chained_ability"); + + // ──────────────────── Instance fields ──────────────────── + private final String id; + private final int ordinal; + + private SyncType(String id, int ordinal) { + this.id = id; + this.ordinal = ordinal; + } + + // ──────────────────── Public API ──────────────────── + + /** + * The canonical namespaced identifier, e.g. {@code "cnpc:faction"}. + */ + public String getId() { + return id; + } + + /** + * Stable integer ordinal assigned at registration time. + * Used for wire encoding during the migration period only. + */ + public int ordinal() { + return ordinal; + } + + // ──────────────────── Registration ──────────────────── + + /** + * Register a new {@code SyncType} with the given canonical ID. + * + * @param id namespaced identifier ({@code modid:path}) + * @return the newly created and registered {@code SyncType} + * @throws IllegalArgumentException if the ID is null, empty, or lacks a colon + * @throws IllegalStateException if a type with the same ID is already registered + * @throws IllegalStateException if the registry has been frozen + */ + public static SyncType register(String id) { + if (id == null || id.isEmpty()) throw new IllegalArgumentException("SyncType id must not be null or empty"); + if (!id.contains(":")) throw new IllegalArgumentException("SyncType id must be namespaced (modid:path): " + id); + if (REGISTRY.containsKey(id)) throw new IllegalStateException("Duplicate SyncType registration: " + id); + + SyncType type = new SyncType(id, nextOrdinal++); + REGISTRY.put(id, type); + return type; + } + + /** + * Look up a registered SyncType by its canonical string ID. + * + * @return the registered type, or {@code null} if not found + */ + public static SyncType byId(String id) { + return id == null ? null : REGISTRY.get(id); + } + + /** + * Look up a registered SyncType by its ordinal. + * Used during migration for decoding ordinal-based wire traffic. + * + * @return the registered type, or {@code null} if ordinal is out of range + */ + public static SyncType byOrdinal(int ordinal) { + if (ordinal < 0) return null; + + for (SyncType type : REGISTRY.values()) + if (type.ordinal == ordinal) return type; + + return null; + } + + /** + * Returns all registered SyncType instances in registration order. + */ + public static Collection values() { + return Collections.unmodifiableCollection(REGISTRY.values()); + } + + // ──────────────────── Object overrides ──────────────────── + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof SyncType)) return false; + return id.equals(((SyncType) o).id); + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public String toString() { + return id; + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java index 75e0c40ae..103c2e5fa 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java @@ -8,32 +8,33 @@ import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumDataPacket; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.network.packets.player.SyncRevisionInfoPacket; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.AuctionClientConfig; import noppes.npcs.client.ClientCacheHandler; -import noppes.npcs.config.ConfigMain; import noppes.npcs.client.ScriptClientConfig; +import noppes.npcs.config.ConfigMain; import noppes.npcs.controllers.AuctionConfigSync; import noppes.npcs.controllers.ScriptConfigSync; import java.io.IOException; -import java.util.EnumMap; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; public final class LoginPacket extends AbstractPacket { public static final String packetName = "CNPC+|Login"; private String serverCacheKey = ""; - private final EnumMap revisionSnapshot = new EnumMap<>(EnumSyncType.class); + private final Map revisionSnapshot = new LinkedHashMap<>(); public LoginPacket() { } - public LoginPacket(String serverCacheKey, EnumMap revisionSnapshot) { + public LoginPacket(String serverCacheKey, Map revisionSnapshot) { if (serverCacheKey != null) { this.serverCacheKey = serverCacheKey; } @@ -58,17 +59,15 @@ public final class LoginPacket extends AbstractPacket { out.writeBoolean(ConfigMain.ProfilesEnabled); ByteBufUtils.writeString(out, serverCacheKey); out.writeShort(revisionSnapshot.size()); - for (Map.Entry entry : revisionSnapshot.entrySet()) { + for (Map.Entry entry : revisionSnapshot.entrySet()) { out.writeInt(entry.getKey().ordinal()); out.writeInt(entry.getValue()); } - // Send auction config (server-side sync) NBTTagCompound auctionConfig = new NBTTagCompound(); AuctionConfigSync.writeToNBT(auctionConfig); ByteBufUtils.writeNBT(out, auctionConfig); - // Send script config (server-side sync) NBTTagCompound scriptConfig = new NBTTagCompound(); ScriptConfigSync.writeToNBT(scriptConfig); ByteBufUtils.writeNBT(out, scriptConfig); @@ -82,20 +81,20 @@ public final class LoginPacket extends AbstractPacket { String serverKey = ByteBufUtils.readString(in); int revisionCount = in.readUnsignedShort(); - EnumMap serverRevisions = new EnumMap<>(EnumSyncType.class); + Map serverRevisions = new LinkedHashMap<>(); for (int i = 0; i < revisionCount; i++) { - EnumSyncType type = EnumSyncType.values()[in.readInt()]; + SyncType type = SyncType.byOrdinal(in.readInt()); int revision = in.readInt(); - serverRevisions.put(type, revision); + if (type != null) { + serverRevisions.put(type, revision); + } } ClientCacheHandler.setActiveServer(serverKey, serverRevisions); - // Read auction config NBTTagCompound auctionConfig = ByteBufUtils.readNBT(in); AuctionClientConfig.readFromNBT(auctionConfig); - // Read script config NBTTagCompound scriptConfig = ByteBufUtils.readNBT(in); ScriptClientConfig.readFromNBT(scriptConfig); diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ProfileSharedQuestPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ProfileSharedQuestPacket.java new file mode 100644 index 000000000..6fa6187c9 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ProfileSharedQuestPacket.java @@ -0,0 +1,57 @@ +package kamkeel.npcs.network.packets.data; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ProfileClientConfig; +import noppes.npcs.controllers.ProfileConfigSync; + +import java.io.IOException; + +public final class ProfileSharedQuestPacket extends AbstractPacket { + public static final String packetName = "Data|ProfileSharedQuest"; + + private NBTTagCompound compound; + + public ProfileSharedQuestPacket() { + } + + public ProfileSharedQuestPacket(NBTTagCompound compound) { + this.compound = compound; + } + + @Override + public Enum getType() { + return EnumDataPacket.PROFILE_SHARED_QUEST; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, this.compound); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + ProfileClientConfig.readFromNBT(nbt); + } + + public static void sendToPlayer(EntityPlayerMP player) { + NBTTagCompound compound = ProfileConfigSync.writeToNBT(player); + PacketHandler.Instance.sendToPlayer(new ProfileSharedQuestPacket(compound), player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java new file mode 100644 index 000000000..aa7dd62aa --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java @@ -0,0 +1,110 @@ +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 kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Lightweight packet that syncs cooldown state (global + per-ability) to the client. + * Sent when cooldowns are rolled, reset, or on login. + */ +public final class AbilityCooldownSyncPacket extends AbstractPacket { + public static final String packetName = "Data|AbilityCooldownSync"; + + private long globalCooldownEndTime; + private int globalCooldownDuration; + private HashMap perAbilityCooldownEndTimes; + private HashMap perAbilityCooldownDurations; + + public AbilityCooldownSyncPacket() { + } + + public AbilityCooldownSyncPacket(long globalEndTime, int globalDuration, + HashMap perEndTimes, + HashMap perDurations) { + this.globalCooldownEndTime = globalEndTime; + this.globalCooldownDuration = globalDuration; + this.perAbilityCooldownEndTimes = perEndTimes; + this.perAbilityCooldownDurations = perDurations; + } + + @Override + public Enum getType() { + return EnumDataPacket.ABILITY_COOLDOWN_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeLong(globalCooldownEndTime); + out.writeInt(globalCooldownDuration); + + // Write per-ability cooldowns + int count = perAbilityCooldownEndTimes != null ? perAbilityCooldownEndTimes.size() : 0; + out.writeInt(count); + if (count > 0) { + for (Map.Entry entry : perAbilityCooldownEndTimes.entrySet()) { + ByteBufUtils.writeUTF8String(out, entry.getKey()); + out.writeLong(entry.getValue()); + Integer dur = perAbilityCooldownDurations.get(entry.getKey()); + out.writeInt(dur != null ? dur : 0); + } + } + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + long globalEndTime = in.readLong(); + int globalDuration = in.readInt(); + + int count = in.readInt(); + HashMap perEndTimes = new HashMap<>(); + HashMap perDurations = new HashMap<>(); + for (int i = 0; i < count; i++) { + String key = ByteBufUtils.readUTF8String(in); + long endTime = in.readLong(); + int duration = in.readInt(); + perEndTimes.put(key, endTime); + perDurations.put(key, duration); + } + + PlayerData data = ClientCacheHandler.playerData; + if (data != null && data.abilityData != null) { + data.abilityData.applyCooldownSync(globalEndTime, globalDuration, perEndTimes, perDurations); + } + } + + /** + * Send the player's current cooldown state to their client. + */ + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null || data.abilityData == null) return; + + PacketHandler.Instance.sendToPlayer(new AbilityCooldownSyncPacket( + data.abilityData.getCooldownEndTime(), + data.abilityData.getGlobalCooldownDurationValue(), + data.abilityData.getPerAbilityCooldownEndTimes(), + data.abilityData.getPerAbilityCooldownDurations() + ), player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java new file mode 100644 index 000000000..7ce46f97b --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java @@ -0,0 +1,105 @@ +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.controllers.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerAbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSyncPacket extends AbstractPacket { + public static final String packetName = "Data|AbilityHotbarSync"; + + private NBTTagCompound hotbarNBT; + + public AbilityHotbarSyncPacket() { + } + + public AbilityHotbarSyncPacket(NBTTagCompound hotbarNBT) { + this.hotbarNBT = hotbarNBT; + } + + @Override + public Enum getType() { + return EnumDataPacket.ABILITY_HOTBAR_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, hotbarNBT); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt == null) return; + + PlayerData data = ClientCacheHandler.playerData; + if (data != null) { + data.hotbarData.readFromNBT(nbt); + } + } + + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + PlayerAbilityHotbarData hotbarData = data.hotbarData; + boolean anyCleared = false; + + // Validate all slots before sending + if (AbilityController.Instance != null) { + for (int i = 0; i < hotbarData.slots.length; i++) { + AbilityHotbarData slot = hotbarData.slots[i]; + if (slot.isEmpty()) continue; + + boolean valid; + if (slot.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slot.abilityKey); + } + + if (valid && data.abilityData != null) { + valid = data.abilityData.hasUnlockedAbility(slot.abilityKey); + // For chains, also check with resolved key in case key format differs + if (!valid && slot.isChainKey()) { + valid = data.abilityData.hasUnlockedAbility("chain:" + slot.getResolveKey()); + } + } + + if (!valid) { + slot.reset(); + anyCleared = true; + } + } + } + + NBTTagCompound nbt = new NBTTagCompound(); + hotbarData.writeToNBT(nbt); + PacketHandler.Instance.sendToPlayer(new AbilityHotbarSyncPacket(nbt), player); + + if (anyCleared) { + data.save(); + } + } +} 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..5d62b1bcf --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java @@ -0,0 +1,87 @@ +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) + * bit 5: ability is in ACTIVE phase + */ +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; + public static final byte FLAG_WAS_FLYING_AT_LOCK = 16; + public static final byte FLAG_ACTIVE_PHASE = 32; + + 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/data/ability/PlayerAbilitySyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilitySyncPacket.java index 08df836aa..2353623b2 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilitySyncPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilitySyncPacket.java @@ -11,6 +11,7 @@ import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.data.PlayerData; @@ -53,7 +54,7 @@ public final class PlayerAbilitySyncPacket extends AbstractPacket { NBTTagCompound nbt = ByteBufUtils.readNBT(in); if (nbt == null) return; - PlayerData data = PlayerData.get(player); + PlayerData data = ClientCacheHandler.playerData; if (data != null) { data.abilityData.readFromNBT(nbt); } diff --git a/src/main/java/kamkeel/npcs/network/packets/data/energy/BarrierClientSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/energy/BarrierClientSyncPacket.java new file mode 100644 index 000000000..b0b2bd7a5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/energy/BarrierClientSyncPacket.java @@ -0,0 +1,77 @@ +package kamkeel.npcs.network.packets.data.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.io.IOException; + +/** + * Syncs all barrier client-relevant state to tracking clients. + * Includes visual properties and barrier-specific data (dome radius, panel dimensions, etc.). + * Sent server->client when scripts call syncClient() on an already-spawned energy barrier. + */ +public final class BarrierClientSyncPacket extends AbstractPacket { + + private int entityId; + private NBTTagCompound syncData; + + public BarrierClientSyncPacket() { + } + + public BarrierClientSyncPacket(int entityId, NBTTagCompound syncData) { + this.entityId = entityId; + this.syncData = syncData; + } + + @Override + public Enum getType() { + return EnumDataPacket.BARRIER_CLIENT_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(entityId); + ByteBufUtils.writeNBT(out, syncData); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + int id = in.readInt(); + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt == null) return; + + World world = Minecraft.getMinecraft().theWorld; + if (world == null) return; + + Entity entity = world.getEntityByID(id); + if (entity instanceof EntityEnergyBarrier) { + ((EntityEnergyBarrier) entity).applyClientSyncData(nbt); + } + } + + public static void sendToTracking(EntityEnergyBarrier barrier, NBTTagCompound syncData) { + if (barrier == null || syncData == null) return; + PacketHandler.Instance.sendTracking( + new BarrierClientSyncPacket(barrier.getEntityId(), syncData), + barrier + ); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/energy/ProjectileClientSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/energy/ProjectileClientSyncPacket.java new file mode 100644 index 000000000..fce1e0713 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/energy/ProjectileClientSyncPacket.java @@ -0,0 +1,78 @@ +package kamkeel.npcs.network.packets.data.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.io.IOException; + +/** + * Syncs all projectile client-relevant state to tracking clients. + * Includes position, motion, visual properties, and movement settings. + * Sent server->client when scripts call syncClient() or fireAt() on + * an already-spawned energy projectile. + */ +public final class ProjectileClientSyncPacket extends AbstractPacket { + + private int entityId; + private NBTTagCompound syncData; + + public ProjectileClientSyncPacket() { + } + + public ProjectileClientSyncPacket(int entityId, NBTTagCompound syncData) { + this.entityId = entityId; + this.syncData = syncData; + } + + @Override + public Enum getType() { + return EnumDataPacket.PROJECTILE_CLIENT_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(entityId); + ByteBufUtils.writeNBT(out, syncData); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + int id = in.readInt(); + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt == null) return; + + World world = Minecraft.getMinecraft().theWorld; + if (world == null) return; + + Entity entity = world.getEntityByID(id); + if (entity instanceof EntityEnergyProjectile) { + ((EntityEnergyProjectile) entity).applyClientSyncData(nbt); + } + } + + public static void sendToTracking(EntityEnergyProjectile projectile, NBTTagCompound syncData) { + if (projectile == null || syncData == null) return; + PacketHandler.Instance.sendTracking( + new ProjectileClientSyncPacket(projectile.getEntityId(), syncData), + projectile + ); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/energy/ProjectileReflectPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/energy/ProjectileReflectPacket.java new file mode 100644 index 000000000..3950b0b28 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/energy/ProjectileReflectPacket.java @@ -0,0 +1,79 @@ +package kamkeel.npcs.network.packets.data.energy; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.io.IOException; + +/** + * Syncs projectile reflection state to all tracking clients. + * Sent server→client after a successful barrier reflection so the client + * can update ownerEntityId, position, motion, colors, and type-specific + * reflection data (beam mode, laser direction, disc boomerang, etc.). + */ +public final class ProjectileReflectPacket extends AbstractPacket { + public static final String packetName = "Data|ProjectileReflect"; + + private int entityId; + private NBTTagCompound reflectData; + + public ProjectileReflectPacket() { + } + + public ProjectileReflectPacket(int entityId, NBTTagCompound reflectData) { + this.entityId = entityId; + this.reflectData = reflectData; + } + + @Override + public Enum getType() { + return EnumDataPacket.PROJECTILE_REFLECT; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(entityId); + ByteBufUtils.writeNBT(out, reflectData); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + int id = in.readInt(); + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt == null) return; + + World world = Minecraft.getMinecraft().theWorld; + if (world == null) return; + + Entity entity = world.getEntityByID(id); + if (entity instanceof EntityEnergyProjectile) { + ((EntityEnergyProjectile) entity).applyReflectionData(nbt); + } + } + + public static void sendToTracking(EntityEnergyProjectile projectile, NBTTagCompound reflectData) { + if (projectile == null || reflectData == null) return; + PacketHandler.Instance.sendTracking( + new ProjectileReflectPacket(projectile.getEntityId(), reflectData), + projectile + ); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/energycharge/EnergyChargeRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/data/energycharge/EnergyChargeRemovePacket.java new file mode 100644 index 000000000..e9a3a4db6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/energycharge/EnergyChargeRemovePacket.java @@ -0,0 +1,60 @@ +package kamkeel.npcs.network.packets.data.energycharge; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; + +import java.io.IOException; + +/** + * Removes a client-only charging preview entity. + */ +public final class EnergyChargeRemovePacket extends AbstractPacket { + public static final String packetName = "Data|EnergyChargeRemove"; + + private String instanceId; + + public EnergyChargeRemovePacket() { + } + + public EnergyChargeRemovePacket(String instanceId) { + this.instanceId = instanceId; + } + + @Override + public Enum getType() { + return EnumDataPacket.ENERGY_CHARGE_REMOVE; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, instanceId); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String id = ByteBufUtils.readString(in); + if (id != null && EnergyChargePreviewManager.ClientInstance != null) { + EnergyChargePreviewManager.ClientInstance.removePreview(id); + } + } + + public static void sendToTracking(String instanceId, Entity trackingEntity) { + if (instanceId == null || trackingEntity == null) return; + PacketHandler.Instance.sendTracking(new EnergyChargeRemovePacket(instanceId), trackingEntity); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/energycharge/EnergyChargeSpawnPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/energycharge/EnergyChargeSpawnPacket.java new file mode 100644 index 000000000..16957aaaa --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/energycharge/EnergyChargeSpawnPacket.java @@ -0,0 +1,108 @@ +package kamkeel.npcs.network.packets.data.energycharge; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.io.IOException; +import java.lang.reflect.Constructor; + +/** + * Spawns a client-only charging preview entity from serialized spawn data. + */ +public final class EnergyChargeSpawnPacket extends AbstractPacket { + public static final String packetName = "Data|EnergyChargeSpawn"; + + private String instanceId; + private String entityClassName; + private NBTTagCompound spawnNbt; + + public EnergyChargeSpawnPacket() { + } + + public EnergyChargeSpawnPacket(String instanceId, String entityClassName, NBTTagCompound spawnNbt) { + this.instanceId = instanceId; + this.entityClassName = entityClassName; + this.spawnNbt = spawnNbt; + } + + @Override + public Enum getType() { + return EnumDataPacket.ENERGY_CHARGE_SPAWN; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, instanceId); + ByteBufUtils.writeString(out, entityClassName); + ByteBufUtils.writeNBT(out, spawnNbt); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String id = ByteBufUtils.readString(in); + String className = ByteBufUtils.readString(in); + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + + if (id == null || className == null || nbt == null) return; + if (EnergyChargePreviewManager.ClientInstance == null) return; + + World world = Minecraft.getMinecraft().theWorld; + if (world == null) return; + + EntityEnergyProjectile preview = createPreviewEntity(className, world); + if (preview == null) return; + + preview.setPreviewMode(true); + preview.importSpawnNBT(nbt); + + // Ensure the preview follows current owner immediately on first render frame. + Entity owner = preview.getOwnerEntity(); + if (owner instanceof net.minecraft.entity.EntityLivingBase) { + preview.setPreviewOwner((net.minecraft.entity.EntityLivingBase) owner); + } + + EnergyChargePreviewManager.ClientInstance.addPreview(id, preview); + } + + @SideOnly(Side.CLIENT) + private static EntityEnergyProjectile createPreviewEntity(String className, World world) { + try { + Class clazz = Class.forName(className); + if (!EntityEnergyProjectile.class.isAssignableFrom(clazz)) { + return null; + } + + Constructor constructor = clazz.getConstructor(World.class); + Object instance = constructor.newInstance(world); + return (EntityEnergyProjectile) instance; + } catch (Exception ignored) { + return null; + } + } + + public static void sendToTracking(String instanceId, EntityEnergyProjectile previewEntity, Entity trackingEntity) { + if (previewEntity == null || trackingEntity == null) return; + String className = previewEntity.getClass().getName(); + NBTTagCompound nbt = previewEntity.exportSpawnNBT(); + PacketHandler.Instance.sendTracking(new EnergyChargeSpawnPacket(instanceId, className, nbt), trackingEntity); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/energyexplosion/EnergyExplosionSpawnPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/energyexplosion/EnergyExplosionSpawnPacket.java new file mode 100644 index 000000000..e227b8562 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/energyexplosion/EnergyExplosionSpawnPacket.java @@ -0,0 +1,74 @@ +package kamkeel.npcs.network.packets.data.energyexplosion; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.entity.EntityEnergyExplosion; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.io.IOException; + +/** + * Spawns a client-side explosion visual entity from serialized spawn data. + */ +public final class EnergyExplosionSpawnPacket extends AbstractPacket { + public static final String packetName = "Data|EnergyExplosionSpawn"; + + private String instanceId; + private NBTTagCompound spawnNbt; + + public EnergyExplosionSpawnPacket() { + } + + public EnergyExplosionSpawnPacket(String instanceId, NBTTagCompound spawnNbt) { + this.instanceId = instanceId; + this.spawnNbt = spawnNbt; + } + + @Override + public Enum getType() { + return EnumDataPacket.ENERGY_EXPLOSION_SPAWN; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, instanceId); + ByteBufUtils.writeNBT(out, spawnNbt); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + ByteBufUtils.readString(in); // Keep wire compatibility for future instance tracking. + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + + if (nbt == null) return; + + World world = Minecraft.getMinecraft().theWorld; + if (world == null) return; + + EntityEnergyExplosion preview = new EntityEnergyExplosion(world); + preview.importSpawnNBT(nbt); + world.spawnEntityInWorld(preview); + } + + public static void sendToTracking(String instanceId, EntityEnergyExplosion previewEntity, Entity trackingEntity) { + if (instanceId == null || previewEntity == null || trackingEntity == null) return; + NBTTagCompound nbt = previewEntity.exportSpawnNBT(); + PacketHandler.Instance.sendTracking(new EnergyExplosionSpawnPacket(instanceId, nbt), trackingEntity); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/large/GuiDataPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/large/GuiDataPacket.java index 631e32bf2..784d0fe1c 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/large/GuiDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/large/GuiDataPacket.java @@ -9,13 +9,9 @@ import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumDataPacket; import kamkeel.npcs.util.ByteBufUtils; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.client.gui.util.GuiContainerNPCInterface; -import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.IGuiData; import java.io.IOException; @@ -59,15 +55,6 @@ public final class GuiDataPacket extends LargeAbstractPacket { @SideOnly(Side.CLIENT) @Override protected void handleCompleteData(ByteBuf data, EntityPlayer player) throws IOException { - GuiScreen gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiNPCInterface && ((GuiNPCInterface) gui).hasSubGui()) { - gui = ((GuiNPCInterface) gui).getSubGui(); - } else if (gui instanceof GuiContainerNPCInterface && ((GuiContainerNPCInterface) gui).hasSubGui()) { - gui = ((GuiContainerNPCInterface) gui).getSubGui(); - } - if (gui instanceof IGuiData) { - NBTTagCompound nbt = ByteBufUtils.readBigNBT(data); - ((IGuiData) gui).setGuiData(nbt); - } + IGuiData.legacySetGuiData(ByteBufUtils.readBigNBT(data)); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/data/large/SyncEffectPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/large/SyncEffectPacket.java index 66d7a5756..026ec44bf 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/large/SyncEffectPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/large/SyncEffectPacket.java @@ -4,7 +4,7 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper; import kamkeel.npcs.network.LargeAbstractPacket; import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketHandler; @@ -54,7 +54,7 @@ public final class SyncEffectPacket extends LargeAbstractPacket { return; try { NBTTagCompound tag = ByteBufUtils.readBigNBT(data); - SyncController.clientSyncEffects(tag); + PlayerEffectSyncHelper.clientSyncEffects(tag); } catch (RuntimeException e) { LogWriter.error(String.format("Attempted to Sync Effects but it was too big")); } diff --git a/src/main/java/kamkeel/npcs/network/packets/data/large/SyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/large/SyncPacket.java index 77b2122b4..dcd940a50 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/large/SyncPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/large/SyncPacket.java @@ -10,7 +10,7 @@ import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumDataPacket; import kamkeel.npcs.network.enums.EnumSyncAction; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; @@ -22,16 +22,13 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -/** - * A large sync packet that sends chunked data to the client for a given SyncType - * along with a SyncAction (RELOAD, UPDATE, REMOVE). - */ public final class SyncPacket extends LargeAbstractPacket { - private EnumSyncType enumSyncType; + private SyncType syncType; private EnumSyncAction enumSyncAction; private NBTTagCompound syncData; private int operationID; + private String operationKey; private int revision = -1; private byte[] cachedPayload; private byte[][] cachedChunks; @@ -39,23 +36,21 @@ public final class SyncPacket extends LargeAbstractPacket { public SyncPacket() { } - /** - * Constructs a new LargeSyncPacket. - */ - public SyncPacket(EnumSyncType enumSyncType, EnumSyncAction enumSyncAction, int catId, NBTTagCompound syncData) { - this(enumSyncType, enumSyncAction, catId, -1, syncData); + public SyncPacket(SyncType syncType, EnumSyncAction enumSyncAction, int catId, NBTTagCompound syncData) { + this(syncType, enumSyncAction, catId, null, -1, syncData); } - public SyncPacket(EnumSyncType enumSyncType, EnumSyncAction enumSyncAction, int catId, int revision, NBTTagCompound syncData) { - this.enumSyncType = enumSyncType; + public SyncPacket(SyncType syncType, EnumSyncAction enumSyncAction, int operationId, String operationKey, int revision, NBTTagCompound syncData) { + this.syncType = syncType; this.enumSyncAction = enumSyncAction; this.syncData = syncData; - this.operationID = catId; + this.operationID = operationId; + this.operationKey = operationKey; this.revision = revision; } - public SyncPacket(EnumSyncType enumSyncType, SyncController.CachedSyncPayload payload) { - this.enumSyncType = enumSyncType; + public SyncPacket(SyncType syncType, SyncController.CachedSyncPayload payload) { + this.syncType = syncType; this.enumSyncAction = EnumSyncAction.RELOAD; this.operationID = -1; this.revision = payload.getRevision(); @@ -79,13 +74,21 @@ public final class SyncPacket extends LargeAbstractPacket { return cachedPayload; } + boolean hasKey = operationKey != null; + boolean hasNbt = syncData != null; + ByteBuf buffer = Unpooled.buffer(); try { - buffer.writeInt(enumSyncType.ordinal()); + buffer.writeInt(syncType.ordinal()); buffer.writeInt(enumSyncAction.ordinal()); buffer.writeInt(operationID); buffer.writeInt(revision); - ByteBufUtils.writeBigNBT(buffer, syncData); + + // UPDATE/REMOVE UNIQUE FIELDS + buffer.writeBoolean(hasKey); + if (hasKey) ByteBufUtils.writeString(buffer, operationKey); + buffer.writeBoolean(hasNbt); + if (hasNbt) ByteBufUtils.writeBigNBT(buffer, syncData); byte[] bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); @@ -131,39 +134,40 @@ public final class SyncPacket extends LargeAbstractPacket { if (CustomNpcs.side() != Side.CLIENT) return; - // Reconstruct everything from the ByteBuf int syncTypeOrdinal = data.readInt(); int syncActionOrdinal = data.readInt(); - int categoryID = data.readInt(); - int incomingRevision = data.readInt(); + operationID = data.readInt(); + revision = data.readInt(); - EnumSyncType type = EnumSyncType.values()[syncTypeOrdinal]; EnumSyncAction action = EnumSyncAction.values()[syncActionOrdinal]; - try { - NBTTagCompound tag = ByteBufUtils.readBigNBT(data); - // Now do your client-side logic (similar to your old clientSync() or clientSyncUpdate() approach) - handleSyncPacketClient(type, action, categoryID, incomingRevision, tag); - } catch (RuntimeException e) { - LogWriter.error(String.format("Attempted to Sync %s but it was too big", type.toString())); + + // These fields only exist for UPDATE/REMOVE + if (action != EnumSyncAction.RELOAD) { + if (data.readBoolean()) operationKey = ByteBufUtils.readString(data); + if (data.readBoolean()) syncData = ByteBufUtils.readBigNBT(data); + } else + syncData = ByteBufUtils.readBigNBT(data); + + + syncType = SyncType.byOrdinal(syncTypeOrdinal); + if (syncType == null) { + LogWriter.error("[SyncPacket] Unknown sync type ordinal: " + syncTypeOrdinal + "; skipping"); + return; } + + handleSync(syncType, action, operationID, operationKey, revision, syncData); } - private void handleSyncPacketClient( - EnumSyncType enumSyncType, - EnumSyncAction enumSyncAction, - int id, - int incomingRevision, - NBTTagCompound data - ) { - switch (enumSyncAction) { + private void handleSync(SyncType type, EnumSyncAction action, int id, String key, int revision, NBTTagCompound data) { + switch (action) { case RELOAD: - SyncController.clientSync(enumSyncType, incomingRevision, data); + SyncController.clientHandleAll(type, revision, data); break; case UPDATE: - SyncController.clientUpdate(enumSyncType, id, incomingRevision, data); + SyncController.clientHandleUpdate(type, id, key, revision, data); break; case REMOVE: - SyncController.clientSyncRemove(enumSyncType, id, incomingRevision); + SyncController.clientHandleRemove(type, id, key, revision); break; } } diff --git a/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java index 3ce74eb4c..cf0fb3a36 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java @@ -17,6 +17,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import noppes.npcs.NoppesUtilServer; import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionPage; import noppes.npcs.constants.EnumGuiType; import noppes.npcs.constants.EnumRoleType; import noppes.npcs.controllers.AuctionController; @@ -39,7 +40,8 @@ public class AuctionActionPacket extends AbstractPacket { private long amount; private NBTTagCompound data; - public AuctionActionPacket() {} + public AuctionActionPacket() { + } private AuctionActionPacket(Action action) { this.action = action; @@ -57,7 +59,9 @@ public class AuctionActionPacket extends AbstractPacket { } @Override - public boolean needsNPC() { return false; } // Allow opening via command without NPC + public boolean needsNPC() { + return false; + } // Allow opening via command without NPC // ========================================= // Client-side static methods @@ -116,7 +120,9 @@ public class AuctionActionPacket extends AbstractPacket { PacketClient.sendClient(packet); } - /** Request listings from server with filter and page */ + /** + * Request listings from server with filter and page + */ @SideOnly(Side.CLIENT) public static void requestListings(AuctionFilter filter, int page) { AuctionActionPacket packet = new AuctionActionPacket(Action.RequestListings); @@ -130,10 +136,14 @@ public class AuctionActionPacket extends AbstractPacket { // ========================================= @Override - public Enum getType() { return EnumPlayerPacket.AuctionAction; } + public Enum getType() { + return EnumPlayerPacket.AuctionAction; + } @Override - public PacketChannel getChannel() { return PacketHandler.PLAYER_PACKET; } + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } @Override @SideOnly(Side.CLIENT) @@ -290,7 +300,10 @@ public class AuctionActionPacket extends AbstractPacket { long startingPrice = in.readLong(); String buyoutStr = ByteBufUtils.readString(in); long buyoutPrice = 0; - try { buyoutPrice = Long.parseLong(buyoutStr); } catch (NumberFormatException ignored) {} + try { + buyoutPrice = Long.parseLong(buyoutStr); + } catch (NumberFormatException ignored) { + } NBTTagCompound itemNBT = ByteBufUtils.readNBT(in); if (itemNBT == null) return "No item data received."; @@ -298,6 +311,10 @@ public class AuctionActionPacket extends AbstractPacket { ItemStack item = ItemStack.loadItemStackFromNBT(itemNBT); if (item == null) return "Invalid item data."; + // Validate stack size + if (item.stackSize <= 0) return "Invalid item amount."; + if (item.stackSize > item.getMaxStackSize()) return "Stack size exceeds item maximum."; + // Remove item from inventory first if (!removeItemFromInventory(player, item)) { return "Item not found in inventory."; @@ -315,13 +332,8 @@ public class AuctionActionPacket extends AbstractPacket { private void handleOpenPage(ByteBuf in, EntityPlayerMP player) { int page = in.readInt(); - EnumGuiType guiType; - switch (page) { - case 0: guiType = EnumGuiType.PlayerAuction; break; - case 1: guiType = EnumGuiType.PlayerAuctionSell; break; - case 2: guiType = EnumGuiType.PlayerAuctionTrades; break; - default: guiType = EnumGuiType.PlayerAuction; break; - } + EnumAuctionPage auctionPage = EnumAuctionPage.fromOrdinal(page); + EnumGuiType guiType = auctionPage.getGuiType(); NoppesUtilServer.sendOpenGui(player, guiType, npc); // Send trades data when opening the trades page @@ -333,7 +345,9 @@ public class AuctionActionPacket extends AbstractPacket { } } - /** Send full trades data to player (listings, bids, claims) */ + /** + * Send full trades data to player (listings, bids, claims) + */ private void sendTradesData(EntityPlayerMP player, AuctionController controller) { NBTTagCompound response = new NBTTagCompound(); response.setBoolean("TradesData", true); @@ -481,6 +495,9 @@ public class AuctionActionPacket extends AbstractPacket { } else { // Need only part of stack stack.splitStack(needed); + if (stack.stackSize <= 0) { + player.inventory.setInventorySlotContents(i, null); + } needed = 0; } } 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 a58b896f4..3592e1a9a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -57,19 +57,19 @@ public final class SpecialKeyStatePacket extends AbstractPacket { boolean wasDown = data.isSpecialKeyDown(); data.setSpecialKeyDown(keyDown); - // Trigger ability activation on key press (rising edge) + // Trigger ability activation or cancel 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); + // If currently executing an ability, try to cancel via double-press + if (data.abilityData.isExecutingAbility() || data.abilityData.isExecutingChain()) { + data.abilityData.tryCancelAbility(); + } else { + data.abilityData.activateAbility(player); + } } } } diff --git a/src/main/java/kamkeel/npcs/network/packets/player/SyncRevisionInfoPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/SyncRevisionInfoPacket.java index 769b086b7..b6becdaab 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SyncRevisionInfoPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SyncRevisionInfoPacket.java @@ -8,13 +8,13 @@ import kamkeel.npcs.network.AbstractPacket; import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumPlayerPacket; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import java.io.IOException; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.Map; public class SyncRevisionInfoPacket extends AbstractPacket { @@ -23,12 +23,12 @@ public class SyncRevisionInfoPacket extends AbstractPacket { private String serverKey = ""; private String previousServerKey = ""; - private final EnumMap revisions = new EnumMap<>(EnumSyncType.class); + private final Map revisions = new LinkedHashMap<>(); public SyncRevisionInfoPacket() { } - public SyncRevisionInfoPacket(String serverKey, String previousServerKey, EnumMap revisions) { + public SyncRevisionInfoPacket(String serverKey, String previousServerKey, Map revisions) { if (serverKey != null) { this.serverKey = serverKey; } @@ -56,7 +56,7 @@ public class SyncRevisionInfoPacket extends AbstractPacket { ByteBufUtils.writeString(out, serverKey); ByteBufUtils.writeString(out, previousServerKey); out.writeShort(revisions.size()); - for (Map.Entry entry : revisions.entrySet()) { + for (Map.Entry entry : revisions.entrySet()) { out.writeInt(entry.getKey().ordinal()); out.writeInt(entry.getValue()); } @@ -71,13 +71,15 @@ public class SyncRevisionInfoPacket extends AbstractPacket { String incomingServerKey = ByteBufUtils.readString(in); String incomingPreviousKey = ByteBufUtils.readString(in); int revisionCount = in.readUnsignedShort(); - EnumMap incomingRevisions = new EnumMap<>(EnumSyncType.class); + Map incomingRevisions = new LinkedHashMap<>(); for (int i = 0; i < revisionCount; i++) { - EnumSyncType type = EnumSyncType.values()[in.readInt()]; + SyncType type = SyncType.byOrdinal(in.readInt()); int revision = in.readInt(); - incomingRevisions.put(type, revision); + if (type != null) { + incomingRevisions.put(type, revision); + } } - SyncController.handleClientRevisionReport((EntityPlayerMP) player, incomingServerKey, incomingPreviousKey, incomingRevisions); + SyncController.completeLoginRevisionHandshake((EntityPlayerMP) player, incomingServerKey, incomingPreviousKey, incomingRevisions); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java new file mode 100644 index 000000000..687a00a1f --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java @@ -0,0 +1,91 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSavePacket extends AbstractPacket { + public static final String packetName = "Player|AbilityHotbarSave"; + + private int slotIndex; + private NBTTagCompound slotData; + + public AbilityHotbarSavePacket() { + } + + public AbilityHotbarSavePacket(int slotIndex, NBTTagCompound slotData) { + this.slotIndex = slotIndex; + this.slotData = slotData; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityHotbarSave; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(slotIndex); + ByteBufUtils.writeNBT(out, slotData); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + int slot = in.readInt(); + NBTTagCompound compound = ByteBufUtils.readNBT(in); + if (compound == null) return; + + if (slot < 0 || slot >= AbilityHotbarData.TOTAL_SLOTS) return; + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + AbilityHotbarData slotData = data.hotbarData.getSlot(slot); + if (slotData == null) return; + + slotData.readFromNBT(compound.getCompoundTag("AbilityHotbar" + slot)); + + // Validate the ability key + boolean valid = true; + if (!slotData.isEmpty() && AbilityController.Instance != null) { + if (slotData.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slotData.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slotData.abilityKey); + } + + if (valid && data.abilityData != null) { + valid = data.abilityData.hasUnlockedAbility(slotData.abilityKey); + // For chains, also check with resolved key in case key format differs + if (!valid && slotData.isChainKey()) { + valid = data.abilityData.hasUnlockedAbility("chain:" + slotData.getResolveKey()); + } + } + } + + if (!valid) { + slotData.reset(); + } + + data.save(); + AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java new file mode 100644 index 000000000..87affdc1b --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java @@ -0,0 +1,59 @@ +package kamkeel.npcs.network.packets.player.ability; + +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.EnumPlayerPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSelectPacket extends AbstractPacket { + public static final String packetName = "Player|AbilityHotbarSelect"; + + private String abilityKey; + + public AbilityHotbarSelectPacket() { + } + + public AbilityHotbarSelectPacket(String abilityKey) { + this.abilityKey = abilityKey; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityHotbarSelect; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityKey != null ? abilityKey : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String key = ByteBufUtils.readString(in); + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null || data.abilityData == null) return; + + if (key == null || key.isEmpty()) { + // Deselect + data.abilityData.setSelectedIndex(-1); + } else { + // A key the player no longer has deselects rather than leaving the previous + // selection in place, which would fire a different ability than the one shown. + data.abilityData.setSelectedIndex(data.abilityData.getUnlockedAbilityList().indexOf(key)); + } + data.save(); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java new file mode 100644 index 000000000..199bd3e76 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java @@ -0,0 +1,76 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.StatCollector; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityTogglePacket extends AbstractPacket { + public static final String packetName = "Player|AbilityToggle"; + private String abilityKey; + + public AbilityTogglePacket() { + } + + public AbilityTogglePacket(String abilityKey) { + this.abilityKey = abilityKey; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityToggle; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityKey != null ? abilityKey : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String key = ByteBufUtils.readString(in); + if (key == null || key.isEmpty()) return; + if (AbilityController.Instance == null) return; + + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null || !ability.isToggleable() || !ability.getAllowedBy().allowsPlayer()) return; + + PlayerData playerData = PlayerData.get(player); + if (playerData == null || playerData.abilityData == null) return; + if (!playerData.abilityData.hasUnlockedAbility(key)) return; + + int newState = playerData.abilityData.toggleAbility(key); + + // Sync toggle states to client (toggle may have side effects like mutual exclusivity) + playerData.abilityData.syncToClient(); + + String displayName = ability.getDisplayName(); + if (newState > 0) { + String stateLabel = ability.getToggleStateLabel(newState); + if (stateLabel != null) { + player.addChatMessage(new ChatComponentText("\u00A7a" + displayName + " " + stateLabel)); + } else { + String enabled = StatCollector.translateToLocal("gui.enabled"); + player.addChatMessage(new ChatComponentText("\u00A7a" + displayName + " " + enabled)); + } + } else { + String disabled = StatCollector.translateToLocal("gui.disabled"); + player.addChatMessage(new ChatComponentText("\u00A7c" + displayName + " " + disabled)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/GuiRequestPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/GuiRequestPacket.java index fbfae0a6e..b880d141a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/GuiRequestPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/GuiRequestPacket.java @@ -11,6 +11,9 @@ import kamkeel.npcs.network.enums.EnumItemPacketType; import kamkeel.npcs.network.enums.EnumRequestPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import noppes.npcs.CustomNpcsPermissions; import noppes.npcs.NoppesUtilServer; import noppes.npcs.constants.EnumGuiType; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesGetAllPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesGetAllPacket.java index eb74bbce4..bf2e4efb4 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesGetAllPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesGetAllPacket.java @@ -6,6 +6,8 @@ import io.netty.buffer.ByteBuf; 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 net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -39,6 +41,8 @@ public class AbilitiesGetAllPacket extends AbstractPacket { public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { if (!(player instanceof EntityPlayerMP)) return; + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; NoppesUtilServer.sendAbilityTypesInfo((EntityPlayerMP) player); } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcSavePacket.java index a7a032d9f..531e6351d 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcSavePacket.java @@ -64,6 +64,7 @@ public final class AbilitiesNpcSavePacket extends AbstractPacket { return; NBTTagCompound compound = ByteBufUtils.readNBT(in); + if (compound == null) return; npc.abilities.readFromNBT(compound); } } 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..42a63a79e --- /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.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +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(false); + compound.setBoolean("BuiltIn", true); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitiesGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitiesGetPacket.java new file mode 100644 index 000000000..97ccfa52d --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitiesGetPacket.java @@ -0,0 +1,51 @@ +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.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 net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.NoppesUtilServer; + +import java.io.IOException; + +/** + * Request packet to get list of all chained ability names. + */ +public final class ChainedAbilitiesGetPacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilitiesGet"; + + public ChainedAbilitiesGetPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilitiesGet; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + NoppesUtilServer.sendChainedAbilitiesData((EntityPlayerMP) player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityClonePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityClonePacket.java new file mode 100644 index 000000000..07ab7d3d1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityClonePacket.java @@ -0,0 +1,71 @@ +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.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +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 noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; + +import java.io.IOException; + +public final class ChainedAbilityClonePacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilityClone"; + + private String name; + + public ChainedAbilityClonePacket() { + } + + public ChainedAbilityClonePacket(String name) { + this.name = name; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilityClone; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_ABILITY; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, name); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + String chainName = ByteBufUtils.readString(in); + ChainedAbility clone = AbilityController.Instance.cloneChainedAbility(chainName); + if (clone != null) { + NoppesUtilServer.sendChainedAbilitiesData((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, clone.writeNBT(false)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java new file mode 100644 index 000000000..cecc8c9e5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java @@ -0,0 +1,68 @@ +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.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +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 chained ability by name. + */ +public final class ChainedAbilityGetPacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilityGet"; + + private String name; + + public ChainedAbilityGetPacket() { + } + + public ChainedAbilityGetPacket(String name) { + this.name = name; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilityGet; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, name); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + String chainName = ByteBufUtils.readString(in); + ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName); + if (chain != null) { + NBTTagCompound compound = chain.writeNBT(false); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityRemovePacket.java new file mode 100644 index 000000000..b373d6331 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityRemovePacket.java @@ -0,0 +1,69 @@ +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.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.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; + +import java.io.IOException; + +/** + * Request packet to remove a chained ability by name. + */ +public final class ChainedAbilityRemovePacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilityRemove"; + + private String name; + + public ChainedAbilityRemovePacket() { + } + + public ChainedAbilityRemovePacket(String name) { + this.name = name; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilityRemove; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_ABILITY; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, name); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + String chainName = ByteBufUtils.readString(in); + AbilityController.Instance.deleteChainedAbility(chainName); + NoppesUtilServer.sendChainedAbilitiesData((EntityPlayerMP) player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java new file mode 100644 index 000000000..f270a8785 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java @@ -0,0 +1,79 @@ +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.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +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 noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; + +import java.io.IOException; + +/** + * Request packet to save a chained ability. + */ +public final class ChainedAbilitySavePacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilitySave"; + + private NBTTagCompound chainNBT; + + public ChainedAbilitySavePacket() { + } + + public ChainedAbilitySavePacket(NBTTagCompound chainNBT) { + this.chainNBT = chainNBT; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilitySave; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_ABILITY; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, chainNBT); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + NBTTagCompound compound = ByteBufUtils.readNBT(in); + if (compound == null) return; + ChainedAbility chain = new ChainedAbility(); + chain.readNBT(compound); + + if (chain.getName() != null && !chain.getName().isEmpty()) { + AbilityController.Instance.saveChainedAbility(chain); + NoppesUtilServer.sendChainedAbilitiesData((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, chain.writeNBT(false)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CopyAbilityScriptsPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CopyAbilityScriptsPacket.java new file mode 100644 index 000000000..628b761f8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CopyAbilityScriptsPacket.java @@ -0,0 +1,130 @@ +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.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +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.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; + +import java.io.IOException; + +/** + * Copies script data from a source ability/chain to a target UUID. + * Used when cloning into an NPC as inline - the clone gets a new UUID + * but needs the source's script handler copied server-side (scripts are never sent to client). + * + * Mode 0 = ability scripts, Mode 1 = chained ability scripts. + */ +public final class CopyAbilityScriptsPacket extends AbstractPacket { + public static String packetName = "Request|CopyAbilityScripts"; + + public static final int MODE_ABILITY = 0; + public static final int MODE_CHAINED = 1; + + private int mode; + private String sourceName; + private String targetId; + + public CopyAbilityScriptsPacket() { + } + + public CopyAbilityScriptsPacket(String sourceName, String targetId) { + this(MODE_ABILITY, sourceName, targetId); + } + + public CopyAbilityScriptsPacket(int mode, String sourceName, String targetId) { + this.mode = mode; + this.sourceName = sourceName; + this.targetId = targetId; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CopyAbilityScripts; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_ABILITY; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeByte(mode); + ByteBufUtils.writeString(out, sourceName); + ByteBufUtils.writeString(out, targetId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int mode = in.readByte(); + String sourceName = ByteBufUtils.readString(in); + String targetId = ByteBufUtils.readString(in); + + if (targetId == null || targetId.isEmpty()) return; + + if (mode == MODE_CHAINED) { + copyChainedAbilityScripts(sourceName, targetId); + } else { + copyAbilityScripts(sourceName, targetId); + } + } + + private void copyAbilityScripts(String sourceKey, String targetId) { + // Try name-based lookup first + Ability source = AbilityController.Instance.getCustomAbility(sourceKey); + + AbilityScript sourceHandler; + if (source != null) { + sourceHandler = source.getScriptHandler(); + } else { + // sourceKey might be a UUID - try direct handler lookup + sourceHandler = AbilityController.Instance.abilityScriptHandlers.get(sourceKey); + } + if (sourceHandler == null) return; + + NBTTagCompound scriptNbt = sourceHandler.writeToNBT(new NBTTagCompound()); + AbilityScript targetHandler = new AbilityScript(targetId); + targetHandler.readFromNBT(scriptNbt); + AbilityController.Instance.abilityScriptHandlers.put(targetId, targetHandler); + } + + private void copyChainedAbilityScripts(String sourceName, String targetId) { + ChainedAbility source = AbilityController.Instance.getChainedAbility(sourceName); + if (source == null) return; + + ChainedAbilityScript sourceHandler = source.getScriptHandler(); + if (sourceHandler == null) return; + + NBTTagCompound scriptNbt = sourceHandler.writeToNBT(new NBTTagCompound()); + ChainedAbilityScript targetHandler = new ChainedAbilityScript(targetId); + targetHandler.readFromNBT(scriptNbt); + AbilityController.Instance.chainedAbilityScriptHandlers.put(targetId, targetHandler); + } +} 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/network/packets/request/ability/CustomAbilityClonePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityClonePacket.java new file mode 100644 index 000000000..03045a25f --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityClonePacket.java @@ -0,0 +1,71 @@ +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.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +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 noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; + +import java.io.IOException; + +public final class CustomAbilityClonePacket extends AbstractPacket { + public static String packetName = "Request|CustomAbilityClone"; + + private String name; + + public CustomAbilityClonePacket() { + } + + public CustomAbilityClonePacket(String name) { + this.name = name; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CustomAbilityClone; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_ABILITY; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, name); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + String abilityName = ByteBufUtils.readString(in); + Ability clone = AbilityController.Instance.cloneCustomAbility(abilityName); + if (clone != null) { + NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, clone.writeNBT(false)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java index d95051a66..b0556926a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java @@ -3,8 +3,8 @@ 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.AbilityController; 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; @@ -20,18 +20,18 @@ import net.minecraft.nbt.NBTTagCompound; import java.io.IOException; /** - * Request packet to get a specific custom ability by UUID. + * Request packet to get a specific custom ability by name. */ public final class CustomAbilityGetPacket extends AbstractPacket { public static String packetName = "Request|CustomAbilityGet"; - private String uuid; + private String name; public CustomAbilityGetPacket() { } - public CustomAbilityGetPacket(String uuid) { - this.uuid = uuid; + public CustomAbilityGetPacket(String name) { + this.name = name; } @Override @@ -47,7 +47,7 @@ public final class CustomAbilityGetPacket extends AbstractPacket { @SideOnly(Side.CLIENT) @Override public void sendData(ByteBuf out) throws IOException { - ByteBufUtils.writeString(out, uuid); + ByteBufUtils.writeString(out, name); } @Override @@ -58,12 +58,10 @@ public final class CustomAbilityGetPacket extends AbstractPacket { if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) return; - String id = ByteBufUtils.readString(in); - Ability ability = AbilityController.Instance.getCustomAbility(id); + String abilityName = ByteBufUtils.readString(in); + Ability ability = AbilityController.Instance.getCustomAbility(abilityName); if (ability != null) { - NBTTagCompound compound = ability.writeNBT(); - // Include the UUID so the client can track it - compound.setString("_uuid", id); + NBTTagCompound compound = ability.writeNBT(false); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityRemovePacket.java index 3ef040700..ae65c374f 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityRemovePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityRemovePacket.java @@ -3,7 +3,7 @@ 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.AbilityController; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.network.AbstractPacket; import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketHandler; @@ -19,18 +19,18 @@ import noppes.npcs.NoppesUtilServer; import java.io.IOException; /** - * Request packet to remove a custom ability by UUID. + * Request packet to remove a custom ability by name. */ public final class CustomAbilityRemovePacket extends AbstractPacket { public static String packetName = "Request|CustomAbilityRemove"; - private String uuid; + private String name; public CustomAbilityRemovePacket() { } - public CustomAbilityRemovePacket(String uuid) { - this.uuid = uuid; + public CustomAbilityRemovePacket(String name) { + this.name = name; } @Override @@ -51,7 +51,7 @@ public final class CustomAbilityRemovePacket extends AbstractPacket { @SideOnly(Side.CLIENT) @Override public void sendData(ByteBuf out) throws IOException { - ByteBufUtils.writeString(out, uuid); + ByteBufUtils.writeString(out, name); } @Override diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java index d5ca1c556..8c075bb25 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java @@ -3,8 +3,8 @@ 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.AbilityController; 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; @@ -66,12 +66,12 @@ public final class CustomAbilitySavePacket extends AbstractPacket { return; NBTTagCompound compound = ByteBufUtils.readNBT(in); + if (compound == null) return; Ability ability = AbilityController.Instance.fromNBT(compound); if (ability != null) { AbilityController.Instance.saveCustomAbility(ability); NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); - NBTTagCompound responseNbt = ability.writeNBT(); - responseNbt.setString("_uuid", ability.getId()); + NBTTagCompound responseNbt = ability.writeNBT(false); GuiDataPacket.sendGuiData((EntityPlayerMP) player, responseNbt); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationClonePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationClonePacket.java new file mode 100644 index 000000000..b9797f684 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationClonePacket.java @@ -0,0 +1,69 @@ +package kamkeel.npcs.network.packets.request.animation; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.Animation; + +import java.io.IOException; + +public final class AnimationClonePacket extends AbstractPacket { + public static String packetName = "Request|AnimationClone"; + + private int id; + + public AnimationClonePacket() { + } + + public AnimationClonePacket(int id) { + this.id = id; + } + + @Override + public Enum getType() { + return EnumRequestPacket.AnimationClone; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_ANIMATION; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(this.id); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int animationId = in.readInt(); + Animation clone = AnimationController.getInstance().cloneAnimation(animationId); + if (clone != null) { + NoppesUtilServer.sendAnimationDataAll((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, clone.writeToNBT()); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/animation/BuiltInAnimationGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/animation/BuiltInAnimationGetPacket.java index e214689d8..d25935892 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/animation/BuiltInAnimationGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/animation/BuiltInAnimationGetPacket.java @@ -15,7 +15,6 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.BuiltInAnimation; import java.io.IOException; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/auction/ManageAuctionPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/auction/ManageAuctionPacket.java new file mode 100644 index 000000000..f2ad4c961 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/auction/ManageAuctionPacket.java @@ -0,0 +1,523 @@ +package kamkeel.npcs.network.packets.request.auction; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.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.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumGuiType; +import noppes.npcs.constants.EnumClaimType; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.data.AuctionClaim; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Admin-only global auction management packet. + */ +public class ManageAuctionPacket extends AbstractPacket { + private static final int PAGE_SIZE = 45; + + private Action action; + private int page; + private boolean flag; + private String text; + private long amount; + private long amount2; + private int amountInt; + private NBTTagCompound data; + + public ManageAuctionPacket() { + } + + private ManageAuctionPacket(Action action) { + this.action = action; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ManageAuctionAction; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_AUCTION; + } + + @Override + public boolean needsNPC() { + return false; + } + + // ========================================= + // Client Send Helpers + // ========================================= + + @SideOnly(Side.CLIENT) + public static void requestListings(AuctionFilter filter, int page) { + ManageAuctionPacket packet = new ManageAuctionPacket(Action.REQUEST_LISTINGS); + packet.page = page; + packet.data = filter != null ? filter.writeToNBT(new NBTTagCompound()) : new NBTTagCompound(); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void requestGlobalClaims(int page) { + ManageAuctionPacket packet = new ManageAuctionPacket(Action.REQUEST_CLAIMS); + packet.page = page; + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void createFakeListing(ItemStack item, String sellerName, long startingPrice, long buyoutPrice, int durationHours) { + if (item == null) return; + + ManageAuctionPacket packet = new ManageAuctionPacket(Action.CREATE_FAKE); + packet.text = sellerName != null ? sellerName : ""; + packet.amount = startingPrice; + packet.amount2 = buyoutPrice; + packet.amountInt = durationHours; + packet.data = new NBTTagCompound(); + item.writeToNBT(packet.data); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void manageListing(String listingId, boolean cancelCompletely) { + ManageAuctionPacket packet = new ManageAuctionPacket(Action.MANAGE_LISTING); + packet.text = listingId; + packet.flag = cancelCompletely; + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void claimGlobalItem(String claimId) { + ManageAuctionPacket packet = new ManageAuctionPacket(Action.CLAIM_ITEM); + packet.text = claimId; + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void claimGlobalCurrency(String claimId) { + ManageAuctionPacket packet = new ManageAuctionPacket(Action.CLAIM_CURRENCY); + packet.text = claimId; + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void openBidding(String listingId) { + ManageAuctionPacket packet = new ManageAuctionPacket(Action.OPEN_BIDDING); + packet.text = listingId; + PacketClient.sendClient(packet); + } + + // ========================================= + // Serialization + // ========================================= + + @Override + @SideOnly(Side.CLIENT) + public void sendData(ByteBuf out) throws IOException { + out.writeInt(action.ordinal()); + + switch (action) { + case REQUEST_LISTINGS: + out.writeInt(page); + ByteBufUtils.writeNBT(out, data); + break; + case REQUEST_CLAIMS: + out.writeInt(page); + break; + case CREATE_FAKE: + ByteBufUtils.writeString(out, text); + out.writeLong(amount); + out.writeLong(amount2); + out.writeInt(amountInt); + ByteBufUtils.writeNBT(out, data); + break; + case MANAGE_LISTING: + ByteBufUtils.writeString(out, text); + out.writeBoolean(flag); + break; + case CLAIM_ITEM: + case CLAIM_CURRENCY: + case OPEN_BIDDING: + ByteBufUtils.writeString(out, text); + break; + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) return; + EntityPlayerMP playerMP = (EntityPlayerMP) player; + + if (!CustomNpcsPermissions.hasCustomPermission(playerMP, "customnpcs.global.auction")) { + sendError(playerMP, "Missing permission: customnpcs.global.auction"); + return; + } + + int actionOrdinal = in.readInt(); + if (actionOrdinal < 0 || actionOrdinal >= Action.values().length) return; + Action requestedAction = Action.values()[actionOrdinal]; + + AuctionController controller = AuctionController.getInstance(); + if (controller == null) { + sendError(playerMP, "Auction system is not available."); + return; + } + + String result = null; + switch (requestedAction) { + case REQUEST_LISTINGS: + handleRequestListings(in, playerMP, controller); + break; + case REQUEST_CLAIMS: + handleRequestClaims(in, playerMP, controller); + break; + case CREATE_FAKE: + result = handleCreateFake(in, playerMP, controller); + break; + case MANAGE_LISTING: + result = handleManageListing(in, playerMP, controller); + break; + case CLAIM_ITEM: + result = handleClaimItem(in, playerMP, controller); + break; + case CLAIM_CURRENCY: + result = handleClaimCurrency(in, playerMP, controller); + break; + case OPEN_BIDDING: + handleOpenBidding(in, playerMP, controller); + break; + } + + if (result != null) { + sendError(playerMP, result); + } + } + + // ========================================= + // Handlers + // ========================================= + + private void handleRequestListings(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + int requestPage = Math.max(0, in.readInt()); + NBTTagCompound filterNbt = ByteBufUtils.readNBT(in); + + AuctionFilter filter = new AuctionFilter(); + if (filterNbt != null) { + filter.readFromNBT(filterNbt); + } + + int totalListings = controller.getTotalActiveListings(filter); + int totalPages = Math.max(1, (int) Math.ceil((double) totalListings / PAGE_SIZE)); + int safePage = Math.min(requestPage, totalPages - 1); + List listings = controller.getActiveListings(filter, safePage, PAGE_SIZE); + + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("ManageAuctionListingsData", true); + response.setInteger("Page", safePage); + response.setInteger("TotalPages", totalPages); + response.setInteger("TotalListings", totalListings); + + NBTTagList list = new NBTTagList(); + for (AuctionListing listing : listings) { + list.appendTag(listing.writeToNBT(new NBTTagCompound())); + } + response.setTag("Listings", list); + GuiDataPacket.sendGuiData(player, response); + } + + private void handleRequestClaims(ByteBuf in, EntityPlayerMP player, AuctionController controller) { + int requestPage = Math.max(0, in.readInt()); + + // Global "trades" page contains global claims + active global listings, + // ordered like My Trades: sold claims, outbid claims, won claims, active listings, expired claims. + List allClaims = controller.getAllGlobalClaims(); + List allListings = controller.getActiveGlobalListings(); + int totalClaims = allClaims.size(); + int totalListings = allListings.size(); + + List soldClaims = new ArrayList(); + List outbidClaims = new ArrayList(); + List wonClaims = new ArrayList(); + List expiredClaims = new ArrayList(); + for (AuctionClaim claim : allClaims) { + if (claim == null) continue; + if (claim.type == EnumClaimType.CURRENCY) { + soldClaims.add(claim); + } else if (claim.type == EnumClaimType.REFUND) { + outbidClaims.add(claim); + } else if (claim.type == EnumClaimType.ITEM) { + if (claim.isReturned) { + expiredClaims.add(claim); + } else { + wonClaims.add(claim); + } + } else { + wonClaims.add(claim); + } + } + + List ordered = new ArrayList(); + appendClaims(ordered, soldClaims); + appendClaims(ordered, outbidClaims); + appendClaims(ordered, wonClaims); + for (AuctionListing listing : allListings) { + ordered.add(Entry.forListing(listing)); + } + appendClaims(ordered, expiredClaims); + + int totalEntries = ordered.size(); + + int totalPages = Math.max(1, (int) Math.ceil((double) totalEntries / PAGE_SIZE)); + int safePage = Math.min(requestPage, totalPages - 1); + + int start = safePage * PAGE_SIZE; + int end = Math.min(totalEntries, start + PAGE_SIZE); + List pageClaims = new ArrayList(); + List pageListings = new ArrayList(); + + for (int i = start; i < end; i++) { + Entry entry = ordered.get(i); + if (entry.claim != null) { + pageClaims.add(entry.claim); + } else if (entry.listing != null) { + pageListings.add(entry.listing); + } + } + + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("ManageAuctionClaimsData", true); + response.setInteger("Page", safePage); + response.setInteger("TotalPages", totalPages); + response.setInteger("TotalClaims", totalClaims); + response.setInteger("TotalListings", totalListings); + response.setInteger("TotalEntries", totalEntries); + + NBTTagList claimList = new NBTTagList(); + for (AuctionClaim claim : pageClaims) { + claimList.appendTag(claim.writeToNBT(new NBTTagCompound())); + } + response.setTag("Claims", claimList); + + NBTTagList listingList = new NBTTagList(); + for (AuctionListing listing : pageListings) { + listingList.appendTag(listing.writeToNBT(new NBTTagCompound())); + } + response.setTag("Listings", listingList); + GuiDataPacket.sendGuiData(player, response); + } + + private static void appendClaims(List out, List claims) { + if (claims == null || claims.isEmpty()) return; + for (AuctionClaim claim : claims) { + out.add(Entry.forClaim(claim)); + } + } + + private String handleCreateFake(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + if (!ConfigMarket.AuctionEnabled) { + return "Auction is disabled."; + } + + String sellerName = ByteBufUtils.readString(in); + long startingPrice = in.readLong(); + long buyoutPrice = in.readLong(); + int durationHours = in.readInt(); + NBTTagCompound itemNbt = ByteBufUtils.readNBT(in); + + if (itemNbt == null) { + return "No item data received."; + } + ItemStack item = ItemStack.loadItemStackFromNBT(itemNbt); + if (item == null) { + return "Invalid item data."; + } + + // Consume staged item from admin inventory like normal auction sell flow. + if (!removeItemFromInventory(player, item)) { + return "Item not found in inventory."; + } + + String result = controller.createGlobalListing(player, sellerName, item, startingPrice, buyoutPrice, durationHours); + if (result != null) { + // Failed create, return item (or drop to avoid loss). + // Use same reference so partial add mutates stackSize, then drop only the remainder. + if (!player.inventory.addItemStackToInventory(item)) { + player.entityDropItem(item, 0.5f); + } + } + if (result == null) { + sendRefresh(player, true); + } + return result; + } + + private String handleManageListing(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String listingId = ByteBufUtils.readString(in); + boolean cancelCompletely = in.readBoolean(); + String result = controller.adminStopListingToGlobal(listingId, player, cancelCompletely); + if (result == null) { + sendRefresh(player, false); + } + return result; + } + + private String handleClaimItem(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String claimId = ByteBufUtils.readString(in); + String result = controller.claimGlobalItem(claimId, player); + if (result == null) { + sendRefresh(player, false); + } + return result; + } + + private String handleClaimCurrency(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String claimId = ByteBufUtils.readString(in); + String result = controller.claimGlobalCurrency(claimId, player); + if (result == null) { + sendRefresh(player, false); + } + return result; + } + + private void handleOpenBidding(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String listingId = ByteBufUtils.readString(in); + AuctionListing listing = controller.getListing(listingId); + if (listing == null || !listing.isActive()) { + sendError(player, "Listing not found or has ended."); + return; + } + + NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuctionBidding, npc); + + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("BiddingData", true); + response.setTag("Listing", listing.writeToNBT(new NBTTagCompound())); + response.setLong("Balance", controller.getPlayerBalance(player)); + response.setBoolean("IsOwnListing", listing.isSeller(player.getUniqueID())); + GuiDataPacket.sendGuiData(player, response); + } + + private void sendError(EntityPlayerMP player, String message) { + player.addChatMessage(new net.minecraft.util.ChatComponentText( + net.minecraft.util.EnumChatFormatting.RED + "[Global Auction] " + message)); + } + + private void sendRefresh(EntityPlayerMP player, boolean created) { + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("ManageAuctionRefresh", true); + response.setBoolean("ManageAuctionCreateSuccess", created); + GuiDataPacket.sendGuiData(player, response); + } + + /** + * Checks if two ItemStacks are the same type (item, damage, NBT) ignoring stack size. + */ + private boolean areItemsSameType(ItemStack item1, ItemStack item2) { + if (item1 == null || item2 == null) + return item1 == item2; + if (item1.getItem() != item2.getItem()) + return false; + if (item1.getItemDamage() != item2.getItemDamage()) + return false; + return ItemStack.areItemStackTagsEqual(item1, item2); + } + + private int countItemsInInventory(EntityPlayerMP player, ItemStack target) { + int count = 0; + for (int i = 0; i < player.inventory.mainInventory.length; i++) { + ItemStack stack = player.inventory.mainInventory[i]; + if (stack != null && areItemsSameType(stack, target)) { + count += stack.stackSize; + } + } + return count; + } + + /** + * Removes items from inventory, consuming from multiple stacks if needed. + * Returns true if successful, false if not enough items. + */ + private boolean removeItemFromInventory(EntityPlayerMP player, ItemStack target) { + if (target == null) return false; + + int needed = target.stackSize; + int available = countItemsInInventory(player, target); + if (available < needed) { + return false; + } + + for (int i = 0; i < player.inventory.mainInventory.length && needed > 0; i++) { + ItemStack stack = player.inventory.mainInventory[i]; + if (stack == null || !areItemsSameType(stack, target)) + continue; + + if (needed >= stack.stackSize) { + needed -= stack.stackSize; + player.inventory.mainInventory[i] = null; + } else { + stack.splitStack(needed); + if (stack.stackSize <= 0) { + player.inventory.setInventorySlotContents(i, null); + } + needed = 0; + } + } + + player.inventory.markDirty(); + return true; + } + + private static class Entry { + final AuctionClaim claim; + final AuctionListing listing; + + private Entry(AuctionClaim claim, AuctionListing listing) { + this.claim = claim; + this.listing = listing; + } + + static Entry forClaim(AuctionClaim claim) { + return new Entry(claim, null); + } + + static Entry forListing(AuctionListing listing) { + return new Entry(null, listing); + } + } + + private enum Action { + REQUEST_LISTINGS, + REQUEST_CLAIMS, + CREATE_FAKE, + MANAGE_LISTING, + CLAIM_ITEM, + CLAIM_CURRENCY, + OPEN_BIDDING + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/category/AbilityCategoryMovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/category/AbilityCategoryMovePacket.java new file mode 100644 index 000000000..4912bcd28 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/category/AbilityCategoryMovePacket.java @@ -0,0 +1,81 @@ +package kamkeel.npcs.network.packets.request.category; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.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.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.controllers.CategoryManager; + +import java.io.IOException; + +public final class AbilityCategoryMovePacket extends AbstractPacket { + public static String packetName = "NPC|AbCatMove"; + + private int catType; + private String name; + private int catId; + + public AbilityCategoryMovePacket(int catType, String name, int catId) { + this.catType = catType; + this.name = name; + this.catId = catId; + } + + public AbilityCategoryMovePacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.AbilityCategoryMoveItem; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(catType); + ByteBufUtils.writeString(out, name); + out.writeInt(catId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int type = in.readInt(); + String itemName = ByteBufUtils.readString(in); + int cat = in.readInt(); + + // Validate target category exists (0 = Uncategorized is always valid) + CategoryManager cm = CategorySavePacket.getManager(type); + if (cm == null) return; + if (cat != CategoryManager.UNCATEGORIZED_ID && cm.getCategory(cat) == null) return; + + switch (type) { + case EnumCategoryType.ABILITY: + AbilityController.Instance.moveCustomAbilityToCategory(itemName, cat); + break; + case EnumCategoryType.CHAINED_ABILITY: + AbilityController.Instance.moveChainedAbilityToCategory(itemName, cat); + break; + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryItemsRequestPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryItemsRequestPacket.java new file mode 100644 index 000000000..fef2a0f2e --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryItemsRequestPacket.java @@ -0,0 +1,100 @@ +package kamkeel.npcs.network.packets.request.category; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.ScrollDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import kamkeel.npcs.controllers.AbilityController; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.LinkedItemController; +import noppes.npcs.controllers.TagController; + +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.UUID; + +public final class CategoryItemsRequestPacket extends AbstractPacket { + public static String packetName = "NPC|CatItems"; + + private int catType; + private int catId; + + public CategoryItemsRequestPacket(int catType, int catId) { + this.catType = catType; + this.catId = catId; + } + + public CategoryItemsRequestPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CategoryItemsRequest; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(catType); + out.writeInt(catId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int type = in.readInt(); + int categoryId = in.readInt(); + + Map items = getItemsByCat(type, categoryId); + ScrollDataPacket.sendScrollData((EntityPlayerMP) player, items, EnumScrollData.CATEGORY_GROUP); + + // Send tag map for the items + HashMap> tagMap = getTagMapByCat(type, categoryId); + if (tagMap != null) { + TagController.sendCategoryTagMap((EntityPlayerMP) player, tagMap); + } + } + + private static Map getItemsByCat(int type, int catId) { + switch (type) { + case EnumCategoryType.EFFECT: return CustomEffectController.getInstance().getItemsByCategoryScrollData(catId); + case EnumCategoryType.ANIMATION: return AnimationController.getInstance().getItemsByCategoryScrollData(catId); + case EnumCategoryType.LINKED_ITEM: return LinkedItemController.getInstance().getItemsByCategoryScrollData(catId); + case EnumCategoryType.ABILITY: return AbilityController.Instance.getCustomAbilityItemsByCategoryScrollData(catId); + case EnumCategoryType.CHAINED_ABILITY: return AbilityController.Instance.getChainedAbilityItemsByCategoryScrollData(catId); + } + return new HashMap<>(); + } + + private static HashMap> getTagMapByCat(int type, int catId) { + switch (type) { + case EnumCategoryType.EFFECT: return CustomEffectController.getInstance().getItemTagMapForCategory(catId); + case EnumCategoryType.LINKED_ITEM: return LinkedItemController.getInstance().getItemTagMapForCategory(catId); + case EnumCategoryType.ABILITY: return AbilityController.Instance.getCustomAbilityTagMapForCategory(catId); + } + return null; + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryListRequestPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryListRequestPacket.java new file mode 100644 index 000000000..303e2ed08 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryListRequestPacket.java @@ -0,0 +1,64 @@ +package kamkeel.npcs.network.packets.request.category; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.ScrollDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.CategoryManager; + +import java.io.IOException; + +public final class CategoryListRequestPacket extends AbstractPacket { + public static String packetName = "NPC|CatList"; + + private int catType; + + public CategoryListRequestPacket(int catType) { + this.catType = catType; + } + + public CategoryListRequestPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CategoryListRequest; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(catType); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int type = in.readInt(); + + CategoryManager cm = CategorySavePacket.getManager(type); + if (cm == null) + return; + + ScrollDataPacket.sendScrollData((EntityPlayerMP) player, cm.getCategoryScrollData(), EnumScrollData.CATEGORY_LIST); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryMoveItemPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryMoveItemPacket.java new file mode 100644 index 000000000..4953bcf0c --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryMoveItemPacket.java @@ -0,0 +1,80 @@ +package kamkeel.npcs.network.packets.request.category; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import kamkeel.npcs.controllers.AbilityController; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.CategoryManager; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.LinkedItemController; + +import java.io.IOException; + +public final class CategoryMoveItemPacket extends AbstractPacket { + public static String packetName = "NPC|CatMove"; + + private int catType; + private int itemId; + private int catId; + + public CategoryMoveItemPacket(int catType, int itemId, int catId) { + this.catType = catType; + this.itemId = itemId; + this.catId = catId; + } + + public CategoryMoveItemPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CategoryMoveItem; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(catType); + out.writeInt(itemId); + out.writeInt(catId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int type = in.readInt(); + int item = in.readInt(); + int cat = in.readInt(); + + // Validate target category exists (0 = Uncategorized is always valid) + CategoryManager cm = CategorySavePacket.getManager(type); + if (cm == null) return; + if (cat != CategoryManager.UNCATEGORIZED_ID && cm.getCategory(cat) == null) return; + + switch (type) { + case EnumCategoryType.EFFECT: CustomEffectController.getInstance().moveItemToCategory(item, cat); break; + case EnumCategoryType.ANIMATION: AnimationController.getInstance().moveItemToCategory(item, cat); break; + case EnumCategoryType.LINKED_ITEM: LinkedItemController.getInstance().moveItemToCategory(item, cat); break; + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryRemovePacket.java new file mode 100644 index 000000000..ecc9e6652 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/category/CategoryRemovePacket.java @@ -0,0 +1,70 @@ +package kamkeel.npcs.network.packets.request.category; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.ScrollDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.CategoryManager; + +import java.io.IOException; + +public final class CategoryRemovePacket extends AbstractPacket { + public static String packetName = "NPC|CatRemove"; + + private int catType; + private int categoryId; + + public CategoryRemovePacket(int catType, int categoryId) { + this.catType = catType; + this.categoryId = categoryId; + } + + public CategoryRemovePacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CategoryRemove; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(catType); + out.writeInt(categoryId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int type = in.readInt(); + int catId = in.readInt(); + + CategoryManager cm = CategorySavePacket.getManager(type); + if (cm == null) + return; + + cm.removeCategory(catId); + CategorySavePacket.saveController(type); + ScrollDataPacket.sendScrollData((EntityPlayerMP) player, cm.getCategoryScrollData(), EnumScrollData.CATEGORY_LIST); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/category/CategorySavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/category/CategorySavePacket.java new file mode 100644 index 000000000..15eafa3fd --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/category/CategorySavePacket.java @@ -0,0 +1,107 @@ +package kamkeel.npcs.network.packets.request.category; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.ScrollDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import kamkeel.npcs.controllers.AbilityController; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.CategoryManager; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.LinkedItemController; +import noppes.npcs.controllers.data.Category; + +import java.io.IOException; + +public final class CategorySavePacket extends AbstractPacket { + public static String packetName = "NPC|CatSave"; + + private int catType; + private NBTTagCompound categoryNBT; + + public CategorySavePacket(int catType, NBTTagCompound categoryNBT) { + this.catType = catType; + this.categoryNBT = categoryNBT; + } + + public CategorySavePacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CategorySave; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(catType); + ByteBufUtils.writeNBT(out, categoryNBT); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int type = in.readInt(); + NBTTagCompound compound = ByteBufUtils.readNBT(in); + + CategoryManager cm = getManager(type); + if (cm == null) + return; + + Category cat = new Category(); + cat.readNBT(compound); + + if (cat.id <= 0) { + cm.createCategory(cat.title); + } else { + cm.saveCategory(cat); + } + + saveController(type); + ScrollDataPacket.sendScrollData((EntityPlayerMP) player, cm.getCategoryScrollData(), EnumScrollData.CATEGORY_LIST); + } + + public static CategoryManager getManager(int type) { + switch (type) { + case EnumCategoryType.EFFECT: return CustomEffectController.getInstance().categoryManager; + case EnumCategoryType.ANIMATION: return AnimationController.getInstance().categoryManager; + case EnumCategoryType.LINKED_ITEM: return LinkedItemController.getInstance().categoryManager; + case EnumCategoryType.ABILITY: return AbilityController.Instance.customAbilityCategories; + case EnumCategoryType.CHAINED_ABILITY: return AbilityController.Instance.chainedAbilityCategories; + } + return null; + } + + public static void saveController(int type) { + switch (type) { + case EnumCategoryType.EFFECT: CustomEffectController.getInstance().saveEffectLoadMap(); break; + case EnumCategoryType.ANIMATION: AnimationController.getInstance().saveAnimationMap(); break; + case EnumCategoryType.LINKED_ITEM: LinkedItemController.getInstance().saveLinkedItemsMap(); break; + case EnumCategoryType.ABILITY: break; // abilities save per-file, no bulk save needed + case EnumCategoryType.CHAINED_ABILITY: break; + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java index 926c5519c..158896eaf 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java @@ -10,10 +10,10 @@ 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 kamkeel.npcs.util.ByteBufUtils; import noppes.npcs.controllers.ServerTagMapController; import noppes.npcs.controllers.data.TagMap; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectClonePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectClonePacket.java new file mode 100644 index 000000000..b946e0f0f --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectClonePacket.java @@ -0,0 +1,69 @@ +package kamkeel.npcs.network.packets.request.effects; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.io.IOException; + +public final class EffectClonePacket extends AbstractPacket { + public static String packetName = "Request|EffectClone"; + + private int id; + + public EffectClonePacket() { + } + + public EffectClonePacket(int id) { + this.id = id; + } + + @Override + public Enum getType() { + return EnumRequestPacket.EffectClone; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_EFFECT; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(this.id); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int effectId = in.readInt(); + CustomEffect clone = CustomEffectController.getInstance().cloneEffect(effectId); + if (clone != null) { + NoppesUtilServer.sendCustomEffectDataAll((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, clone.writeToNBT(false)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectSavePacket.java index 785ccdf4f..b0c4b5ed6 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/effects/EffectSavePacket.java @@ -7,6 +7,7 @@ import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.PacketUtil; import kamkeel.npcs.network.enums.EnumItemPacketType; import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -72,5 +73,6 @@ public class EffectSavePacket extends AbstractPacket { } NoppesUtilServer.sendCustomEffectDataAll((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, effect.writeToNBT(false)); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/jobs/JobSpawnerAddPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/jobs/JobSpawnerAddPacket.java index f6b7fa2dc..8143aeef9 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/jobs/JobSpawnerAddPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/jobs/JobSpawnerAddPacket.java @@ -28,6 +28,7 @@ public final class JobSpawnerAddPacket extends AbstractPacket { private String selected; private int activeTab; + private String folderName; private int slot; private NBTTagCompound compound; @@ -39,6 +40,15 @@ public final class JobSpawnerAddPacket extends AbstractPacket { this.isServer = isServer; this.selected = selected; this.activeTab = activeTab; + this.folderName = null; + this.slot = slot; + } + + public JobSpawnerAddPacket(boolean isServer, String selected, String folderName, int slot) { + this.isServer = isServer; + this.selected = selected; + this.activeTab = -1; + this.folderName = folderName; this.slot = slot; } @@ -75,6 +85,9 @@ public final class JobSpawnerAddPacket extends AbstractPacket { if (this.isServer) { ByteBufUtils.writeString(out, selected); out.writeInt(this.activeTab); + if (this.activeTab == -1) { + ByteBufUtils.writeString(out, folderName != null ? folderName : ""); + } out.writeInt(this.slot); } else { out.writeInt(this.slot); @@ -96,7 +109,15 @@ public final class JobSpawnerAddPacket extends AbstractPacket { JobSpawner job = (JobSpawner) npc.jobInterface; boolean useServerClone = in.readBoolean(); if (useServerClone) { - NBTTagCompound compound = ServerCloneController.Instance.getCloneData(null, ByteBufUtils.readString(in), in.readInt()); + String selected = ByteBufUtils.readString(in); + int tab = in.readInt(); + NBTTagCompound compound; + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + compound = ServerCloneController.Instance.getCloneData(null, selected, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(null, selected, tab); + } job.setJobCompound(in.readInt(), compound); } else { job.setJobCompound(in.readInt(), ByteBufUtils.readNBT(in)); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemClonePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemClonePacket.java new file mode 100644 index 000000000..5eda0f5d0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemClonePacket.java @@ -0,0 +1,69 @@ +package kamkeel.npcs.network.packets.request.linked; + +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.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.controllers.LinkedItemController; +import noppes.npcs.controllers.data.LinkedItem; + +import java.io.IOException; + +public final class LinkedItemClonePacket extends AbstractPacket { + public static String packetName = "Request|LinkedItemClone"; + + private int id; + + public LinkedItemClonePacket() { + } + + public LinkedItemClonePacket(int id) { + this.id = id; + } + + @Override + public Enum getType() { + return EnumRequestPacket.LinkedItemClone; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.GLOBAL_LINKED; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(this.id); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + int linkedId = in.readInt(); + LinkedItem clone = LinkedItemController.getInstance().cloneLinkedItem(linkedId); + if (clone != null) { + NoppesUtilServer.sendLinkedItemDataAll((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, clone.writeToNBT(false)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemSavePacket.java index d7fd58eeb..2e1e2ae52 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/linked/LinkedItemSavePacket.java @@ -9,6 +9,7 @@ import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.PacketUtil; import kamkeel.npcs.network.enums.EnumItemPacketType; import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -73,5 +74,6 @@ public final class LinkedItemSavePacket extends AbstractPacket { } NoppesUtilServer.sendLinkedItemDataAll((EntityPlayerMP) player); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, linkedItem.writeToNBT(false)); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/role/RoleSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/role/RoleSavePacket.java index d63f2603c..21d0f2667 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/role/RoleSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/role/RoleSavePacket.java @@ -14,6 +14,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.roles.RoleTrader; import java.io.IOException; @@ -63,7 +64,13 @@ public final class RoleSavePacket extends AbstractPacket { if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) return; - npc.roleInterface.readFromNBT(ByteBufUtils.readNBT(in)); + NBTTagCompound roleCompound = ByteBufUtils.readNBT(in); + if (npc.roleInterface instanceof RoleTrader) { + // An admin edit wins over the linked market; the market is written from it afterwards. + ((RoleTrader) npc.roleInterface).readFromNBT(roleCompound, false); + } else { + npc.roleInterface.readFromNBT(roleCompound); + } npc.updateClient = true; } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/AbilityScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/AbilityScriptPacket.java new file mode 100644 index 000000000..53802cc88 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/AbilityScriptPacket.java @@ -0,0 +1,132 @@ +package kamkeel.npcs.network.packets.request.script; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.LogWriter; +import noppes.npcs.config.ConfigDebug; +import noppes.npcs.config.ConfigScript; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.IScriptHandler; + +import java.io.IOException; + +public final class AbilityScriptPacket extends AbstractPacket { + public static String packetName = "Request|AbilityScript"; + + private Action type; + private String abilityId; + private int page; + private int maxSize; + private NBTTagCompound compound; + + public AbilityScriptPacket() { + } + + public AbilityScriptPacket(Action type, String abilityId, int page, int maxSize, NBTTagCompound compound) { + this.type = type; + this.abilityId = abilityId; + this.page = page; + this.maxSize = maxSize; + this.compound = compound; + } + + @Override + public Enum getType() { + return EnumRequestPacket.AbilityScript; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.SCRIPT_PLAYER; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(type.ordinal()); + ByteBufUtils.writeUTF8String(out, abilityId); + + if (type == Action.SAVE) { + out.writeInt(this.page); + out.writeInt(this.maxSize); + ByteBufUtils.writeNBT(out, this.compound); + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) + return; + + int actionOrd = in.readInt(); + if (actionOrd < 0 || actionOrd >= Action.values().length) return; + Action requestedAction = Action.values()[actionOrd]; + String id = ByteBufUtils.readUTF8String(in); + + Ability ability = AbilityController.Instance.resolveAbility(id); + if (ability == null) { + // Ability not yet saved — store handler in global map so scripts persist + // until the ability is saved via CustomAbilitySavePacket + AbilityScript data = AbilityController.Instance.abilityScriptHandlers.get(id); + if (data == null) { + data = new AbilityScript(id); + AbilityController.Instance.abilityScriptHandlers.put(id, data); + } + if (requestedAction == Action.GET) { + PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player); + } else { + data.saveScript(in); + } + return; + } + + AbilityScript data = ability.getOrCreateScriptHandler(); + if (requestedAction == Action.GET) { + PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player); + } else { + data.saveScript(in); + // Persist to disk + AbilityController.Instance.saveCustomAbility(ability); + if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { + LogWriter.script(String.format("[%s] (Player) %s SAVED ABILITY SCRIPT %s [%s]", + "ABILITY SCRIPTS", player.getCommandSenderName(), ability.getName(), ability.getId())); + } + } + } + + public static void Save(String abilityId, int id, int maxSize, NBTTagCompound compound) { + PacketClient.sendClient(new AbilityScriptPacket(Action.SAVE, abilityId, id, maxSize, compound)); + } + + public static void Get(String abilityId) { + PacketClient.sendClient(new AbilityScriptPacket(Action.GET, abilityId, -1, -1, new NBTTagCompound())); + } + + private enum Action { + GET, + SAVE + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/ChainedAbilityScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/ChainedAbilityScriptPacket.java new file mode 100644 index 000000000..4b1dd5504 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/ChainedAbilityScriptPacket.java @@ -0,0 +1,132 @@ +package kamkeel.npcs.network.packets.request.script; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.LogWriter; +import noppes.npcs.config.ConfigDebug; +import noppes.npcs.config.ConfigScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import noppes.npcs.controllers.data.IScriptHandler; + +import java.io.IOException; + +public final class ChainedAbilityScriptPacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilityScript"; + + private Action type; + private String chainId; + private int page; + private int maxSize; + private NBTTagCompound compound; + + public ChainedAbilityScriptPacket() { + } + + public ChainedAbilityScriptPacket(Action type, String chainId, int page, int maxSize, NBTTagCompound compound) { + this.type = type; + this.chainId = chainId; + this.page = page; + this.maxSize = maxSize; + this.compound = compound; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilityScript; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.SCRIPT_PLAYER; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(type.ordinal()); + ByteBufUtils.writeUTF8String(out, chainId); + + if (type == Action.SAVE) { + out.writeInt(this.page); + out.writeInt(this.maxSize); + ByteBufUtils.writeNBT(out, this.compound); + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) + return; + + int actionOrd = in.readInt(); + if (actionOrd < 0 || actionOrd >= Action.values().length) return; + Action requestedAction = Action.values()[actionOrd]; + String id = ByteBufUtils.readUTF8String(in); + + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(id); + if (chain == null) { + // Chain not yet saved — store handler in global map so scripts persist + // until the chain is saved via ChainedAbilitySavePacket + ChainedAbilityScript data = AbilityController.Instance.chainedAbilityScriptHandlers.get(id); + if (data == null) { + data = new ChainedAbilityScript(id); + AbilityController.Instance.chainedAbilityScriptHandlers.put(id, data); + } + if (requestedAction == Action.GET) { + PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player); + } else { + data.saveScript(in); + } + return; + } + + ChainedAbilityScript data = chain.getOrCreateScriptHandler(); + if (requestedAction == Action.GET) { + PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player); + } else { + data.saveScript(in); + // Persist to disk + AbilityController.Instance.saveChainedAbility(chain); + if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { + LogWriter.script(String.format("[%s] (Player) %s SAVED CHAIN SCRIPT %s [%s]", + "CHAIN SCRIPTS", player.getCommandSenderName(), chain.getName(), chain.getId())); + } + } + } + + public static void Save(String chainId, int id, int maxSize, NBTTagCompound compound) { + PacketClient.sendClient(new ChainedAbilityScriptPacket(Action.SAVE, chainId, id, maxSize, compound)); + } + + public static void Get(String chainId) { + PacketClient.sendClient(new ChainedAbilityScriptPacket(Action.GET, chainId, -1, -1, new NBTTagCompound())); + } + + private enum Action { + GET, + SAVE + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/EffectScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/EffectScriptPacket.java index 8171f085d..0570078df 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/script/EffectScriptPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/EffectScriptPacket.java @@ -92,7 +92,7 @@ public final class EffectScriptPacket extends AbstractPacket { } else { data.saveScript(in); if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { - LogWriter.script(String.format("[%s] (Player) %s SAVED EFFECT %s [%s]", "EFFECT SCRIPTS", player.getCommandSenderName(), effect.getName())); + LogWriter.script(String.format("[%s] (Player) %s SAVED EFFECT %s [%s]", "EFFECT SCRIPTS", player.getCommandSenderName(), effect.getName(), effect.id)); } } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java index d025fcb26..8930fabc3 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java @@ -1,7 +1,5 @@ package kamkeel.npcs.network.packets.request.script; -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; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/tags/TagsGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/tags/TagsGetPacket.java index 4414131f1..85fe8e5c3 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/tags/TagsGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/tags/TagsGetPacket.java @@ -6,8 +6,6 @@ import io.netty.buffer.ByteBuf; 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 net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -38,9 +36,6 @@ public final class TagsGetPacket extends AbstractPacket { @Override public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { - if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.WAND, EnumItemPacketType.CLONER)) - return; - NoppesUtilServer.sendTagDataAll((EntityPlayerMP) player); } diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index 5ee5936b1..415262da7 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -1,7 +1,8 @@ package kamkeel.npcs.util; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.data.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.data.energy.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; @@ -46,6 +54,9 @@ public class AnchorPointHelper { private static final float FALLBACK_FORWARD = 0.1f; // Slight forward offset private static final float FALLBACK_ARM_HEIGHT = 0.45f; // Hand height when arms hang down (near hip) + // Default arm scale (no scaling) + private static final ModelScalePart DEFAULT_ARM_SCALE = new ModelScalePart(); + /** * Calculate world position for an anchor point on an entity. */ @@ -67,10 +78,11 @@ public class AnchorPointHelper { float anchorZ = anchorData.anchorOffsetZ; double x = entity.posX; - double y = entity.posY; + // EYE uses getEyeHeight() which already gives the correct offset from posY, + // so the client player correction would double-subtract and place it at feet level + double y = entity.posY + (anchor == AnchorPoint.EYE ? 0 : getClientPlayerYCorrection(entity)); double z = entity.posZ; - float headYaw = (float) Math.toRadians(entity.rotationYawHead); float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); switch (anchor) { @@ -98,6 +110,9 @@ public class AnchorPointHelper { case CHEST: y += height * CHEST_HEIGHT; break; + + case EYE: + return calculateEyePosition(entity, anchorData, scale); } // Rotate offsets relative to entity's body yaw @@ -107,9 +122,105 @@ public class AnchorPointHelper { 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); } + private static Vec3 calculateEyePosition(EntityLivingBase entity, EnergyAnchorData anchorData, float scale) { + double pivotWorldX = entity.posX; + double pivotWorldY = entity.posY + entity.getEyeHeight(); + double pivotWorldZ = entity.posZ; + + float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); + + float[] rotations = getHeadBoneRotations(entity); + + double ox = -anchorData.anchorOffsetX * scale; + double oy = -anchorData.anchorOffsetY * scale; + double oz = -anchorData.anchorOffsetZ * scale; + + // X rotation + double cosX = Math.cos(rotations[0]); + double sinX = Math.sin(rotations[0]); + double ry = oy * cosX - oz * sinX; + double rz = oy * sinX + oz * cosX; + double rx = ox; + oy = ry; oz = rz; + + // Y rotation + double cosY = Math.cos(rotations[1]); + double sinY = Math.sin(rotations[1]); + double rx2 = rx * cosY + oz * sinY; + double rz2 = -rx * sinY + oz * cosY; + rx = rx2; oz = rz2; + + // Z rotation + double cosZ = Math.cos(rotations[2]); + double sinZ = Math.sin(rotations[2]); + double rx3 = rx * cosZ - oy * sinZ; + double ry3 = rx * sinZ + oy * cosZ; + rx = rx3; oy = ry3; + + double cosYaw = Math.cos(bodyYaw); + double sinYaw = Math.sin(bodyYaw); + + double worldOffsetX = rx * cosYaw + oz * sinYaw; + double worldOffsetZ = rx * sinYaw - oz * cosYaw; + double worldOffsetY = -oy; // model Y-down → world Y-up + + double x = pivotWorldX + worldOffsetX; + double y = pivotWorldY + worldOffsetY; + double z = pivotWorldZ + worldOffsetZ; + + FramePart fullModel = getFullModelPart(entity); + if (fullModel != null) { + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + Vec3 rotatedFull = applyFullModelToWorldOffset(fullModel, entity, dx, dy, dz, bodyYaw, scale); + return Vec3.createVectorHelper( + entity.posX + rotatedFull.xCoord, + entity.posY + rotatedFull.yCoord, + entity.posZ + rotatedFull.zCoord + ); + } + + return Vec3.createVectorHelper(x, y, z); + } + + private static float[] getHeadBoneRotations(EntityLivingBase entity) { + // Try animated HEAD part first + AnimationData animData = AnimationData.getData(entity); + if (animData != null && animData.isActive() && animData.animation != null) { + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame != null) { + FramePart headPart = frame.frameParts.get(EnumAnimationPart.HEAD); + if (headPart != null) { + return getRotations(headPart, entity); + } + } + } + + // Fallback: live head angles + float pitch = (float) Math.toRadians(entity.rotationPitch); + float yawDelta = (float) Math.toRadians(entity.rotationYawHead - entity.renderYawOffset); + + return new float[]{ pitch, yawDelta, 0f }; + } + /** * Get model scale factor for an entity. * NPCs have configurable model size, players use default scale. @@ -122,8 +233,17 @@ public class AnchorPointHelper { return 1f; } - // Default arm scale (no scaling) - private static final ModelScalePart DEFAULT_ARM_SCALE = new ModelScalePart(); + /** + * 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; + } /** * Get arm scale for an entity. @@ -138,16 +258,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; } /** @@ -246,7 +382,7 @@ 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; // Rotate offsets relative to entity's body yaw @@ -319,7 +455,7 @@ 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; // Rotate offsets relative to entity's body yaw @@ -347,6 +483,8 @@ public class AnchorPointHelper { return ABOVE_HEAD_HEIGHT; case CHEST: return CHEST_HEIGHT; + case EYE: + return EYE_HEIGHT; default: return FRONT_HEIGHT; } @@ -355,6 +493,7 @@ public class AnchorPointHelper { /** * 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) { @@ -364,4 +503,100 @@ public class AnchorPointHelper { 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/AttributeAttackUtil.java b/src/main/java/kamkeel/npcs/util/AttributeAttackUtil.java index f2fd8bf44..76f6fbffa 100644 --- a/src/main/java/kamkeel/npcs/util/AttributeAttackUtil.java +++ b/src/main/java/kamkeel/npcs/util/AttributeAttackUtil.java @@ -7,7 +7,9 @@ import noppes.npcs.config.ConfigMain; import noppes.npcs.controllers.MagicController; import noppes.npcs.controllers.data.Magic; import noppes.npcs.controllers.data.MagicEntry; +import noppes.npcs.controllers.data.MagicData; import noppes.npcs.controllers.data.PlayerData; +import net.minecraft.entity.EntityLivingBase; import noppes.npcs.entity.EntityNPCInterface; import java.util.HashMap; @@ -20,10 +22,17 @@ import static kamkeel.npcs.controllers.AttributeController.getTracker; public class AttributeAttackUtil { private static final Random random = new Random(); + + /** + * Crit decision from the last LivingAttackEvent for vanilla/modded mob targets. + * Set in LivingAttackEvent, consumed in LivingHurtEvent. + * null = no roll occurred, true = critted, false = did not crit. + */ + public static Boolean lastAttackCritted = null; // --- Helper Classes & Methods --- // Container for allocation results. - private static class AllocationResult { + public static class AllocationResult { public Map allocation; public float leftover; @@ -37,7 +46,7 @@ public class AttributeAttackUtil { * Allocates physical damage into magic allocations based on MagicData splits. * Returns both a mapping (magic ID -> allocated damage) and any leftover physical damage. */ - private static AllocationResult allocateMagicDamage(float physicalDamage, Map magicData) { + public static AllocationResult allocateMagicDamage(float physicalDamage, Map magicData) { Map allocation = new HashMap<>(); float totalSplit = 0f; if (magicData != null) { @@ -57,7 +66,7 @@ public class AttributeAttackUtil { /** * Adds extra magic damage from attribute sources if attributes are enabled. */ - private static void addAttributeMagicDamage(Map allocation, + public static void addAttributeMagicDamage(Map allocation, Map attributeDamage, Map magicBoost) { if (!ConfigMain.AttributesEnabled) return; @@ -74,7 +83,7 @@ public class AttributeAttackUtil { * Applies magic interactions. For each magic in the allocation, multiplies its damage by (1 + bonus) * for each opposing magic the defender possesses. */ - private static void applyMagicInteractions(Map allocation, + public static void applyMagicInteractions(Map allocation, Set defenderMagicIDs, MagicController magicController) { for (Map.Entry entry : allocation.entrySet()) { @@ -97,7 +106,7 @@ public class AttributeAttackUtil { * Applies defender magic defenses if attributes are enabled. * Subtracts tracker-based magic defense (scaled by resistance) from each magic allocation. */ - private static float applyDefenderMagicDefense(Map allocation, + public static float applyDefenderMagicDefense(Map allocation, PlayerAttributeTracker defender, MagicController magicController) { if (!ConfigMain.AttributesEnabled) return 0f; @@ -168,10 +177,31 @@ public class AttributeAttackUtil { public static float applyCrit(float damage, PlayerAttributeTracker tracker) { if (ConfigMain.AttributesEnabled) { + if (rollCrit(tracker)) + damage = applyCritDamage(damage, tracker); + } + return damage; + } + + /** + * Rolls for a critical hit based on the tracker's CRITICAL_CHANCE attribute. + */ + public static boolean rollCrit(PlayerAttributeTracker tracker) { + if (ConfigMain.AttributesEnabled && tracker != null) { float critChance = tracker.getAttributeValue(CustomAttributes.CRITICAL_CHANCE); + return random.nextFloat() < (critChance / 100f); + } + return false; + } + + /** + * Applies crit damage unconditionally (no chance roll). + * Use when the crit decision was already made via {@link #rollCrit}. + */ + public static float applyCritDamage(float damage, PlayerAttributeTracker tracker) { + if (ConfigMain.AttributesEnabled && tracker != null) { float critBonus = tracker.getAttributeValue(CustomAttributes.CRITICAL_DAMAGE); - if (random.nextFloat() < (critChance / 100f)) - damage = (damage * (1 + (float) ConfigMain.AttributesCriticalBoost / 100f)) + critBonus; + damage = (damage * (1 + (float) ConfigMain.AttributesCriticalBoost / 100f)) + critBonus; } return damage; } @@ -256,4 +286,141 @@ public class AttributeAttackUtil { return mainDamage + gearDamage; } + + // --- Magic Interaction Utility --- + + /** + * Calculate magic interaction multiplier between attacker's magic types + * and defender's magic types. Used for barrier defense and entity-vs-entity interactions. + * + * @param attackerMagic Attacker's magic data (projectile or weapon) + * @param defenderMagic Defender's magic data (barrier or entity) + * @return Multiplier (1.0 = no interaction, >1.0 = bonus damage, <1.0 = resistance) + */ + public static float calculateMagicInteractionMultiplier(MagicData attackerMagic, MagicData defenderMagic) { + if (attackerMagic == null || defenderMagic == null) return 1.0f; + if (attackerMagic.isEmpty() || defenderMagic.isEmpty()) return 1.0f; + + MagicController mc = MagicController.getInstance(); + float multiplier = 1.0f; + + for (int attackMagicId : attackerMagic.getMagics().keySet()) { + Magic magic = mc.getMagic(attackMagicId); + if (magic == null || magic.interactions == null) continue; + for (Map.Entry interaction : magic.interactions.entrySet()) { + if (defenderMagic.getMagics().containsKey(interaction.getKey())) { + multiplier *= (1 + interaction.getValue()); + } + } + } + return multiplier; + } + + // --- Ability Damage Pipeline --- + + /** + * Apply gear magic boost percentages to the split-allocated magic damage. + * This multiplies each magic type's allocated damage by (1 + boost/100). + * Unlike {@link #addAttributeMagicDamage}, this does NOT add flat gear damage — + * it only applies the percentage multiplier from gear to the existing allocation. + */ + public static void applyMagicBoostToAllocation(Map allocation, Map magicBoost) { + if (!ConfigMain.AttributesEnabled) return; + for (Map.Entry entry : allocation.entrySet()) { + float boost = magicBoost.getOrDefault(entry.getKey(), 0f); + if (boost != 0f) { + entry.setValue(entry.getValue() * (1 + boost / 100f)); + } + } + } + + /** + * Apply gear magic boost percentages to barrier/dome health. + * Each magic type's split determines what portion of health is affected by its boost. + * E.g., Thunder [100%] dome + 50% Thunder gear boost = health * 1.5 + */ + public static float applyMagicBoostToHealth(EntityPlayer caster, MagicData magicData, float health) { + if (!ConfigMain.AttributesEnabled) return health; + if (magicData == null || magicData.isEmpty()) return health; + + PlayerAttributeTracker tracker = getTracker(caster); + if (tracker == null) return health; + + float multiplier = 1.0f; + for (Map.Entry entry : magicData.getMagics().entrySet()) { + float split = entry.getValue().split; + float boost = tracker.magicBoost.getOrDefault(entry.getKey(), 0f); + multiplier += split * (boost / 100f); + } + return health * multiplier; + } + + /** + * Apply the magic pipeline to ability damage. Works for both player and NPC casters. + * Abilities do NOT get main attack or critical boosts — they have their own scaling. + * This handles: + *

    + *
  • Magic allocation (splits from ability/caster magic data)
  • + *
  • Gear magic boost multipliers on split damage (player casters only, no flat gear damage)
  • + *
  • Magic interactions vs defender
  • + *
  • Defender magic defense/resistance (player defenders only)
  • + *
+ * If no magic data is present, damage passes through unchanged. + * + * @param caster Caster (player or NPC) + * @param target Target entity + * @param damage Base ability damage (already scaled by ability's own system) + * @param abilityMagic Resolved magic data (ability's own, or caster's fallback) + * @return Final damage after magic splits, boosts, interactions, and defense + */ + public static float calculateAbilityDamage(EntityLivingBase caster, EntityLivingBase target, + float damage, MagicData abilityMagic) { + if (abilityMagic == null || abilityMagic.isEmpty()) return damage; + + // 1. Allocate base damage into magic types using ability's splits + AllocationResult result = allocateMagicDamage(damage, abilityMagic.getMagics()); + float leftover = result.leftover; + + // 2. Apply gear magic boost multipliers to the split allocation (player casters only) + if (caster instanceof EntityPlayer && ConfigMain.AttributesEnabled) { + PlayerAttributeTracker tracker = getTracker((EntityPlayer) caster); + if (tracker != null) { + applyMagicBoostToAllocation(result.allocation, tracker.magicBoost); + } + } + + // 3. Magic interactions against target + MagicController magicController = MagicController.getInstance(); + Set defenderMagicIDs = null; + + if (target instanceof EntityPlayer) { + PlayerData defenderData = PlayerData.get((EntityPlayer) target); + if (defenderData != null) { + defenderMagicIDs = new HashSet<>(defenderData.magicData.getMagics().keySet()); + } + } else if (target instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) target; + if (npc.stats != null && npc.stats.magicData != null) { + defenderMagicIDs = new HashSet<>(npc.stats.magicData.getMagics().keySet()); + } + } + + if (defenderMagicIDs != null) { + applyMagicInteractions(result.allocation, defenderMagicIDs, magicController); + } + + // 4. Apply defender magic defense (player defenders with attributes only) + if (target instanceof EntityPlayer && ConfigMain.AttributesEnabled) { + PlayerAttributeTracker defenderTracker = getTracker((EntityPlayer) target); + if (defenderTracker != null) { + float adjustedMagic = applyDefenderMagicDefense(result.allocation, defenderTracker, magicController); + return leftover + adjustedMagic; + } + } + + // Sum magic damage + float magicTotal = 0f; + for (float val : result.allocation.values()) magicTotal += val; + return leftover + magicTotal; + } } diff --git a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java index 9cc361b5d..d16df9347 100644 --- a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java +++ b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java @@ -14,10 +14,12 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; +import net.minecraft.client.settings.GameSettings; import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.KeyPressHandler; +import noppes.npcs.client.gui.player.GuiAuctionInterface; import noppes.npcs.controllers.MagicController; import noppes.npcs.controllers.data.Magic; -import org.lwjgl.input.Keyboard; import java.util.ArrayList; import java.util.Collections; @@ -230,14 +232,14 @@ public class AttributeItemUtil { * Returns the item tooltip. */ @SideOnly(Side.CLIENT) - public static List getToolTip(List original, NBTTagCompound compound) { + public static List getToolTip(List original, NBTTagCompound compound, boolean override) { List tooltip = new ArrayList<>(original); // Get the RPGCore compound and then the Attributes compound. NBTTagCompound rpgCore = compound.hasKey(TAG_RPGCORE) ? compound.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound(); NBTTagCompound attrTag = rpgCore.hasKey(TAG_ATTRIBUTES) ? rpgCore.getCompoundTag(TAG_ATTRIBUTES) : new NBTTagCompound(); - if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode())) { + if (KeyPressHandler.isKeyBindDown(ClientProxy.NPCButton) || override) { List newTooltips = new ArrayList<>(); - if (!tooltip.isEmpty()) { + if (!tooltip.isEmpty() && !override) { newTooltips.add(tooltip.get(0)); } @@ -325,9 +327,13 @@ public class AttributeItemUtil { newTooltips.addAll(buildSection(reqEntries)); } - tooltip = newTooltips; + if(override){ + tooltip.addAll(newTooltips); + } else { + tooltip = newTooltips; + } } else { - String keyName = Keyboard.getKeyName(ClientProxy.NPCButton.getKeyCode()); + String keyName = GameSettings.getKeyDisplayString(ClientProxy.NPCButton.getKeyCode()); tooltip.add(EnumChatFormatting.YELLOW + "" + EnumChatFormatting.ITALIC + StatCollector.translateToLocal("rpgcore:tooltip").replace("%key%", keyName)); } diff --git a/src/main/java/kamkeel/npcs/util/BukkitUtil.java b/src/main/java/kamkeel/npcs/util/BukkitUtil.java index 29f4a522f..1252fc67c 100644 --- a/src/main/java/kamkeel/npcs/util/BukkitUtil.java +++ b/src/main/java/kamkeel/npcs/util/BukkitUtil.java @@ -98,6 +98,7 @@ public class BukkitUtil { /** * Checks if a specific Bukkit plugin is enabled. + * * @param pluginName the plugin name to check * @return true if the plugin is enabled */ @@ -115,6 +116,7 @@ public class BukkitUtil { /** * Gets a Bukkit OfflinePlayer by name. + * * @param playerName the player name * @return the OfflinePlayer object, or null if not available */ @@ -131,6 +133,7 @@ public class BukkitUtil { /** * Gets a Bukkit Player by name (online players only). + * * @param playerName the player name * @return the Player object, or null if not online or not available */ @@ -147,6 +150,7 @@ public class BukkitUtil { /** * Gets a service provider from Bukkit's ServicesManager. + * * @param serviceClass the service class to get * @return the service provider, or null if not available */ diff --git a/src/main/java/kamkeel/npcs/util/CNPCDebug.java b/src/main/java/kamkeel/npcs/util/CNPCDebug.java new file mode 100644 index 000000000..66cdf3c77 --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/CNPCDebug.java @@ -0,0 +1,163 @@ +package kamkeel.npcs.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Formatter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.StreamHandler; + +/** + * Debug logging system for CNPC+ entities. + * Writes to logs/cnpc_debug/[type]_[side].log (file only, no console output). + * Toggle at runtime via /cnpcdebugger [type] (client) or /kam debug [type] (server). + */ +public class CNPCDebug { + + private static final String DIR = "logs/cnpc_debug"; + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss"); + + // Runtime toggle state per type, separate for client and server + private static final Map serverToggles = new ConcurrentHashMap<>(); + private static final Map clientToggles = new ConcurrentHashMap<>(); + + // Per-type file handlers (lazily initialized) + private static final Map serverHandlers = new ConcurrentHashMap<>(); + private static final Map clientHandlers = new ConcurrentHashMap<>(); + + // ==================== TOGGLE API ==================== + + /** + * Toggle server-side debug for given type. Returns new state. + */ + public static boolean toggleServer(String type) { + type = type.toLowerCase(); + boolean newState = !isServerEnabled(type); + serverToggles.put(type, newState); + if (newState) { + ensureHandler(type, false); + } + return newState; + } + + /** + * Toggle client-side debug for given type. Returns new state. + */ + public static boolean toggleClient(String type) { + type = type.toLowerCase(); + boolean newState = !isClientEnabled(type); + clientToggles.put(type, newState); + if (newState) { + ensureHandler(type, true); + } + return newState; + } + + public static boolean isServerEnabled(String type) { + Boolean val = serverToggles.get(type.toLowerCase()); + return val != null && val; + } + + public static boolean isClientEnabled(String type) { + Boolean val = clientToggles.get(type.toLowerCase()); + return val != null && val; + } + + // ==================== LOGGING API ==================== + + /** + * Log a debug message for the given type on the given side. + * Callers should guard with isServerEnabled/isClientEnabled for performance. + */ + public static void log(String type, boolean client, String msg) { + type = type.toLowerCase(); + Map toggles = client ? clientToggles : serverToggles; + Boolean enabled = toggles.get(type); + if (enabled == null || !enabled) return; + + Handler handler = ensureHandler(type, client); + if (handler == null) return; + + String side = client ? "CLIENT" : "SERVER"; + String timestamp; + synchronized (DATE_FORMAT) { + timestamp = DATE_FORMAT.format(new Date()); + } + String formatted = "[" + timestamp + "][" + side + "][DEBUG-" + type.toUpperCase() + "] " + msg + System.lineSeparator(); + + LogRecord record = new LogRecord(Level.INFO, formatted); + handler.publish(record); + handler.flush(); + } + + /** + * Log on server side. + */ + public static void logServer(String type, String msg) { + log(type, false, msg); + } + + /** + * Log on client side. + */ + public static void logClient(String type, String msg) { + log(type, true, msg); + } + + // ==================== INTERNALS ==================== + + private static Handler ensureHandler(String type, boolean client) { + Map handlers = client ? clientHandlers : serverHandlers; + Handler existing = handlers.get(type); + if (existing != null) return existing; + + synchronized (CNPCDebug.class) { + existing = handlers.get(type); + if (existing != null) return existing; + + try { + File dir = new File(DIR); + if (!dir.exists()) dir.mkdirs(); + + String side = client ? "client" : "server"; + File file = new File(dir, type + "_" + side + ".log"); + + // Rotate old log + if (file.exists()) { + File backup = new File(dir, type + "_" + side + "-prev.log"); + if (backup.exists()) backup.delete(); + file.renameTo(backup); + } + + Handler handler = new StreamHandler(new FileOutputStream(file), new Formatter() { + @Override + public String format(LogRecord record) { + return record.getMessage(); + } + }); + handler.setLevel(Level.ALL); + handlers.put(type, handler); + + // Log header + String timestamp; + synchronized (DATE_FORMAT) { + timestamp = DATE_FORMAT.format(new Date()); + } + LogRecord header = new LogRecord(Level.INFO, + "[" + timestamp + "][" + (client ? "CLIENT" : "SERVER") + "][DEBUG-" + type.toUpperCase() + "] Debug logging started" + System.lineSeparator()); + handler.publish(header); + handler.flush(); + + return handler; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + } +} diff --git a/src/main/java/kamkeel/npcs/util/FileNameHelper.java b/src/main/java/kamkeel/npcs/util/FileNameHelper.java new file mode 100644 index 000000000..6248600fb --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/FileNameHelper.java @@ -0,0 +1,97 @@ +package kamkeel.npcs.util; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Utility helpers for filename-safe ability/chained names. + * Allowed characters are letters, digits, underscore, and dash. + */ +public final class FileNameHelper { + + private static final Set WINDOWS_RESERVED_NAMES = new HashSet(Arrays.asList( + "CON", "PRN", "AUX", "NUL", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" + )); + + private FileNameHelper() { + } + + /** + * Sanitize a name to a filename-safe identifier. + * Whitespace becomes underscores; unsupported chars are removed. + */ + public static String sanitizeName(String input, String fallback) { + String sanitized = sanitizeInternal(input); + if (sanitized.isEmpty()) { + sanitized = sanitizeInternal(fallback); + } + if (sanitized.isEmpty()) { + sanitized = "Ability"; + } + if (isReservedWindowsName(sanitized)) { + sanitized = "_" + sanitized; + } + return sanitized; + } + + /** + * Sanitize textfield input without forcing a fallback. + */ + public static String sanitizeTextInput(String input) { + return sanitizeInternal(input); + } + + /** + * Quick check for compatibility with sanitized identifier rules. + */ + public static boolean isFileNameCompatible(String value) { + if (value == null || value.isEmpty()) return false; + if (isReservedWindowsName(value)) return false; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (!Character.isLetterOrDigit(c) && c != '_' && c != '-') { + return false; + } + } + return true; + } + + /** + * Human-readable fallback display text for sanitized names. + */ + public static String toDisplayName(String value) { + if (value == null || value.isEmpty()) return ""; + return value.replace('_', ' '); + } + + private static String sanitizeInternal(String raw) { + if (raw == null) return ""; + String trimmed = raw.trim(); + if (trimmed.isEmpty()) return ""; + + StringBuilder out = new StringBuilder(trimmed.length()); + + for (int i = 0; i < trimmed.length(); i++) { + char c = trimmed.charAt(i); + if (Character.isLetterOrDigit(c)) { + out.append(c); + } else if (c == '_' || c == '-') { + out.append(c); + } else if (Character.isWhitespace(c)) { + if (out.length() == 0) continue; + char last = out.charAt(out.length() - 1); + if (last == '_') continue; + out.append('_'); + } + } + + return out.toString(); + } + + private static boolean isReservedWindowsName(String value) { + return WINDOWS_RESERVED_NAMES.contains(value.toUpperCase()); + } +} diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index ff6b0f24e..d1e23ad63 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -1,22 +1,32 @@ package kamkeel.npcs.util; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import noppes.npcs.LogWriter; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; import java.util.function.Supplier; public class Register { public static final Map> REGISTERED_NAMESPACES = new LinkedHashMap<>(); public static final Map NAMESPACE_DISPLAY_NAMES = new LinkedHashMap<>(); - private final String registryKey; + protected final String registryKey; protected final String namespace; protected final Map> entries = new LinkedHashMap<>(); - private Register(String registryKey, String namespace) { + public Register(String registryKey, String namespace) { this.registryKey = registryKey; this.namespace = namespace; } @@ -26,6 +36,31 @@ public class Register { return factory.get(); } + public Map> getEntries() { + return entries; + } + + public void forEach(Consumer action) { + entries.values().forEach(s -> action.accept(s.get())); + } + + public static Register create(String registryKey, String namespace, String displayName) { + registerNamespace(registryKey, namespace, displayName); + return new Register<>(registryKey, namespace); + } + + public static void registerNamespace(String registryKey, String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey(registryKey)) + REGISTERED_NAMESPACES.put(registryKey, new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get(registryKey).contains(namespace)) { + LogWriter.error("REGISTER: Namespace " + namespace + " already registered for registry " + registryKey + "!"); + } + + REGISTERED_NAMESPACES.get(registryKey).add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + } + public static boolean isEmpty(String registryKey) { if (REGISTERED_NAMESPACES.isEmpty()) return true; @@ -35,41 +70,66 @@ public class Register { 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>> variantEntries = new LinkedHashMap<>(); + 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 AbilityVariant registerVariant(String typeId, String variantName, String group, Consumer configurator) { + return registerVariant(typeId, variantName, () -> new AbilityVariant(variantName, group, configurator)); + } + + public AbilityVariant registerVariant(String typeId, String factoryName, Supplier factory) { + if (!variantEntries.containsKey(typeId)) { + variantEntries.put(typeId, new HashMap<>()); + } + + Map> type = variantEntries.get(typeId); + + String name = registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"); + type.put(name, factory); + 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.getValue()); + if (!typeOnly.contains(entry.getKey())) { + AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get()); + } + } + + for (Map.Entry>> entry : variantEntries.entrySet()) { + String typeId = entry.getKey(); + Map> map = entry.getValue(); + for (Map.Entry> innerEntry : map.entrySet()) { + AbilityController.Instance.registerVariant(typeId, innerEntry.getValue().get()); + } } } @@ -103,11 +163,23 @@ 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; for (Map.Entry> entry : entries.entrySet()) { - String name = entry.getKey().substring(entry.getKey().indexOf(namespace + ".") + 1); + String prefix = registryKey + "." + namespace + "."; + String key = entry.getKey(); + String name = key.substring(prefix.length()); AnimationController.Instance.loadBuiltInAnimation(modClass, path, name); } } catch (Exception e) { @@ -128,4 +200,69 @@ public class Register { return new Register.Animations(modClass, animationsPath, namespace); } } + + public static class EffectActions extends Register { + + private EffectActions(String namespace) { + super("effect_action", namespace); + } + + public IEffectAction register(String name, IEffectAction action) { + String key = namespace + ":" + name.trim().toLowerCase().replaceAll(" ", "_"); + entries.put(key, () -> action); + return action; + } + + public void register() { + for (Map.Entry> entry : entries.entrySet()) { + AbilityController.Instance.registerEffectAction(entry.getValue().get()); + } + } + + public static Register.EffectActions create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("effect_action")) + REGISTERED_NAMESPACES.put("effect_action", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("effect_action").contains(namespace)) { + LogWriter.error("REGISTER EFFECT ACTIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("effect_action").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.EffectActions(namespace); + } + } + + public static class Conditions extends Register { + + private Conditions(String namespace) { + super("condition", namespace); + } + + public AbilityCondition register(String name, Supplier factory) { + entries.put(registryKey + "." + namespace + "." + name, factory); + return factory.get(); + } + + public void register() { + for (Map.Entry> entry : entries.entrySet()) { + AbilityController.Instance.registerCondition(entry.getValue()); + } + } + + public static Register.Conditions create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("condition")) + REGISTERED_NAMESPACES.put("condition", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("condition").contains(namespace)) { + LogWriter.error("REGISTER CONDITIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("condition").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.Conditions(namespace); + } + } } diff --git a/src/main/java/kamkeel/npcs/util/VaultUtil.java b/src/main/java/kamkeel/npcs/util/VaultUtil.java index c25ea3f3a..47e294e57 100644 --- a/src/main/java/kamkeel/npcs/util/VaultUtil.java +++ b/src/main/java/kamkeel/npcs/util/VaultUtil.java @@ -178,6 +178,7 @@ public class VaultUtil { /** * Checks if a player has an account in the economy system. + * * @param player the player to check * @return true if the player has an account */ @@ -187,6 +188,7 @@ public class VaultUtil { /** * Checks if a player has an account in the economy system. + * * @param playerName the player name to check * @return true if the player has an account */ @@ -207,6 +209,7 @@ public class VaultUtil { /** * Gets the balance of a player. + * * @param player the player * @return the player's balance, or 0 if not available */ @@ -216,6 +219,7 @@ public class VaultUtil { /** * Gets the balance of a player by name. + * * @param playerName the player name * @return the player's balance, or 0 if not available */ @@ -236,6 +240,7 @@ public class VaultUtil { /** * Checks if a player has at least the specified amount. + * * @param player the player * @param amount the amount to check * @return true if the player has at least the specified amount @@ -246,8 +251,9 @@ public class VaultUtil { /** * Checks if a player has at least the specified amount. + * * @param playerName the player name - * @param amount the amount to check + * @param amount the amount to check * @return true if the player has at least the specified amount */ public static boolean has(String playerName, double amount) { @@ -267,6 +273,7 @@ public class VaultUtil { /** * Withdraws money from a player's account. + * * @param player the player * @param amount the amount to withdraw * @return true if the transaction was successful @@ -277,8 +284,9 @@ public class VaultUtil { /** * Withdraws money from a player's account. + * * @param playerName the player name - * @param amount the amount to withdraw + * @param amount the amount to withdraw * @return true if the transaction was successful */ public static boolean withdrawMoney(String playerName, double amount) { @@ -301,6 +309,7 @@ public class VaultUtil { /** * Adds money to a player's account (deposit). + * * @param player the player * @param amount the amount to add * @return true if the transaction was successful @@ -311,8 +320,9 @@ public class VaultUtil { /** * Adds money to a player's account (deposit). + * * @param playerName the player name - * @param amount the amount to add + * @param amount the amount to add * @return true if the transaction was successful */ public static boolean addMoney(String playerName, double amount) { @@ -336,6 +346,7 @@ public class VaultUtil { /** * Sets a player's balance to the specified amount. * This withdraws all money first, then deposits the new amount. + * * @param player the player * @param amount the new balance * @return true if the transaction was successful @@ -347,8 +358,9 @@ public class VaultUtil { /** * Sets a player's balance to the specified amount. * This withdraws all money first, then deposits the new amount. + * * @param playerName the player name - * @param amount the new balance + * @param amount the new balance * @return true if the transaction was successful */ public static boolean setBalance(String playerName, double amount) { @@ -368,6 +380,7 @@ public class VaultUtil { /** * Formats an amount according to the economy plugin's settings. + * * @param amount the amount to format * @return the formatted string, or the raw number as string if not available */ @@ -384,6 +397,7 @@ public class VaultUtil { /** * Gets the plural currency name (e.g., "Dollars"). + * * @return the plural currency name, or "coins" if not available */ public static String getCurrencyNamePlural() { @@ -399,6 +413,7 @@ public class VaultUtil { /** * Gets the singular currency name (e.g., "Dollar"). + * * @return the singular currency name, or "coin" if not available */ public static String getCurrencyNameSingular() { @@ -414,6 +429,7 @@ public class VaultUtil { /** * Creates an account for the player if one doesn't exist. + * * @param player the player * @return true if the account was created or already exists */ @@ -423,6 +439,7 @@ public class VaultUtil { /** * Creates an account for the player if one doesn't exist. + * * @param playerName the player name * @return true if the account was created or already exists */ @@ -459,6 +476,7 @@ public class VaultUtil { /** * Gets a list of all bank names. + * * @return list of bank names, or empty list if not available */ @SuppressWarnings("unchecked") @@ -475,6 +493,7 @@ public class VaultUtil { /** * Gets the balance of a bank. + * * @param bankName the bank name * @return the bank balance, or 0 if not available */ @@ -492,8 +511,9 @@ public class VaultUtil { /** * Checks if a bank has at least the specified amount. + * * @param bankName the bank name - * @param amount the amount to check + * @param amount the amount to check * @return true if the bank has at least the specified amount */ public static boolean bankHas(String bankName, double amount) { @@ -510,8 +530,9 @@ public class VaultUtil { /** * Withdraws money from a bank. + * * @param bankName the bank name - * @param amount the amount to withdraw + * @param amount the amount to withdraw * @return true if the transaction was successful */ public static boolean bankWithdraw(String bankName, double amount) { @@ -528,8 +549,9 @@ public class VaultUtil { /** * Deposits money into a bank. + * * @param bankName the bank name - * @param amount the amount to deposit + * @param amount the amount to deposit * @return true if the transaction was successful */ public static boolean bankDeposit(String bankName, double amount) { @@ -546,8 +568,9 @@ public class VaultUtil { /** * Transfers money from one player to another. - * @param from the player to take money from - * @param to the player to give money to + * + * @param from the player to take money from + * @param to the player to give money to * @param amount the amount to transfer * @return true if the transfer was successful */ @@ -557,9 +580,10 @@ public class VaultUtil { /** * Transfers money from one player to another. + * * @param fromPlayerName the player name to take money from - * @param toPlayerName the player name to give money to - * @param amount the amount to transfer + * @param toPlayerName the player name to give money to + * @param amount the amount to transfer * @return true if the transfer was successful */ public static boolean transfer(String fromPlayerName, String toPlayerName, double amount) { diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java new file mode 100644 index 000000000..12f1fd793 --- /dev/null +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -0,0 +1,1365 @@ +package noppes.npcs; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; +import kamkeel.npcs.controllers.data.ability.ConcurrentSlot; +import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.scripted.event.AbilityEvent; +import noppes.npcs.controllers.data.Animation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Shared base class for NPC and Player ability data management. + * Contains the common ability lifecycle logic: tick, phase transitions, + * animation/telegraph/sound management, cooldown state, and position/rotation locking. + *

+ * Subclasses must implement abstract methods for entity-specific behavior: + * event firing, rotation/position application, telegraph packets, and cooldown rolling. + * + * @see DataAbilities - NPC implementation + * @see noppes.npcs.controllers.data.PlayerAbilityData - Player implementation + */ +public abstract class AbstractDataAbilities { + + /** + * Safety timeout (ticks) for abilities stuck in ACTIVE phase. + * If an ability stays in ACTIVE for longer than this without calling signalCompletion(), + * it is force-completed to prevent permanent stuck state. 30 seconds at 20 TPS. + */ + protected static final int MAX_ACTIVE_PHASE_TICKS = 600; + + // ═══════════════════════════════════════════════════════════════════ + // SHARED RUNTIME STATE (not saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Currently executing ability (null if none) + */ + protected Ability currentAbility; + + /** + * World time when global cooldown ends + */ + protected long cooldownEndTime = 0; + + /** + * Duration of the current global cooldown in ticks (for progress calculation) + */ + protected int globalCooldownDuration = 0; + + /** + * Per-ability cooldown end times. Key = ability key, Value = world time when cooldown ends. + */ + protected HashMap perAbilityCooldownEndTimes = new HashMap<>(); + + /** + * Per-ability cooldown durations in ticks (for progress calculation). + */ + protected HashMap perAbilityCooldownDurations = new HashMap<>(); + + /** + * Rotation lock state + */ + protected boolean rotationLocked = false; + protected float lockedYaw = 0; + protected float lockedPitch = 0; + + /** + * Position lock state + */ + protected boolean positionLocked = false; + protected boolean wasFlyingAtLock = false; + protected double lockedPosX = 0; + protected double lockedPosY = 0; + protected double lockedPosZ = 0; + + /** + * Chained ability execution state + */ + protected ChainedAbility currentChain; + protected int chainEntryIndex = -1; + protected int chainDelayRemaining = -1; + + /** + * Set when interrupt already rolled cooldown (prevents double cooldown on NPC dazed completion). + */ + protected boolean interruptCooldownRolled = false; + + /** + * Concurrent ability execution slots. Ticked independently alongside the primary ability. + * Concurrent abilities skip animations, sounds, and movement/rotation locks. + */ + protected List concurrentSlots = new ArrayList<>(); + + // ═══════════════════════════════════════════════════════════════════ + // ABSTRACT METHODS - Subclasses must implement + // ═══════════════════════════════════════════════════════════════════ + + /** + * Get the entity this ability data belongs to (NPC or Player). + */ + protected abstract EntityLivingBase getEntity(); + + /** + * Get the current target for ability execution. + */ + protected abstract EntityLivingBase getTarget(); + + /** + * Get the current world time. + */ + protected abstract long getWorldTime(); + + // -- Event Firing (unified via EventHooks) -- + + protected void fireTickEvent(Ability ability, EntityLivingBase target) { + EventHooks.onAbilityTick(ability, getEntity(), target, ability.getPhase().ordinal(), ability.getCurrentTick()); + } + + protected boolean fireExecuteEvent(Ability ability, EntityLivingBase target) { + return EventHooks.onAbilityExecute(ability, getEntity(), target); + } + + protected void fireCompleteEvent(Ability ability, EntityLivingBase target) { + EventHooks.onAbilityComplete(ability, getEntity(), target); + } + + protected void fireInterruptEvent(Ability ability, EntityLivingBase target, + DamageSource source, float damage) { + EventHooks.onAbilityInterrupt(ability, getEntity(), target, source, damage); + } + + protected boolean fireToggleEvent(Ability ability, int oldState, int newState) { + return EventHooks.onAbilityToggle(ability, getEntity(), oldState, newState); + } + + protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) { + AbilityEvent.ToggleUpdateEvent event = new AbilityEvent.ToggleUpdateEvent(getEntity(), ability, tick, state); + EventHooks.onAbilityToggleUpdate(ability, event); + return event.isEnabled(); + } + + // -- Chain Events (unified via EventHooks) -- + + protected void fireChainStartEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) { + EventHooks.onChainStart(chain, getEntity(), entryIndex, target); + } + + protected void fireChainNextEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) { + EventHooks.onChainNext(chain, getEntity(), entryIndex, target); + } + + protected void fireChainCompleteEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) { + EventHooks.onChainComplete(chain, getEntity(), entryIndex, target); + } + + protected void fireChainInterruptEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target, + DamageSource source, float damage) { + EventHooks.onChainInterrupt(chain, getEntity(), entryIndex, target, source, damage); + } + + // -- Telegraph -- + + /** + * Spawn telegraphs for an ability. + */ + protected abstract void spawnTelegraph(Ability ability, EntityLivingBase target); + + /** + * Remove telegraphs for an ability. + */ + protected abstract void removeTelegraph(Ability ability); + + // -- Animation/Sound Data Access -- + + /** + * Set animation data on the entity. + */ + protected abstract void setAnimationData(Animation animation); + + /** + * Clear animation data on the entity. + */ + protected abstract void clearAnimationData(); + + /** + * Play a sound at the entity's location. + */ + protected abstract void playAbilitySound(String sound); + + // -- Rotation (subclass handles extra fields and application) -- + + /** + * Capture rotation values for locking. NPC captures 4 fields, Player captures 2. + */ + protected abstract void captureLockedRotation(); + + // -- Completion -- + + /** + * Roll cooldown after ability completes. + * NPC: random(min, max) + ability offset. Player: ability's base cooldownTicks. + */ + protected abstract void rollCooldown(Ability ability); + + /** + * Additional completion logic (NPC clears lastTarget, Player clears key/target and syncs). + */ + protected abstract void onAbilityComplete(); + + /** + * Roll cooldown after a chained ability completes. + * NPC: random(min, max) + chain.cooldownTicks. Player: chain.cooldownTicks only. + */ + protected abstract void rollChainCooldown(ChainedAbility chain); + + + // -- Hooks (optional overrides) -- + + /** + * Called before onExecute in ACTIVE phase. NPC uses this for faceTarget/hitScan. + */ + protected void onPreExecute(Ability ability, EntityLivingBase target) { + } + + /** + * Called after the phase switch. NPC uses this for hit scan updates and movement control. + */ + protected void onPostPhaseTick(Ability ability, EntityLivingBase target) { + } + + /** + * Additional lock releases in BURST_DELAY. NPC releases hitScan. + */ + protected void onBurstDelayReleaseLocks() { + } + + /** + * Hook for retargeting during chain execution when target dies. NPC overrides, Player returns null. + */ + protected EntityLivingBase retargetForChain() { + return null; + } + + // ═══════════════════════════════════════════════════════════════════ + // SHARED ANIMATION METHODS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Play an animation on the entity. + */ + public void playAbilityAnimation(Animation animation) { + if (animation == null) return; + if (AnimationController.Instance == null) return; + setAnimationData(animation); + } + + public void playAbilityAnimation(int animation) { + if (animation < 0) return; + if (AnimationController.Instance == null) return; + if (AnimationController.Instance.get(animation) == null) return; + playAbilityAnimation((Animation) AnimationController.Instance.get(animation)); + } + + public void playAbilityAnimation(String animation) { + if (animation.isEmpty()) return; + if (AnimationController.Instance == null) return; + if (AnimationController.Instance.get(animation, true) == null) return; + playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true)); + } + + /** + * Stop any currently playing ability animation. + */ + protected void stopAbilityAnimation() { + clearAnimationData(); + } + + // ═══════════════════════════════════════════════════════════════════ + // STATE QUERIES + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if an ability is currently executing. + */ + public boolean isExecutingAbility() { + return currentAbility != null && currentAbility.isExecuting(); + } + + /** + * True when an executing ability grants invulnerability for its current phase. + */ + public boolean isCurrentAbilityInvulnerable() { + return currentAbility != null + && currentAbility.isExecuting() + && currentAbility.isInvulnerableForCurrentPhase(); + } + + /** + * Get the currently executing ability. + */ + public Ability getCurrentAbility() { + return currentAbility; + } + + /** + * Get the active defend ability if one is currently defending. + */ + public AbilityDefend getActiveDefend() { + if (currentAbility instanceof AbilityDefend) { + AbilityDefend defend = (AbilityDefend) currentAbility; + if (defend.isDefending()) { + return defend; + } + } + return null; + } + + /** + * Check if a chained ability is currently executing. + */ + public boolean isExecutingChain() { + return currentChain != null; + } + + /** + * Get the currently executing chained ability. + */ + public ChainedAbility getCurrentChain() { + return currentChain; + } + + // ═══════════════════════════════════════════════════════════════════ + // TOGGLE STATE (active toggles, independent of currentAbility) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Currently active toggles. Key = ability key, Value = toggle entry with state and tick counter. + */ + protected Map activeToggles = new LinkedHashMap<>(); + + /** + * Cycle a toggle ability to its next state. + * Off(0) -> State 1 -> State 2 -> ... -> State N -> Off(0) + * + * @param key The ability key (e.g., "npcdbc:ki_fist") + * @return The new state (0 = off, 1+ = active state number) + */ + public int toggleAbility(String key) { + AbilityToggleEntry existing = activeToggles.get(key); + if (existing != null) { + int currentState = existing.getState(); + int maxStates = existing.getAbility().getToggleStates(); + if (currentState < maxStates) { + return cycleToggleState(key, existing, currentState, currentState + 1); + } else { + deactivateToggle(key); + return 0; + } + } else { + return activateToggle(key, 1) ? 1 : 0; + } + } + + /** + * Get the current toggle state for an ability. + * @return 0 if not active, 1+ for active state + */ + public int getToggleState(String key) { + AbilityToggleEntry entry = activeToggles.get(key); + return entry != null ? entry.getState() : 0; + } + + /** + * Set a toggle to a specific state. 0 = deactivate, 1+ = specific state. + */ + public void setToggleState(String key, int state) { + if (state <= 0) { + if (activeToggles.containsKey(key)) { + deactivateToggle(key); + } + return; + } + AbilityToggleEntry existing = activeToggles.get(key); + if (existing != null) { + int currentState = existing.getState(); + if (currentState != state) { + cycleToggleState(key, existing, currentState, state); + } + } else { + activateToggle(key, state); + } + } + + /** + * Check if a toggle ability is currently active (any state > 0). + */ + public boolean isAbilityToggled(String key) { + return activeToggles.containsKey(key); + } + + /** + * Get all active toggle keys. + */ + public Set getActiveToggleKeys() { + return new LinkedHashSet<>(activeToggles.keySet()); + } + + private boolean activateToggle(String key, int state) { + Ability ability = AbilityController.Instance != null + ? AbilityController.Instance.resolveAbility(key) : null; + if (ability == null || !ability.isToggleable()) return false; + if (state < 1 || state > ability.getToggleStates()) state = 1; + + if (fireToggleEvent(ability, 0, state)) return false; + + AbilityToggleEntry entry = new AbilityToggleEntry(ability, state); + activeToggles.put(key, entry); + ability.onToggle(getEntity(), 0, state); + onToggleStateChanged(key, true, state); + return true; + } + + private int cycleToggleState(String key, AbilityToggleEntry entry, int oldState, int newState) { + Ability ability = entry.getAbility(); + if (newState < 1 || newState > ability.getToggleStates()) return oldState; + + if (fireToggleEvent(ability, oldState, newState)) return oldState; + + entry.setState(newState); + ability.onToggle(getEntity(), oldState, newState); + onToggleStateChanged(key, true, newState); + return newState; + } + + private void deactivateToggle(String key) { + AbilityToggleEntry entry = activeToggles.get(key); + if (entry == null) return; + int oldState = entry.getState(); + + if (fireToggleEvent(entry.getAbility(), oldState, 0)) return; + + activeToggles.remove(key); + entry.getAbility().onToggle(getEntity(), oldState, 0); + onToggleStateChanged(key, false, 0); + } + + /** + * Tick all active toggles. Call from tick() each game tick. + * Toggles with hasActiveToggle=true get their onToggleTick() called. + * If onToggleTick returns false, the toggle is auto-deactivated. + * Every 10 ticks, fires a toggle update event for ALL active toggles. + */ + protected void tickActiveToggles() { + if (activeToggles.isEmpty()) return; + + EntityLivingBase entity = getEntity(); + List toRemove = null; + + for (Map.Entry mapEntry : new ArrayList<>(activeToggles.entrySet())) { + AbilityToggleEntry entry = mapEntry.getValue(); + entry.incrementTick(); + + if (entry.getAbility().hasActiveToggle()) { + if (!entry.getAbility().onToggleTick(entity, entry.getTickCount(), entry.getState())) { + if (toRemove == null) toRemove = new ArrayList<>(); + toRemove.add(mapEntry.getKey()); + continue; + } + } + + if (entry.getTickCount() % 10 == 0) { + boolean enabled = fireToggleUpdateEvent(entry.getAbility(), entry.getTickCount(), entry.getState()); + if (!enabled) { + if (toRemove == null) toRemove = new ArrayList<>(); + toRemove.add(mapEntry.getKey()); + } + } + } + + if (toRemove != null) { + for (String key : toRemove) { + AbilityToggleEntry entry = activeToggles.remove(key); + if (entry != null) { + int oldState = entry.getState(); + entry.getAbility().onToggle(entity, oldState, 0); + onToggleStateChanged(key, false, 0); + } + } + } + } + + /** + * Hook for subclass to react to toggle state changes (sync packets, script events). + */ + protected void onToggleStateChanged(String key, boolean active, int state) { + } + + + /** + * Clear all active toggles (e.g., on death/reset). + * Calls onToggle for each active toggle to signal deactivation. + */ + protected void clearActiveToggles() { + if (activeToggles.isEmpty()) return; + EntityLivingBase entity = getEntity(); + for (Map.Entry mapEntry : activeToggles.entrySet()) { + AbilityToggleEntry entry = mapEntry.getValue(); + entry.getAbility().onToggle(entity, entry.getState(), 0); + } + activeToggles.clear(); + } + + /** + * Add a toggle entry directly without calling onToggle. + * Used for client-side sync and NBT restoration. + * @param key The ability key + * @param state The toggle state (0 = remove, 1+ = set at state) + */ + public void setToggleEntryDirect(String key, int state) { + if (state > 0) { + Ability ability = AbilityController.Instance != null + ? AbilityController.Instance.resolveAbility(key) : null; + if (ability != null && ability.isToggleable()) { + activeToggles.put(key, new AbilityToggleEntry(ability, state)); + } + } else { + activeToggles.remove(key); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // COOLDOWN MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if on cooldown. + */ + public boolean isOnCooldown() { + return getWorldTime() < cooldownEndTime; + } + + /** + * Get remaining cooldown ticks. + */ + public long getRemainingCooldown() { + long remaining = cooldownEndTime - getWorldTime(); + return remaining > 0 ? remaining : 0; + } + + /** + * Reset cooldown (allow immediate ability use). + */ + public void resetCooldown() { + cooldownEndTime = 0; + } + + /** + * Set the cooldown end time directly. + */ + public void setCooldownEndTime(long endTime) { + cooldownEndTime = endTime; + } + + /** + * Get the global cooldown end time. + */ + public long getCooldownEndTime() { + return cooldownEndTime; + } + + /** + * Get the global cooldown duration value. + */ + public int getGlobalCooldownDurationValue() { + return globalCooldownDuration; + } + + /** + * Get the per-ability cooldown end times map. + */ + public HashMap getPerAbilityCooldownEndTimes() { + return perAbilityCooldownEndTimes; + } + + /** + * Get the per-ability cooldown durations map. + */ + public HashMap getPerAbilityCooldownDurations() { + return perAbilityCooldownDurations; + } + + /** + * Apply cooldown sync data from server. Called on client side. + */ + public void applyCooldownSync(long globalEndTime, int globalDuration, + HashMap perEndTimes, + HashMap perDurations) { + this.cooldownEndTime = globalEndTime; + this.globalCooldownDuration = globalDuration; + this.perAbilityCooldownEndTimes = perEndTimes; + this.perAbilityCooldownDurations = perDurations; + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-ABILITY COOLDOWN MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if a specific ability is on its per-ability cooldown. + */ + public boolean isOnPerAbilityCooldown(String key) { + Long endTime = perAbilityCooldownEndTimes.get(key); + return endTime != null && getWorldTime() < endTime; + } + + /** + * Set a per-ability cooldown. + */ + public void setPerAbilityCooldown(String key, long endTime, int duration) { + perAbilityCooldownEndTimes.put(key, endTime); + perAbilityCooldownDurations.put(key, duration); + } + + /** + * Reset a specific per-ability cooldown. + */ + public void resetPerAbilityCooldown(String key) { + perAbilityCooldownEndTimes.remove(key); + perAbilityCooldownDurations.remove(key); + } + + /** + * Reset all per-ability cooldowns. + */ + public void resetAllPerAbilityCooldowns() { + perAbilityCooldownEndTimes.clear(); + perAbilityCooldownDurations.clear(); + } + + /** + * Get global cooldown progress for HUD rendering. + * @return 1.0 when cooldown just started (fully covered), 0.0 when done + */ + public float getGlobalCooldownProgress() { + if (globalCooldownDuration <= 0) return 0f; + long remaining = cooldownEndTime - getWorldTime(); + if (remaining <= 0) return 0f; + return Math.min(1f, (float) remaining / globalCooldownDuration); + } + + /** + * Get per-ability cooldown progress for HUD rendering. + * @return 1.0 when cooldown just started (fully covered), 0.0 when done + */ + public float getPerAbilityCooldownProgress(String key) { + Long endTime = perAbilityCooldownEndTimes.get(key); + Integer duration = perAbilityCooldownDurations.get(key); + if (endTime == null || duration == null || duration <= 0) return 0f; + long remaining = endTime - getWorldTime(); + if (remaining <= 0) return 0f; + return Math.min(1f, (float) remaining / duration); + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current position to lock entity in place. + */ + protected void captureLockedPosition() { + EntityLivingBase entity = getEntity(); + lockedPosX = entity.posX; + lockedPosY = entity.posY; + lockedPosZ = entity.posZ; + positionLocked = true; + + // Record flight state at lock time so airborne players stay at their height + // even if their flight system deactivates during input suppression + wasFlyingAtLock = entity instanceof net.minecraft.entity.player.EntityPlayer + && AbilityController.Instance != null + && AbilityController.Instance.isPlayerFlying((net.minecraft.entity.player.EntityPlayer) entity); + + onPositionLockChanged(true); + } + + /** + * Release position lock. + */ + protected void releaseLockedPosition() { + positionLocked = false; + wasFlyingAtLock = false; + onPositionLockChanged(false); + } + + /** + * Whether the entity was flying when the position lock was captured. + */ + public boolean wasFlyingAtLock() { + return wasFlyingAtLock; + } + + /** + * Hook for subclass to react to position lock state changes (e.g., NPC sets data watcher flag). + */ + protected void onPositionLockChanged(boolean locked) { + } + + // ═══════════════════════════════════════════════════════════════════ + // ROTATION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Release rotation control. + */ + protected void releaseRotationControl() { + rotationLocked = false; + onRotationLockChanged(false); + } + + /** + * Hook for subclass to react to rotation lock state changes (e.g., NPC sets flag, clears hitScan). + */ + protected void onRotationLockChanged(boolean locked) { + } + + // ═══════════════════════════════════════════════════════════════════ + // CORE TICK - Phase transition logic shared between NPC and Player + // ═══════════════════════════════════════════════════════════════════ + + /** + * Tick the currently executing ability. Handles all phase transitions, + * telegraph/animation/sound lifecycle, and burst management. + *

+ * This is the core shared logic between DataAbilities and PlayerAbilityData. + * Subclass-specific behavior is injected via abstract methods and hooks. + */ + protected void tickCurrentAbility() { + // Handle chain delay between entries + if (chainDelayRemaining > 0) { + chainDelayRemaining--; + if (chainDelayRemaining <= 0) { + EntityLivingBase chainTarget = getTarget(); + // Check if target is dead and retarget + if (currentChain != null && chainTarget != null && chainTarget.isDead) { + chainTarget = retargetForChain(); + if (chainTarget == null) { + completeChain(); + return; + } + } + if (startChainEntry(chainTarget)) { + fireChainNextEvent(currentChain, chainEntryIndex, chainTarget); + launchConsecutiveConcurrentEntries(chainTarget); + } + } + // Tick concurrent slots even during chain delay + tickConcurrentSlots(); + return; + } + + EntityLivingBase entity = getEntity(); + EntityLivingBase target = getTarget(); + AbilityPhase oldPhase = currentAbility.getPhase(); + + // Tick advances time and possibly changes phase + boolean phaseChanged = currentAbility.tick(); + + // Fire tick event + fireTickEvent(currentAbility, target); + + // Script may have completed/cancelled the ability during the tick event + if (currentAbility == null) return; + if (!currentAbility.isExecuting()) { + // tick() itself can end the ability (DAZED -> IDLE). Run its completion here, + // otherwise it stays the current ability forever and nothing else can start. + if (phaseChanged && currentAbility.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(target); + } + return; + } + + // Fire extender tick hook (e.g., per-tick resource drain) + if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, entity, target, + currentAbility.getPhase(), currentAbility.getCurrentTick())) { + interruptCurrentAbility(null, 0); + return; + } + + // Handle phase-specific logic + switch (currentAbility.getPhase()) { + case WINDUP: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up locks, telegraph, sound, animation + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(currentAbility, target); + playAbilitySound(currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } + currentAbility.onWindUpTick(entity, target, currentAbility.getCurrentTick()); + break; + + case ACTIVE: + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { + // Just entered ACTIVE phase - lock telegraph positions + for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { + telegraph.lockPosition(); + } + + // Remove telegraph unless the ability keeps it during active phase + if (!currentAbility.keepTelegraphDuringActive()) { + removeTelegraph(currentAbility); + } + + // Handle rotation control transition from WINDUP to ACTIVE + if (currentAbility.isRotationLockedDuringActive()) { + if (!rotationLocked) { + captureLockedRotation(); + } + } else if (rotationLocked) { + 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 + if (!currentAbility.keepTelegraphDuringActive()) { + playAbilitySound(currentAbility.getActiveSound()); + } + playAbilityAnimation(currentAbility.getActiveAnimation()); + + // Pre-execute hook (NPC: snap to face target for hit scan) + onPreExecute(currentAbility, target); + + // Fire execute event (cancelable) + if (fireExecuteEvent(currentAbility, target)) { + // Script cancelled — abort cleanly instead of leaving stuck in ACTIVE + currentAbility.interrupt(); + handleAbilityCompletion(target); + return; + } + + // Call onExecute + currentAbility.onExecute(entity, target); + + // Check if ability completed during onExecute + if (currentAbility.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(target); + return; + } + } + + currentAbility.onActiveTick(entity, target, currentAbility.getCurrentTick()); + + // Play pending defend reaction animation + sound (counter strike, dodge roll, etc.) + if (currentAbility instanceof AbilityDefend) { + AbilityDefend defend = (AbilityDefend) currentAbility; + Animation defendAnim = defend.consumeDefendAnimation(); + if (defendAnim != null) { + playAbilityAnimation(defendAnim); + playAbilitySound(currentAbility.getActiveSound()); + defend.scheduleReturnToActive(currentAbility.getCurrentTick(), defendAnim); + } + // Return to active animation after defend animation finishes (Counter → guard stance) + if (defend.shouldReturnToActiveAnimation(currentAbility.getCurrentTick())) { + Animation activeAnim = currentAbility.getActiveAnimation(); + if (activeAnim != null) { + playAbilityAnimation(activeAnim); + } + } + } + + // Check if ability completed during onActiveTick + if (currentAbility.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(target); + return; + } + + // Auto-complete for burst overlap mode only. + // Non-overlap waits for all entities to die naturally (via allDead check in onActiveTick). + if (currentAbility.isBurstEnabled() + && currentAbility.isBurstOverlap() + && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() + && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { + currentAbility.signalCompletion(); + } + + // Check if ability entered burst delay + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + onBurstDelayReleaseLocks(); + } + + // Safety timeout: force-complete if stuck in ACTIVE too long. + // Individual ability types should have their own timeouts well below this; + // this is a last-resort failsafe to prevent permanent stuck state. + if (currentAbility != null && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.getCurrentTick() > MAX_ACTIVE_PHASE_TICKS) { + currentAbility.cancel(); + handleAbilityCompletion(target); + return; + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + break; + + case DAZED: + // Dazed phase - just wait for phase transition + break; + + case IDLE: + // Ability completed (reached via tick() from DAZED) + handleAbilityCompletion(target); + break; + } + + // Post-phase hook (NPC: hit scan + movement control) + onPostPhaseTick(currentAbility, target); + + // Tick concurrent slots independently + tickConcurrentSlots(); + } + + // ═══════════════════════════════════════════════════════════════════ + // ABILITY COMPLETION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Handle ability completion. Called when ability phase becomes IDLE. + * If a chain is active, advances to the next entry instead of completing. + */ + protected void handleAbilityCompletion(EntityLivingBase target) { + if (currentAbility == null) return; + + // Remove any remaining telegraphs + removeTelegraph(currentAbility); + + // Fire extender complete hook + AbilityController.Instance.fireOnAbilityComplete(currentAbility, getEntity(), target, false); + + // Call onComplete callback + currentAbility.onComplete(getEntity(), target); + + // Fire complete event + fireCompleteEvent(currentAbility, target); + + // Release locks + releaseRotationControl(); + releaseLockedPosition(); + stopAbilityAnimation(); + + // Chain mode: advance to next entry instead of completing + if (currentChain != null) { + // AFTER semantics: delay from the CURRENT (just-completed) entry + ChainedAbilityEntry completedEntry = currentChain.getEntries().get(chainEntryIndex); + int delay = completedEntry.getDelayTicks(); + + chainEntryIndex++; + + // Skip any consecutive concurrent entries — launch them to concurrent slots + launchConsecutiveConcurrentEntries(target); + + if (chainEntryIndex < currentChain.getEntries().size()) { + // Check if target died and retarget + if (target != null && target.isDead) { + target = retargetForChain(); + if (target == null) { + completeChain(); + return; + } + } + + // Enforce minimum 1-tick delay between chain entries + chainDelayRemaining = Math.max(1, delay); + currentAbility = null; + return; + } + // All entries complete + completeChain(); + return; + } + + // Normal (non-chain) completion + if (interruptCooldownRolled) { + // Cooldown was already rolled during interrupt (e.g., chain interrupted, NPC ticked through DAZED) + interruptCooldownRolled = false; + } else { + rollCooldown(currentAbility); + } + onAbilityComplete(); + } + + // ═══════════════════════════════════════════════════════════════════ + // EXECUTE IMMEDIATE + // ═══════════════════════════════════════════════════════════════════ + + /** + * Execute an ability immediately (no windup). Called when windUpTicks is 0. + */ + protected void executeImmediate(Ability ability, EntityLivingBase target) { + // Spawn telegraph for abilities that persist during active phase (e.g., Custom Ability) + if (ability.keepTelegraphDuringActive()) { + spawnTelegraph(ability, target); + } + + // Play active sound and animation + playAbilitySound(ability.getActiveSound()); + playAbilityAnimation(ability.getActiveAnimation()); + + // Fire execute event (cancelable) + if (fireExecuteEvent(ability, target)) { + // Script cancelled — abort cleanly instead of leaving stuck in ACTIVE + ability.interrupt(); + handleAbilityCompletion(target); + return; + } + + // Call onExecute + ability.onExecute(getEntity(), target); + + // Check if ability completed during onExecute + if (ability.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(target); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // INTERRUPTION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Interrupt the currently executing ability. + * Shared interrupt logic: remove telegraph, play dazed animation, + * release locks, fire events, call ability.interrupt(). + */ + public void interruptCurrentAbility(DamageSource source, float damage) { + if (currentAbility != null && currentAbility.isExecuting()) { + // Remove telegraph + removeTelegraph(currentAbility); + + // Fire extender complete hook (interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, getEntity(), getTarget(), true); + + // Fire interrupt event + fireInterruptEvent(currentAbility, getTarget(), source, damage); + + // Call ability callbacks + currentAbility.onInterrupt(getEntity(), source, damage); + currentAbility.interrupt(); + + // Play dazed animation + stopAbilityAnimation(); + playAbilityAnimation(currentAbility.getDazedAnimation()); + + // Release locks + releaseRotationControl(); + releaseLockedPosition(); + + // If chain was active, fire interrupt event, roll cooldown and clear chain state + if (currentChain != null) { + rollChainCooldown(currentChain); + interruptCooldownRolled = true; + fireChainInterruptEvent(currentChain, chainEntryIndex, getTarget(), source, damage); + currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + } + + // Interrupt all concurrent slots + interruptConcurrentSlots(); + + // Let subclass handle cleanup + onInterruptComplete(); + } + } + + /** + * Hook called after interrupt completes. Subclass handles clearing state and syncing. + * NPC: keeps currentAbility (ticks through DAZED). Player: clears immediately. + */ + protected void onInterruptComplete() { + } + + /** + * Cancel the currently executing ability (voluntary player action). + * Unlike interrupt, this always goes directly to IDLE (never DAZED), + * immediately rolls cooldown, and clears state. + * Also handles cancellation during chain delay (between chain entries). + */ + public void cancelCurrentAbility() { + boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting(); + boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0; + + if (!hasExecutingAbility && !isInChainDelay) return; + + if (hasExecutingAbility) { + AbilityPhase phase = currentAbility.getPhase(); + // Only allow cancel during WINDUP phase + if (phase != AbilityPhase.WINDUP) return; + + // Remove telegraph + removeTelegraph(currentAbility); + + // Fire extender complete hook (cancelled = interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, getEntity(), getTarget(), true); + + // Fire interrupt event (source=null, damage=0 for voluntary cancel) + fireInterruptEvent(currentAbility, getTarget(), null, 0); + + // Cancel the ability (cleanup + go directly to IDLE, no DAZED) + currentAbility.onInterrupt(getEntity(), null, 0); + currentAbility.cancel(); + + // Release locks and stop animation + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + } + + // Roll cooldown + if (currentChain != null) { + rollChainCooldown(currentChain); + currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + } else if (currentAbility != null) { + rollCooldown(currentAbility); + } + + // Interrupt all concurrent slots + interruptConcurrentSlots(); + + // Clear state via the normal completion path + onAbilityComplete(); + } + + /** + * Cleanly complete the currently executing ability. + * Unlike cancel/interrupt, this triggers the normal completion path + * (fires abilityComplete event, rolls cooldown, advances chains). + * Only works during the ACTIVE phase. + */ + public void completeCurrentAbility() { + if (currentAbility == null || !currentAbility.isExecuting()) return; + if (currentAbility.getPhase() != AbilityPhase.ACTIVE) return; + + // Signal completion on the ability (handles cleanup, detach/freeOnCast, burst logic) + if (!currentAbility.signalCompletion()) return; + + // If signalCompletion moved to IDLE, handle the clean completion path + if (currentAbility.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(getTarget()); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // CHAINED ABILITY EXECUTION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Start executing a chained ability. Sets up chain state and starts the first entry. + * + * @param chain The chained ability to execute (should be a deep copy) + * @param target The initial target + * @return true if the chain was started + */ + protected boolean startChain(ChainedAbility chain, EntityLivingBase target) { + if (chain == null || chain.getEntries().isEmpty()) return false; + + currentChain = chain; + chainEntryIndex = 0; + chainDelayRemaining = -1; + + // AFTER semantics: no delay before first entry (delay applies after each entry completes) + boolean started = startChainEntry(target); + if (started) { + fireChainStartEvent(currentChain, 0, target); + launchConsecutiveConcurrentEntries(target); + } + return started; + } + + /** + * Start the current chain entry's ability. + */ + protected boolean startChainEntry(EntityLivingBase target) { + if (currentChain == null || chainEntryIndex < 0 || chainEntryIndex >= currentChain.getEntries().size()) { + completeChain(); + return false; + } + + ChainedAbilityEntry entry = currentChain.getEntries().get(chainEntryIndex); + Ability ability = entry.resolve(); + if (ability == null) { + // Broken reference - complete chain + completeChain(); + return false; + } + + // Validate the resolved ability's UserType matches the chain's allowed context. + // The chain's own UserType was already checked at selection time, but individual + // abilities may have stricter restrictions (e.g., PLAYER_ONLY in an NPC chain). + if (!ability.getAllowedBy().allowsNpc() && getEntity() instanceof noppes.npcs.entity.EntityNPCInterface) { + // Skip this entry - ability doesn't allow NPCs + completeChain(); + return false; + } + if (!ability.getAllowedBy().allowsPlayer() && getEntity() instanceof net.minecraft.entity.player.EntityPlayer) { + // Skip this entry - ability doesn't allow players + completeChain(); + return false; + } + + // If windUpAll=false, only the first ability windups; subsequent abilities skip windup + if (!currentChain.isWindUpAll() && chainEntryIndex > 0) { + ability.setWindUpTicks(0); + } + + // Start the ability (skip its own conditions - chain conditions were already checked) + currentAbility = ability; + ability.start(target); + + if (ability.getPhase() == AbilityPhase.ACTIVE) { + // Windup was 0 - capture locks for immediate active phase, then execute + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } + executeImmediate(ability, target); + } else { + // Normal windup flow + if (ability.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(ability, target); + playAbilitySound(ability.getWindUpSound()); + playAbilityAnimation(ability.getWindUpAnimation()); + } + + return true; + } + + // ═══════════════════════════════════════════════════════════════════ + // CONCURRENT SLOT MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Tick all active concurrent slots. Remove completed ones. + * Called from tickCurrentAbility() and during chain delay countdown. + */ + protected void tickConcurrentSlots() { + if (concurrentSlots.isEmpty()) return; + + EntityLivingBase entity = getEntity(); + EntityLivingBase target = getTarget(); + + Iterator it = concurrentSlots.iterator(); + while (it.hasNext()) { + ConcurrentSlot slot = it.next(); + slot.tick(entity, target); + if (slot.isCompleted()) { + it.remove(); + } + } + } + + /** + * After starting a primary chain entry, scan forward and launch any consecutive + * concurrent entries (with delay=0) to concurrent slots immediately. + * This enables simultaneous execution of Effect abilities alongside the primary. + */ + protected void launchConsecutiveConcurrentEntries(EntityLivingBase target) { + if (currentChain == null) return; + + List entries = currentChain.getEntries(); + while (chainEntryIndex + 1 < entries.size()) { + ChainedAbilityEntry nextEntry = entries.get(chainEntryIndex + 1); + Ability resolved = nextEntry.resolve(); + if (resolved == null || !resolved.isConcurrentCapable() + || !nextEntry.isConcurrentEnabled()) break; + + // Only auto-launch concurrent entries with 0 delay + if (nextEntry.getDelayTicks() > 0) break; + + // Advance past this entry in the chain (it runs concurrently, not sequentially) + chainEntryIndex++; + + // Deep copy the ability so it has its own state + Ability concurrentCopy = AbilityController.Instance.fromNBT(resolved.writeNBT(true)); + if (concurrentCopy == null) continue; + + ConcurrentSlot slot = new ConcurrentSlot(concurrentCopy); + concurrentSlots.add(slot); + slot.start(getEntity(), target); + } + } + + /** + * Interrupt all active concurrent slots. Called on ability interrupt or combat reset. + */ + protected void interruptConcurrentSlots() { + for (ConcurrentSlot slot : concurrentSlots) { + slot.interrupt(); + } + concurrentSlots.clear(); + } + + /** + * Complete the chain execution. Rolls chain cooldown and clears all chain state. + * NOTE: Does NOT clear concurrent slots — they outlive the chain and tick independently. + */ + protected void completeChain() { + if (currentChain != null) { + rollChainCooldown(currentChain); + fireChainCompleteEvent(currentChain, chainEntryIndex, getTarget()); + currentChain.clearInstanceScript(); + } + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + currentAbility = null; + onAbilityComplete(); + } +} diff --git a/src/main/java/noppes/npcs/AnimationMixinFunctions.java b/src/main/java/noppes/npcs/AnimationMixinFunctions.java index 4a6eb1db5..e5c6d2089 100644 --- a/src/main/java/noppes/npcs/AnimationMixinFunctions.java +++ b/src/main/java/noppes/npcs/AnimationMixinFunctions.java @@ -209,21 +209,31 @@ public class AnimationMixinFunctions { return null; } - public static void playerFullModel_head(Entity p_78088_1_, CallbackInfo callbackInfo) { - if (!DBCAddon.IsAvailable() && ClientCacheHandler.playerAnimations.containsKey(p_78088_1_.getUniqueID())) { - AnimationData animData = ClientCacheHandler.playerAnimations.get(p_78088_1_.getUniqueID()); - if (animData != null && animData.isActive()) { - Frame frame = (Frame) animData.animation.currentFrame(); - if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) { - FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); - part.interpolateOffset(); - part.interpolateAngles(); - float pi = 180 / (float) Math.PI; - GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]); - GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0); - GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0); - GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1); - } + public static void playerFullModel_head(Entity entity, CallbackInfo callbackInfo) { + if (!ClientCacheHandler.playerAnimations.containsKey(entity.getUniqueID())) return; + + AnimationData animData = ClientCacheHandler.playerAnimations.get(entity.getUniqueID()); + if (animData == null || !animData.isActive()) return; + + // Snap body rotation to head so animations face the look direction + if (entity instanceof EntityLivingBase) { + EntityLivingBase living = (EntityLivingBase) entity; + living.renderYawOffset = living.rotationYaw; + living.prevRenderYawOffset = living.prevRotationYaw; + } + + // FULL_MODEL GL transforms (non-DBC only) + if (!DBCAddon.IsAvailable()) { + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) { + FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); + part.interpolateOffset(); + part.interpolateAngles(); + float pi = 180 / (float) Math.PI; + GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]); + GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0); + GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0); + GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1); } } } diff --git a/src/main/java/noppes/npcs/CommonProxy.java b/src/main/java/noppes/npcs/CommonProxy.java index ee65ad6a5..0c60d14ac 100644 --- a/src/main/java/noppes/npcs/CommonProxy.java +++ b/src/main/java/noppes/npcs/CommonProxy.java @@ -13,18 +13,19 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.FakePlayer; import noppes.npcs.api.IWorld; import noppes.npcs.blocks.tiles.TileNpcContainer; +import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumGuiType; -import noppes.npcs.containers.ContainerAuction; +import noppes.npcs.containers.ContainerAnvilRepair; import noppes.npcs.containers.ContainerAuctionBidding; -import noppes.npcs.containers.ContainerAuctionTrades; import noppes.npcs.containers.ContainerAuctionListing; import noppes.npcs.containers.ContainerAuctionSell; -import noppes.npcs.containers.ContainerAnvilRepair; +import noppes.npcs.containers.ContainerAuctionTrades; import noppes.npcs.containers.ContainerCarpentryBench; import noppes.npcs.containers.ContainerCrate; import noppes.npcs.containers.ContainerCustomGui; import noppes.npcs.containers.ContainerMail; import noppes.npcs.containers.ContainerManageBanks; +import noppes.npcs.containers.ContainerManageAuction; import noppes.npcs.containers.ContainerManageRecipes; import noppes.npcs.containers.ContainerMerchantAdd; import noppes.npcs.containers.ContainerNPCBankLarge; @@ -43,7 +44,6 @@ import noppes.npcs.containers.ContainerNpcQuestReward; import noppes.npcs.containers.ContainerNpcQuestTypeItem; import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.controllers.data.PlayerData; -import noppes.npcs.config.ConfigScript; import noppes.npcs.entity.EntityNPCInterface; public class CommonProxy implements IGuiHandler { @@ -137,6 +137,9 @@ public class CommonProxy implements IGuiHandler { if (gui == EnumGuiType.ManageBanks) return new ContainerManageBanks(player); + if (gui == EnumGuiType.ManageAuction) + return new ContainerManageAuction(player); + if (gui == EnumGuiType.MerchantAdd) return new ContainerMerchantAdd(player, ServerEventsHandler.Merchant, player.worldObj); @@ -222,6 +225,14 @@ public class CommonProxy implements IGuiHandler { public void buildPackageIndex() { } + /** + * Called from the mod's FMLLoadCompleteEvent, after every other mod has finished loading. + * Anything that has to observe another mod's registrations belongs here rather than in + * load(), and it stays on the proxy so client-only types never reach the server. + */ + public void loadComplete() { + } + public boolean isScriptingEnabled() { return ConfigScript.ScriptingEnabled; } diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 0bc081429..7274a490e 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -21,13 +21,25 @@ import io.github.somehussar.janinoloader.api.IDynamicCompilerBuilder; import kamkeel.npcs.addon.AddonManager; import kamkeel.npcs.command.CommandKamkeel; import kamkeel.npcs.command.profile.CommandProfile; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.SyncController; import kamkeel.npcs.controllers.TelegraphController; -import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker; import kamkeel.npcs.controllers.data.profile.CNPCData; import kamkeel.npcs.developer.Developer; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityEnergySweeper; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.entity.EntityEnergySlicer; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.util.BukkitUtil; import net.minecraft.block.Block; @@ -55,6 +67,7 @@ import noppes.npcs.compat.PixelmonHelper; import noppes.npcs.config.ConfigMain; import noppes.npcs.config.LoadConfiguration; import noppes.npcs.config.legacy.LegacyConfig; +import noppes.npcs.controllers.APIRegistry; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.AuctionController; import noppes.npcs.controllers.BankController; @@ -86,11 +99,6 @@ import noppes.npcs.entity.EntityNpcDragon; import noppes.npcs.entity.EntityNpcPony; import noppes.npcs.entity.EntityNpcSlime; import noppes.npcs.entity.EntityProjectile; -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 noppes.npcs.entity.old.EntityNPCDwarfFemale; import noppes.npcs.entity.old.EntityNPCDwarfMale; import noppes.npcs.entity.old.EntityNPCElfFemale; @@ -117,7 +125,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.1") public class CustomNpcs { @SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy") @@ -287,11 +295,15 @@ public class CustomNpcs { registerNewEntity(EntityChairMount.class, "CustomNpcChairMount", 64, 10, false); registerNewEntity(EntityProjectile.class, "throwableitem", 64, 3, true); registerNewEntity(EntityMagicProjectile.class, "magicprojectile", 64, 3, true); - registerNewEntity(EntityAbilityOrb.class, "abilityorb", 64, 3, true); - registerNewEntity(EntityAbilityDisc.class, "abilitydisc", 64, 3, true); - registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 3, true); - registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 3, true); - registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true); + registerNewEntity(EntityAbilityOrb.class, "abilityorb", 64, 1, true); + registerNewEntity(EntityAbilityDisc.class, "abilitydisc", 64, 1, true); + registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 1, true); + registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 160, 1, true); + registerNewEntity(EntityEnergySweeper.class, "abilitysweeper", 64, 3, true); + registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true); + registerNewEntity(EntityEnergyDome.class, "energydome", 64, 3, true); + registerNewEntity(EntityEnergyPanel.class, "energypanel", 64, 3, true); + registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 1, true); new RecipeController(); @@ -305,6 +317,11 @@ public class CustomNpcs { new AddonManager(); new AttributeController(); new MagicController(); + + SyncController.register(); + + + APIRegistry.Instance.register("CNPC+ API", "https://kamkeel.github.io/CustomNPC-Plus/"); } @EventHandler @@ -326,7 +343,19 @@ public class CustomNpcs { @EventHandler public void loadComplete(FMLLoadCompleteEvent ev) { + // Runs after every other mod has loaded. Kept on the proxy: the client side registers + // inventory tabs, and naming those types here would drag client-only GUI classes into + // a class the server loads. + proxy.loadComplete(); proxy.buildPackageIndex(); + + // Load built-in animations on the client so they're available for ability preview. + // On dedicated servers, AnimationController.load() only runs on the server JVM, + // leaving the client without built-in animation data. In singleplayer, load() + // runs later during server start and reloads everything, so this is harmless. + if (FMLCommonHandler.instance().getSide().isClient()) { + AnimationController.Instance.loadClientBuiltIns(); + } } @EventHandler @@ -336,6 +365,7 @@ public class CustomNpcs { clientJaninoCompiler = null; Server = event.getServer(); + AnimationController.Instance.load(); ChunkController.Instance.clear(); FactionController.getInstance().load(); MagicController.getInstance().load(); @@ -345,7 +375,6 @@ public class CustomNpcs { new GlobalDataController(); new SpawnController(); new LinkedNpcController(); - new AnimationController(); AbilityController.Instance.load(); TelegraphController.init(); @@ -413,6 +442,10 @@ public class CustomNpcs { AuctionController.Instance.save(); } + EntityEnergyProjectile.clearAllProjectiles(); + EntityEnergyBarrier.clearAllBarriers(); + EnergyChargeTracker.Instance.clear(); + if (FMLCommonHandler.instance().getSide().isClient()) clientJaninoCompiler = null; globalJaninoCompiler = null; diff --git a/src/main/java/noppes/npcs/CustomNpcsPermissions.java b/src/main/java/noppes/npcs/CustomNpcsPermissions.java index af9b2b9af..d27a509e5 100644 --- a/src/main/java/noppes/npcs/CustomNpcsPermissions.java +++ b/src/main/java/noppes/npcs/CustomNpcsPermissions.java @@ -69,6 +69,7 @@ public class CustomNpcsPermissions { public static final Permission GLOBAL_MAGIC = new Permission("customnpcs.global.magic"); public static final Permission GLOBAL_ABILITY = new Permission("customnpcs.global.ability"); public static final Permission GLOBAL_EFFECT = new Permission("customnpcs.global.effect"); + public static final Permission GLOBAL_AUCTION = new Permission("customnpcs.global.auction"); public static final Permission SPAWNER_MOB = new Permission("customnpcs.spawner.mob"); public static final Permission SPAWNER_CREATE = new Permission("customnpcs.spawner.create"); diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 5e1ff694f..3888df2d5 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -1,33 +1,37 @@ package noppes.npcs; +import kamkeel.npcs.controllers.AbilityController; 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.AbilitySlot; -import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; +import kamkeel.npcs.controllers.data.ability.AbilityAction; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.enums.RotationMode; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.DamageSource; -import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AbilityEvent; - +import noppes.npcs.EventHooks; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Random; /** * Manages NPC abilities - storage, selection, execution, and cooldowns. - * Follows the DataStats/DataAI pattern for NPC data management. + * Extends AbstractDataAbilities for shared ability lifecycle logic. */ -public class DataAbilities { +public class DataAbilities extends AbstractDataAbilities { private final EntityNPCInterface npc; private final Random random = new Random(); @@ -37,9 +41,9 @@ public class DataAbilities { // ═══════════════════════════════════════════════════════════════════ /** - * List of ability slots this NPC can use (inline or reference). + * Unified list of action slots (abilities and chained abilities). */ - private List abilitySlots = new ArrayList<>(); + private List actionSlots = new ArrayList<>(); /** * Whether the ability system is enabled for this NPC @@ -57,19 +61,9 @@ public class DataAbilities { public int maxCooldown = 200; // ═══════════════════════════════════════════════════════════════════ - // RUNTIME STATE (not saved) + // NPC-SPECIFIC RUNTIME STATE (not saved) // ═══════════════════════════════════════════════════════════════════ - /** - * Currently executing ability (null if none) - */ - private transient Ability currentAbility; - - /** - * World time when NPC cooldown ends (can select next ability) - */ - private transient long cooldownEndTime = 0; - /** * Last target used for ability execution */ @@ -81,32 +75,34 @@ public class DataAbilities { private transient List recentHitTimes = new ArrayList<>(); /** - * Locked rotation values for ACTIVE phase when movement is locked. - * Stored when entering ACTIVE phase, applied every tick to prevent rotation changes. + * NPC-specific locked rotation fields (yawHead, renderYawOffset). + * Base class handles lockedYaw and lockedPitch. */ - private transient boolean rotationLocked = false; - private transient float lockedYaw = 0; private transient float lockedYawHead = 0; 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() + * Set during onPostPhaseTick(), applied after super.onLivingUpdate() * to override AI look helper rotation. */ private transient boolean hitScanActive = false; private transient EntityLivingBase hitScanTarget = null; + private transient float currentTrackSpeed = 0; + private transient float trackedYaw = 0; + private transient float trackedPitch = 0; + private transient boolean trackLerpedThisTick = false; + private transient boolean preserveTrackedRotation = false; + + /** + * Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15 + */ + private static final int ROTATION_CONTROLLED_FLAG = 16; + + /** + * Bit flag for position lock in data watcher slot 15 + */ + private static final int POSITION_LOCKED_FLAG = 32; // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR @@ -116,6 +112,194 @@ public class DataAbilities { this.npc = npc; } + // ═══════════════════════════════════════════════════════════════════ + // ABSTRACT METHOD IMPLEMENTATIONS + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected EntityLivingBase getEntity() { + return npc; + } + + @Override + protected EntityLivingBase getTarget() { + return lastTarget != null ? lastTarget : npc.getAttackTarget(); + } + + @Override + protected long getWorldTime() { + return npc.worldObj.getTotalWorldTime(); + } + + @Override + protected void spawnTelegraph(Ability ability, EntityLivingBase target) { + List telegraphs = ability.createTelegraphs(npc, target); + if (!telegraphs.isEmpty()) { + ability.setTelegraphInstances(telegraphs); + for (TelegraphInstance telegraph : telegraphs) { + TelegraphSpawnPacket.sendToTracking(telegraph, npc); + } + } + } + + @Override + protected void removeTelegraph(Ability ability) { + List telegraphs = ability.getTelegraphInstances(); + for (TelegraphInstance telegraph : telegraphs) { + TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), npc); + } + ability.setTelegraphInstances(null); + } + + @Override + protected void setAnimationData(Animation animation) { + npc.display.animationData.setEnabled(true); + npc.display.animationData.setAnimation(animation); + npc.display.animationData.updateClient(); + } + + @Override + protected void clearAnimationData() { + npc.display.animationData.setAnimation(null); + npc.display.animationData.updateClient(); + } + + @Override + protected void playAbilitySound(String sound) { + if (sound != null && !sound.isEmpty()) { + npc.worldObj.playSoundAtEntity(npc, sound, 1.0f, 1.0f); + } + } + + @Override + protected void captureLockedRotation() { + lockedYaw = npc.rotationYaw; + lockedYawHead = npc.rotationYawHead; + lockedRenderYawOffset = npc.renderYawOffset; + lockedPitch = npc.rotationPitch; + rotationLocked = true; + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); + } + + @Override + protected void rollCooldown(Ability ability) { + // Always roll NPC global cooldown (pacing timer) + int baseCooldown = minCooldown; + if (maxCooldown > minCooldown) { + baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); + } + long now = npc.worldObj.getTotalWorldTime(); + + if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) { + // The ability's own cooldown is tracked against the ability, so the global timer + // only paces how often the NPC acts. Folding the ability's cooldown into it as + // well would always outlast the per-ability entry and make it unreachable. + cooldownEndTime = now + baseCooldown; + setPerAbilityCooldown(ability.getName(), now + ability.getCooldownTicks(), ability.getCooldownTicks()); + } else { + cooldownEndTime = now + baseCooldown + ability.getCooldownTicks(); + } + } + + @Override + protected void rollChainCooldown(ChainedAbility chain) { + long now = npc.worldObj.getTotalWorldTime(); + boolean perAbility = chain.isPerAbilityCooldown() && chain.getCooldownTicks() > 0; + + if (!chain.isIgnoreCooldown()) { + int baseCooldown = minCooldown; + if (maxCooldown > minCooldown) { + baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); + } + cooldownEndTime = perAbility ? now + baseCooldown : now + baseCooldown + chain.getCooldownTicks(); + } + + if (perAbility) { + setPerAbilityCooldown(chain.getName(), now + chain.getCooldownTicks(), chain.getCooldownTicks()); + } + } + + @Override + protected EntityLivingBase retargetForChain() { + return npc.getAttackTarget(); + } + + @Override + protected void onAbilityComplete() { + currentAbility = null; + lastTarget = null; + } + + // ═══════════════════════════════════════════════════════════════════ + // HOOK OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void onPreExecute(Ability ability, EntityLivingBase target) { + // Face target before execute so startMoving() reads correct rotation + // Use trackSpeed so the NPC plays catchup rather than instant-snapping + if (ability.isHitScanForCurrentPhase() && target != null) { + float speed = ability.getTrackSpeed(); + if (speed <= 0) { + faceTarget(target); + } else { + faceTarget(target, speed); + } + } + } + + @Override + protected void onPostPhaseTick(Ability ability, EntityLivingBase target) { + // Reset per-tick lerp flag so faceTarget only computes the lerp once per tick + trackLerpedThisTick = false; + + // Update hit scan state - actual facing is deferred to applyRotationControl() + // which runs AFTER super.onLivingUpdate() to override AI look helper + if (ability != null && ability.isExecuting() && target != null) { + if (ability.isHitScanForCurrentPhase()) { + enableHitScan(target, ability.getTrackSpeed()); + } else { + // Release hit scan if it was previously active + if (hitScanActive) { + releaseRotationControl(); + } + // FREE mode: use AI look helper during ability execution since combat AI may not run + if (ability.getRotationMode() == RotationMode.FREE) { + npc.getLookHelper().setLookPositionWithEntity(target, 30.0F, 30.0F); + } + } + } else if (hitScanActive) { + releaseRotationControl(); + } + + // Apply movement control if ability is still executing + if (ability != null && ability.isExecuting()) { + applyMovementControl(); + } + } + + @Override + protected void onBurstDelayReleaseLocks() { + if (hitScanActive) { + preserveTrackedRotation = true; + releaseRotationControl(); + } + } + + @Override + protected void onPositionLockChanged(boolean locked) { + npc.setBoolFlag(locked, POSITION_LOCKED_FLAG); + } + + @Override + protected void onRotationLockChanged(boolean locked) { + if (!locked) { + hitScanActive = false; + hitScanTarget = null; + } + npc.setBoolFlag(locked, ROTATION_CONTROLLED_FLAG); + } + // ═══════════════════════════════════════════════════════════════════ // TICK - Called from EntityNPCInterface.onLivingUpdate() // ═══════════════════════════════════════════════════════════════════ @@ -143,175 +327,33 @@ public class DataAbilities { if (rotationLocked || hitScanActive) releaseRotationControl(); if (positionLocked) releaseLockedPosition(); } + // Clear chain and concurrent state + if (currentChain != null) currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + interruptConcurrentSlots(); return; } // Safety: release orphaned locks if no ability is actively executing - if (currentAbility == null || !currentAbility.isExecuting()) { + if ((currentAbility == null || !currentAbility.isExecuting()) && chainDelayRemaining <= 0) { if (rotationLocked || hitScanActive) releaseRotationControl(); if (positionLocked) releaseLockedPosition(); } - // Tick current ability if executing - if (currentAbility != null && currentAbility.isExecuting()) { + // Tick active toggles (independent of currentAbility) + tickActiveToggles(); + + // Tick current ability if executing, or tick chain delay between entries + if (chainDelayRemaining > 0 || (currentAbility != null && currentAbility.isExecuting())) { tickCurrentAbility(); } } - /** - * Tick the currently executing ability. - */ - private void tickCurrentAbility() { - EntityLivingBase target = lastTarget != null ? lastTarget : npc.getAttackTarget(); - AbilityPhase oldPhase = currentAbility.getPhase(); - - // Tick advances time and possibly changes phase - boolean phaseChanged = currentAbility.tick(); - - // Fire tick event for scripts - fireTickEvent(currentAbility, target); - - // Handle phase-specific logic - switch (currentAbility.getPhase()) { - case WINDUP: - 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, npc.worldObj, currentAbility.getCurrentTick()); - break; - - case ACTIVE: - if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { - // Just entered ACTIVE phase - lock telegraph position if it was following - // This commits the ability to its current target position - TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); - if (telegraph != null) { - telegraph.lockPosition(); - } - - // Remove telegraph - it has served its purpose - removeTelegraph(currentAbility); - - // Handle rotation control transition from WINDUP to ACTIVE - if (currentAbility.isRotationLockedDuringActive()) { - if (!rotationLocked) { - captureLockedRotation(); - } - } else if (rotationLocked) { - releaseRotationControl(); - } - - // Handle position lock transition from WINDUP to ACTIVE - if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { - if (!positionLocked) { - captureLockedPosition(); - } - } else if (positionLocked) { - releaseLockedPosition(); - } - - // Burst re-fire without replay: let entity-spawning abilities spawn+fire in one step - if (oldPhase == AbilityPhase.BURST_DELAY && !currentAbility.isBurstReplayAnimations()) { - currentAbility.onBurstRefire(npc, target, npc.worldObj); - } - - // Play active sound and animation - 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); - if (NpcAPI.EVENT_BUS.post(executeEvent)) { - // Event was cancelled - skip execution but continue to recovery - return; - } - - // Call onExecute - currentAbility.onExecute(npc, target, npc.worldObj); - - // Check if ability completed during onExecute (signalCompletion was called) - if (currentAbility.getPhase() == AbilityPhase.IDLE) { - handleAbilityCompletion(target); - return; - } - } - currentAbility.onActiveTick(npc, target, npc.worldObj, 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.isBurstOverlap() - && 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: - // Dazed phase - NPC cannot attack, just wait for daze to end - break; - - case IDLE: - // Ability completed (reached via tick() phase transition from DAZED) - handleAbilityCompletion(target); - 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(); - } - } - /** * Apply movement control based on lock movement settings. - * Called every tick during ability execution. + * Called every tick during ability execution via onPostPhaseTick(). */ private void applyMovementControl() { if (currentAbility == null) return; @@ -330,61 +372,12 @@ public class DataAbilities { } } - /** - * Handle ability completion - called when ability phase becomes IDLE. - * This can happen from: - * - signalCompletion() called in onExecute() or onActiveTick() - * - tick() transitioning from DAZED to IDLE - */ - private void handleAbilityCompletion(EntityLivingBase target) { - if (currentAbility == null) return; - - // Call onComplete callback - currentAbility.onComplete(npc, target); - - // Fire complete event - AbilityEvent.CompleteEvent completeEvent = new AbilityEvent.CompleteEvent( - npc.wrappedNPC, currentAbility, target); - NpcAPI.EVENT_BUS.post(completeEvent); - - // Release locks before cleanup - releaseRotationControl(); - releaseLockedPosition(); - - // Clean up and roll cooldown (this sets currentAbility to null) - onAbilityComplete(); - } - - /** - * Called when an ability completes. - * Calculates cooldown as: random(minCooldown, maxCooldown) + ability's cooldown offset - */ - private void onAbilityComplete() { - if (currentAbility != null) { - // Stop any ability animation - stopAbilityAnimation(); - - // Release locks - releaseRotationControl(); - releaseLockedPosition(); - - // Calculate cooldown: random(min, max) + ability offset - int abilityCooldownOffset = currentAbility.getCooldownTicks(); - rollCooldown(); - // Add ability-specific cooldown offset - cooldownEndTime += abilityCooldownOffset; - - currentAbility = null; - lastTarget = null; - } - } - // ═══════════════════════════════════════════════════════════════════ // ABILITY SELECTION - Called from CombatHandler // ═══════════════════════════════════════════════════════════════════ /** - * Try to select and start an ability for the given target. + * Try to select and start an ability or chained ability for the given target. * Called by CombatHandler when NPC is in combat and ready for an ability. * * @param target The combat target @@ -395,24 +388,61 @@ public class DataAbilities { return false; } - Ability selected = selectAbility(target); - if (selected == null) { + // Build eligible pool from unified action slots + List eligible = new ArrayList<>(); + List weights = new ArrayList<>(); + int totalWeight = 0; + + for (AbilityAction slot : actionSlots) { + IAbilityAction action = slot.getAction(); + if (action != null && isActionEligible(slot, action, target)) { + eligible.add(action); + weights.add(action.getWeight()); + totalWeight += action.getWeight(); + } + } + + if (eligible.isEmpty() || totalWeight <= 0) { return false; } - return startAbility(selected, target); + // Weighted random selection + int roll = random.nextInt(totalWeight); + int cumulative = 0; + IAbilityAction selected = null; + for (int i = 0; i < eligible.size(); i++) { + cumulative += weights.get(i); + if (roll < cumulative) { + selected = eligible.get(i); + break; + } + } + if (selected == null) { + selected = eligible.get(eligible.size() - 1); + } + + // Dispatch + lastTarget = target; + if (selected.isChain()) { + return startChain((ChainedAbility) selected, target); + } else { + return startAbility((Ability) selected, target); + } } /** * Check if an ability can be selected right now. */ public boolean canSelectAbility() { - if (!enabled || abilitySlots.isEmpty()) { + if (!enabled || actionSlots.isEmpty()) { return false; } if (currentAbility != null && currentAbility.isExecuting()) { return false; } + if (isExecutingChain()) { + return false; + } // Check if still on cooldown if (npc.worldObj.getTotalWorldTime() < cooldownEndTime) { return false; @@ -421,68 +451,52 @@ public class DataAbilities { } /** - * Select an ability using weighted random from eligible abilities. + * Check if an action (ability or chain) is eligible for use. */ - private Ability selectAbility(EntityLivingBase target) { - List eligible = new ArrayList<>(); - int totalWeight = 0; - - for (Ability ability : getAbilities()) { - if (isAbilityEligible(ability, target)) { - eligible.add(ability); - totalWeight += ability.getWeight(); - } + private boolean isActionEligible(AbilityAction slot, IAbilityAction action, EntityLivingBase target) { + if (!action.getAllowedBy().allowsNpc()) { + return false; } - - if (eligible.isEmpty() || totalWeight <= 0) { - return null; - } - - // Weighted random selection - int roll = random.nextInt(totalWeight); - int cumulative = 0; - for (Ability ability : eligible) { - cumulative += ability.getWeight(); - if (roll < cumulative) { - return ability; - } - } - - return eligible.get(eligible.size() - 1); - } - - /** - * Check if a specific ability is eligible for use. - */ - private boolean isAbilityEligible(Ability ability, EntityLivingBase target) { - // Check UserType allows NPCs - if (!ability.getAllowedBy().allowsNpc()) { + if (!slot.isSlotEnabled()) { return false; } - // Check enabled - if (!ability.isEnabled()) { + // Ability-specific: check if already executing + if (!action.isChain() && ((Ability) action).isExecuting()) { return false; } - // Check if already executing - if (ability.isExecuting()) { + // Chain-specific: must have entries + if (action.isChain() && ((ChainedAbility) action).getEntries().isEmpty()) { return false; } - // Check range + // Range check if (target != null) { float distance = npc.getDistanceToEntity(target); - if (distance < ability.getMinRange() || distance > ability.getMaxRange()) { + if (distance < action.getMinRange() || distance > action.getMaxRange()) { return false; } } - // Check conditions - if (!ability.checkConditions(npc, target)) { + // Conditions + if (!action.checkConditions(npc, target)) { return false; } + // Per-ability cooldown filter: ability/chain may have its own independent cooldown + if (!action.isChain()) { + Ability ab = (Ability) action; + if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) { + return false; + } + } else { + ChainedAbility ch = (ChainedAbility) action; + if (ch.isPerAbilityCooldown() && isOnPerAbilityCooldown(ch.getName())) { + return false; + } + } + return true; } @@ -491,10 +505,12 @@ public class DataAbilities { */ private boolean startAbility(Ability ability, EntityLivingBase target) { // Fire start event (cancelable) - AbilityEvent.StartEvent startEvent = new AbilityEvent.StartEvent( - npc.wrappedNPC, ability, target); - if (NpcAPI.EVENT_BUS.post(startEvent)) { - // Event was cancelled - don't start the ability + if (EventHooks.onAbilityStart(ability, npc, target)) { + return false; + } + + // Fire extender start hook (e.g., resource cost checks) + if (!AbilityController.Instance.fireOnAbilityStart(ability, npc, target)) { return false; } @@ -503,7 +519,13 @@ public class DataAbilities { ability.start(target); if (ability.getPhase() == AbilityPhase.ACTIVE) { - // Windup was 0 — skip telegraph/windup and go straight to active + // Windup was 0 — capture locks for immediate active phase, then execute + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } executeImmediate(ability, target); } else { // Normal windup flow @@ -521,136 +543,6 @@ public class DataAbilities { return true; } - /** - * Execute an ability immediately (no windup). - * Called when windUpTicks is 0. - */ - private void executeImmediate(Ability ability, EntityLivingBase target) { - // Lock rotation if rotation is locked during ACTIVE phase - if (ability.isRotationLockedDuringActive()) { - captureLockedRotation(); - } - if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { - captureLockedPosition(); - } - - // Play active sound and animation - playAbilitySound(ability.getActiveSound()); - playAbilityAnimation(ability.getActiveAnimation()); - - // Fire execute event (cancelable) - AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent( - npc.wrappedNPC, ability, target); - if (NpcAPI.EVENT_BUS.post(executeEvent)) { - return; - } - - // Call onExecute - ability.onExecute(npc, target, npc.worldObj); - - // Check if ability completed during onExecute - if (ability.getPhase() == AbilityPhase.IDLE) { - handleAbilityCompletion(target); - } - } - - /** - * Play a sound at the NPC's location. - */ - private void playAbilitySound(String sound) { - if (sound != null && !sound.isEmpty()) { - npc.worldObj.playSoundAtEntity(npc, sound, 1.0f, 1.0f); - } - } - - /** - * Play an animation on the NPC by ID. - * Public so abilities can trigger animations directly if needed. - * - * @param animation The animation to play, or null if none - */ - public void playAbilityAnimation(Animation animation) { - if (animation == null) return; - if (AnimationController.Instance == null) return; - - npc.display.animationData.setEnabled(true); - npc.display.animationData.setAnimation(animation); - npc.display.animationData.updateClient(); - } - - public void playAbilityAnimation(int animation) { - if (animation < 0) return; - if (AnimationController.Instance == null) return; - if (AnimationController.Instance.get(animation) == null) return; - - playAbilityAnimation((Animation) AnimationController.Instance.get(animation)); - } - - public void playAbilityAnimation(String animation) { - if (animation.isEmpty()) return; - if (AnimationController.Instance == null) return; - if (AnimationController.Instance.get(animation, true) == null) return; - - playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true)); - } - - /** - * Stop any currently playing ability animation. - */ - private void stopAbilityAnimation() { - npc.display.animationData.setAnimation(null); - npc.display.animationData.updateClient(); - } - - /** - * Spawn and send telegraph 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); - } - } - - /** - * Remove telegraph when ability ends or is interrupted. - */ - private void removeTelegraph(Ability ability) { - TelegraphInstance telegraph = ability.getTelegraphInstance(); - if (telegraph != null) { - TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), npc); - ability.setTelegraphInstance(null); - } - } - - // ═══════════════════════════════════════════════════════════════════ - // COOLDOWN MANAGEMENT - // ═══════════════════════════════════════════════════════════════════ - - /** - * Check if NPC is on cooldown (cannot use any ability). - */ - public boolean isOnCooldown() { - return npc.worldObj.getTotalWorldTime() < cooldownEndTime; - } - - /** - * Get remaining cooldown ticks. - */ - public long getRemainingCooldown() { - long remaining = cooldownEndTime - npc.worldObj.getTotalWorldTime(); - return remaining > 0 ? remaining : 0; - } - - /** - * Reset cooldown (allow immediate ability use). - */ - public void resetCooldown() { - cooldownEndTime = 0; - } - // ═══════════════════════════════════════════════════════════════════ // INTERRUPTION - Called from CombatHandler on damage // ═══════════════════════════════════════════════════════════════════ @@ -663,15 +555,15 @@ public class DataAbilities { * @return true if ability was interrupted */ public boolean onDamage(DamageSource source, float amount) { - // Track hit for hit count condition - recordHit(); - if (currentAbility == null || !currentAbility.isExecuting()) { return false; } + if (currentAbility.isInvulnerableForCurrentPhase()) { + return false; + } - currentAbility.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount); - + // Track hit for hit count condition + recordHit(); if (currentAbility.canInterrupt(source)) { interruptCurrentAbility(source, amount); return true; @@ -680,18 +572,6 @@ public class DataAbilities { return false; } - /** - * Get the damage reduction factor if a Guard ability is currently active. - * - * @return The damage reduction factor (0.0 = no reduction, 1.0 = full immunity), or 0 if not guarding - */ - public float getGuardDamageReduction() { - if (currentAbility instanceof AbilityGuard) { - return ((AbilityGuard) currentAbility).getDamageReductionFactor(); - } - return 0.0f; - } - /** * Record a hit for the hit count condition. * Includes periodic cleanup to prevent memory leak. @@ -729,36 +609,6 @@ public class DataAbilities { return count; } - /** - * Interrupt the currently executing ability. - * If interrupted during WINDUP, the ability will transition to DAZED phase. - * When DAZED completes, the ability will move to IDLE and onAbilityComplete() is called. - */ - public void interruptCurrentAbility(DamageSource source, float damage) { - if (currentAbility != null) { - // Remove telegraph early - removeTelegraph(currentAbility); - - // Stop any ability animation - stopAbilityAnimation(); - - // Release locks - releaseRotationControl(); - releaseLockedPosition(); - - // Fire interrupt event - AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent( - npc.wrappedNPC, currentAbility, lastTarget, source, damage); - NpcAPI.EVENT_BUS.post(interruptEvent); - - currentAbility.onInterrupt(npc, source, damage); - currentAbility.interrupt(); // Transitions to DAZED if interrupted during WINDUP - - // Don't clear currentAbility - let it tick through DAZED phase - // When DAZED ends and phase becomes IDLE, onAbilityComplete() will be called - } - } - /** * Force stop the current ability (no interrupt event). */ @@ -772,6 +622,11 @@ public class DataAbilities { currentAbility = null; lastTarget = null; } + // Also clear chain state + if (currentChain != null) currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; } /** @@ -779,7 +634,7 @@ public class DataAbilities { * If an ability is currently executing, it will be cancelled. * * @param ability The ability to start - * @param target The target entity (can be null for self-targeted abilities) + * @param target The target entity (can be null for self-targeted abilities) * @return true if the ability was started successfully */ public boolean forceStartAbility(Ability ability, EntityLivingBase target) { @@ -806,7 +661,7 @@ public class DataAbilities { * Execute an ability on this NPC by key (built-in name or custom UUID). * The NPC does NOT need to have this ability assigned. * - * @param key The ability key (built-in name or custom UUID) + * @param key The ability key (built-in name or custom UUID) * @param target The target entity (can be null for self-targeted abilities) * @return true if the ability was started successfully */ @@ -827,39 +682,6 @@ public class DataAbilities { // SCRIPT EVENTS // ═══════════════════════════════════════════════════════════════════ - /** - * Fire the ability tick event for scripts. - */ - private void fireTickEvent(Ability ability, EntityLivingBase target) { - AbilityEvent.TickEvent event = new AbilityEvent.TickEvent( - npc.wrappedNPC, ability, target, - ability.getPhase().ordinal(), ability.getCurrentTick()); - NpcAPI.EVENT_BUS.post(event); - } - - /** - * Fire an ability hit event. Called by abilities when they hit an entity. - * Returns null if the event was cancelled, otherwise returns the (possibly modified) event. - * - * @param ability The ability doing the hit - * @param target The original target of the ability - * @param hitEntity The entity being hit - * @param damage The damage amount - * @param knockback The horizontal knockback - * @param knockbackUp The vertical knockback - * @return The event (with possibly modified values), or null if cancelled - */ - public AbilityEvent.HitEvent fireHitEvent(Ability ability, EntityLivingBase target, - EntityLivingBase hitEntity, float damage, - float knockback, float knockbackUp) { - AbilityEvent.HitEvent event = new AbilityEvent.HitEvent( - npc.wrappedNPC, ability, target, hitEntity, damage, knockback, knockbackUp); - if (NpcAPI.EVENT_BUS.post(event)) { - return null; // Cancelled - } - return event; - } - /** * Get the NPC this DataAbilities belongs to. */ @@ -878,9 +700,12 @@ public class DataAbilities { */ public void reset() { stopCurrentAbility(); + clearActiveToggles(); + interruptConcurrentSlots(); + resetAllPerAbilityCooldowns(); // Roll cooldown so NPC doesn't immediately attack after reset - rollCooldown(); + rollCooldownOnReset(); // Reset execution state on all resolved abilities for (Ability ability : getAbilities()) { @@ -889,10 +714,10 @@ public class DataAbilities { } /** - * Roll a new cooldown using the min/max range. - * Called after ability completes and on reset. + * Roll a new cooldown using the min/max range (without ability offset). + * Called on reset when no ability is involved. */ - private void rollCooldown() { + private void rollCooldownOnReset() { int baseCooldown = minCooldown; if (maxCooldown > minCooldown) { baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); @@ -901,15 +726,22 @@ public class DataAbilities { } // ═══════════════════════════════════════════════════════════════════ - // ABILITY LIST MANAGEMENT + // ACTION SLOT MANAGEMENT // ═══════════════════════════════════════════════════════════════════ /** - * Get resolved abilities from all slots, filtering out broken references. + * Get the unified action slot list. + */ + public List getAbilityActions() { + return actionSlots; + } + + /** + * Get resolved abilities from all ability slots, filtering out broken references and chains. */ public List getAbilities() { List resolved = new ArrayList<>(); - for (AbilitySlot slot : abilitySlots) { + for (AbilityAction slot : actionSlots) { Ability a = slot.getAbility(); if (a != null) { resolved.add(a); @@ -918,39 +750,62 @@ public class DataAbilities { return resolved; } - /** Get the raw slot list (for GUI access). */ - public List getAbilitySlots() { - return abilitySlots; - } - - /** Add an inline ability. */ + /** + * Add an inline ability. + */ public void addAbility(Ability ability) { - abilitySlots.add(AbilitySlot.inline(ability)); + actionSlots.add(AbilityAction.inline(ability)); } - /** Add a reference ability by key (built-in name or custom UUID). */ + /** + * Add a reference ability by key (built-in name or custom ability name). + */ public void addAbilityReference(String key) { - abilitySlots.add(AbilitySlot.reference(key)); + actionSlots.add(AbilityAction.abilityReference(key)); } - public void removeAbility(int index) { - if (index >= 0 && index < abilitySlots.size()) { - abilitySlots.remove(index); + /** + * Add a chained ability reference by name. + */ + public void addChainReference(String name) { + if (name != null && !name.isEmpty()) { + for (AbilityAction slot : actionSlots) { + if (slot.isChainReference() && name.equals(slot.getReferenceId())) { + return; // Prevent duplicates + } + } + actionSlots.add(AbilityAction.chainReference(name)); } } + /** + * Remove an action slot by index. + */ + public void removeAction(int index) { + if (index >= 0 && index < actionSlots.size()) { + actionSlots.remove(index); + } + } + + public void removeAbility(int index) { + removeAction(index); + } + public void removeAbility(String id) { - abilitySlots.removeIf(slot -> { - if (slot.isReference()) { + actionSlots.removeIf(slot -> { + if (slot.isAbilityReference()) { return slot.getReferenceId().equals(id); } + if (slot.isChainReference()) { + return false; // Don't remove chain references via removeAbility + } Ability a = slot.getAbility(); return a != null && a.getId().equals(id); }); } public Ability getAbility(String id) { - for (AbilitySlot slot : abilitySlots) { + for (AbilityAction slot : actionSlots) { Ability a = slot.getAbility(); if (a != null && a.getId().equals(id)) { return a; @@ -959,44 +814,34 @@ public class DataAbilities { return null; } - /** Check if a slot at a given index is a reference. */ + /** + * Check if a slot at a given index is a reference. + */ public boolean isSlotReference(int index) { - if (index < 0 || index >= abilitySlots.size()) return false; - return abilitySlots.get(index).isReference(); + if (index < 0 || index >= actionSlots.size()) return false; + return actionSlots.get(index).isReference(); } - /** Convert a reference slot to inline. Returns false if resolution fails. */ + /** + * Convert a reference slot to inline. Returns false if resolution fails or is a chain. + */ public boolean convertToInline(int index) { - if (index < 0 || index >= abilitySlots.size()) return false; - return abilitySlots.get(index).convertToInline(); + if (index < 0 || index >= actionSlots.size()) return false; + return actionSlots.get(index).convertToInline(); } public void clearAbilities() { - abilitySlots.clear(); + actionSlots.clear(); } public boolean isEmpty() { - return abilitySlots.isEmpty(); + return actionSlots.isEmpty(); } // ═══════════════════════════════════════════════════════════════════ - // STATE QUERIES + // STATE QUERIES (NPC-specific) // ═══════════════════════════════════════════════════════════════════ - /** - * Check if NPC is currently executing an ability. - */ - public boolean isExecutingAbility() { - return currentAbility != null && currentAbility.isExecuting(); - } - - /** - * Get the currently executing ability. - */ - public Ability getCurrentAbility() { - return currentAbility; - } - /** * Check if ability is controlling NPC movement (AI pathfinding should be blocked). * Called by AI tasks to determine if they should try to path. @@ -1064,72 +909,113 @@ public class DataAbilities { } // ═══════════════════════════════════════════════════════════════════ - // ROTATION CONTROL + // ROTATION CONTROL (NPC-specific: hit scan + 4-field rotation) // ═══════════════════════════════════════════════════════════════════ - /** 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 rotation phase. - */ - private void captureLockedRotation() { - lockedYaw = npc.rotationYaw; - lockedYawHead = npc.rotationYawHead; - lockedRenderYawOffset = npc.renderYawOffset; - lockedPitch = npc.rotationPitch; - rotationLocked = true; - npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); - } - - /** - * Release rotation control (both locked and hit scan). - */ - private void releaseRotationControl() { - rotationLocked = false; - hitScanActive = false; - hitScanTarget = null; - npc.setBoolFlag(false, ROTATION_CONTROLLED_FLAG); - } - /** * Enable hit scan tracking for the given target. */ - private void enableHitScan(EntityLivingBase target) { + private void enableHitScan(EntityLivingBase target, float trackSpeed) { if (!hitScanActive) { hitScanActive = true; npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); + // Preserve tracked rotation across burst delays so the NPC doesn't snap + if (!preserveTrackedRotation) { + trackedYaw = npc.rotationYawHead; + trackedPitch = npc.rotationPitch; + } + preserveTrackedRotation = false; } hitScanTarget = target; + currentTrackSpeed = trackSpeed; } + private static final double DEG_TO_RAD = Math.PI / 180.0; + private static final double RAD_TO_DEG = 180.0 / Math.PI; + /** - * Snap the NPC to face the target instantly. + * Face the target with optional track speed (linear speed in blocks/second). + * When trackSpeed <= 0, snaps instantly. + * When trackSpeed > 0, the NPC's aim point moves at trackSpeed blocks/second, + * converted to angular velocity based on distance. This makes tracking feel + * consistent regardless of range — directly comparable to player movement speed. */ - private void faceTarget(EntityLivingBase target) { + private void faceTarget(EntityLivingBase target, float trackSpeed) { 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); + float targetYaw = (float) (Math.atan2(-dx, dz) * RAD_TO_DEG); + float targetPitch = (float) (-(Math.atan2(dy, distXZ)) * RAD_TO_DEG); - npc.rotationYaw = yaw; - npc.rotationYawHead = yaw; - npc.renderYawOffset = yaw; - npc.rotationPitch = pitch; - npc.prevRotationYaw = yaw; - npc.prevRotationYawHead = yaw; - npc.prevRenderYawOffset = yaw; - npc.prevRotationPitch = pitch; + if (trackSpeed <= 0) { + // Instant snap + trackedYaw = targetYaw; + trackedPitch = targetPitch; + npc.rotationYaw = targetYaw; + npc.rotationYawHead = targetYaw; + npc.renderYawOffset = targetYaw; + npc.rotationPitch = targetPitch; + npc.prevRotationYaw = targetYaw; + npc.prevRotationYawHead = targetYaw; + npc.prevRenderYawOffset = targetYaw; + npc.prevRotationPitch = targetPitch; + } else { + if (!trackLerpedThisTick) { + trackLerpedThisTick = true; + + // Convert linear speed (blocks/sec) to angular speed (degrees/tick) + // using the actual distance to the target + double dist = Math.max(1.0, Math.sqrt(dx * dx + dy * dy + dz * dz)); + float blocksPerTick = trackSpeed / 20.0f; + float maxAngularSpeed = (float) (Math.atan2(blocksPerTick, dist) * RAD_TO_DEG); + + float yawDiff = wrapAngle(targetYaw - trackedYaw); + float pitchDiff = targetPitch - trackedPitch; + + float totalAngle = (float) Math.sqrt(yawDiff * yawDiff + pitchDiff * pitchDiff); + if (totalAngle > maxAngularSpeed) { + float scale = maxAngularSpeed / totalAngle; + yawDiff *= scale; + pitchDiff *= scale; + } + + trackedYaw = trackedYaw + yawDiff; + trackedPitch = trackedPitch + pitchDiff; + } + + // Set prev to current before updating (for smooth client interpolation) + npc.prevRotationYaw = npc.rotationYaw; + npc.prevRotationYawHead = npc.rotationYawHead; + npc.prevRenderYawOffset = npc.renderYawOffset; + npc.prevRotationPitch = npc.rotationPitch; + + npc.rotationYaw = trackedYaw; + npc.rotationYawHead = trackedYaw; + npc.renderYawOffset = trackedYaw; + npc.rotationPitch = trackedPitch; + } + } + + /** + * Snap the NPC to face the target instantly (no delay). + */ + private void faceTarget(EntityLivingBase target) { + faceTarget(target, 0); + } + + private static float wrapAngle(float angle) { + angle = angle % 360.0f; + if (angle >= 180.0f) angle -= 360.0f; + if (angle < -180.0f) angle += 360.0f; + return angle; } /** * 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. */ @@ -1151,7 +1037,7 @@ public class DataAbilities { // Server: apply the appropriate rotation if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) { - faceTarget(hitScanTarget); + faceTarget(hitScanTarget, currentTrackSpeed); } else if (rotationLocked) { npc.rotationYaw = lockedYaw; npc.rotationYawHead = lockedYawHead; @@ -1173,33 +1059,9 @@ public class DataAbilities { } // ═══════════════════════════════════════════════════════════════════ - // POSITION LOCKING + // POSITION LOCKING (NPC-specific: data watcher + client-side logic) // ═══════════════════════════════════════════════════════════════════ - /** 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 @@ -1255,27 +1117,72 @@ public class DataAbilities { compound.setInteger("AbilityMinCooldown", minCooldown); compound.setInteger("AbilityMaxCooldown", maxCooldown); - NBTTagList abilityList = new NBTTagList(); - for (AbilitySlot slot : abilitySlots) { - abilityList.appendTag(slot.writeNBT()); + NBTTagList actionList = new NBTTagList(); + for (AbilityAction slot : actionSlots) { + actionList.appendTag(slot.writeNBT(true)); } - compound.setTag("Abilities", abilityList); + compound.setTag("AbilityActions", actionList); + + // Active toggles (compound format with state) + NBTTagList toggleList = new NBTTagList(); + for (Map.Entry entry : activeToggles.entrySet()) { + NBTTagCompound toggleNbt = new NBTTagCompound(); + toggleNbt.setString("Key", entry.getKey()); + toggleNbt.setInteger("State", entry.getValue().getState()); + toggleList.appendTag(toggleNbt); + } + compound.setTag("ActiveToggles", toggleList); return compound; } public void readFromNBT(NBTTagCompound compound) { - enabled = compound.getBoolean("AbilitiesEnabled"); + enabled = compound.hasKey("AbilitiesEnabled") ? compound.getBoolean("AbilitiesEnabled") : true; minCooldown = compound.getInteger("AbilityMinCooldown"); maxCooldown = compound.getInteger("AbilityMaxCooldown"); - abilitySlots.clear(); - NBTTagList abilityList = compound.getTagList("Abilities", 10); - for (int i = 0; i < abilityList.tagCount(); i++) { - NBTTagCompound abilityNBT = abilityList.getCompoundTagAt(i); - AbilitySlot slot = AbilitySlot.fromNBT(abilityNBT); - if (slot != null) { - abilitySlots.add(slot); + actionSlots.clear(); + + if (compound.hasKey("AbilityActions")) { + // New unified format + NBTTagList actionList = compound.getTagList("AbilityActions", 10); + for (int i = 0; i < actionList.tagCount(); i++) { + AbilityAction slot = AbilityAction.fromNBT(actionList.getCompoundTagAt(i)); + if (slot != null) { + actionSlots.add(slot); + } + } + } else { + // Legacy migration: read old separate lists + if (compound.hasKey("Abilities")) { + NBTTagList abilityList = compound.getTagList("Abilities", 10); + for (int i = 0; i < abilityList.tagCount(); i++) { + AbilityAction slot = AbilityAction.fromNBT(abilityList.getCompoundTagAt(i)); + if (slot != null) { + actionSlots.add(slot); + } + } + } + if (compound.hasKey("ChainedAbilities")) { + NBTTagList chainList = compound.getTagList("ChainedAbilities", 8); + for (int i = 0; i < chainList.tagCount(); i++) { + String ref = chainList.getStringTagAt(i); + if (ref != null && !ref.isEmpty()) { + actionSlots.add(AbilityAction.chainReference(ref)); + } + } + } + } + + // Active toggles - restore state directly (no onToggle callback during load) + activeToggles.clear(); + if (compound.hasKey("ActiveToggles")) { + NBTTagList toggleNbt = compound.getTagList("ActiveToggles", 10); // 10 = TAG_COMPOUND + for (int i = 0; i < toggleNbt.tagCount(); i++) { + NBTTagCompound entry = toggleNbt.getCompoundTagAt(i); + String key = entry.getString("Key"); + int state = entry.hasKey("State") ? entry.getInteger("State") : 1; + setToggleEntryDirect(key, state); } } } 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..3507a3c04 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.EntityEnergyProjectile; import kamkeel.npcs.network.packets.data.AchievementPacket; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; @@ -16,9 +17,12 @@ 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.IAnimatable; import noppes.npcs.api.entity.ICustomNpc; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.entity.IProjectile; @@ -49,9 +53,19 @@ import noppes.npcs.controllers.data.RecipeScript; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.entity.EntityProjectile; import noppes.npcs.scripted.NpcAPI; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.api.event.IAbilityEvent; +import noppes.npcs.api.event.IChainEvent; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import noppes.npcs.scripted.event.AbilityEvent; import noppes.npcs.scripted.event.AnimationEvent; +import noppes.npcs.scripted.event.ChainEvent; 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; @@ -59,10 +73,10 @@ import noppes.npcs.scripted.event.NpcEvent; import noppes.npcs.scripted.event.PartyEvent; import noppes.npcs.scripted.event.ProjectileEvent; import noppes.npcs.scripted.event.RecipeScriptEvent; +import noppes.npcs.scripted.event.player.AuctionEvent; import noppes.npcs.scripted.event.player.CustomGuiEvent; import noppes.npcs.scripted.event.player.DialogEvent; import noppes.npcs.scripted.event.player.FactionEvent; -import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import noppes.npcs.scripted.event.player.PlayerEvent; import noppes.npcs.scripted.event.player.PlayerEvent.ChatEvent; import noppes.npcs.scripted.event.player.PlayerEvent.ContainerOpen; @@ -78,6 +92,7 @@ import noppes.npcs.scripted.item.ScriptItemStack; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; +import java.util.HashMap; public class EventHooks { public EventHooks() { @@ -448,6 +463,158 @@ public class EventHooks { NpcAPI.EVENT_BUS.post(event); } + // ==================== ENERGY PROJECTILE EVENTS ==================== + + public static void onEnergyProjectileFired(EntityEnergyProjectile 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(EntityEnergyProjectile projectile, int tick) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.UpdateEvent event = new EnergyProjectileEvent.UpdateEvent(wrapped, tick); + 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(EntityEnergyProjectile 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(EntityEnergyProjectile 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(EntityEnergyProjectile 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); + } + + // ==================== ENERGY BARRIER EVENTS ==================== + + private static void dispatchBarrierEvent(net.minecraft.entity.Entity barrierEntity, int ownerEntityId, + noppes.npcs.scripted.event.EnergyBarrierEvent event, EnumScriptType type) { + ScriptController.Instance.globalNpcScripts.callScript(type, event); + + net.minecraft.entity.Entity owner = barrierEntity.worldObj.getEntityByID(ownerEntityId); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(type, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(type, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + public static void onEnergyBarrierSpawned(net.minecraft.entity.Entity barrierEntity, int ownerEntityId) { + noppes.npcs.api.entity.IEnergyBarrier wrapped = (noppes.npcs.api.entity.IEnergyBarrier) NpcAPI.Instance().getIEntity(barrierEntity); + noppes.npcs.scripted.event.EnergyBarrierEvent.SpawnedEvent event = new noppes.npcs.scripted.event.EnergyBarrierEvent.SpawnedEvent(wrapped); + dispatchBarrierEvent(barrierEntity, ownerEntityId, event, EnumScriptType.ENERGY_BARRIER_SPAWNED); + } + + public static void onEnergyBarrierTick(net.minecraft.entity.Entity barrierEntity, int ownerEntityId) { + noppes.npcs.api.entity.IEnergyBarrier wrapped = (noppes.npcs.api.entity.IEnergyBarrier) NpcAPI.Instance().getIEntity(barrierEntity); + noppes.npcs.scripted.event.EnergyBarrierEvent.UpdateEvent event = new noppes.npcs.scripted.event.EnergyBarrierEvent.UpdateEvent(wrapped); + dispatchBarrierEvent(barrierEntity, ownerEntityId, event, EnumScriptType.ENERGY_BARRIER_TICK); + } + + public static float onEnergyBarrierHit(net.minecraft.entity.Entity barrierEntity, int ownerEntityId, + EntityEnergyProjectile projectile, float damage) { + noppes.npcs.api.entity.IEnergyBarrier wrappedBarrier = (noppes.npcs.api.entity.IEnergyBarrier) NpcAPI.Instance().getIEntity(barrierEntity); + noppes.npcs.api.entity.IEnergyProjectile wrappedProjectile = projectile != null + ? (noppes.npcs.api.entity.IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile) : null; + noppes.npcs.scripted.event.EnergyBarrierEvent.HitEvent event = new noppes.npcs.scripted.event.EnergyBarrierEvent.HitEvent(wrappedBarrier, wrappedProjectile, damage); + dispatchBarrierEvent(barrierEntity, ownerEntityId, event, EnumScriptType.ENERGY_BARRIER_HIT); + if (event.isCanceled()) return -1; + return event.getDamage(); + } + + public static void onEnergyBarrierDestroyed(net.minecraft.entity.Entity barrierEntity, int ownerEntityId) { + noppes.npcs.api.entity.IEnergyBarrier wrapped = (noppes.npcs.api.entity.IEnergyBarrier) NpcAPI.Instance().getIEntity(barrierEntity); + noppes.npcs.scripted.event.EnergyBarrierEvent.DestroyedEvent event = new noppes.npcs.scripted.event.EnergyBarrierEvent.DestroyedEvent(wrapped); + dispatchBarrierEvent(barrierEntity, ownerEntityId, event, EnumScriptType.ENERGY_BARRIER_DESTROYED); + } + public static void onPlayerInit(PlayerDataScript handler, IPlayer player) { PlayerEvent.InitEvent event = new PlayerEvent.InitEvent(player); handler.callScript(EnumScriptType.INIT, event); @@ -693,11 +860,155 @@ public class EventHooks { return NpcAPI.EVENT_BUS.post(event); } - public static boolean onPlayerAbilityHit(PlayerDataScript handler, PlayerAbilityEvent.HitEvent event) { - handler.callScript(EnumScriptType.ABILITY_HIT, event); + // ==================== ABILITY EVENTS (Unified NPC/Player) ==================== + + private static IScriptHandler getEntityScriptHandler(IEntityLivingBase entity) { + if (entity instanceof ICustomNpc) { + return ((EntityNPCInterface) ((ICustomNpc) entity).getMCEntity()).script; + } else if (entity instanceof IPlayer && ScriptController.Instance != null) { + return ScriptController.Instance.getPlayerScripts( + (EntityPlayer) ((IPlayer) entity).getMCEntity()); + } + return null; + } + + /** + * Dispatches an ability event through the three-tier routing chain: + *

    + *
  1. AbilityScript — fires for BOTH NPC and Player casters
  2. + *
  3. Entity script handler — routes to the caster's own handler: + * NPC casters fire on the NPC script handler only, + * Player casters fire on the Player script handler only
  4. + *
  5. EVENT_BUS — global event bus, fires last
  6. + *
+ * + * @return true if the event was cancelled (for @Cancelable events) + */ + private static boolean postAbilityEvent(Ability ability, Event event) { + IAbilityEvent abilityEvent = (IAbilityEvent) event; + + // 1. Internal ability script (fires for ALL — both NPC and Player) + // Use per-instance script so each execution has isolated variable state + AbilityScript abScript = ability.getOrCreateInstanceScript(); + if (abScript != null) { + abScript.callScript(abilityEvent.getHookName(), event); + } + + // Short-circuit if cancelled by ability script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 2. Entity script handler (NPC → NPC handler, Player → Player handler, never cross-fires) + IScriptHandler handler = getEntityScriptHandler(abilityEvent.getEntity()); + if (handler != null && !handler.isClient()) { + handler.callScript(abilityEvent.getHookName(), event); + } + + // Short-circuit if cancelled by entity script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 3. EVENT_BUS (global — fires last) return NpcAPI.EVENT_BUS.post(event); } + private static boolean postChainEvent(ChainedAbility chain, Event event) { + IChainEvent chainEvent = (IChainEvent) event; + + // 1. Internal chain script (fires first) + // Use per-instance script so each execution has isolated variable state + ChainedAbilityScript chainScript = chain.getOrCreateInstanceScript(); + if (chainScript != null) { + chainScript.callScript(chainEvent.getHookName(), event); + } + + // Short-circuit if cancelled by chain script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 2. Entity script handler (NPC or Player) + IScriptHandler handler = getEntityScriptHandler(chainEvent.getEntity()); + if (handler != null && !handler.isClient()) { + handler.callScript(chainEvent.getHookName(), event); + } + + // Short-circuit if cancelled by entity script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 3. EVENT_BUS (global — fires last) + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onAbilityStart(Ability ability, EntityLivingBase entity, EntityLivingBase target) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.StartEvent(entity, ability, target)); + } + + public static boolean onAbilityExecute(Ability ability, EntityLivingBase entity, EntityLivingBase target) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.ExecuteEvent(entity, ability, target)); + } + + public static boolean onAbilityTick(Ability ability, EntityLivingBase entity, EntityLivingBase target, int phase, int tick) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.TickEvent(entity, ability, target, phase, tick)); + } + + public static boolean onAbilityComplete(Ability ability, EntityLivingBase entity, EntityLivingBase target) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.CompleteEvent(entity, ability, target)); + } + + public static boolean onAbilityInterrupt(Ability ability, EntityLivingBase entity, EntityLivingBase target, + DamageSource source, float damage) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.InterruptEvent(entity, ability, target, source, damage)); + } + + public static boolean onAbilityHit(Ability ability, AbilityEvent.HitEvent event) { + if (ability == null || event == null) return false; + return postAbilityEvent(ability, event); + } + + public static boolean onAbilityDefend(Ability ability, AbilityEvent.DefendEvent event) { + if (ability == null || event == null) return false; + return postAbilityEvent(ability, event); + } + + public static boolean onAbilityToggle(Ability ability, EntityLivingBase entity, int oldState, int newState) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.ToggleEvent(entity, ability, oldState, newState)); + } + + public static boolean onAbilityToggleUpdate(Ability ability, AbilityEvent.ToggleUpdateEvent event) { + if (ability == null || event == null) return false; + return postAbilityEvent(ability, event); + } + + // Chain events + + public static void onChainStart(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) { + postChainEvent(chain, new ChainEvent.StartEvent(entity, chain, entryIndex, target)); + } + + public static void onChainNext(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) { + postChainEvent(chain, new ChainEvent.NextEvent(entity, chain, entryIndex, target)); + } + + public static void onChainComplete(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) { + postChainEvent(chain, new ChainEvent.CompleteEvent(entity, chain, entryIndex, target)); + } + + public static void onChainInterrupt(ChainedAbility chain, EntityLivingBase entity, int entryIndex, + EntityLivingBase target, DamageSource source, float damage) { + postChainEvent(chain, new ChainEvent.InterruptEvent(entity, chain, entryIndex, target, source, damage)); + } + public static void onPlayerChangeDim(PlayerDataScript handler, IPlayer player, int fromDim, int toDim) { PlayerEvent.ChangedDimension event = new PlayerEvent.ChangedDimension(player, fromDim, toDim); handler.callScript(EnumScriptType.CHANGED_DIM, event); @@ -748,12 +1059,24 @@ public class EventHooks { NpcAPI.EVENT_BUS.post(event); } + private static final HashMap, String> forgeEventNameCache = new HashMap<>(); + + private static String getForgeEventName(Event event) { + Class clazz = event.getClass(); + String cached = forgeEventNameCache.get(clazz); + if (cached != null) + return cached; + String eventName = clazz.getName(); + int i = eventName.lastIndexOf("."); + eventName = StringUtils.uncapitalize(eventName.substring(i + 1).replace("$", "")); + forgeEventNameCache.put(clazz, eventName); + return eventName; + } + public static void onForgeEvent(ForgeEvent ev, Event event) { ForgeDataScript handler = ScriptController.Instance.forgeScripts; if (handler.isEnabled()) { - String eventName = event.getClass().getName(); - int i = eventName.lastIndexOf("."); - eventName = StringUtils.uncapitalize(eventName.substring(i + 1).replace("$", "")); + String eventName = getForgeEventName(event); if (event.isCancelable()) { ev.setCanceled(event.isCanceled()); } @@ -1071,4 +1394,31 @@ public class EventHooks { } postAnimationEvent(new AnimationEvent.FrameEvent.Exited(animation, frame)); } + + // ==================== AUCTION EVENTS ==================== + + public static boolean onAuctionCreate(PlayerDataScript handler, AuctionEvent.CreateEvent event) { + handler.callScript(EnumScriptType.AUCTION_CREATE, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onAuctionBid(PlayerDataScript handler, AuctionEvent.BidEvent event) { + handler.callScript(EnumScriptType.AUCTION_BID, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onAuctionBuyout(PlayerDataScript handler, AuctionEvent.BuyoutEvent event) { + handler.callScript(EnumScriptType.AUCTION_BUYOUT, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onAuctionCancel(PlayerDataScript handler, AuctionEvent.CancelEvent event) { + handler.callScript(EnumScriptType.AUCTION_CANCEL, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onAuctionClaim(PlayerDataScript handler, AuctionEvent.ClaimEvent event) { + handler.callScript(EnumScriptType.AUCTION_CLAIM, event); + return NpcAPI.EVENT_BUS.post(event); + } } diff --git a/src/main/java/noppes/npcs/NPCSpawning.java b/src/main/java/noppes/npcs/NPCSpawning.java index ef143024c..ed633c8f7 100644 --- a/src/main/java/noppes/npcs/NPCSpawning.java +++ b/src/main/java/noppes/npcs/NPCSpawning.java @@ -28,28 +28,45 @@ import noppes.npcs.scripted.event.CustomNPCsEvent; import java.util.ArrayList; import java.util.Collections; -import java.util.Iterator; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Random; import java.util.Set; public class NPCSpawning { private static Set eligibleChunksForSpawning = Sets.newHashSet(); + private static final byte CHUNK_SPAWN_RADIUS = 7; + private static final int SPAWN_ATTEMPTS_PER_CHUNK = 3; + private static final int NATURAL_CAP_PER_256_CHUNKS = 70; + private static final long RUNTIME_SPAWN_TICK_INTERVAL = 20L; + private static final int RUNTIME_SPAWN_CYCLE_TICKS = 400; + private static final String NATURAL_SPAWN_ID_TAG = "CNPCNaturalSpawnId"; + private static final String NATURAL_SPAWN_NAME_TAG = "CNPCNaturalSpawnName"; + private static final String NATURAL_SPAWN_TIME_TAG = "CNPCNaturalSpawnTime"; + private static final Map SPAWN_COOLDOWNS = new HashMap(); + private static final Map RUNTIME_CHUNK_STATES = new HashMap(); private static boolean animalSpawn; private static boolean monsterSpawn; private static boolean airSpawn; private static boolean liquidSpawn; + private static class RuntimeChunkState { + public ArrayList chunks = new ArrayList(); + public int index = 0; + public int signature = 0; + } + public static void findChunksForSpawning(WorldServer world) { - if (SpawnController.Instance.data.isEmpty() || world.getWorldInfo().getWorldTotalTime() % 400L != 0L) + if (SpawnController.Instance.data.isEmpty() || world.getWorldInfo().getWorldTotalTime() % RUNTIME_SPAWN_TICK_INTERVAL != 0L) return; eligibleChunksForSpawning.clear(); for (int i = 0; i < world.playerEntities.size(); ++i) { EntityPlayer entityplayer = (EntityPlayer) world.playerEntities.get(i); int j = MathHelper.floor_double(entityplayer.posX / 16.0D); int k = MathHelper.floor_double(entityplayer.posZ / 16.0D); - byte size = 7; + byte size = CHUNK_SPAWN_RADIUS; for (int x = -size; x <= size; ++x) { for (int z = -size; z <= size; ++z) { @@ -60,22 +77,29 @@ public class NPCSpawning { } } } - if (countNPCs(world) > eligibleChunksForSpawning.size()) { + int cap = getScaledNaturalCap(eligibleChunksForSpawning.size()); + int npcCount = countNaturalSpawnedNPCs(world); + if (npcCount >= cap) { return; } - ArrayList tmp = new ArrayList(eligibleChunksForSpawning); - Collections.shuffle(tmp); - Iterator iterator = tmp.iterator(); + HashMap spawnEntryCounts = getNaturalSpawnEntryCounts(world); + int chunkBudget = getRuntimeChunkBudget(eligibleChunksForSpawning.size()); + List chunksToProcess = getRuntimeChunkBatch(world, chunkBudget); - while (iterator.hasNext()) { - ChunkCoordIntPair chunkcoordintpair1 = iterator.next(); + for (ChunkCoordIntPair chunkcoordintpair1 : chunksToProcess) { + if (npcCount >= cap) { + return; + } ChunkPosition chunkposition = getChunk(world, chunkcoordintpair1.chunkXPos, chunkcoordintpair1.chunkZPos); int j1 = chunkposition.chunkPosX; int y = chunkposition.chunkPosY; int l1 = chunkposition.chunkPosZ; - for (int i = 0; i < 3; i++) { + for (int i = 0; i < SPAWN_ATTEMPTS_PER_CHUNK; i++) { + if (npcCount >= cap) { + return; + } int x = j1; int z = l1; byte b1 = 6; @@ -85,25 +109,71 @@ public class NPCSpawning { String name = world.getBiomeGenForCoords(x, z).biomeName; SpawnData data = SpawnController.Instance.getRandomSpawnData(name, world.provider.dimensionId); - if (data == null || !canCreatureTypeSpawnAtLocation(data, world, x, y, z) || world.getClosestPlayer(x, y, z, 24.0D) != null) + if (data == null) continue; - spawnData(data, world, x, y, z); + if (trySpawnWithEntryConfig(data, world, x, y, z, world.rand, spawnEntryCounts)) { + npcCount++; + } } } } - public static int countNPCs(World world) { + private static int getRuntimeChunkBudget(int eligibleChunkCount) { + if (eligibleChunkCount <= 0) { + return 0; + } + int runsPerCycle = Math.max(1, (int) (RUNTIME_SPAWN_CYCLE_TICKS / RUNTIME_SPAWN_TICK_INTERVAL)); + return Math.max(1, (int) Math.ceil((double) eligibleChunkCount / runsPerCycle)); + } + + private static List getRuntimeChunkBatch(World world, int chunkBudget) { + ArrayList result = new ArrayList(); + if (chunkBudget <= 0 || eligibleChunksForSpawning.isEmpty()) { + return result; + } + + int dimensionId = world.provider.dimensionId; + RuntimeChunkState state = RUNTIME_CHUNK_STATES.get(dimensionId); + if (state == null) { + state = new RuntimeChunkState(); + RUNTIME_CHUNK_STATES.put(dimensionId, state); + } + + int signature = eligibleChunksForSpawning.hashCode(); + if (state.chunks.isEmpty() || state.signature != signature || state.index >= state.chunks.size()) { + state.chunks = new ArrayList(eligibleChunksForSpawning); + Collections.shuffle(state.chunks); + state.index = 0; + state.signature = signature; + } + + int remaining = state.chunks.size() - state.index; + int count = Math.min(chunkBudget, Math.max(0, remaining)); + for (int i = 0; i < count; i++) { + result.add(state.chunks.get(state.index++)); + } + return result; + } + + private static int countNaturalSpawnedNPCs(World world) { int count = 0; List list = world.loadedEntityList; for (Entity entity : list) { - if (entity instanceof EntityNPCInterface) { + if (entity instanceof EntityNPCInterface && !entity.isDead && entity.getEntityData().hasKey(NATURAL_SPAWN_ID_TAG)) { count++; } } return count; } + private static int getScaledNaturalCap(int eligibleChunkCount) { + if (eligibleChunkCount <= 0) { + return 0; + } + return Math.max(1, NATURAL_CAP_PER_256_CHUNKS * eligibleChunkCount / 256); + } + protected static ChunkPosition getChunk(World world, int x, int z) { Chunk chunk = world.getChunkFromChunkCoords(x, z); int k = x * 16 + world.rand.nextInt(16); @@ -112,9 +182,134 @@ public class NPCSpawning { return new ChunkPosition(k, i1, l); } + private static int getCap(World world) { + Set chunkSet = Sets.newHashSet(); + for (int i = 0; i < world.playerEntities.size(); ++i) { + EntityPlayer entityplayer = (EntityPlayer) world.playerEntities.get(i); + int j = MathHelper.floor_double(entityplayer.posX / 16.0D); + int k = MathHelper.floor_double(entityplayer.posZ / 16.0D); + byte size = CHUNK_SPAWN_RADIUS; + + for (int x = -size; x <= size; ++x) { + for (int z = -size; z <= size; ++z) { + chunkSet.add(new ChunkCoordIntPair(x + j, z + k)); + } + } + } + return getScaledNaturalCap(chunkSet.size()); + } + + private static HashMap getNaturalSpawnEntryCounts(World world) { + HashMap counts = new HashMap(); + List list = world.loadedEntityList; + for (Entity entity : list) { + if (entity == null || entity.isDead || !(entity instanceof EntityNPCInterface)) { + continue; + } + NBTTagCompound entityData = entity.getEntityData(); + if (!entityData.hasKey(NATURAL_SPAWN_ID_TAG)) { + continue; + } + int spawnId = entityData.getInteger(NATURAL_SPAWN_ID_TAG); + Integer count = counts.get(spawnId); + counts.put(spawnId, count == null ? 1 : count + 1); + } + return counts; + } + + private static long getSpawnCooldownKey(World world, int spawnId) { + return ((long) world.provider.dimensionId << 32) ^ (spawnId & 0xffffffffL); + } + + private static boolean isSpawnOnCooldown(World world, SpawnData data) { + if (data.cooldownTicks <= 0 || data.id < 0) { + return false; + } + long key = getSpawnCooldownKey(world, data.id); + Long lastSpawnTick = SPAWN_COOLDOWNS.get(key); + if (lastSpawnTick == null) { + return false; + } + long tickDelta = world.getWorldInfo().getWorldTotalTime() - lastSpawnTick; + if (tickDelta < 0) { + SPAWN_COOLDOWNS.remove(key); + return false; + } + return tickDelta < data.cooldownTicks; + } + + private static void markSpawnCooldown(World world, SpawnData data) { + if (data.cooldownTicks <= 0 || data.id < 0) { + return; + } + long key = getSpawnCooldownKey(world, data.id); + SPAWN_COOLDOWNS.put(key, world.getWorldInfo().getWorldTotalTime()); + } + + private static boolean isSpawnEntryAtCapacity(SpawnData data, Map spawnEntryCounts) { + if (data.maxAlive <= 0 || data.id < 0) { + return false; + } + Integer currentCount = spawnEntryCounts.get(data.id); + return currentCount != null && currentCount >= data.maxAlive; + } + + private static void incrementSpawnEntryCount(SpawnData data, Map spawnEntryCounts) { + if (data.id < 0) { + return; + } + Integer currentCount = spawnEntryCounts.get(data.id); + spawnEntryCounts.put(data.id, currentCount == null ? 1 : currentCount + 1); + } + + private static boolean hasNearbyPlayer(SpawnData data, World world, int x, int y, int z) { + if (data.playerMinDistance <= 0) { + return false; + } + return world.getClosestPlayer(x, y, z, data.playerMinDistance) != null; + } + + private static boolean trySpawnWithEntryConfig(SpawnData data, World world, int x, int y, int z, Random rand, Map spawnEntryCounts) { + if (y < data.spawnHeightMin || y > data.spawnHeightMax) { + return false; + } + if (isSpawnEntryAtCapacity(data, spawnEntryCounts) || isSpawnOnCooldown(world, data)) { + return false; + } + + int attempts = Math.max(1, data.attemptsPerCycle); + for (int attempt = 0; attempt < attempts; attempt++) { + int attemptX = x; + int attemptZ = z; + if (attempt > 0) { + attemptX += rand.nextInt(5) - rand.nextInt(5); + attemptZ += rand.nextInt(5) - rand.nextInt(5); + } + + if (!canCreatureTypeSpawnAtLocation(data, world, attemptX, y, attemptZ) || hasNearbyPlayer(data, world, attemptX, y, attemptZ)) { + continue; + } + if (spawnData(data, world, attemptX, y, attemptZ)) { + incrementSpawnEntryCount(data, spawnEntryCounts); + markSpawnCooldown(world, data); + return true; + } + } + return false; + } + public static void performWorldGenSpawning(World world, int x, int z, Random rand) { + int cap = getCap(world); + int npcCount = countNaturalSpawnedNPCs(world); + if (npcCount >= cap) { + return; + } + HashMap spawnEntryCounts = getNaturalSpawnEntryCounts(world); BiomeGenBase biome = world.getBiomeGenForCoords(x + 8, z + 8); while (rand.nextFloat() < biome.getSpawningChance()) { + if (npcCount >= cap) { + return; + } SpawnData data = SpawnController.Instance.getRandomSpawnData(biome.biomeName, world.provider.dimensionId); if (data == null) continue; @@ -127,6 +322,9 @@ public class NPCSpawning { int i2 = k1; for (int k2 = 0; k2 < 4; ++k2) { + if (npcCount >= cap) { + return; + } int l2 = world.getTopSolidOrLiquidBlock(j1, k1); if (l2 > data.spawnHeightMax || l2 < data.spawnHeightMin) { continue; @@ -134,14 +332,16 @@ public class NPCSpawning { l2 = l2 + (int) ((data.spawnHeightMax - l2) * Math.random()); } - if (!canCreatureTypeSpawnAtLocation(data, world, j1, l2, k1)) { + if (!trySpawnWithEntryConfig(data, world, j1, l2, k1, rand, spawnEntryCounts)) { j1 += rand.nextInt(5) - rand.nextInt(5); for (k1 += rand.nextInt(5) - rand.nextInt(5); j1 < x || j1 >= x + size || k1 < z || k1 >= z + size; k1 = i2 + rand.nextInt(5) - rand.nextInt(5)) { j1 = l1 + rand.nextInt(5) - rand.nextInt(5); } - } else if (spawnData(data, world, j1, l2, k1)) + } else { + npcCount++; break; + } } } @@ -184,12 +384,23 @@ public class NPCSpawning { if (spawnEntity instanceof EntityCustomNpc) { EntityCustomNpc npc = (EntityCustomNpc) spawnEntity; npc.stats.spawnCycle = 3; + if (data.despawnMode == SpawnData.DESPAWN_FORCE_PERSISTENT) { + npc.stats.canDespawn = false; + npc.stats.playerSetCanDespawn = false; + } else if (data.despawnMode == SpawnData.DESPAWN_FORCE_NATURAL) { + npc.stats.canDespawn = true; + npc.stats.playerSetCanDespawn = true; + } + npc.syncDespawnPersistence(); npc.ais.returnToStart = false; npc.ais.startPos = new int[]{x, y, z}; npc.updateAI = true; npc.updateClient = true; npc.getNavigator().clearPathEntity(); } + entityliving.getEntityData().setInteger(NATURAL_SPAWN_ID_TAG, data.id); + entityliving.getEntityData().setString(NATURAL_SPAWN_NAME_TAG, data.name); + entityliving.getEntityData().setLong(NATURAL_SPAWN_TIME_TAG, world.getWorldInfo().getWorldTotalTime()); spawnEntity.setLocationAndAngles(x + 0.5, y, z + 0.5, world.rand.nextFloat() * 360.0F, 0.0F); } catch (Exception exception) { exception.printStackTrace(); @@ -239,4 +450,3 @@ public class NPCSpawning { return animalSpawn || monsterSpawn || caveSpawn || liquidSpawn; } } - diff --git a/src/main/java/noppes/npcs/NoppesUtilServer.java b/src/main/java/noppes/npcs/NoppesUtilServer.java index b076d9484..28903a25f 100644 --- a/src/main/java/noppes/npcs/NoppesUtilServer.java +++ b/src/main/java/noppes/npcs/NoppesUtilServer.java @@ -1,9 +1,9 @@ package noppes.npcs; import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; 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; import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket; @@ -613,7 +613,7 @@ public class NoppesUtilServer { playerdata.save(); } if (pl != null) { - SyncController.syncPlayer((EntityPlayerMP) pl); + SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl); } sendPlayerData(type, player, name); } @@ -754,29 +754,51 @@ public class NoppesUtilServer { if (controller != null) { int index = 0; for (String typeId : controller.getTypes()) { + if (!controller.isAllowedByNPC(typeId) && !controller.isAllowedByBoth(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) { + for (String name : controller.getAbilityNames()) { + Ability ability = controller.getAbility(name); + if (ability != null) { + map.put(ability.getName(), ability.getAllowedBy().ordinal()); + } + } + } + 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; + AbilityController controller = 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++); + for (String name : controller.getCustomAbilityNames()) { + Ability ability = controller.getCustomAbility(name); + if (ability == null) continue; + map.put(name, ability.getAllowedBy().ordinal()); } } sendScrollData(player, map, EnumScrollData.CUSTOM_ABILITIES); } + public static void sendChainedAbilitiesData(EntityPlayerMP player) { + HashMap map = new HashMap(); + int index = 0; + for (String name : AbilityController.Instance.getChainedAbilityNamesSet()) { + map.put(name, index++); + } + sendScrollData(player, map, EnumScrollData.CHAINED_ABILITIES); + } + public static DialogOption setNpcDialog(int slot, int dialogId, EntityPlayer player) throws IOException { return setNpcDialog(slot, dialogId, getEditingNpc(player)); } @@ -1180,7 +1202,7 @@ public class NoppesUtilServer { playerdata.save(); if (pl != null) { - SyncController.syncPlayer((EntityPlayerMP) pl); + SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl); } } @@ -1212,7 +1234,7 @@ public class NoppesUtilServer { playerdata.save(); if (pl != null) { - SyncController.syncPlayer((EntityPlayerMP) pl); + SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl); } } } diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 0541f64c4..3e7fa07d9 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -6,10 +6,22 @@ import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.addon.DBCAddon; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.AttributeController; -import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.attribute.tracker.PlayerAttributeTracker; +import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper; +import kamkeel.npcs.controllers.sync.handlers.PlayerDataSyncHandler; +import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.type.AbilityCounter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; +import kamkeel.npcs.controllers.data.ability.type.AbilityDodge; +import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; import kamkeel.npcs.util.AttributeAttackUtil; import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.ContainerPlayer; @@ -100,13 +112,38 @@ 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() + || current.getPhase() != AbilityPhase.ACTIVE) { + boolean sFlying = playerData.abilityData.wasFlyingAtLock() + || AbilityController.Instance.isPlayerFlying(player); + + player.motionX = 0; + if (!sFlying) { + player.motionY = Math.min(player.motionY, 0); + } else { + player.motionY = 0; + } + player.motionZ = 0; + player.velocityChanged = true; + } + } + + // Zero WASD input during ability-controlled movement to prevent + // moveEntityWithHeading from interfering with ability velocity + { + Ability current = playerData.abilityData.getCurrentAbility(); + if (current != null && current.hasAbilityMovement() + && current.getPhase() == AbilityPhase.ACTIVE) { + player.moveForward = 0; + player.moveStrafing = 0; + } } if (playerData.updateClient) { - SyncController.syncPlayerData((EntityPlayerMP) player, true); + PlayerDataSyncHandler.syncPlayerData((EntityPlayerMP) player, true); playerData.updateClient = false; } @@ -114,8 +151,13 @@ public class ScriptPlayerEventHandler { playerData.timers.update(); } - if (player.ticksExisted % 10 == 0) - SyncController.syncEffects((EntityPlayerMP) player); + if (player.ticksExisted % 10 == 0) { + EntityPlayerMP mp = (EntityPlayerMP) player; + PlayerEffectSyncHelper.syncEffects(mp); + PlayerAbilitySyncHelper.syncAbilityCooldowns(mp); + PlayerAbilitySyncPacket.sendToPlayer(mp); + playerData.abilityData.ensureLockStateClear(); + } if (player.ticksExisted % 10 == 0) CustomEffectController.Instance.runEffects(player); @@ -322,6 +364,12 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { + // Fully reset ability state on dimension change (no cooldown rollover) + PlayerData playerData = PlayerData.get(event.player); + if (playerData != null) { + playerData.abilityData.resetOnDimensionChange(); + } + 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 +520,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 +581,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(); } @@ -547,6 +604,7 @@ public class ScriptPlayerEventHandler { if (event.entityLiving.worldObj instanceof WorldServer) { boolean cancel = event.isCanceled(); Entity source = NoppesUtilServer.GetDamageSource(event.source); + if (event.entityLiving instanceof EntityPlayerMP) { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); noppes.npcs.scripted.event.player.PlayerEvent.AttackedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.AttackedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source); @@ -568,12 +626,41 @@ public class ScriptPlayerEventHandler { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.source.getEntity()); float attackAmount = event.ammount; - if (ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable()) - attackAmount = AttributeAttackUtil.calculateOutgoing((EntityPlayer) event.source.getEntity(), attackAmount); + AttributeAttackUtil.lastAttackCritted = null; + if (ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable()) { + EntityPlayer attackPlayer = (EntityPlayer) event.source.getEntity(); + attackAmount = AttributeAttackUtil.calculateOutgoing(attackPlayer, attackAmount); + // For vanilla/modded mob targets, roll crit once and store for LivingHurtEvent + if (!(event.entityLiving instanceof EntityPlayerMP) && !(event.entityLiving instanceof EntityNPCInterface)) { + PlayerAttributeTracker tracker = AttributeController.getTracker(attackPlayer); + if (AttributeAttackUtil.rollCrit(tracker)) { + AttributeAttackUtil.lastAttackCritted = true; + attackAmount = AttributeAttackUtil.applyCritDamage(attackAmount, tracker); + } else { + AttributeAttackUtil.lastAttackCritted = false; + } + } + } noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent pevent1 = new noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.source.getEntity()), event.entityLiving, attackAmount, event.source); cancel = cancel || EventHooks.onPlayerAttack(handler, pevent1); } + + // Dodge & Counter: cancel attack entirely + if (!cancel && event.entityLiving instanceof EntityPlayerMP) { + PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving); + if (pData != null && pData.abilityData != null) { + AbilityDefend defend = pData.abilityData.getActiveDefend(); + if (defend instanceof AbilityDodge || defend instanceof AbilityCounter) { + EntityLivingBase attacker = source instanceof EntityLivingBase ? (EntityLivingBase) source : null; + float result = defend.onDefend(attacker, event.source, event.ammount); + if (result != event.ammount) { + cancel = true; + } + } + } + } + event.setCanceled(cancel); } } @@ -592,13 +679,41 @@ public class ScriptPlayerEventHandler { event.ammount = AttributeAttackUtil.calculateDamagePlayerToPlayer((EntityPlayer) source, (EntityPlayer) event.entityLiving, event.ammount); } else if (!(event.entityLiving instanceof EntityNPCInterface) && source instanceof EntityPlayer) { event.ammount = AttributeAttackUtil.calculateOutgoing((EntityPlayer) source, event.ammount); + if (AttributeAttackUtil.lastAttackCritted != null) { + // Use the crit decision from LivingAttackEvent + if (AttributeAttackUtil.lastAttackCritted) + event.ammount = AttributeAttackUtil.applyCritDamage(event.ammount, AttributeController.getTracker((EntityPlayer) source)); + AttributeAttackUtil.lastAttackCritted = null; + } else { + // Fallback: roll independently (no preceding LivingAttackEvent) + event.ammount = AttributeAttackUtil.applyCrit(event.ammount, AttributeController.getTracker((EntityPlayer) source)); + } } } if (event.entityLiving instanceof EntityPlayerMP) { + // Handle ability damage interactions + PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving); + if (pData != null && pData.abilityData != null && pData.abilityData.isExecutingAbility()) { + if (pData.abilityData.isCurrentAbilityInvulnerable()) { + event.ammount = 0; + cancel = true; + } else { + // Guard: reduce damage + AbilityDefend defend = pData.abilityData.getActiveDefend(); + if (defend instanceof AbilityGuard) { + EntityLivingBase attacker = source instanceof EntityLivingBase ? (EntityLivingBase) source : null; + event.ammount = defend.onDefend(attacker, event.source, event.ammount); + } + + float modified = pData.abilityData.onDamage(event.source, event.ammount); + event.ammount = modified; + } + } + 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); + cancel = cancel || EventHooks.onPlayerDamaged(handler, pevent); event.ammount = pevent.damage; } @@ -619,6 +734,14 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { + // Reset ability state for reconstructed entity and re-sync to client. + // The death handler already interrupted the ability (with events/cooldowns), + // so this just cleans up transient state and syncs the new entity. + PlayerData playerData = PlayerData.get(event.player); + if (playerData != null) { + playerData.abilityData.resetOnRespawn(); + } + 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/ServerEventsHandler.java b/src/main/java/noppes/npcs/ServerEventsHandler.java index bf1c75c73..b8e2825ca 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -4,10 +4,15 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.sync.handlers.CarpentryRecipeSyncHandler; +import kamkeel.npcs.controllers.sync.handlers.WorkbenchRecipeSyncHandler; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; import kamkeel.npcs.network.enums.EnumSyncAction; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import kamkeel.npcs.network.packets.data.ClonerPacket; import kamkeel.npcs.network.packets.data.MarkDataPacket; import kamkeel.npcs.network.packets.data.SoundManagementPacket; @@ -151,6 +156,52 @@ public class ServerEventsHandler { } } + @SubscribeEvent + public void barrierAbsorbDamage(LivingAttackEvent event) { + if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote) + return; + + EntityEnergyBarrier barrier = EntityEnergyBarrier.getAbsorbingBarrier(event.entityLiving); + if (barrier != null) { + // Redirect the caster's damage to their barrier + barrier.absorbDamage(event.ammount); + event.setCanceled(true); + } + } + + @SubscribeEvent + public void domeItemBlacklist(PlayerInteractEvent event) { + if (event.action == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) return; + EntityPlayer player = event.entityPlayer; + if (player == null || player.worldObj == null || player.worldObj.isRemote) return; + + ItemStack held = player.getHeldItem(); + if (held == null) return; + + String itemId = net.minecraft.item.Item.itemRegistry.getNameForObject(held.getItem()); + if (itemId == null) return; + + String[] blacklist = noppes.npcs.config.ConfigEnergy.DomeItemBlacklist; + if (blacklist == null) return; + + boolean blacklisted = false; + for (String banned : blacklist) { + if (banned.equals(itemId)) { + blacklisted = true; + break; + } + } + if (!blacklisted) return; + + List barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier instanceof EntityEnergyDome && barrier.isEntityInside(player)) { + event.setCanceled(true); + return; + } + } + } + @SubscribeEvent public void partyDamagedEvent(LivingAttackEvent event) { if (!(event.source != null && event.source.getEntity() instanceof EntityPlayer) || !(event.entityLiving instanceof EntityPlayer) || FMLCommonHandler.instance().getEffectiveSide().isClient()) @@ -206,20 +257,22 @@ public class ServerEventsHandler { if (block == Blocks.crafting_table && event.action == Action.RIGHT_CLICK_BLOCK && !player.worldObj.isRemote) { PacketHandler.Instance.sendToPlayer(new SyncPacket( - EnumSyncType.WORKBENCH_RECIPES, + SyncType.WORKBENCH_RECIPES, EnumSyncAction.RELOAD, -1, - SyncController.getCurrentRevision(EnumSyncType.WORKBENCH_RECIPES), - SyncController.workbenchNBT() + null, + SyncController.getCurrentServerRevision(SyncType.WORKBENCH_RECIPES), + WorkbenchRecipeSyncHandler.getInstance().serializeAll() ), (EntityPlayerMP) player); } if (block == CustomItems.carpentyBench && event.action == Action.RIGHT_CLICK_BLOCK && !player.worldObj.isRemote) { PacketHandler.Instance.sendToPlayer(new SyncPacket( - EnumSyncType.CARPENTRY_RECIPES, + SyncType.CARPENTRY_RECIPES, EnumSyncAction.RELOAD, -1, - SyncController.getCurrentRevision(EnumSyncType.CARPENTRY_RECIPES), - SyncController.carpentryNBT() + null, + SyncController.getCurrentServerRevision(SyncType.CARPENTRY_RECIPES), + CarpentryRecipeSyncHandler.getInstance().serializeAll() ), (EntityPlayerMP) player); } if ((block == CustomItems.banner || block == CustomItems.wallBanner || block == CustomItems.sign) && event.action == Action.RIGHT_CLICK_BLOCK) { @@ -252,6 +305,7 @@ public class ServerEventsHandler { public void invoke(LivingDeathEvent event) { if (event.entityLiving.worldObj.isRemote) return; + EnergyChargeTracker.Instance.removeAllForCaster(event.entityLiving.getEntityId()); if (event.source.getEntity() != null) { if (event.source.getEntity() instanceof EntityPlayer) { doExcalibur((EntityPlayer) event.source.getEntity(), event.entityLiving); @@ -482,12 +536,24 @@ public class ServerEventsHandler { @SubscribeEvent public void populateChunk(PopulateChunkEvent.Post event) { - NPCSpawning.performWorldGenSpawning(event.world, event.chunkX, event.chunkZ, event.rand); + NPCSpawning.performWorldGenSpawning(event.world, event.chunkX << 4, event.chunkZ << 4, event.rand); } @SubscribeEvent public void playerTracking(PlayerEvent.StartTracking event) { - if (!(event.target instanceof EntityPlayerMP || event.target instanceof EntityNPCInterface) || event.target.worldObj.isRemote) + if (event.target.worldObj.isRemote) return; + + // Energy charge visuals: send active charges for newly tracked entity + if (event.target instanceof EntityLivingBase + && event.entityPlayer instanceof EntityPlayerMP) { + EnergyChargeTracker.Instance.sendToPlayer( + event.target.getEntityId(), + (EntityPlayerMP) event.entityPlayer, + (int) event.target.worldObj.getTotalWorldTime() + ); + } + + if (!(event.target instanceof EntityPlayerMP || event.target instanceof EntityNPCInterface)) return; AnimationData animationData = AnimationData.getData(event.target); diff --git a/src/main/java/noppes/npcs/ServerTickHandler.java b/src/main/java/noppes/npcs/ServerTickHandler.java index 2639c6ab5..52bebe1ef 100644 --- a/src/main/java/noppes/npcs/ServerTickHandler.java +++ b/src/main/java/noppes/npcs/ServerTickHandler.java @@ -6,9 +6,11 @@ import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.SyncController; -import noppes.npcs.controllers.AuctionController; +import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper; +import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.WorldServer; +import noppes.npcs.controllers.AuctionController; import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.controllers.data.action.ActionManager; @@ -45,11 +47,13 @@ public class ServerTickHandler { playerData.onLogin(); } - ProfileController.Instance.login(player); SyncController.beginLogin(player); - SyncController.syncEffects(player); + PlayerEffectSyncHelper.syncEffects(player); ScriptController.Instance.syncClientScripts(player); + // Sync clean ability state to the new client (after beginLogin initializes sync state) + PlayerAbilitySyncHelper.syncAbilities(player); + // Send auction notifications on login if (AuctionController.Instance != null) { AuctionController.Instance.onPlayerLogin(player); diff --git a/src/main/java/noppes/npcs/VersionCompatibility.java b/src/main/java/noppes/npcs/VersionCompatibility.java index 98dd6c20e..ee81b2012 100644 --- a/src/main/java/noppes/npcs/VersionCompatibility.java +++ b/src/main/java/noppes/npcs/VersionCompatibility.java @@ -4,6 +4,7 @@ import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagInt; import net.minecraft.nbt.NBTTagList; +import noppes.npcs.constants.EnumPotionType; import noppes.npcs.controllers.data.Line; import noppes.npcs.controllers.data.Lines; import noppes.npcs.entity.EntityNPCInterface; @@ -23,6 +24,16 @@ public class VersionCompatibility { boolean aimShot = compound.getBoolean("AimWhileShooting"); compound.setInteger("AimType", !aimShot ? 0 : 1); } + + // Fire projectiles used to ignite unconditionally. The ignite check now also requires + // pBurnItem, which reads false when the key is absent, so restore it for anything + // saved before the flag existed. Shipped alongside revision 23, so anything already + // at 23 was written by a build that had the flag. + if (compound.hasKey("pEffect") && !compound.hasKey("pBurnItem")) { + if (EnumPotionType.fromOrdinal(compound.getInteger("pEffect")) == EnumPotionType.Fire) { + compound.setBoolean("pBurnItem", true); + } + } } if (npc.npcVersion < 22) { if (compound.hasKey("CanLeap")) { diff --git a/src/main/java/noppes/npcs/ai/CombatHandler.java b/src/main/java/noppes/npcs/ai/CombatHandler.java index ff81e4821..6947a986e 100644 --- a/src/main/java/noppes/npcs/ai/CombatHandler.java +++ b/src/main/java/noppes/npcs/ai/CombatHandler.java @@ -1,7 +1,6 @@ package noppes.npcs.ai; import kamkeel.npcs.addon.DBCAddon; -import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -80,16 +79,6 @@ public class CombatHandler { aggressors.put(el, f + damageAmount); } - // Handle guard counter before interruption - -// if (npc.abilities.getCurrentAbility() instanceof AbilityGuard) { -// AbilityGuard guard = -// (AbilityGuard) npc.abilities.getCurrentAbility(); -// if (guard.isGuarding() && e instanceof EntityLivingBase) { -// guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount); -// } -// } - // Check for ability interruption npc.abilities.onDamage(source, damageAmount); } diff --git a/src/main/java/noppes/npcs/ai/EntityAITransform.java b/src/main/java/noppes/npcs/ai/EntityAITransform.java index 9f565bccc..b0c3fa30e 100644 --- a/src/main/java/noppes/npcs/ai/EntityAITransform.java +++ b/src/main/java/noppes/npcs/ai/EntityAITransform.java @@ -10,7 +10,10 @@ public class EntityAITransform extends EntityAIBase { public EntityAITransform(EntityNPCInterface npc) { this.npc = npc; - setMutexBits(AiMutex.PASSIVE); + // No mutex: this only polls the world time and flips the transform, it drives nothing. + // Claiming PASSIVE let any running movement or look task starve it, so the day/night + // swap only fired in the gaps where those yielded - such as while saying a line. + setMutexBits(0); } @Override diff --git a/src/main/java/noppes/npcs/blocks/BlockBorder.java b/src/main/java/noppes/npcs/blocks/BlockBorder.java index 3781b9c72..db7761b1c 100644 --- a/src/main/java/noppes/npcs/blocks/BlockBorder.java +++ b/src/main/java/noppes/npcs/blocks/BlockBorder.java @@ -67,10 +67,6 @@ public class BlockBorder extends BlockContainer { } tile.rotation = l; - - if (par5EntityLivingBase instanceof EntityPlayer && par1World.isRemote) { - CustomNpcs.proxy.openGui(x, y, z, EnumGuiType.Border, (EntityPlayer) par5EntityLivingBase); - } } private TileBorder getTile(World world, int x, int y, int z) { diff --git a/src/main/java/noppes/npcs/blocks/BlockNpcRedstone.java b/src/main/java/noppes/npcs/blocks/BlockNpcRedstone.java index e97096c72..6f89b442a 100644 --- a/src/main/java/noppes/npcs/blocks/BlockNpcRedstone.java +++ b/src/main/java/noppes/npcs/blocks/BlockNpcRedstone.java @@ -49,13 +49,6 @@ public class BlockNpcRedstone extends BlockContainer { par1World.notifyBlocksOfNeighborChange(par2, par3, par4 + 1, this); } - @Override - public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityliving, ItemStack item) { - if (entityliving instanceof EntityPlayer && world.isRemote) { - CustomNpcs.proxy.openGui(i, j, k, EnumGuiType.RedstoneBlock, (EntityPlayer) entityliving); - } - } - @Override public void onBlockDestroyedByPlayer(World par1World, int par2, int par3, int par4, int par5) { onBlockAdded(par1World, par2, par3, par4); diff --git a/src/main/java/noppes/npcs/blocks/BlockWaypoint.java b/src/main/java/noppes/npcs/blocks/BlockWaypoint.java index 7e2dd87d3..e91f43d25 100644 --- a/src/main/java/noppes/npcs/blocks/BlockWaypoint.java +++ b/src/main/java/noppes/npcs/blocks/BlockWaypoint.java @@ -12,10 +12,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import noppes.npcs.CustomItems; -import noppes.npcs.CustomNpcs; import noppes.npcs.CustomNpcsPermissions; import noppes.npcs.blocks.tiles.TileWaypoint; -import noppes.npcs.constants.EnumGuiType; public class BlockWaypoint extends BlockContainer { diff --git a/src/main/java/noppes/npcs/client/AuctionClientConfig.java b/src/main/java/noppes/npcs/client/AuctionClientConfig.java index 7d6854e4c..a94bab504 100644 --- a/src/main/java/noppes/npcs/client/AuctionClientConfig.java +++ b/src/main/java/noppes/npcs/client/AuctionClientConfig.java @@ -7,17 +7,17 @@ import net.minecraft.nbt.NBTTagCompound; /** * Client-side cache for auction configuration synced from server. * Prevents client from using local ConfigMarket which may differ from server settings. - * + *

* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in * AuctionConfigSync to avoid @SideOnly crashes on dedicated servers. */ @SideOnly(Side.CLIENT) public class AuctionClientConfig { // Cached values from server - private static long listingFee = 0; + private static volatile long listingFee = 0; private static String currencyName = "Coins"; private static int auctionDurationHours = 24; - private static double minBidIncrement = 0.05; + private static volatile double minBidIncrement = 0.05; private static int maxActiveListings = 8; private static int claimExpirationDays = 20; private static boolean auctionEnabled = false; @@ -38,7 +38,7 @@ public class AuctionClientConfig { claimExpirationDays = compound.getInteger("ClaimExpirationDays"); if (currencyName.isEmpty()) { - currencyName = "Gold"; + currencyName = "Coins"; } } @@ -56,11 +56,31 @@ public class AuctionClientConfig { } // Getters - public static boolean isAuctionEnabled() { return auctionEnabled; } - public static long getListingFee() { return listingFee; } - public static String getCurrencyName() { return currencyName; } - public static int getAuctionDurationHours() { return auctionDurationHours; } - public static double getMinBidIncrement() { return minBidIncrement; } - public static int getMaxActiveListings() { return maxActiveListings; } - public static int getClaimExpirationDays() { return claimExpirationDays; } + public static boolean isAuctionEnabled() { + return auctionEnabled; + } + + public static long getListingFee() { + return listingFee; + } + + public static String getCurrencyName() { + return currencyName; + } + + public static int getAuctionDurationHours() { + return auctionDurationHours; + } + + public static double getMinBidIncrement() { + return minBidIncrement; + } + + public static int getMaxActiveListings() { + return maxActiveListings; + } + + public static int getClaimExpirationDays() { + return claimExpirationDays; + } } 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..fb3d88c6e --- /dev/null +++ b/src/main/java/noppes/npcs/client/ClientAbilityState.java @@ -0,0 +1,65 @@ +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 boolean wasFlyingAtLock = false; + public static boolean activePhase = 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; + wasFlyingAtLock = (flags & PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK) != 0; + activePhase = (flags & PlayerAbilityStatePacket.FLAG_ACTIVE_PHASE) != 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; + wasFlyingAtLock = false; + activePhase = false; + lockedYaw = 0; + lockedPitch = 0; + } +} diff --git a/src/main/java/noppes/npcs/client/ClientCacheHandler.java b/src/main/java/noppes/npcs/client/ClientCacheHandler.java index 30b14be83..53dfb9959 100644 --- a/src/main/java/noppes/npcs/client/ClientCacheHandler.java +++ b/src/main/java/noppes/npcs/client/ClientCacheHandler.java @@ -1,6 +1,6 @@ package noppes.npcs.client; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.controllers.MusicController; @@ -18,8 +18,8 @@ import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.controllers.data.SkinOverlay; import noppes.npcs.util.CacheHashMap; -import java.util.EnumMap; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; @@ -32,14 +32,14 @@ public class ClientCacheHandler { private static String activeServerKey = ""; private static String lastServerKey = ""; - private static final Map> clientRevisionCache = new HashMap<>(); + private static final Map> clientRevisionCache = new HashMap<>(); public static Party party; public static boolean allowProfiles = true; public static boolean allowParties = true; - public static void setActiveServer(String serverKey, EnumMap serverRevisions) { + public static void setActiveServer(String serverKey, Map serverRevisions) { String normalizedKey = serverKey == null ? "" : serverKey; String previousKey = activeServerKey == null ? "" : activeServerKey; lastServerKey = previousKey; @@ -54,9 +54,9 @@ public class ClientCacheHandler { return; } - EnumMap cached = clientRevisionCache.computeIfAbsent( + Map cached = clientRevisionCache.computeIfAbsent( activeServerKey, - ignored -> new EnumMap<>(EnumSyncType.class) + ignored -> new LinkedHashMap<>() ); if (serverRevisions != null && !serverRevisions.isEmpty()) { cached.keySet().retainAll(serverRevisions.keySet()); @@ -67,19 +67,19 @@ public class ClientCacheHandler { return lastServerKey == null ? "" : lastServerKey; } - public static EnumMap getCachedRevisionsForServer(String serverKey) { + public static Map getCachedRevisionsForServer(String serverKey) { String key = serverKey == null ? "" : serverKey; if (key.isEmpty()) { - return new EnumMap<>(EnumSyncType.class); + return new LinkedHashMap<>(); } - EnumMap revisions = clientRevisionCache.get(key); + Map revisions = clientRevisionCache.get(key); if (revisions == null) { - return new EnumMap<>(EnumSyncType.class); + return new LinkedHashMap<>(); } - return new EnumMap<>(revisions); + return new LinkedHashMap<>(revisions); } - public static void updateClientRevision(EnumSyncType type, int revision) { + public static void updateClientRevision(SyncType type, int revision) { if (revision < 0) { return; } @@ -87,9 +87,9 @@ public class ClientCacheHandler { if (key.isEmpty()) { return; } - EnumMap revisions = clientRevisionCache.computeIfAbsent( + Map revisions = clientRevisionCache.computeIfAbsent( key, - ignored -> new EnumMap<>(EnumSyncType.class) + ignored -> new LinkedHashMap<>() ); revisions.put(type, revision); } @@ -124,15 +124,13 @@ public class ClientCacheHandler { ClientCacheHandler.customOverlays.clear(); ClientCacheHandler.skinOverlays.clear(); ClientCacheHandler.playerAnimations.clear(); + ProfileClientConfig.reset(); - // Clear Texture Caches GuiSoundSelection.cachedDomains.clear(); GuiTextureSelection.cachedTextures.clear(); - // Clear music/bard sounds MusicController.Instance.stopAllSounds(); - // Clear Quest Tracker HudComponent component = ClientHudManager.getInstance().getHudComponents().get(EnumHudComponent.QuestTracker); if (component != null) { component.loadData(new NBTTagCompound()); @@ -145,7 +143,6 @@ public class ClientCacheHandler { ClientCacheHandler.customOverlays.clear(); ClientCacheHandler.skinOverlays.clear(); - // Clear Texture Caches GuiSoundSelection.cachedDomains.clear(); GuiTextureSelection.cachedTextures.clear(); } diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index a7a0f2b39..bffda878d 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -20,12 +20,14 @@ import net.minecraftforge.client.event.RenderHandEvent; import net.minecraftforge.client.event.RenderLivingEvent; import net.minecraftforge.client.event.RenderPlayerEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; -import noppes.npcs.client.gui.player.AuctionTooltipHandler; import noppes.npcs.client.gui.customoverlay.OverlayCustom; import noppes.npcs.client.gui.hud.ClientHudManager; import noppes.npcs.client.gui.hud.CompassHudComponent; import noppes.npcs.client.gui.hud.EnumHudComponent; import noppes.npcs.client.gui.hud.QuestTrackingComponent; +import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent; +import noppes.npcs.client.gui.player.AuctionTooltipHandler; +import noppes.npcs.client.KeyPressHandler; import noppes.npcs.client.renderer.MarkRenderer; import noppes.npcs.client.renderer.RenderCNPCPlayer; import noppes.npcs.constants.EnumAnimationPart; @@ -84,9 +86,43 @@ public class ClientEventHandler { @SubscribeEvent public void onMouse(MouseEvent event) { - if (Minecraft.getMinecraft().currentScreen != null) + // Always track mouse button state for KeyPressHandler FIRST. + // Canceled MouseEvents skip FML's MouseInputEvent entirely + // (Minecraft.java: if postMouseEvent() continue), so this is the + // only reliable place to capture mouse button press/release. + if (event.button >= 0) { + KeyPressHandler.trackMouseButton(event.button, event.buttonstate); + } + + 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; + } + + // Ability Hotbar: Hold HUD key + scroll wheel to cycle + if (event.dwheel != 0 && KeyPressHandler.isHudKeyHeld()) { + AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance() + .getHudComponents().get(EnumHudComponent.AbilityHotbar); + if (comp != null && comp.hasAnyAbilities()) { + if (event.dwheel > 0) { + comp.onCyclePrev(); + } else { + comp.onCycleNext(); + } + event.setCanceled(true); + return; + } + } + ArrayList removeList = new ArrayList<>(); for (Map.Entry entry : disabledButtonTimes.entrySet()) { if (entry.getValue() > 0) { @@ -114,6 +150,7 @@ public class ClientEventHandler { if (ClientHudManager.getInstance().getHudComponents().isEmpty()) { ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestTracker, new QuestTrackingComponent(Minecraft.getMinecraft())); ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestCompass, new CompassHudComponent(Minecraft.getMinecraft())); + ClientHudManager.getInstance().registerHud(EnumHudComponent.AbilityHotbar, new AbilityHotbarComponent(Minecraft.getMinecraft())); } ClientHudManager.getInstance().renderAllHUDs(event.partialTicks); diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index 88b113e44..2c5edf9e2 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -6,8 +6,32 @@ import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ObfuscationReflectionHelper; import kamkeel.npcs.addon.client.DBCClient; +import kamkeel.npcs.client.command.CommandCNPCDebugger; +import kamkeel.npcs.client.renderer.RenderEnergyBeam; +import kamkeel.npcs.client.renderer.RenderEnergyDisc; +import kamkeel.npcs.client.renderer.RenderEnergyLaser; +import kamkeel.npcs.client.renderer.RenderEnergyOrb; +import kamkeel.npcs.client.renderer.RenderSweeper; +import kamkeel.npcs.client.renderer.RenderZone; +import kamkeel.npcs.client.renderer.RenderEnergyDome; +import kamkeel.npcs.client.renderer.RenderEnergyPanel; +import kamkeel.npcs.client.renderer.EnergyChargePreviewRenderer; +import kamkeel.npcs.client.renderer.RenderEnergyExplosion; +import kamkeel.npcs.client.renderer.RenderEnergySlicer; import kamkeel.npcs.client.renderer.TelegraphRenderer; +import kamkeel.npcs.client.renderer.lightning.LightningHandler; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityEnergySweeper; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityEnergyExplosion; +import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.model.ModelBiped; @@ -30,6 +54,7 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraftforge.client.ClientCommandHandler; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.FakePlayer; @@ -88,12 +113,13 @@ import noppes.npcs.client.gui.global.GuiNPCManageAnimations; import noppes.npcs.client.gui.global.GuiNPCManageBanks; import noppes.npcs.client.gui.global.GuiNPCManageDialogs; import noppes.npcs.client.gui.global.GuiNPCManageEffects; -import noppes.npcs.client.gui.global.GuiNpcManageAbilities; import noppes.npcs.client.gui.global.GuiNPCManageFactions; import noppes.npcs.client.gui.global.GuiNPCManageLinked; import noppes.npcs.client.gui.global.GuiNPCManageQuest; import noppes.npcs.client.gui.global.GuiNPCManageTags; import noppes.npcs.client.gui.global.GuiNPCManageTransporters; +import noppes.npcs.client.gui.global.GuiNpcManageAbilities; +import noppes.npcs.client.gui.global.GuiNpcManageAuction; import noppes.npcs.client.gui.global.GuiNpcManageMagic; import noppes.npcs.client.gui.global.GuiNpcManageRecipes; import noppes.npcs.client.gui.global.GuiNpcQuestReward; @@ -105,15 +131,15 @@ import noppes.npcs.client.gui.mainmenu.GuiNpcAI; import noppes.npcs.client.gui.mainmenu.GuiNpcAdvanced; import noppes.npcs.client.gui.mainmenu.GuiNpcDisplay; import noppes.npcs.client.gui.mainmenu.GuiNpcStats; +import noppes.npcs.client.gui.player.GuiAuctionBidding; +import noppes.npcs.client.gui.player.GuiAuctionListing; +import noppes.npcs.client.gui.player.GuiAuctionSell; +import noppes.npcs.client.gui.player.GuiAuctionTrades; import noppes.npcs.client.gui.player.GuiBigSign; import noppes.npcs.client.gui.player.GuiCrate; import noppes.npcs.client.gui.player.GuiMailbox; import noppes.npcs.client.gui.player.GuiMailmanWrite; import noppes.npcs.client.gui.player.GuiNPCBankChest; -import noppes.npcs.client.gui.player.GuiAuctionBidding; -import noppes.npcs.client.gui.player.GuiAuctionTrades; -import noppes.npcs.client.gui.player.GuiAuctionListing; -import noppes.npcs.client.gui.player.GuiAuctionSell; import noppes.npcs.client.gui.player.GuiNPCTrader; import noppes.npcs.client.gui.player.GuiNpcAnvil; import noppes.npcs.client.gui.player.GuiNpcCarpentryBench; @@ -133,6 +159,8 @@ import noppes.npcs.client.gui.roles.GuiNpcTransporter; import noppes.npcs.client.gui.script.GuiScriptGlobal; import noppes.npcs.client.gui.script.GuiScriptInterface; import noppes.npcs.client.gui.util.script.PackageFinder; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.type.ClassIndex; import noppes.npcs.client.model.ModelNPCGolem; import noppes.npcs.client.model.ModelNpcCrystal; import noppes.npcs.client.model.ModelNpcDragon; @@ -146,17 +174,6 @@ import noppes.npcs.client.renderer.RenderNpcCrystal; import noppes.npcs.client.renderer.RenderNpcDragon; import noppes.npcs.client.renderer.RenderNpcSlime; import noppes.npcs.client.renderer.RenderProjectile; -import kamkeel.npcs.client.renderer.RenderAbilityOrb; -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.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 noppes.npcs.client.renderer.blocks.BlockBannerRenderer; import noppes.npcs.client.renderer.blocks.BlockBarrelRenderer; import noppes.npcs.client.renderer.blocks.BlockBeamRenderer; @@ -192,18 +209,22 @@ import noppes.npcs.client.renderer.items.ItemShortLampRenderer; import noppes.npcs.client.renderer.items.ItemTallLampRenderer; import noppes.npcs.client.renderer.items.ItemToolRenderer; import noppes.npcs.client.renderer.items.ScriptedBlockItemRenderer; -import noppes.npcs.client.ScriptClientConfig; import noppes.npcs.config.ConfigClient; import noppes.npcs.config.ConfigItem; import noppes.npcs.config.ConfigMain; import noppes.npcs.config.StringCache; import noppes.npcs.constants.EnumGuiType; import noppes.npcs.containers.ContainerAnvilRepair; +import noppes.npcs.containers.ContainerAuctionBidding; +import noppes.npcs.containers.ContainerAuctionListing; +import noppes.npcs.containers.ContainerAuctionSell; +import noppes.npcs.containers.ContainerAuctionTrades; import noppes.npcs.containers.ContainerCarpentryBench; import noppes.npcs.containers.ContainerCrate; import noppes.npcs.containers.ContainerCustomGui; import noppes.npcs.containers.ContainerMail; import noppes.npcs.containers.ContainerManageBanks; +import noppes.npcs.containers.ContainerManageAuction; import noppes.npcs.containers.ContainerManageRecipes; import noppes.npcs.containers.ContainerNPCBankInterface; import noppes.npcs.containers.ContainerNPCCompanion; @@ -211,11 +232,6 @@ import noppes.npcs.containers.ContainerNPCFollower; import noppes.npcs.containers.ContainerNPCFollowerHire; import noppes.npcs.containers.ContainerNPCFollowerSetup; import noppes.npcs.containers.ContainerNPCInv; -import noppes.npcs.containers.ContainerAuction; -import noppes.npcs.containers.ContainerAuctionBidding; -import noppes.npcs.containers.ContainerAuctionTrades; -import noppes.npcs.containers.ContainerAuctionListing; -import noppes.npcs.containers.ContainerAuctionSell; import noppes.npcs.containers.ContainerNPCTrader; import noppes.npcs.containers.ContainerNPCTraderSetup; import noppes.npcs.containers.ContainerNpcItemGiver; @@ -251,6 +267,9 @@ import java.util.Random; public class ClientProxy extends CommonProxy { public static KeyBinding NPCButton; public static KeyBinding SpecialKey; + public static KeyBinding AbilityHudKey; + public static KeyBinding AbilityNextKey; + public static KeyBinding AbilityPrevKey; public static final Random RAND = new Random(); public static FontContainer Font; @@ -265,17 +284,23 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerEntityRenderingHandler(EntityNpcDragon.class, new RenderNpcDragon(new ModelNpcDragon(0.0F), 0.5F)); RenderingRegistry.registerEntityRenderingHandler(EntityNpcSlime.class, new RenderNpcSlime(new ModelNpcSlime(16), new ModelNpcSlime(0), 0.25F)); RenderingRegistry.registerEntityRenderingHandler(EntityProjectile.class, new RenderProjectile()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderAbilityOrb()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderAbilityDisc()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderEnergyOrb()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderEnergyDisc()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderEnergyLaser()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderEnergyBeam()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergySweeper.class, new RenderSweeper()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderZone()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergyExplosion.class, new RenderEnergyExplosion()); RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc()); RenderingRegistry.registerEntityRenderingHandler(EntityNPCGolem.class, new RenderNPCHumanMale( new ModelNPCGolem(0), new ModelNPCGolem(1F), new ModelNPCGolem(0.5F))); FMLCommonHandler.instance().bus().register(new ClientTickHandler()); + FMLCommonHandler.instance().bus().register(new KeyPressHandler()); ClientRegistry.bindTileEntitySpecialRenderer(TileBlockAnvil.class, new BlockCarpentryBenchRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(TileMailbox.class, new BlockMailboxRenderer()); @@ -321,11 +346,19 @@ public class ClientProxy extends CommonProxy { } NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc"); - SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_B, "key.categories.customnpc"); + SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_GRAVE, "key.categories.customnpc"); ClientRegistry.registerKeyBinding(NPCButton); ClientRegistry.registerKeyBinding(SpecialKey); + AbilityHudKey = new KeyBinding("key.customnpcs.abilityHudKey", Keyboard.KEY_LMENU, "key.categories.customnpc"); + ClientRegistry.registerKeyBinding(AbilityHudKey); + + AbilityNextKey = new KeyBinding("key.customnpcs.abilityNext", Keyboard.KEY_NONE, "key.categories.customnpc"); + AbilityPrevKey = new KeyBinding("key.customnpcs.abilityPrev", Keyboard.KEY_NONE, "key.categories.customnpc"); + ClientRegistry.registerKeyBinding(AbilityNextKey); + ClientRegistry.registerKeyBinding(AbilityPrevKey); + new PresetController(CustomNpcs.Dir); if (ConfigMain.EnableUpdateChecker) { @@ -337,20 +370,19 @@ public class ClientProxy extends CommonProxy { ClientTagMapController.Instance = new ClientTagMapController(); MinecraftForge.EVENT_BUS.register(new ClientEventHandler()); + // Debug commands + ClientCommandHandler.instance.registerCommand(new CommandCNPCDebugger()); + // Telegraph rendering system TelegraphManager.initClient(); MinecraftForge.EVENT_BUS.register(new TelegraphRenderer()); + // Energy charge preview rendering system + EnergyChargePreviewManager.initClient(); + MinecraftForge.EVENT_BUS.register(new EnergyChargePreviewRenderer()); + // Lightning effect rendering system MinecraftForge.EVENT_BUS.register(new LightningHandler()); - - if (ConfigClient.InventoryGuiEnabled) { - MinecraftForge.EVENT_BUS.register(new TabRegistry()); - if (TabRegistry.getTabList().isEmpty()) { - TabRegistry.registerTab(new InventoryTabVanilla()); - } - TabRegistry.registerTab(new InventoryTabCustomNpc()); - } } public FakePlayer getCommandPlayer(IWorld world) { @@ -390,7 +422,8 @@ public class ClientProxy extends CommonProxy { @Override public PlayerData getPlayerData(EntityPlayer player) { - if (player.getUniqueID() == Minecraft.getMinecraft().thePlayer.getUniqueID()) { + EntityPlayer local = Minecraft.getMinecraft().thePlayer; + if (local != null && player.getUniqueID().equals(local.getUniqueID())) { if (ClientCacheHandler.playerData != null) { if (ClientCacheHandler.playerData.player != player) { ClientCacheHandler.playerData.player = player; @@ -486,6 +519,9 @@ public class ClientProxy extends CommonProxy { else if (gui == EnumGuiType.ManageRecipes) return new GuiNpcManageRecipes(npc, (ContainerManageRecipes) container); + else if (gui == EnumGuiType.ManageAuction) + return new GuiNpcManageAuction(npc, (ContainerManageAuction) container); + else if (gui == EnumGuiType.ManageDialogs) return new GuiNPCManageDialogs(npc); @@ -512,9 +548,7 @@ public class ClientProxy extends CommonProxy { abilityNpc.width = 0.6f; } return new GuiNpcManageAbilities(abilityNpc, npc != null); - } - - else if (gui == EnumGuiType.MainMenuGlobal) + } else if (gui == EnumGuiType.MainMenuGlobal) return new GuiNPCGlobalMainMenu(npc); else if (gui == EnumGuiType.MainMenuAI) @@ -816,9 +850,24 @@ public class ClientProxy extends CommonProxy { return Minecraft.getMinecraft().currentScreen != null; } + @Override + public void loadComplete() { + // Deferred from load() so TConstruct has registered its own tabs first - registering + // ours before it left the vanilla tab duplicated. + if (ConfigClient.InventoryGuiEnabled) { + MinecraftForge.EVENT_BUS.register(new TabRegistry()); + if (TabRegistry.getTabList().isEmpty()) { + TabRegistry.registerTab(new InventoryTabVanilla()); + } + TabRegistry.registerTab(new InventoryTabCustomNpc()); + } + } + public void buildPackageIndex() { try { PackageFinder.init(Thread.currentThread().getContextClassLoader()); + ClassIndex.init(); + JSTypeRegistry.getInstance().initializeFromResources(); } catch (IOException e) { } } @@ -882,6 +931,28 @@ public class ClientProxy extends CommonProxy { return Minecraft.getMinecraft().fontRenderer.getStringWidth(text); } + /** + * Return the width of a string when rendered with the specified font style (bold/italic). + * + * @param text the string to measure + * @param fontStyle combination of {@link java.awt.Font#BOLD} and {@link java.awt.Font#ITALIC}, + * or {@link java.awt.Font#PLAIN} for normal style + * @return the width in pixels + */ + public int width(String text, int fontStyle) { + if (useCustomFont) + return textFont.getStringWidth(text, fontStyle); + if (fontStyle == java.awt.Font.PLAIN) + return Minecraft.getMinecraft().fontRenderer.getStringWidth(text); + StringBuilder sb = new StringBuilder(); + if ((fontStyle & java.awt.Font.BOLD) != 0) + sb.append('\u00A7').append('l'); + if ((fontStyle & java.awt.Font.ITALIC) != 0) + sb.append('\u00A7').append('o'); + sb.append(text); + return Minecraft.getMinecraft().fontRenderer.getStringWidth(sb.toString()); + } + public FontContainer copy() { FontContainer font = new FontContainer(); font.textFont = textFont; @@ -891,7 +962,7 @@ public class ClientProxy extends CommonProxy { public void drawString(String text, int x, int y, int color) { if (useCustomFont) { - textFont.renderString(text, x, y, color, true); + // textFont.renderString(text, x, y, color, true); textFont.renderString(text, x, y, color, false); } else { Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(text, x, y, color); diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index af5b6a7fc..51c6886cf 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -2,39 +2,34 @@ package noppes.npcs.client; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; +import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.client.renderer.lightning.LightningBolt; +import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.player.CheckPlayerValue; -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; import net.minecraft.world.World; -import noppes.npcs.CustomNpcs; import noppes.npcs.client.controllers.MusicController; import noppes.npcs.client.controllers.ScriptSoundController; import noppes.npcs.client.gui.hud.ClientHudManager; import noppes.npcs.client.gui.hud.CompassHudComponent; import noppes.npcs.client.gui.hud.EnumHudComponent; import noppes.npcs.client.gui.hud.HudComponent; -import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory; import noppes.npcs.client.renderer.RenderNPCInterface; import noppes.npcs.constants.EnumRoleType; import noppes.npcs.constants.MarkType; +import noppes.npcs.CustomNpcs; import noppes.npcs.controllers.data.MarkData; -import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.roles.RoleMount; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import tconstruct.client.tabs.InventoryTabCustomNpc; import java.util.ArrayList; @@ -45,10 +40,7 @@ public class ClientTickHandler { private int prevWidth = 0; private int prevHeight = 0; private boolean otherContainer = false; - private int buttonPressed = -1; - private long buttonTime = 0L; - private final int[] ignoreKeys = new int[]{157, 29, 54, 42, 184, 56, 220, 219}; - private boolean lastSpecialKeyDown = false; + private boolean wasMovementSuppressed = false; @SubscribeEvent(priority = EventPriority.LOWEST) public void onClientTick(TickEvent.ClientTickEvent event) { @@ -56,20 +48,49 @@ public class ClientTickHandler { if ((this.prevWorld == null || mc.theWorld == null) && this.prevWorld != mc.theWorld) { if (mc.theWorld == null) { ClientCacheHandler.clearCache(); + ClientAbilityState.reset(); + if (EnergyChargePreviewManager.ClientInstance != null) { + EnergyChargePreviewManager.ClientInstance.clear(); + } } 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()); - if (specialKeyDown != lastSpecialKeyDown) { - PlayerData data = CustomNpcs.proxy.getPlayerData(player); - if (data != null) { - data.setSpecialKeyDown(specialKeyDown); - } - SpecialKeyStatePacket.send(specialKeyDown); - lastSpecialKeyDown = specialKeyDown; + boolean shouldSuppress = ClientAbilityState.shouldSuppressMovementInput(); + boolean suppressInput = mc.currentScreen == null && shouldSuppress; + if (!suppressInput && wasMovementSuppressed) { + syncMovementKeyStates(mc); + } + wasMovementSuppressed = suppressInput; + + // Suppress player keyboard input during ability-controlled phases. + // Only suppress key binds when no GUI screen is open (screens already capture input). + if (suppressInput) { + // Unpress movement keybinds at the source BEFORE updatePlayerMoveState() reads them. + 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); + } + + // Zero movement input regardless of GUI state — the ability lock must + // hold the player in place even when chat or other screens are open. + if (shouldSuppress) { + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + mc.thePlayer.movementInput.sneak = false; + } + if (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) { @@ -84,9 +105,63 @@ 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. + // Motion zeroing runs regardless of GUI state so the player doesn't fall + // when opening chat or other screens during an ability lock. + if (ClientAbilityState.shouldSuppressMovementInput()) { + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + mc.thePlayer.movementInput.sneak = false; + + // Zero all motion — position lock holds the player in place (server is authoritative) + if (!ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionX = 0; + mc.thePlayer.motionZ = 0; + } + + // Zero vertical motion: grounded players can't jump, flying players are frozen in air + if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) + && !ClientAbilityState.hasAbilityMovement) { + if (ClientAbilityState.wasFlyingAtLock) { + mc.thePlayer.motionY = 0; + } else { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + } + } + } + + if (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(); + } } + + // Tick telegraph manager AFTER entity updates so telegraph positions + // match entity interpolation (Phase.END runs after world tick) + if (TelegraphManager.ClientInstance != null) { + TelegraphManager.ClientInstance.tick(mc.theWorld); + } + + // Tick packet-driven energy charge previews + if (EnergyChargePreviewManager.ClientInstance != null) { + EnergyChargePreviewManager.ClientInstance.tick(mc.theWorld); + } + + // Update lightning bolts for ability effects + LightningBolt.updateAll(); + return; } if (mc.thePlayer != null && mc.thePlayer.openContainer instanceof ContainerPlayer) { @@ -112,13 +187,6 @@ public class ClientTickHandler { MusicController.Instance.onUpdate(); ScriptSoundController.Instance.onUpdate(); - // Tick telegraph manager for ability warnings - if (TelegraphManager.ClientInstance != null) { - TelegraphManager.ClientInstance.tick(mc.theWorld); - } - - // Update lightning bolts for ability effects - LightningBolt.updateAll(); if (Minecraft.getMinecraft().thePlayer != null && (prevWidth != mc.displayWidth || prevHeight != mc.displayHeight)) { prevWidth = mc.displayWidth; prevHeight = mc.displayHeight; @@ -133,44 +201,52 @@ public class ClientTickHandler { } } - @SubscribeEvent - public void onMouse(InputEvent.MouseInputEvent event) { - if (Mouse.getEventButton() == -1 && Mouse.getEventDWheel() == 0) + /** + * Enforce ability lock motion constraints right before entity update. + * The Phase.END zeroing in onClientTick can be overwritten by other mods' + * ClientTickEvent Phase.START handlers (e.g. flight mods re-applying gravity). + * PlayerTickEvent fires after all ClientTickEvent handlers but before + * player.onUpdate(), making this the definitive point to enforce motion locks. + */ + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerTick(TickEvent.PlayerTickEvent event) { + if (event.phase != Phase.START || event.side != Side.CLIENT) return; - InputDevicePacket.sendMouse(Mouse.getEventButton(), Mouse.getEventDWheel(), Mouse.isButtonDown(Mouse.getEventButton())); - } + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer == null) + return; - @SubscribeEvent - public void onKey(InputEvent.KeyInputEvent event) { - if (ClientProxy.NPCButton.isPressed()) { - Minecraft mc = Minecraft.getMinecraft(); - if (mc.currentScreen == null) { - InventoryTabCustomNpc.tabHelper(); - } else if (mc.currentScreen instanceof GuiCNPCInventory) - mc.setIngameFocus(); + if (!ClientAbilityState.shouldSuppressMovementInput()) + return; + + if (!ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionX = 0; + mc.thePlayer.motionZ = 0; } - if (!Keyboard.isRepeatEvent()) { - int key = Keyboard.getEventKey(); - boolean keyDown = Keyboard.isKeyDown(key); - - InputDevicePacket.sendKeyboard(key, keyDown); - } - } - - private boolean isIgnoredKey(int key) { - int[] var2 = this.ignoreKeys; - int var3 = var2.length; - - for (int var4 = 0; var4 < var3; ++var4) { - int i = var2[var4]; - if (i == key) { - return true; + if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) + && !ClientAbilityState.hasAbilityMovement) { + if (ClientAbilityState.wasFlyingAtLock) { + mc.thePlayer.motionY = 0; + } else { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); } } + } - return false; + private void syncMovementKeyStates(Minecraft mc) { + syncKeyBindingState(mc.gameSettings.keyBindForward); + syncKeyBindingState(mc.gameSettings.keyBindBack); + syncKeyBindingState(mc.gameSettings.keyBindLeft); + syncKeyBindingState(mc.gameSettings.keyBindRight); + syncKeyBindingState(mc.gameSettings.keyBindJump); + syncKeyBindingState(mc.gameSettings.keyBindSneak); + syncKeyBindingState(mc.gameSettings.keyBindSprint); + } + + private void syncKeyBindingState(KeyBinding keyBinding) { + KeyBinding.setKeyBindState(keyBinding.getKeyCode(), KeyPressHandler.isKeyBindDown(keyBinding)); } private final int SCAN_RANGE = 128; diff --git a/src/main/java/noppes/npcs/client/CustomNpcResourceListener.java b/src/main/java/noppes/npcs/client/CustomNpcResourceListener.java index 2f2bc3115..ed186d9cd 100644 --- a/src/main/java/noppes/npcs/client/CustomNpcResourceListener.java +++ b/src/main/java/noppes/npcs/client/CustomNpcResourceListener.java @@ -9,12 +9,13 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import noppes.npcs.CustomNpcs; import noppes.npcs.LogWriter; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.token.ScriptColorScheme; import javax.imageio.ImageIO; import java.awt.Graphics; import java.awt.image.BufferedImage; -import java.io.File; -import java.io.InputStream; +import java.io.*; public class CustomNpcResourceListener implements IResourceManagerReloadListener { @@ -29,7 +30,15 @@ public class CustomNpcResourceListener implements SimpleReloadableResourceManager simplemanager = (SimpleReloadableResourceManager) var1; FolderResourcePack pack = new FolderResourcePack(CustomNpcs.Dir); + LogWriter.info("[ResourceListener] Adding FolderResourcePack (as fallback): " + CustomNpcs.Dir.getAbsolutePath()); simplemanager.reloadResourcePack(pack); + + ScriptColorScheme.reloadColorScheme(var1); + + // Reload scripting .d.ts files + JSTypeRegistry registry = JSTypeRegistry.getInstance(); + registry.clear(); + registry.initializeFromResources(); try { DefaultTextColor = Integer.parseInt(StatCollector.translateToLocal("customnpcs.defaultTextColor"), 16); diff --git a/src/main/java/noppes/npcs/client/ImageDownloadAlt.java b/src/main/java/noppes/npcs/client/ImageDownloadAlt.java index 7d986948f..f8d3b4857 100644 --- a/src/main/java/noppes/npcs/client/ImageDownloadAlt.java +++ b/src/main/java/noppes/npcs/client/ImageDownloadAlt.java @@ -8,6 +8,7 @@ import net.minecraft.client.renderer.texture.SimpleTexture; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; +import noppes.npcs.config.ConfigClient; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -101,18 +102,10 @@ public class ImageDownloadAlt extends SimpleTexture { HttpURLConnection connection = null; try { URL url = new URL(ImageDownloadAlt.this.imageUrl); - connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy()); - connection.setDoInput(true); - connection.setDoOutput(false); - connection.setRequestProperty("Content-Type", "image/png"); - connection.setRequestProperty("Expect", "100-continue"); - //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"); - connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - // Modify Accept Redirect - if (isImgurLink(url)) { - connection.setRequestProperty("Accept", "*/*"); - } + // Adding a config so people can switch back if needed. + // TODO: Remove config option if improved works better + connection = ConfigClient.ImprovedImageDownloadConnection ? setupConnectionImproved(url) : setupConnectionOld(url); connection.connect(); @@ -152,6 +145,44 @@ public class ImageDownloadAlt extends SimpleTexture { this.imageThread.start(); } + private HttpURLConnection setupConnectionOld(URL url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy()); + // setups stuff which basically tells the browser if this a get or post request + connection.setDoInput(true); + connection.setDoOutput(false); + + // ??? I believe these are used to tell the receiver what you are sending to them + // Not what you expect to receive from them. + connection.setRequestProperty("Content-Type", "image/png"); + connection.setRequestProperty("Expect", "100-continue"); + //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + + // Modify Accept Redirect + if (isImgurLink(url)) { + connection.setRequestProperty("Accept", "*/*"); + } + return connection; + } + + private HttpURLConnection setupConnectionImproved(URL url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy()); + + connection.setRequestMethod("GET"); + // Basically redundant because I set it as a GET request? + // Better safe than sorry ig. + connection.setDoInput(true); + connection.setDoOutput(false); + + // Random ass user agent I grabbed from my snooping on imgur + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0"); + // I tell the server what I want to receive. + // TODO: Should this just accept PNGs? + connection.setRequestProperty("Accept", "image/png,image/*"); + + return connection; + } + // Check if the URL is an Imgur link private static boolean isImgurLink(URL url) { diff --git a/src/main/java/noppes/npcs/client/KeyPressHandler.java b/src/main/java/noppes/npcs/client/KeyPressHandler.java new file mode 100644 index 000000000..61731c522 --- /dev/null +++ b/src/main/java/noppes/npcs/client/KeyPressHandler.java @@ -0,0 +1,223 @@ +package noppes.npcs.client; + +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.InputEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import kamkeel.npcs.network.packets.player.InputDevicePacket; +import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import noppes.npcs.CustomNpcs; +import noppes.npcs.client.gui.hud.ClientHudManager; +import noppes.npcs.client.gui.hud.EnumHudComponent; +import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent; +import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import tconstruct.client.tabs.InventoryTabCustomNpc; + +/** + * Centralized input handler for CustomNPC+ keybindings. + * Handles both keyboard and mouse input events so keybinds work + * regardless of whether they're bound to a key or mouse button. + *

+ * All keybind state queries (pressed, held, released) should go through + * this class to avoid crashes with mouse-bound keys. + *

+ * Mouse button states are tracked from MouseEvent (Forge bus) via + * {@link #trackMouseButton}, because canceled MouseEvents cause Minecraft + * to skip FML's MouseInputEvent entirely. This is the only reliable source. + */ +public class KeyPressHandler { + + // ── Mouse Button Tracking ──────────────────────────────────────────── + // Tracked from MouseEvent (Forge bus, via ClientEventHandler.onMouse) + // which fires BEFORE cancellation can skip MouseInputEvent. + private static final boolean[] mouseButtonsDown = new boolean[16]; + + // ── Tracked Held States ────────────────────────────────────────────── + private static boolean specialKeyHeld = false; + private static boolean hudKeyHeld = false; + + // ── Event Handlers ────────────────────────────────────────────────── + + @SubscribeEvent + public void onKeyPress(InputEvent.KeyInputEvent event) { + Minecraft mc = Minecraft.getMinecraft(); + + updateHeldStates(mc); + handleNPCButton(mc); + handleAbilityCycleKeys(mc); + + if (!Keyboard.isRepeatEvent()) { + int key = Keyboard.getEventKey(); + boolean keyDown = Keyboard.isKeyDown(key); + + // Block movement keys during ability lock (only when no GUI is open). + if (mc.theWorld != null && mc.currentScreen == null && keyDown + && ClientAbilityState.shouldSuppressMovementInput() && isMovementKey(key)) { + KeyBinding.setKeyBindState(key, false); + return; + } + + InputDevicePacket.sendKeyboard(key, keyDown); + } + } + + @SubscribeEvent + public void onMousePress(InputEvent.MouseInputEvent event) { + Minecraft mc = Minecraft.getMinecraft(); + + // Button state already tracked by trackMouseButton() from MouseEvent. + // Just update held states and handle keybind actions. + updateHeldStates(mc); + handleNPCButton(mc); + handleAbilityCycleKeys(mc); + + int button = Mouse.getEventButton(); + if (button == -1 && Mouse.getEventDWheel() == 0) + return; + + InputDevicePacket.sendMouse(button, Mouse.getEventDWheel(), + button >= 0 && Mouse.getEventButtonState()); + } + + /** + * Per-tick safety net: sync tracked mouse button states with hardware + * in case an event was missed (e.g. window focus loss). + */ + @SubscribeEvent + public void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.START) return; + + // Correct any stuck mouse buttons from missed release events + for (int i = 0; i < mouseButtonsDown.length; i++) { + if (mouseButtonsDown[i] && i < Mouse.getButtonCount() && !Mouse.isButtonDown(i)) { + mouseButtonsDown[i] = false; + } + } + + updateHeldStates(Minecraft.getMinecraft()); + } + + // ── Mouse Button Tracking (called from Forge MouseEvent) ───────────── + + /** + * Called from {@code ClientEventHandler.onMouse(MouseEvent)} at the very + * start, BEFORE any cancellation logic. This is the primary source of + * mouse button state because canceled MouseEvents cause Minecraft to + * skip {@code FMLCommonHandler.fireMouseInput()} entirely, so + * MouseInputEvent never fires for those events. + */ + public static void trackMouseButton(int button, boolean down) { + if (button >= 0 && button < mouseButtonsDown.length) { + mouseButtonsDown[button] = down; + } + updateHeldStates(Minecraft.getMinecraft()); + } + + // ── State Updates ──────────────────────────────────────────────────── + + /** + * Refresh all tracked held states. + * Called on every input event and every tick. + */ + private static void updateHeldStates(Minecraft mc) { + boolean noScreen = mc.currentScreen == null; + + // ── SpecialKey (edge-detected, sends packet on change) ── + boolean specialDown = noScreen && isKeyBindDown(ClientProxy.SpecialKey); + if (specialDown != specialKeyHeld) { + specialKeyHeld = specialDown; + if (mc.thePlayer != null) { + PlayerData data = CustomNpcs.proxy.getPlayerData(mc.thePlayer); + if (data != null) { + data.setSpecialKeyDown(specialDown); + } + SpecialKeyStatePacket.send(specialDown); + } + } + + // ── AbilityHudKey ── + hudKeyHeld = noScreen && isKeyBindDown(ClientProxy.AbilityHudKey); + } + + // ── Keybind Actions ───────────────────────────────────────────────── + + private static void handleNPCButton(Minecraft mc) { + if (ClientProxy.NPCButton == null) return; + if (ClientProxy.NPCButton.isPressed()) { + if (mc.currentScreen == null) { + InventoryTabCustomNpc.tabHelper(); + } else if (mc.currentScreen instanceof GuiCNPCInventory) { + mc.setIngameFocus(); + } + } + } + + private static void handleAbilityCycleKeys(Minecraft mc) { + if (mc.currentScreen != null || mc.theWorld == null) return; + + AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance() + .getHudComponents().get(EnumHudComponent.AbilityHotbar); + if (comp == null || !comp.hasAnyAbilities()) return; + + if (ClientProxy.AbilityNextKey != null && ClientProxy.AbilityNextKey.isPressed()) { + comp.onCycleNext(); + } + if (ClientProxy.AbilityPrevKey != null && ClientProxy.AbilityPrevKey.isPressed()) { + comp.onCyclePrev(); + } + } + + // ── Public State Queries ───────────────────────────────────────────── + + /** + * Whether the SpecialKey is currently held down. + */ + public static boolean isSpecialKeyHeld() { + return specialKeyHeld; + } + + /** + * Whether the AbilityHudKey is currently held down. + */ + public static boolean isHudKeyHeld() { + return hudKeyHeld; + } + + /** + * Check if a KeyBinding is currently held down. + * Works for both keyboard keys (positive codes) and mouse buttons (negative codes). + *

+ * Mouse buttons use event-tracked state (from MouseEvent via trackMouseButton) + * so the result is accurate even when called during keyboard event processing. + */ + public static boolean isKeyBindDown(KeyBinding keyBinding) { + if (keyBinding == null) return false; + int keyCode = keyBinding.getKeyCode(); + if (keyCode == 0) return false; + + if (keyCode < 0) { + int mouseButton = keyCode + 100; + return mouseButton >= 0 && mouseButton < mouseButtonsDown.length + && mouseButtonsDown[mouseButton]; + } + + return keyCode < Keyboard.getKeyCount() && Keyboard.isKeyDown(keyCode); + } + + // ── Internal Helpers ──────────────────────────────────────────────── + + private static 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(); + } +} diff --git a/src/main/java/noppes/npcs/client/ProfileClientConfig.java b/src/main/java/noppes/npcs/client/ProfileClientConfig.java new file mode 100644 index 000000000..8a23cc5ca --- /dev/null +++ b/src/main/java/noppes/npcs/client/ProfileClientConfig.java @@ -0,0 +1,64 @@ +package noppes.npcs.client; + +import kamkeel.npcs.controllers.ProfileController; +import kamkeel.npcs.controllers.data.profile.Profile; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.config.ConfigMain; + +import java.util.HashMap; +import java.util.Map; + +public class ProfileClientConfig { + private static volatile Map sharedQuestTimestamps = new HashMap<>(); + + public static void readFromNBT(NBTTagCompound compound) { + if (compound == null) return; + + Map timestamps = new HashMap<>(); + if (compound.hasKey("SharedQuestTimestamps")) { + NBTTagList list = compound.getTagList("SharedQuestTimestamps", 10); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound entry = list.getCompoundTagAt(i); + timestamps.put(entry.getInteger("Quest"), entry.getLong("Date")); + } + } + sharedQuestTimestamps = timestamps; + } + + public static void reset() { + sharedQuestTimestamps = new HashMap<>(); + } + + /** + * Whether profiles are enabled, checking the correct source for each side. + */ + public static boolean isProfilesEnabled() { + if (ProfileController.Instance != null) + return ConfigMain.ProfilesEnabled; + return ClientCacheHandler.allowProfiles; + } + + /** + * Check if a quest has a shared timestamp, resolving from server or client cache. + */ + public static boolean hasSharedQuest(EntityPlayer player, int questId) { + if (ProfileController.Instance != null) { + Profile profile = ProfileController.Instance.getProfile(player); + return profile != null && profile.sharedQuestTimestamps.containsKey(questId); + } + return sharedQuestTimestamps.containsKey(questId); + } + + /** + * Get the shared quest timestamp, resolving from server or client cache. + */ + public static Long getSharedQuestTimestamp(EntityPlayer player, int questId) { + if (ProfileController.Instance != null) { + Profile profile = ProfileController.Instance.getProfile(player); + return profile != null ? profile.sharedQuestTimestamps.get(questId) : null; + } + return sharedQuestTimestamps.get(questId); + } +} diff --git a/src/main/java/noppes/npcs/client/ScriptClientConfig.java b/src/main/java/noppes/npcs/client/ScriptClientConfig.java index 863f991ba..2af091723 100644 --- a/src/main/java/noppes/npcs/client/ScriptClientConfig.java +++ b/src/main/java/noppes/npcs/client/ScriptClientConfig.java @@ -7,7 +7,7 @@ import net.minecraft.nbt.NBTTagCompound; /** * Client-side cache for script configuration synced from server. * Prevents client from using local ConfigScript which may differ from server settings. - * + *

* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in * ScriptConfigSync to avoid @SideOnly crashes on dedicated servers. */ @@ -46,16 +46,44 @@ public class ScriptClientConfig { } // Setters for individual packet updates - public static void setScriptingEnabled(boolean value) { scriptingEnabled = value; } - public static void setRunLoadedScriptsFirst(boolean value) { runLoadedScriptsFirst = value; } - public static void setGlobalPlayerScripts(boolean value) { globalPlayerScripts = value; } - public static void setGlobalForgeScripts(boolean value) { globalForgeScripts = value; } - public static void setGlobalNPCScripts(boolean value) { globalNPCScripts = value; } + public static void setScriptingEnabled(boolean value) { + scriptingEnabled = value; + } + + public static void setRunLoadedScriptsFirst(boolean value) { + runLoadedScriptsFirst = value; + } + + public static void setGlobalPlayerScripts(boolean value) { + globalPlayerScripts = value; + } + + public static void setGlobalForgeScripts(boolean value) { + globalForgeScripts = value; + } + + public static void setGlobalNPCScripts(boolean value) { + globalNPCScripts = value; + } // Getters - public static boolean isScriptingEnabled() { return scriptingEnabled; } - public static boolean isRunLoadedScriptsFirst() { return runLoadedScriptsFirst; } - public static boolean isGlobalPlayerScripts() { return globalPlayerScripts; } - public static boolean isGlobalForgeScripts() { return globalForgeScripts; } - public static boolean isGlobalNPCScripts() { return globalNPCScripts; } + public static boolean isScriptingEnabled() { + return scriptingEnabled; + } + + public static boolean isRunLoadedScriptsFirst() { + return runLoadedScriptsFirst; + } + + public static boolean isGlobalPlayerScripts() { + return globalPlayerScripts; + } + + public static boolean isGlobalForgeScripts() { + return globalForgeScripts; + } + + public static boolean isGlobalNPCScripts() { + return globalNPCScripts; + } } 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..eb04c2159 --- /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/GuiNpcMobSpawnerFullscreen.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java index 4919ccbae..eabc33fee 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java @@ -74,10 +74,10 @@ public class GuiNpcMobSpawnerFullscreen extends GuiDirectory implements IGuiData this.posZ = posZ; // Configure GuiDirectory layout percentages - leftPanelPercent = 0.15f; + leftPanelPercent = 0.15f; rightPanelPercent = 0.08f; - minLeftPanelW = 120; - minRightPanelW = 62; + minLeftPanelW = 120; + minRightPanelW = 62; PacketClient.sendClient(new CloneAllTagsPacket()); if (GuiNpcMobSpawner.showingClones == 2) { @@ -199,7 +199,7 @@ public class GuiNpcMobSpawnerFullscreen extends GuiDirectory implements IGuiData navScroll.setSelected(getNavSelection()); navScroll.scrollY = Math.min(savedNavScroll, Math.max(0, navScroll.maxScrollY)); - // Phase 2: color nav items orange (selectable) or red (current location, not selectable) + // Phase 2: color nav items orange (selectable) or red (current location) if (movePhase == 2) { String currentNav = getNavSelection(); for (String name : navNames) { diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java index 5291c41cd..6762c5384 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java @@ -8,22 +8,26 @@ import net.minecraft.nbt.NBTTagDouble; import net.minecraft.nbt.NBTTagList; import noppes.npcs.client.controllers.ClientCloneController; import noppes.npcs.client.gui.util.GuiCustomScroll; -import noppes.npcs.client.gui.util.GuiMenuSideButton; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; import java.util.ArrayList; import java.util.List; -public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData { +public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData, ICustomScrollListener { private GuiCustomScroll scroll; + private GuiCustomScroll navScroll; private List list; + private List navList = new ArrayList(); private static String search = ""; public int activeTab = 1; + public String activeFolder = null; public boolean isServer = false; public GuiNpcMobSpawnerSelector() { @@ -50,38 +54,62 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat addButton(new GuiNpcButton(0, guiLeft + 171, guiTop + 80, 80, 20, "gui.done")); addButton(new GuiNpcButton(1, guiLeft + 171, guiTop + 103, 80, 20, "gui.cancel")); - addSideButton(new GuiMenuSideButton(21, guiLeft - 90, this.guiTop + 2, 90, 22, "1")); - addSideButton(new GuiMenuSideButton(22, guiLeft - 90, this.guiTop + 23, 90, 22, "2")); - addSideButton(new GuiMenuSideButton(23, guiLeft - 90, this.guiTop + 44, 90, 22, "3")); - addSideButton(new GuiMenuSideButton(24, guiLeft - 90, this.guiTop + 65, 90, 22, "4")); - addSideButton(new GuiMenuSideButton(25, guiLeft - 90, this.guiTop + 86, 90, 22, "5")); - addSideButton(new GuiMenuSideButton(26, guiLeft - 45, this.guiTop + 107, 45, 22, "6")); - addSideButton(new GuiMenuSideButton(27, guiLeft - 90, this.guiTop + 107, 45, 22, "7")); - addSideButton(new GuiMenuSideButton(28, guiLeft - 45, this.guiTop + 128, 45, 22, "8")); - addSideButton(new GuiMenuSideButton(29, guiLeft - 90, this.guiTop + 128, 45, 22, "9")); - addSideButton(new GuiMenuSideButton(30, guiLeft - 45, this.guiTop + 149, 45, 22, "10")); - addSideButton(new GuiMenuSideButton(31, guiLeft - 90, this.guiTop + 149, 45, 22, "11")); - addSideButton(new GuiMenuSideButton(32, guiLeft - 45, this.guiTop + 170, 45, 22, "12")); - addSideButton(new GuiMenuSideButton(33, guiLeft - 90, this.guiTop + 170, 45, 22, "13")); - addSideButton(new GuiMenuSideButton(34, guiLeft - 45, this.guiTop + 191, 45, 22, "14")); - addSideButton(new GuiMenuSideButton(35, guiLeft - 90, this.guiTop + 191, 45, 22, "15")); + // Navigation scroll (tabs + folders) replacing hardcoded side buttons + buildNavList(); + if (navScroll == null) { + navScroll = new GuiCustomScroll(this, 1); + } else { + navScroll.clear(); + } + navScroll.setSize(90, 210); + navScroll.guiLeft = guiLeft - 94; + navScroll.guiTop = guiTop + 2; + navScroll.setList(navList); + navScroll.setSelected(getNavSelection()); + addScroll(navScroll); - getSideButton(20 + activeTab).active = true; showClones(); } + private void buildNavList() { + navList.clear(); + for (int i = 1; i <= 15; i++) { + navList.add("Tab " + i); + } + if (ClientCloneController.Instance != null) { + for (CloneFolder folder : ClientCloneController.Instance.getFolderList()) { + navList.add(folder.name); + } + } + } + + private String getNavSelection() { + if (activeFolder != null) return activeFolder; + if (activeTab >= 1 && activeTab <= 15) return "Tab " + activeTab; + return "Tab 1"; + } + public String getSelected() { return scroll.getSelected(); } private void showClones() { - if (isServer) { - PacketClient.sendClient(new CloneListPacket(activeTab)); + if (activeFolder != null) { + PacketClient.sendClient(new CloneListPacket(activeFolder)); + } else { + PacketClient.sendClient(new CloneListPacket(activeTab)); + } return; } - this.list = new ArrayList(ClientCloneController.Instance.getClones(activeTab)); + if (activeFolder != null && ClientCloneController.Instance != null) { + this.list = new ArrayList(ClientCloneController.Instance.getClones(activeFolder)); + } else if (ClientCloneController.Instance != null) { + this.list = new ArrayList(ClientCloneController.Instance.getClones(activeTab)); + } else { + this.list = new ArrayList(); + } scroll.setList(getSearchList()); } @@ -95,6 +123,7 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat } private List getSearchList() { + if (list == null) list = new ArrayList(); if (search.isEmpty()) return new ArrayList(list); List list = new ArrayList(); @@ -110,8 +139,15 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat if (sel == null) return null; - NBTTagCompound compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab); - compound.setString("ClonedName", sel); + NBTTagCompound compound; + if (activeFolder != null && ClientCloneController.Instance != null) { + compound = ClientCloneController.Instance.getCloneData(player, sel, activeFolder); + } else { + compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab); + } + if (compound != null) { + compound.setString("ClonedName", sel); + } return compound; } @@ -124,9 +160,28 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat scroll.clear(); close(); } - if (id > 20) { - activeTab = id - 20; - initGui(); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 1) { + String selected = navScroll.getSelected(); + if (selected == null) return; + + if (selected.startsWith("Tab ")) { + try { + int tabNum = Integer.parseInt(selected.substring(4)); + if (tabNum >= 1 && tabNum <= 15) { + activeTab = tabNum; + activeFolder = null; + } + } catch (NumberFormatException ignored) { + } + } else { + activeFolder = selected; + activeTab = -1; + } + showClones(); } } diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcPather.java b/src/main/java/noppes/npcs/client/gui/GuiNpcPather.java index 2a23e474a..eee981bdf 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcPather.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcPather.java @@ -28,7 +28,7 @@ public class GuiNpcPather extends GuiNPCInterface implements IGuiData { drawDefaultBackground = false; xSize = 176; title = "Npc Pather"; - setBackground("smallbg.png"); + setBackground("menubg.png"); ai = npc.ais; PacketClient.sendClient(new MovingPathGetPacket()); } diff --git a/src/main/java/noppes/npcs/client/gui/GuiScript.java b/src/main/java/noppes/npcs/client/gui/GuiScript.java index 8d960e142..96a7efab1 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiScript.java +++ b/src/main/java/noppes/npcs/client/gui/GuiScript.java @@ -2,13 +2,15 @@ package noppes.npcs.client.gui; import kamkeel.npcs.network.packets.request.script.NPCScriptPacket; import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; import net.minecraft.client.gui.GuiYesNo; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.util.StatCollector; import noppes.npcs.NoppesStringUtils; import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.util.SubGuiAPISelect; +import noppes.npcs.client.gui.util.SubGuiConfirmLink; +import noppes.npcs.controllers.APIRegistry; import noppes.npcs.client.gui.script.GuiScriptInterface; import noppes.npcs.client.gui.util.GuiCustomScroll; import noppes.npcs.client.gui.util.GuiMenuTopButton; @@ -16,6 +18,8 @@ import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextArea; import noppes.npcs.client.gui.util.GuiScriptTextArea; +import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer; +import noppes.npcs.constants.EnumScriptType; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; @@ -88,18 +92,25 @@ public class GuiScript extends GuiScriptInterface { super.initGui(); this.guiTop += 10; - // ==================== TOP BUTTONS (hidden in fullscreen) ==================== - if (!isFullscreen) { - GuiMenuTopButton top; - addTopButton(top = new GuiMenuTopButton(13, guiLeft + 4, guiTop - 17, "script.scripts")); - addTopButton(new GuiMenuTopButton(16, guiLeft + (xSize - 102), guiTop - 17, "eventscript.eventScripts")); - addTopButton(new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X")); - top.active = showScript; - addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings")); - top.active = !showScript; - addTopButton(new GuiMenuTopButton(15, top, "gui.website")); + if (isFullscreen) { + FullscreenConfig.paddingTop = 30; } + // ==================== TOP BUTTONS ==================== + boolean isFullscreenView = isFullscreen && showScript; + int menuX = isFullscreenView ? FullscreenConfig.paddingLeft : guiLeft + 4; + int menuY = isFullscreenView ? FullscreenConfig.paddingTop - 20 : guiTop - 17; + int rightX = isFullscreenView ? width - FullscreenConfig.paddingRight : guiLeft + xSize; + + GuiMenuTopButton top; + addTopButton(top = new GuiMenuTopButton(13, menuX, menuY, "script.scripts")); + addTopButton(new GuiMenuTopButton(16, rightX - 102, menuY, "eventscript.eventScripts")); + addTopButton(new GuiMenuTopButton(17, rightX - 22, menuY, "X")); + top.active = showScript; + addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings")); + top.active = !showScript; + addTopButton(new GuiMenuTopButton(15, top, "gui.api")); + if (showScript) { initScriptView(); } else { @@ -158,8 +169,14 @@ public class GuiScript extends GuiScriptInterface { container == null ? "" : container.script); } - activeArea.setLanguage(script.getLanguage()); + // Use the container's language for syntax highlighting, fall back to handler default + String language = (container != null) ? container.getLanguage() : script.getLanguage(); + activeArea.setLanguage(language); activeArea.setScriptContext(getScriptContext()); + + // Set editor globals based on the active NPC hook + String hookName = EnumScriptType.values()[activeTab].function; + applyEditorGlobals(activeArea, hookName); // Setup fullscreen key binding GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> { @@ -182,6 +199,14 @@ public class GuiScript extends GuiScriptInterface { addButton(new GuiNpcButton(100, guiLeft + 315, guiTop + 25, 50, 20, "gui.copy")); addButton(new GuiNpcButton(107, guiLeft + 315, guiTop + 70, 80, 20, "script.loadscript")); + // Disable all buttons until server data arrives + if (!serverDataReceived) { + for (int btnId : new int[]{100, 101, 102, 107}) { + GuiNpcButton btn = getButton(btnId); + if (btn != null) btn.enabled = false; + } + } + GuiCustomScroll scroll = new GuiCustomScroll(this, 0).setUnselectable(); scroll.setSize(100, 120); scroll.guiLeft = guiLeft + 315; @@ -211,11 +236,10 @@ public class GuiScript extends GuiScriptInterface { addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20, consoleOptions.toArray(new String[0]), activeConsole)); - addLabel(new GuiNpcLabel(1, "script.language", guiLeft + 232, guiTop + 30)); + addLabel(new GuiNpcLabel(1, "script.default", guiLeft + 232, guiTop + 30)); List languageOptions = getLanguageOptions(); addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20, languageOptions.toArray(new String[0]), getLanguageIndex(languageOptions))); - getButton(103).enabled = languageOptions.size() > 0; addLabel(new GuiNpcLabel(2, "gui.enabled", guiLeft + 232, guiTop + 53)); addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20, @@ -223,6 +247,29 @@ public class GuiScript extends GuiScriptInterface { if (MinecraftServer.getServer() != null) addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder")); + + // Disable all buttons until server data arrives + if (!serverDataReceived) { + for (int btnId : new int[]{100, 102, 103, 104, 105, 106}) { + GuiNpcButton btn = getButton(btnId); + if (btn != null) btn.enabled = false; + } + } else { + getButton(103).enabled = languageOptions.size() > 0; + } + } + + // Apply editor globals for the active NPC hook. + private void applyEditorGlobals(GuiScriptTextArea activeArea, String hookName) { + if (activeArea == null) + return; + + ScriptTextContainer textContainer = activeArea.getContainer(); + if (textContainer == null) + return; + + if (script != null) + textContainer.setEditorGlobalsMap(script.getEditorGlobals(hookName)); } @Override @@ -240,9 +287,6 @@ public class GuiScript extends GuiScriptInterface { NoppesUtil.openGUI(player, this); if (!result) return; - if (id == 0) { - openLink("https://kamkeel.github.io/CustomNPC-Plus/"); - } if (id == 101) { getTextField(2).setText(NoppesStringUtils.getClipboardContents()); } @@ -274,7 +318,12 @@ public class GuiScript extends GuiScriptInterface { initGui(); } if (guibutton.id == 15) { - displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true)); + if (APIRegistry.Instance.size() == 1) { + String url = APIRegistry.Instance.getEntries().values().iterator().next(); + setSubGui(new SubGuiConfirmLink(url)); + } else { + setSubGui(new SubGuiAPISelect()); + } } if (guibutton.id == 16) { close(); @@ -309,9 +358,13 @@ public class GuiScript extends GuiScriptInterface { } if (guibutton.id == 107) { ScriptContainer container = getCurrentContainer(); - if (container == null) - script.setNPCScript(activeTab, container = new ScriptContainer(this.script)); - setSubGui(new GuiScriptList(languages.get(script.scriptLanguage), container)); + if (container == null) { + container = new ScriptContainer(this.script); + container.setLanguage(script.getLanguage()); + script.setNPCScript(activeTab, container); + } + String lang = container.getLanguage(); + setSubGui(new GuiScriptList(languages.get(lang), container)); } } @@ -319,8 +372,11 @@ public class GuiScript extends GuiScriptInterface { protected void setScript() { if (showScript) { ScriptContainer container = getCurrentContainer(); - if (container == null) - script.setNPCScript(activeTab, container = new ScriptContainer(this.script)); + if (container == null) { + container = new ScriptContainer(this.script); + container.setLanguage(script.getLanguage()); + script.setNPCScript(activeTab, container); + } String text = getTextField(2).getText(); text = text.replace("\r\n", "\n"); text = text.replace("\r", "\n"); @@ -330,6 +386,11 @@ public class GuiScript extends GuiScriptInterface { @Override public void setGuiData(NBTTagCompound compound) { + // Only process the actual NPCScriptPacket response (has ScriptLanguage + Languages) + // Ignore unrelated packets (e.g. script config with ScriptsEnabled/GlobalNPCScriptsEnabled) + if (!compound.hasKey("ScriptLanguage") && !compound.hasKey("Languages")) { + return; + } script.readFromNBT(compound); loadLanguagesData(compound); loaded = true; @@ -337,7 +398,7 @@ public class GuiScript extends GuiScriptInterface { @Override public void save() { - if (loaded) { + if (loaded && serverDataReceived) { setScript(); NPCScriptPacket.Save(script.writeToNBT(new NBTTagCompound())); } @@ -351,24 +412,4 @@ public class GuiScript extends GuiScriptInterface { initGui(); } } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - super.drawScreen(mouseX, mouseY, partialTicks); - - // Draw fullscreen button when in script view (GuiScript uses 0-based activeTab) - if (showScript) { - fullscreenButton.draw(mouseX, mouseY); - } - } - - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) { - // Check fullscreen button first when in script view - if (showScript && fullscreenButton.mouseClicked(mouseX, mouseY, mouseButton)) { - return; - } - super.mouseClicked(mouseX, mouseY, mouseButton); - } } - diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiAnimationFrame.java b/src/main/java/noppes/npcs/client/gui/SubGuiAnimationFrame.java index e5594bf52..68eb9398b 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiAnimationFrame.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiAnimationFrame.java @@ -13,7 +13,7 @@ public class SubGuiAnimationFrame extends SubGuiInterface implements ITextfieldL public SubGuiAnimationFrame(Frame editingFrame) { this.editingFrame = editingFrame; - setBackground("smallbg.png"); + setBackground("menubg.png"); } @Override diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiAnimationOptions.java b/src/main/java/noppes/npcs/client/gui/SubGuiAnimationOptions.java index 27921388b..3d42c0cc0 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiAnimationOptions.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiAnimationOptions.java @@ -11,7 +11,7 @@ public class SubGuiAnimationOptions extends SubGuiInterface { public SubGuiAnimationOptions(Animation animation) { this.animation = animation; - setBackground("smallbg.png"); + setBackground("menubg.png"); } @Override diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiEditText.java b/src/main/java/noppes/npcs/client/gui/SubGuiEditText.java index 5fe7ffe71..1f6fc1bc6 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiEditText.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiEditText.java @@ -11,7 +11,7 @@ public class SubGuiEditText extends SubGuiInterface { public SubGuiEditText(String text) { this.text = text; - setBackground("extrasmallbg.png"); + setBackground("menubg.png"); closeOnEsc = true; xSize = 176; ySize = 71; diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java index cfde598de..77d72442c 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java @@ -6,14 +6,17 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.ClientCacheHandler; -import noppes.npcs.client.gui.global.GuiNPCManageEffects; +import net.minecraft.client.gui.GuiScreen; import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.gui.util.GuiMenuTopButton; import noppes.npcs.client.gui.util.GuiNpcButtonYesNo; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.GuiScrollWindow; import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.SubGuiTagSelect; +import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.controllers.data.CustomEffect; @@ -26,13 +29,13 @@ import java.util.List; import static noppes.npcs.client.gui.player.inventory.GuiCNPCInventory.specialIcons; public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldListener { - private final GuiNPCManageEffects parent; + private final GuiScreen parent; public CustomEffect effect; private final String originalName; private final List topButtons = new ArrayList<>(); - public SubGuiEffectGeneral(GuiNPCManageEffects parent, CustomEffect effect) { + public SubGuiEffectGeneral(GuiScreen parent, CustomEffect effect) { this.effect = effect; this.parent = parent; this.originalName = effect.name; @@ -62,12 +65,14 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi guiTop += 7; int y = guiTop + 7; int x = guiLeft + 4 + 4; - addTextField(new GuiNpcTextField(1, this, this.fontRendererObj, x + 36, y, 280, 20, effect.name)); + addTextField(new GuiNpcTextField(1, this, this.fontRendererObj, x + 36, y, 210, 20, effect.name)); getTextField(1).setMaxStringLength(40); addLabel(new GuiNpcLabel(1, "gui.name", x, y + 5)); - addLabel(new GuiNpcLabel(-1, "ID", x + 320, y + 1)); - addLabel(new GuiNpcLabel(-2, effect.id + "", x + 320, y + 11)); + addLabel(new GuiNpcLabel(-1, "ID", x + 250, y + 1)); + addLabel(new GuiNpcLabel(-2, effect.id + "", x + 250, y + 11)); + + addButton(new GuiNpcButton(40, getTextField(1).xPosition + getTextField(1).width + 30, y, 70, 20, "gui.tags")); y += 23; @@ -108,7 +113,8 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi x = oldX - 4; y += 23; - GuiScrollWindow scrollWindow = new GuiScrollWindow(this, x + 5, y, xSize - 20, ySize - 10 - (y - guiTop), 0) { + int scrollClipHeight = ySize - 10 - (y - guiTop); + GuiScrollWindow scrollWindow = new GuiScrollWindow(this, x + 5, y, xSize - 20, scrollClipHeight, 0) { @Override public void drawComponents(int mouseX, int mouseY, float partialTicks) { super.drawComponents(mouseX, mouseY, partialTicks); @@ -127,8 +133,14 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi int iconWidth = effect.getWidth(); int iconHeight = effect.getHeight(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); + // Animation V offset for preview + if (data.isAnimated()) { + iconY += (int) (data.getCurrentFrameVOffset() * height); + } else if (effect.animated && effect.frameCount > 1) { + iconY += (int) (AnimationHelper.getFrameVOffset(height, effect.frameCount, effect.frametime) * height); + } func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); @@ -183,6 +195,36 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi effect.height )); scrollWindow.addLabel(new GuiNpcLabel(9, "effect.editor.height", scrollWindow.getTextField(9).xPosition - 43, y + 6, 0xFFFFFF)); + y += 25; + + // Animation controls + scrollWindow.addLabel(new GuiNpcLabel(11, "gui.animated", x, y + 5, 0xFFFFFF)); + GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(11, x + 70, y, 50, 20, effect.animated); + animBtn.setHoverText("gui.animated.hover"); + scrollWindow.addButton(animBtn); + + if (effect.animated) { + y += 23; + scrollWindow.addLabel(new GuiNpcLabel(12, "gui.frameCount", x, y + 6, 0xFFFFFF)); + scrollWindow.addTextField(setIntegerOnly( + new GuiNpcTextField(12, this, x + 80, y, 60, 20, "" + effect.frameCount), + 1, + 256, + effect.frameCount + )); + + y += 23; + scrollWindow.addLabel(new GuiNpcLabel(13, "gui.frameTime", x, y + 6, 0xFFFFFF)); + scrollWindow.addTextField(setIntegerOnly( + new GuiNpcTextField(13, this, x + 80, y, 60, 20, "" + effect.frametime), + 1, + 100, + effect.frametime + )); + } + + int contentBottom = y + 20 + 5; + scrollWindow.maxScrollY = Math.max(0, contentBottom - scrollClipHeight); } @@ -205,10 +247,19 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), originalName)); GuiScriptInterface.open(parent, new EffectScript(effect.id)); } + if (id == 40) { + setSubGui(new SubGuiTagSelect(effect.tagUUIDs)); + return; + } if (id == 10) { GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton; effect.lossOnDeath = button.getBoolean(); } + if (id == 11) { + GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton; + effect.animated = button.getBoolean(); + initGui(); + } } @Override @@ -248,6 +299,12 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi case 9: effect.height = guiNpcTextField.getInteger(); break; + case 12: + effect.frameCount = Math.max(1, guiNpcTextField.getInteger()); + break; + case 13: + effect.frametime = Math.max(1, guiNpcTextField.getInteger()); + break; } } diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcAvailabilityDialog.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcAvailabilityDialog.java index 802ede067..d3d93daa2 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcAvailabilityDialog.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcAvailabilityDialog.java @@ -112,19 +112,19 @@ public class SubGuiNpcAvailabilityDialog extends SubGuiInterface implements GuiS } if (button.id == 10) { slot = 1; - setSubGui(new GuiDialogSelection(availabitily.questId)); + setSubGui(new GuiDialogSelection(availabitily.dialogId)); } if (button.id == 11) { slot = 2; - setSubGui(new GuiDialogSelection(availabitily.quest2Id)); + setSubGui(new GuiDialogSelection(availabitily.dialog2Id)); } if (button.id == 12) { slot = 3; - setSubGui(new GuiDialogSelection(availabitily.quest3Id)); + setSubGui(new GuiDialogSelection(availabitily.dialog3Id)); } if (button.id == 13) { slot = 4; - setSubGui(new GuiDialogSelection(availabitily.quest4Id)); + setSubGui(new GuiDialogSelection(availabitily.dialog4Id)); } if (button.id == 20) { availabitily.dialogId = -1; 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..17996759e 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java @@ -1,9 +1,6 @@ package noppes.npcs.client.gui; -import kamkeel.npcs.network.PacketClient; -import kamkeel.npcs.network.packets.request.dialog.DialogSavePacket; import net.minecraft.client.gui.GuiButton; -import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.NoppesUtil; import noppes.npcs.client.gui.util.GuiCustomScroll; import noppes.npcs.client.gui.util.GuiMenuTopButton; @@ -521,8 +518,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..c40c009fe 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,34 @@ 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)); + if (stats.potionType == EnumPotionType.Manual) { + addTextField(new GuiNpcTextField(7, this, fontRendererObj, guiLeft + 85, y, 52, 18, stats.potionAmp + "")); + getTextField(7).integersOnly = true; + getTextField(7).setMinMaxDefault(0, 255, 0); + } else { + 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 +82,21 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi stats.knockback = textfield.getInteger(); } else if (textfield.id == 6) { stats.potionDuration = textfield.getInteger(); + } else if (textfield.id == 7) { + stats.potionAmp = 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()]; + EnumPotionType newType = EnumPotionType.fromOrdinal(button.getValue()); + if (stats.potionType == EnumPotionType.Manual && newType != EnumPotionType.Manual) { + stats.potionAmp = 0; + } + stats.potionType = newType; 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..eee99a12e 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,35 @@ 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)); + if (stats.pEffect == EnumPotionType.Manual) { + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 280, internalY, 52, 20, stats.pEffAmp + "")); + getTextField(10).integersOnly = true; + getTextField(10).setMinMaxDefault(0, 255, 0); + } else { + 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 +138,10 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pSpeed = textfield.getInteger(); } else if (textfield.id == 5) { stats.pDur = textfield.getInteger(); + } else if (textfield.id == 10) { + stats.pEffAmp = textfield.getInteger(); + } else if (textfield.id == 11) { + stats.pManualId = textfield.getInteger(); } } @@ -146,7 +162,11 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pArea = button.getValue(); } if (button.id == 4) { - stats.pEffect = EnumPotionType.values()[button.getValue()]; + EnumPotionType newType = EnumPotionType.fromOrdinal(button.getValue()); + if (stats.pEffect == EnumPotionType.Manual && newType != EnumPotionType.Manual) { + stats.pEffAmp = 0; + } + stats.pEffect = newType; 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/SubGuiSpawningOptions.java b/src/main/java/noppes/npcs/client/gui/SubGuiSpawningOptions.java index 29c33352b..ddce230c3 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiSpawningOptions.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiSpawningOptions.java @@ -5,6 +5,7 @@ import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcButtonYesNo; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.GuiScrollWindow; import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.controllers.data.SpawnData; @@ -15,37 +16,97 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield public SubGuiSpawningOptions(SpawnData data) { this.data = data; setBackground("menubg.png"); - xSize = 216; + xSize = 256; ySize = 216; closeOnEsc = true; } public void initGui() { super.initGui(); - int y = guiTop - 15; + int scrollX = guiLeft + 4; + int scrollY = guiTop + 4; + int scrollW = xSize - 8; + int scrollH = ySize - 34; - addButton(new GuiNpcButtonYesNo(10, guiLeft + 120, y += 22, data.animalSpawning)); - addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", guiLeft + 4, y + 5)); + GuiScrollWindow sw = new GuiScrollWindow(this, scrollX, scrollY, scrollW, scrollH, 0); + sw.drawDefaultBackground = false; + addScrollableGui(0, sw); - addButton(new GuiNpcButtonYesNo(11, guiLeft + 120, y += 22, data.monsterSpawning)); - addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", guiLeft + 4, y + 5)); + int labelX = 4; + int controlX = 132; + int y = 6; - addButton(new GuiNpcButtonYesNo(12, guiLeft + 120, y += 22, data.liquidSpawning)); - addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", guiLeft + 4, y + 5)); + sw.addButton(new GuiNpcButtonYesNo(10, controlX, y, data.animalSpawning)); + sw.addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", labelX, y + 5)); + sw.getButton(10).setHoverText("tooltip.naturalspawns.options.animal"); + y += 22; - addButton(new GuiNpcButtonYesNo(13, guiLeft + 120, y += 22, data.airSpawning)); - addLabel(new GuiNpcLabel(13, "spawning.airSpawning", guiLeft + 4, y + 5)); + sw.addButton(new GuiNpcButtonYesNo(11, controlX, y, data.monsterSpawning)); + sw.addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", labelX, y + 5)); + sw.getButton(11).setHoverText("tooltip.naturalspawns.options.monster"); + y += 22; - addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMin)); - addLabel(new GuiNpcLabel(14, "spawning.minHeight", guiLeft + 4, y + 5)); - addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMax)); - addLabel(new GuiNpcLabel(15, "spawning.maxHeight", guiLeft + 4, y + 5)); - getTextField(14).integersOnly = true; - getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - getTextField(15).integersOnly = true; - getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); + sw.addButton(new GuiNpcButtonYesNo(12, controlX, y, data.liquidSpawning)); + sw.addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", labelX, y + 5)); + sw.getButton(12).setHoverText("tooltip.naturalspawns.options.liquid"); + y += 22; - addButton(new GuiNpcButton(100, guiLeft + 154, guiTop + 192, 60, 20, "gui.done")); + sw.addButton(new GuiNpcButtonYesNo(13, controlX, y, data.airSpawning)); + sw.addLabel(new GuiNpcLabel(13, "spawning.airSpawning", labelX, y + 5)); + sw.getButton(13).setHoverText("tooltip.naturalspawns.options.air"); + y += 22; + + sw.addTextField(new GuiNpcTextField(14, this, controlX, y, 60, 20, "" + data.spawnHeightMin)); + sw.addLabel(new GuiNpcLabel(14, "spawning.minHeight", labelX, y + 5)); + sw.getTextField(14).integersOnly = true; + sw.getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); + sw.getTextField(14).setHoverText("tooltip.naturalspawns.options.minHeight"); + y += 22; + + sw.addTextField(new GuiNpcTextField(15, this, controlX, y, 60, 20, "" + data.spawnHeightMax)); + sw.addLabel(new GuiNpcLabel(15, "spawning.maxHeight", labelX, y + 5)); + sw.getTextField(15).integersOnly = true; + sw.getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); + sw.getTextField(15).setHoverText("tooltip.naturalspawns.options.maxHeight"); + y += 22; + + sw.addTextField(new GuiNpcTextField(16, this, controlX, y, 60, 20, "" + data.maxAlive)); + sw.addLabel(new GuiNpcLabel(16, "spawning.maxAlive", labelX, y + 5)); + sw.getTextField(16).integersOnly = true; + sw.getTextField(16).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + sw.getTextField(16).setHoverText("tooltip.naturalspawns.options.maxAlive"); + y += 22; + + sw.addTextField(new GuiNpcTextField(17, this, controlX, y, 60, 20, "" + data.cooldownTicks)); + sw.addLabel(new GuiNpcLabel(17, "spawning.cooldownTicks", labelX, y + 5)); + sw.getTextField(17).integersOnly = true; + sw.getTextField(17).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + sw.getTextField(17).setHoverText("tooltip.naturalspawns.options.cooldownTicks"); + y += 22; + + sw.addTextField(new GuiNpcTextField(18, this, controlX, y, 60, 20, "" + data.attemptsPerCycle)); + sw.addLabel(new GuiNpcLabel(18, "spawning.attemptsPerCycle", labelX, y + 5)); + sw.getTextField(18).integersOnly = true; + sw.getTextField(18).setMinMaxDefault(1, Integer.MAX_VALUE, 1); + sw.getTextField(18).setHoverText("tooltip.naturalspawns.options.attemptsPerCycle"); + y += 22; + + sw.addTextField(new GuiNpcTextField(19, this, controlX, y, 60, 20, "" + data.playerMinDistance)); + sw.addLabel(new GuiNpcLabel(19, "spawning.playerMinDistance", labelX, y + 5)); + sw.getTextField(19).integersOnly = true; + sw.getTextField(19).setMinMaxDefault(0, Integer.MAX_VALUE, 24); + sw.getTextField(19).setHoverText("tooltip.naturalspawns.options.playerMinDistance"); + y += 22; + + sw.addButton(new GuiNpcButton(20, controlX, y, 100, 20, + new String[]{"spawning.despawn.forceNatural", "spawning.despawn.preserve", "spawning.despawn.forcePersistent"}, data.despawnMode)); + sw.addLabel(new GuiNpcLabel(20, "spawning.despawnMode", labelX, y + 5)); + sw.getButton(20).setHoverText("tooltip.naturalspawns.options.despawnMode"); + y += 22; + + sw.maxScrollY = Math.max(0, y - sw.clipHeight + 8); + + addButton(new GuiNpcButton(100, guiLeft + xSize - 64, guiTop + ySize - 24, 60, 20, "gui.done")); } @Override @@ -64,6 +125,9 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield if (button.id == 13) { data.airSpawning = button.getValue() == 1; } + if (button.id == 20) { + data.setDespawnMode(button.getValue()); + } if (button.id == 100) { close(); } @@ -77,5 +141,17 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield if (textfield.id == 15) { data.spawnHeightMax = textfield.getInteger(); } + if (textfield.id == 16) { + data.setMaxAlive(textfield.getInteger()); + } + if (textfield.id == 17) { + data.setCooldownTicks(textfield.getInteger()); + } + if (textfield.id == 18) { + data.setAttemptsPerCycle(textfield.getInteger()); + } + if (textfield.id == 19) { + data.setPlayerMinDistance(textfield.getInteger()); + } } } diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiTagSelect.java b/src/main/java/noppes/npcs/client/gui/SubGuiTagSelect.java new file mode 100644 index 000000000..ee55e1b63 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiTagSelect.java @@ -0,0 +1,174 @@ +package noppes.npcs.client.gui; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.tags.TagsGetPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +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.IScrollData; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.TagController; +import noppes.npcs.controllers.data.Tag; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; +import java.util.Vector; + +/** + * Reusable SubGui for selecting tags on any taggable object. + * Pass in the current tagUUIDs, get back the modified set on close. + */ +public class SubGuiTagSelect extends SubGuiInterface implements IScrollData, ICustomScrollListener, ITextfieldListener { + private GuiCustomScroll scrollAllTags; + private GuiCustomScroll scrollSelectedTags; + private final ArrayList allTagNames = new ArrayList<>(); + private final ArrayList selectedTagNames = new ArrayList<>(); + private final HashSet tagUUIDs; + private String search = ""; + + public SubGuiTagSelect(HashSet tagUUIDs) { + this.tagUUIDs = tagUUIDs; + setBackground("menubg.png"); + closeOnEsc = true; + xSize = 430; + ySize = 220; + + // Populate selected tag names from UUIDs + TagController tc = TagController.getInstance(); + if (tc != null) { + for (UUID uuid : tagUUIDs) { + Tag tag = tc.getTagFromUUID(uuid); + if (tag != null) { + selectedTagNames.add(tag.name); + } + } + } + + PacketClient.sendClient(new TagsGetPacket()); + } + + public void initGui() { + super.initGui(); + + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("tags.allTags"), guiLeft + 22, guiTop + 11)); + if (scrollAllTags == null) { + scrollAllTags = new GuiCustomScroll(this, 0); + scrollAllTags.setSize(150, 155); + } + scrollAllTags.guiLeft = guiLeft + 20; + scrollAllTags.guiTop = guiTop + 24; + this.addScroll(scrollAllTags); + addTextField(new GuiNpcTextField(4, this, fontRendererObj, guiLeft + 20, guiTop + 24 + 160, 150, 20, search)); + + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("tags.selectedTags"), guiLeft + 252, guiTop + 11)); + if (scrollSelectedTags == null) { + scrollSelectedTags = new GuiCustomScroll(this, 1); + scrollSelectedTags.setSize(150, 180); + } + scrollSelectedTags.guiLeft = guiLeft + 250; + scrollSelectedTags.guiTop = guiTop + 24; + scrollSelectedTags.setList(selectedTagNames); + this.addScroll(scrollSelectedTags); + + addButton(new GuiNpcButton(10, guiLeft + 185, guiTop + 90, 55, 20, ">")); + addButton(new GuiNpcButton(11, guiLeft + 185, guiTop + 112, 55, 20, "<")); + addButton(new GuiNpcButton(12, guiLeft + 185, guiTop + 140, 55, 20, ">>")); + addButton(new GuiNpcButton(13, guiLeft + 185, guiTop + 162, 55, 20, "<<")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 10 && scrollAllTags.hasSelected() && !selectedTagNames.contains(scrollAllTags.getSelected())) { + selectedTagNames.add(scrollAllTags.getSelected()); + } + if (guibutton.id == 12) { + selectedTagNames.clear(); + selectedTagNames.addAll(allTagNames); + } + if (guibutton.id == 11 && scrollSelectedTags.hasSelected()) { + selectedTagNames.remove(scrollSelectedTags.getSelected()); + } + if (guibutton.id == 13) { + selectedTagNames.clear(); + } + initGui(); + } + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + allTagNames.clear(); + allTagNames.addAll(data.keySet()); + allTagNames.sort(String.CASE_INSENSITIVE_ORDER); + scrollAllTags.setList(getSearchList()); + initGui(); + } + + @Override + public void save() { + tagUUIDs.clear(); + TagController tc = TagController.getInstance(); + if (tc != null) { + for (String name : selectedTagNames) { + Tag tag = tc.getTagFromName(name); + if (tag != null) { + tagUUIDs.add(tag.uuid); + } + } + } + } + + public void mouseClicked(int i, int j, int k) { + super.mouseClicked(i, j, k); + if (k == 0 && scrollAllTags != null) + scrollAllTags.mouseClicked(i, j, k); + } + + @Override + public void setSelected(String selected) { + if (scrollAllTags != null) + scrollAllTags.setSelected(selected); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + } + + public void keyTyped(char c, int i) { + if (i == 1) { + close(); + return; + } + super.keyTyped(c, i); + if (getTextField(4) != null) { + if (search.equals(getTextField(4).getText())) + return; + search = getTextField(4).getText().toLowerCase(); + scrollAllTags.setList(getSearchList()); + } + } + + @Override + public void unFocused(GuiNpcTextField guiNpcTextField) { + } + + private List getSearchList() { + if (search.isEmpty()) { + return new ArrayList<>(allTagNames); + } + List list = new ArrayList<>(); + for (String name : allTagNames) { + if (name.toLowerCase().contains(search)) + list.add(name); + } + return list; + } +} 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..086e27569 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java @@ -0,0 +1,92 @@ +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.builder.FieldDef; +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; + + /** + * Builds the trap editor's preset field. + *

+ * This lives here rather than in AbilityTrap because the lambda below carries this class in + * its method descriptor. AbilityTrap is a both-side class, and @SideOnly does not strip the + * synthetic lambda methods it generates - so anything reflecting over its declared methods + * on a server would resolve that descriptor and fail to find this client-only type. + */ + public static FieldDef createPresetField(java.util.function.Consumer applyPreset) { + return FieldDef.subGuiField("gui.applyPreset", + SubGuiTrapPresetSelector::new, + gui -> { + SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui; + if (selector.selectedPreset != null) { + applyPreset.accept(selector.selectedPreset); + } + }); + } + + 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..5bdc9c291 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java @@ -0,0 +1,92 @@ +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.builder.FieldDef; +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; + + /** + * Builds the zone editor's preset field. + *

+ * This lives here rather than in AbilityZone because the lambda below carries this class in + * its method descriptor. AbilityZone is a both-side class, and @SideOnly does not strip the + * synthetic lambda methods it generates - so anything reflecting over its declared methods + * on a server would resolve that descriptor and fail to find this client-only type. + */ + public static FieldDef createPresetField(java.util.function.Consumer applyPreset) { + return FieldDef.subGuiField("gui.applyPreset", + SubGuiZonePresetSelector::new, + gui -> { + SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui; + if (selector.selectedPreset != null) { + applyPreset.accept(selector.selectedPreset); + } + }); + } + + 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 7bc5c3846..c6129b12a 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -1,10 +1,13 @@ package noppes.npcs.client.gui.advanced; +import kamkeel.npcs.controllers.AbilityController; 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.AbilityAction; import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.CopyAbilityScriptsPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; @@ -21,6 +24,7 @@ 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.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.IScrollData; @@ -30,41 +34,91 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.constants.EnumScrollData; import noppes.npcs.entity.EntityNPCInterface; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Vector; /** * GUI for managing NPC abilities. * Shows list of assigned abilities with add/remove/edit controls. */ -public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, ICustomScrollListener, IGuiData, ITextfieldListener, ISubGuiListener, IAbilityConfigCallback { +public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, ICustomScrollListener, IGuiData, ITextfieldListener, ISubGuiListener, IAbilityConfigCallback, IChainedAbilityConfigCallback { + // ── Button IDs ──────────────────────────────────────────────────────────── + private static final int BTN_SCROLL_TYPE = 50; + private static final int BTN_ADD_ABILITY = 70; + private static final int BTN_REMOVE = 71; + private static final int BTN_EDIT = 72; + private static final int BTN_MOVE_UP = 73; + private static final int BTN_MOVE_DOWN = 74; + private static final int BTN_LOAD = 75; + private static final int BTN_SAVE_PRESET = 76; + private static final int BTN_TOGGLE_SLOT = 77; + private static final int BTN_ADD_CHAIN = 78; + private static final int BTN_ENABLED = 100; + + // ── Scroll IDs ──────────────────────────────────────────────────────────── + private static final int SCROLL_TYPES = 0; + private static final int SCROLL_NPC = 1; + + // ── TextField / Label IDs ───────────────────────────────────────────────── + private static final int TF_MIN_COOLDOWN = 101; + private static final int TF_MAX_COOLDOWN = 102; + private static final int TF_SEARCH = 4; + private static final int LBL_TYPES = 1; + private static final int LBL_NPC = 2; + private static final int LBL_MIN_COOLDOWN = 101; + private static final int LBL_MAX_COOLDOWN = 102; + + // ── Scroll lists ────────────────────────────────────────────────────────── private GuiCustomScroll availableTypesScroll; private GuiCustomScroll npcAbilitiesScroll; - // All available ability types (typeId -> index) + // ── Available type data ─────────────────────────────────────────────────── private final HashMap allAbilityTypes = new HashMap<>(); private final HashMap filteredAbilityTypes = new HashMap<>(); - - // Display name to typeId mapping for the available types scroll private final HashMap displayNameToTypeId = new HashMap<>(); - // NPC's current ability slots - private final List npcSlots = new ArrayList<>(); + // ── NPC slot data ───────────────────────────────────────────────────────── + private final List npcSlots = new ArrayList<>(); + private final List rowMapping = new ArrayList<>(); // [slotIdx, entryIdx], entryIdx=-1 = header/standalone - // Settings + // ── NPC settings ────────────────────────────────────────────────────────── private boolean abilitiesEnabled = false; private int minCooldown = 20; private int maxCooldown = 60; + // ── Selection state ─────────────────────────────────────────────────────── private String search = ""; private int selectedAbilityIndex = -1; + private int selectedSlotIndex = -1; + private int selectedEntryIndex = -1; - // Existing preset names for duplicate checking + // ── Pending: chain editing ──────────────────────────────────────────────── + private ChainedAbility pendingChain = null; + private int pendingChainSlotIdx = -1; + + // ── Pending: inline chain-entry editing ────────────────────────────────── + private boolean editingChainEntry = false; + private int editChainSlotIdx = -1; + private int editChainEntryIdx = -1; + private boolean editingChainEntryParent = false; + + // ── Pending: save-as-preset ─────────────────────────────────────────────── + private int pendingSaveSlotIdx = -1; + private int pendingSaveEntryIdx = -1; // -1 for standalone ability private final Set existingPresetNames = new HashSet<>(); - // Pending variant selection + // ── Pending: variant selection ──────────────────────────────────────────── private String pendingTypeId = null; + // ── Static view state (persists across GUI opens) ───────────────────────── public static int modIndex = 0; public static ScrollType scrollType = ScrollType.CNPC; @@ -83,7 +137,8 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public String toString() { switch (this) { - case CNPC: return "CustomNPCs"; + case CNPC: + return "CustomNPCs"; case MODDED: if (Register.isEmpty("ability")) return "modded"; @@ -91,8 +146,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC 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(); + case ALL: + return "filter.all"; + default: + return name(); } } } @@ -103,17 +160,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC int y = guiTop + 10; - addButton(new GuiNpcButton(50, guiLeft + 5, y, 140, 20, scrollType.toString())); + addButton(new GuiNpcButton(BTN_SCROLL_TYPE, guiLeft + 5, y, 140, 20, scrollType.toString())); // Cooldown range: Min Cooldown and Max Cooldown (spaced apart more) - addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 210, y + 5)); - GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 260, y, 40, 20, "" + minCooldown); + addLabel(new GuiNpcLabel(LBL_MIN_COOLDOWN, "ability.minCooldown", guiLeft + 210, y + 5)); + GuiNpcTextField minField = new GuiNpcTextField(TF_MIN_COOLDOWN, this, fontRendererObj, guiLeft + 260, y, 40, 20, "" + minCooldown); minField.setIntegersOnly(); minField.setMinMaxDefault(0, 10000, 20); addTextField(minField); - addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 320, y + 5)); - GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 370, y, 40, 20, "" + maxCooldown); + addLabel(new GuiNpcLabel(LBL_MAX_COOLDOWN, "ability.maxCooldown", guiLeft + 320, y + 5)); + GuiNpcTextField maxField = new GuiNpcTextField(TF_MAX_COOLDOWN, this, fontRendererObj, guiLeft + 370, y, 40, 20, "" + maxCooldown); maxField.setIntegersOnly(); maxField.setMinMaxDefault(0, 10000, 60); addTextField(maxField); @@ -121,27 +178,27 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC 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; + addButton(new GuiNpcButton(BTN_ENABLED, guiLeft + 334, y + 145, 76, 20, new String[]{"gui.disabled", "gui.enabled"}, abilitiesEnabled ? 1 : 0)); + getButton(BTN_ENABLED).packedFGColour = abilitiesEnabled ? 0x00FF00 : 0xFF0000; // Left scroll: available ability types - addLabel(new GuiNpcLabel(1, "ability.availableTypes", guiLeft + 5, y)); + addLabel(new GuiNpcLabel(LBL_TYPES, "ability.availableTypes", guiLeft + 5, y)); if (availableTypesScroll == null) { - availableTypesScroll = new GuiCustomScroll(this, 0); + availableTypesScroll = new GuiCustomScroll(this, SCROLL_TYPES); availableTypesScroll.setSize(140, 130); } availableTypesScroll.guiLeft = guiLeft + 5; availableTypesScroll.guiTop = y + 12; - availableTypesScroll.setList(getFilteredTypeList()); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); addScroll(availableTypesScroll); // Search bar for types - addTextField(new GuiNpcTextField(4, this, fontRendererObj, guiLeft + 5, y + 145, 140, 18, search)); + addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 5, y + 145, 140, 18, search)); // Right scroll: NPC's abilities (widened to use available space) - addLabel(new GuiNpcLabel(2, "ability.npcAbilities", guiLeft + 210, y)); + addLabel(new GuiNpcLabel(LBL_NPC, "ability.npcAbilities", guiLeft + 210, y)); if (npcAbilitiesScroll == null) { - npcAbilitiesScroll = new GuiCustomScroll(this, 1); + npcAbilitiesScroll = new GuiCustomScroll(this, SCROLL_NPC); npcAbilitiesScroll.setSize(200, 130); } else { npcAbilitiesScroll.setSize(200, 130); @@ -153,34 +210,76 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Center buttons: Add/Remove int centerX = guiLeft + 158; - 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); + addButton(new GuiNpcButton(BTN_ADD_ABILITY, centerX, y + 15, 40, 20, ">>>")); // Add + addButton(new GuiNpcButton(BTN_REMOVE, centerX, y + 37, 40, 20, "<<<")); // Remove + getButton(BTN_REMOVE).setEnabled(selectedAbilityIndex >= 0); // Load button (under the add/remove arrows) - addButton(new GuiNpcButton(75, centerX, y + 60, 40, 20, "gui.load")); + addButton(new GuiNpcButton(BTN_LOAD, centerX, y + 60, 40, 20, "gui.load")); - // On/Off toggle for selected ability (under Load button) - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - Ability selectedAbility = npcSlots.get(selectedAbilityIndex).getAbility(); - GuiNpcButton toggleBtn = new GuiNpcButton(77, centerX, y + 112, 40, 20, - new String[]{"gui.off", "gui.on"}, selectedAbility.isEnabled() ? 1 : 0); + // On/Off toggle for selected slot (under Load button) — chains and abilities + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size() && selectedEntryIndex == -1) { + AbilityAction selectedSlot = npcSlots.get(selectedSlotIndex); + boolean isEnabled = selectedSlot.isSlotEnabled(); + GuiNpcButton toggleBtn = new GuiNpcButton(BTN_TOGGLE_SLOT, centerX, y + 112, 40, 20, + new String[]{"gui.off", "gui.on"}, isEnabled ? 1 : 0); addButton(toggleBtn); } + // Check if selected slot is editable + boolean selectedIsBuiltIn = false; + boolean selectedIsChainEntry = selectedEntryIndex >= 0; + boolean selectedIsRefChainEntry = false; + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size()) { + AbilityAction sel = npcSlots.get(selectedSlotIndex); + if (!selectedIsChainEntry && !sel.isChain()) { + Ability a = sel.getAbility(); + if (a != null && a.isBuiltIn()) selectedIsBuiltIn = true; + } + // Chain entries referencing built-in abilities are not editable + if (selectedIsChainEntry && sel.isChain()) { + ChainedAbility biChain = sel.isInlineChain() ? sel.getInlineChain() : sel.getChainedAbility(); + if (biChain != null && selectedEntryIndex < biChain.getEntries().size()) { + Ability resolved = biChain.getEntries().get(selectedEntryIndex).resolve(); + if (resolved != null && resolved.isBuiltIn()) selectedIsBuiltIn = true; + } + } + // Sub-entries of reference chains are not directly editable from the NPC list + if (selectedIsChainEntry && sel.isChainReference()) { + selectedIsRefChainEntry = 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); + addButton(new GuiNpcButton(BTN_EDIT, guiLeft + 210, y + 145, 55, 20, "gui.edit")); + getButton(BTN_EDIT).setEnabled(selectedSlotIndex >= 0 && !selectedIsBuiltIn && !selectedIsRefChainEntry); // Up/Down carrot buttons - addButton(new GuiNpcButton(73, guiLeft + 270, y + 145, 20, 20, "<")); - addButton(new GuiNpcButton(74, guiLeft + 292, y + 145, 20, 20, ">")); - getButton(73).setEnabled(selectedAbilityIndex > 0); - getButton(74).setEnabled(selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1); + addButton(new GuiNpcButton(BTN_MOVE_UP, guiLeft + 270, y + 145, 20, 20, "<")); + addButton(new GuiNpcButton(BTN_MOVE_DOWN, guiLeft + 292, y + 145, 20, 20, ">")); + getButton(BTN_MOVE_UP).setEnabled(selectedSlotIndex > 0 && selectedEntryIndex == -1); + getButton(BTN_MOVE_DOWN).setEnabled(selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size() - 1 && selectedEntryIndex == -1); - // Save button (to the right of carrots, only enabled when ability is selected) - addButton(new GuiNpcButton(76, centerX, y + 82, 40, 20, "gui.save")); - getButton(76).setEnabled(selectedAbilityIndex >= 0); + // Save button — enabled for inline abilities (standalone or chain entry), disabled for references/chains + addButton(new GuiNpcButton(BTN_SAVE_PRESET, centerX, y + 82, 40, 20, "gui.save")); + boolean canSave = false; + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size() && !selectedIsBuiltIn) { + AbilityAction saveSlot = npcSlots.get(selectedSlotIndex); + if (selectedEntryIndex >= 0) { + // Chain entry: only inline entries can be saved + ChainedAbility saveChain = saveSlot.isInlineChain() ? saveSlot.getInlineChain() : null; + if (saveChain != null && selectedEntryIndex < saveChain.getEntries().size()) { + canSave = saveChain.getEntries().get(selectedEntryIndex).isInline(); + } + } else if (!saveSlot.isChain() && !saveSlot.isReference()) { + // Standalone inline ability + canSave = true; + } + } + getButton(BTN_SAVE_PRESET).setEnabled(canSave); + + // Add Chain button + addButton(new GuiNpcButton(BTN_ADD_CHAIN, centerX, y + 135, 40, 20, "ability.addChain")); } @Override @@ -188,7 +287,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC int id = guibutton.id; // Enabled toggle - if (id == 100) { + if (id == BTN_ENABLED) { abilitiesEnabled = ((GuiNpcButton) guibutton).getValue() == 1; initGui(); save(); @@ -196,7 +295,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } // Add ability - if (id == 70) { + if (id == BTN_ADD_ABILITY) { if (availableTypesScroll.hasSelected()) { String displayName = availableTypesScroll.getSelected(); String typeId = displayNameToTypeId.get(displayName); @@ -213,7 +312,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC variants.get(0).apply(newAbility); } newAbility.setId(UUID.randomUUID().toString()); - npcSlots.add(AbilitySlot.inline(newAbility)); + npcSlots.add(AbilityAction.inline(newAbility)); selectedAbilityIndex = npcSlots.size() - 1; updateNpcAbilitiesList(); selectAbilityByIndex(selectedAbilityIndex); @@ -225,11 +324,23 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC return; } - // Remove ability - if (id == 71) { - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - npcSlots.remove(selectedAbilityIndex); + // Remove slot or chain entry + if (id == BTN_REMOVE) { + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size()) { + if (selectedEntryIndex >= 0) { + // Remove entry from chain — not the whole slot + AbilityAction slot = npcSlots.get(selectedSlotIndex); + ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : null; + if (chain != null && selectedEntryIndex < chain.getEntries().size()) { + chain.removeEntry(selectedEntryIndex); + } + } else { + npcSlots.remove(selectedSlotIndex); + } + selectedSlotIndex = -1; + selectedEntryIndex = -1; selectedAbilityIndex = -1; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); updateNpcAbilitiesList(); initGui(); save(); @@ -237,16 +348,55 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC return; } - // Edit ability - if (id == 72) { - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - AbilitySlot slot = npcSlots.get(selectedAbilityIndex); - if (slot.isReference()) { - // Reference slot - ask clone-and-modify vs modify-parent + // Edit ability or chain + if (id == BTN_EDIT) { + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size()) { + AbilityAction slot = npcSlots.get(selectedSlotIndex); + + if (slot.isChain() && selectedEntryIndex == -1) { + // Chain header selected + if (slot.isChainReference()) { + // Reference chain — offer Clone & Modify / Edit Parent + setSubGui(new SubGuiAbilityEditMode()); + } else { + // Inline chain — open chain config directly + ChainedAbility chain = slot.getInlineChain(); + if (chain != null) { + pendingChain = chain; + pendingChainSlotIdx = selectedSlotIndex; + setSubGui(new SubGuiChainedAbilityConfig(chain, this, true, npcSlots)); + } + } + } else if (slot.isChain() && selectedEntryIndex >= 0) { + // Chain entry selected + ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); + if (chain != null && selectedEntryIndex < chain.getEntries().size()) { + ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); + // Built-in abilities are always references — no editing allowed + Ability resolvedEntry = entry.resolve(); + if (resolvedEntry != null && resolvedEntry.isBuiltIn()) return; + + if (entry.isInline() && slot.isInlineChain()) { + // Inline entry in inline chain — edit directly + Ability a = entry.getInlineAbility(); + if (a != null) { + editingChainEntry = true; + editChainSlotIdx = selectedSlotIndex; + editChainEntryIdx = selectedEntryIndex; + a.setNpcInlineEdit(true); + setSubGui(a.createConfigGui(this)); + } + } else { + // Reference entry or entry in reference chain — Clone & Modify / Edit Parent + setSubGui(new SubGuiAbilityEditMode()); + } + } + } else if (slot.isReference()) { setSubGui(new SubGuiAbilityEditMode()); } else { Ability ability = slot.getAbility(); if (ability != null) { + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } } @@ -255,14 +405,14 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } // Move up (carrot left = earlier in list) - if (id == 73) { - if (selectedAbilityIndex > 0) { - AbilitySlot temp = npcSlots.get(selectedAbilityIndex); - npcSlots.set(selectedAbilityIndex, npcSlots.get(selectedAbilityIndex - 1)); - npcSlots.set(selectedAbilityIndex - 1, temp); - selectedAbilityIndex--; + if (id == BTN_MOVE_UP) { + if (selectedSlotIndex > 0 && selectedEntryIndex == -1) { + AbilityAction temp = npcSlots.get(selectedSlotIndex); + npcSlots.set(selectedSlotIndex, npcSlots.get(selectedSlotIndex - 1)); + npcSlots.set(selectedSlotIndex - 1, temp); + selectedSlotIndex--; + selectedAbilityIndex = selectedSlotIndex; updateNpcAbilitiesList(); - selectAbilityByIndex(selectedAbilityIndex); initGui(); save(); } @@ -270,32 +420,56 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } // Move down (carrot right = later in list) - if (id == 74) { - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1) { - AbilitySlot temp = npcSlots.get(selectedAbilityIndex); - npcSlots.set(selectedAbilityIndex, npcSlots.get(selectedAbilityIndex + 1)); - npcSlots.set(selectedAbilityIndex + 1, temp); - selectedAbilityIndex++; + if (id == BTN_MOVE_DOWN) { + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size() - 1 && selectedEntryIndex == -1) { + AbilityAction temp = npcSlots.get(selectedSlotIndex); + npcSlots.set(selectedSlotIndex, npcSlots.get(selectedSlotIndex + 1)); + npcSlots.set(selectedSlotIndex + 1, temp); + selectedSlotIndex++; + selectedAbilityIndex = selectedSlotIndex; updateNpcAbilitiesList(); - selectAbilityByIndex(selectedAbilityIndex); initGui(); save(); } return; } - // Load ability (opens load dialog to add ability directly to NPC) - if (id == 75) { - setSubGui(new SubGuiAbilityLoad(this)); + // Load ability or chain (opens type choice first) + if (id == BTN_LOAD) { + setSubGui(new SubGuiLoadTypeChoice()); return; } - // Save selected ability as custom preset - if (id == 76) { - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - Ability abilityToSave = npcSlots.get(selectedAbilityIndex).getAbility(); - if (abilityToSave != null) { + // Save selected ability as custom preset (converts inline → reference) + if (id == BTN_SAVE_PRESET) { + Ability abilityToSave = null; + pendingSaveSlotIdx = -1; + pendingSaveEntryIdx = -1; + + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size()) { + AbilityAction saveSlot = npcSlots.get(selectedSlotIndex); + + if (selectedEntryIndex >= 0) { + // Saving a chain entry's inline ability + ChainedAbility chain = saveSlot.isInlineChain() ? saveSlot.getInlineChain() : null; + if (chain != null && selectedEntryIndex < chain.getEntries().size()) { + ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); + if (entry.isInline()) { + abilityToSave = entry.getInlineAbility(); + pendingSaveSlotIdx = selectedSlotIndex; + pendingSaveEntryIdx = selectedEntryIndex; + } + } + } else if (!saveSlot.isChain() && !saveSlot.isReference()) { + // Saving a standalone inline ability + abilityToSave = saveSlot.getAbility(); + pendingSaveSlotIdx = selectedSlotIndex; + pendingSaveEntryIdx = -1; + } + + if (abilityToSave != null && !abilityToSave.isBuiltIn()) { if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) { + abilityToSave.setNpcInlineEdit(true); setSubGui(abilityToSave.createConfigGui(this)); } else { setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave, null, existingPresetNames)); @@ -305,22 +479,31 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC return; } - // Toggle selected ability on/off - if (id == 77) { - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - Ability ability = npcSlots.get(selectedAbilityIndex).getAbility(); - if (ability != null) { - ability.setEnabled(((GuiNpcButton) guibutton).getValue() == 1); - updateNpcAbilitiesList(); - selectAbilityByIndex(selectedAbilityIndex); - initGui(); - save(); - } + // Toggle selected slot on/off + if (id == BTN_TOGGLE_SLOT) { + if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size()) { + AbilityAction slot = npcSlots.get(selectedSlotIndex); + boolean enabled = ((GuiNpcButton) guibutton).getValue() == 1; + slot.setEnabled(enabled); + updateNpcAbilitiesList(); + initGui(); + save(); } return; } - if (id == 50) { + // Add Chain button + if (id == BTN_ADD_CHAIN) { + ChainedAbility newChain = new ChainedAbility(); + newChain.setId(UUID.randomUUID().toString()); + newChain.setName("NewChain"); + pendingChain = newChain; + pendingChainSlotIdx = -1; + setSubGui(new SubGuiChainedAbilityConfig(newChain, this, true, npcSlots)); + return; + } + + if (id == BTN_SCROLL_TYPE) { if (scrollType != ScrollType.MODDED) { ScrollType[] values = ScrollType.values(); ScrollType next = values[(scrollType.ordinal() + 1) % values.length]; @@ -365,7 +548,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC filteredAbilityTypes.putAll(getFilteredData(allAbilityTypes)); if (availableTypesScroll != null) { - availableTypesScroll.setList(getFilteredTypeList()); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); } } else if (type == EnumScrollData.CUSTOM_ABILITIES) { existingPresetNames.clear(); @@ -386,7 +569,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Only process NPC ability data, not saved ability preset data // SubGuiAbilityLoad also implements IGuiData and may receive responses // that get forwarded here - ignore those by checking for expected keys - if (!compound.hasKey("Abilities")) { + if (!compound.hasKey("AbilityActions") && !compound.hasKey("Abilities")) { return; } @@ -400,10 +583,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } npcSlots.clear(); - NBTTagList abilityList = compound.getTagList("Abilities", 10); - for (int i = 0; i < abilityList.tagCount(); i++) { - NBTTagCompound abilityNBT = abilityList.getCompoundTagAt(i); - AbilitySlot slot = AbilitySlot.fromNBT(abilityNBT); + // Support both new unified format and legacy format + String tagName = compound.hasKey("AbilityActions") ? "AbilityActions" : "Abilities"; + NBTTagList actionList = compound.getTagList(tagName, 10); + for (int i = 0; i < actionList.tagCount(); i++) { + NBTTagCompound slotNBT = actionList.getCompoundTagAt(i); + AbilityAction slot = AbilityAction.fromNBT(slotNBT); if (slot != null) { npcSlots.add(slot); } @@ -423,11 +608,11 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void keyTyped(char c, int i) { super.keyTyped(c, i); - if (getTextField(4) != null && getTextField(4).isFocused()) { - if (search.equals(getTextField(4).getText())) + if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) { + if (search.equals(getTextField(TF_SEARCH).getText())) return; - search = getTextField(4).getText().toLowerCase(); - availableTypesScroll.setList(getFilteredTypeList()); + search = getTextField(TF_SEARCH).getText().toLowerCase(); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); availableTypesScroll.resetScroll(); } } @@ -462,22 +647,74 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC displayNameToTypeId.clear(); for (String typeId : filteredAbilityTypes.keySet()) { 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)) { + // Search matches either the display name or the typeId (strip color codes for matching) + String stripped = displayName.replaceAll("\u00A7.", ""); + if (search.isEmpty() || stripped.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) { + // Pink for custom ability, light blue for concurrent-capable types, gray for other built-in types + if (typeId.equals("ability.cnpc.custom")) { + displayName = "\u00A7d" + displayName; + } else if (AbilityController.Instance.isConcurrentCapableType(typeId)) { + displayName = "\u00A7b" + displayName; + } else if (AbilityController.Instance.isBuiltInType(typeId)) { + displayName = "\u00A77" + displayName; + } list.add(displayName); displayNameToTypeId.put(displayName, typeId); } } + Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare( + a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", ""))); + + // Pin Custom Ability to top of list + String customEntry = null; + for (String name : list) { + String tid = displayNameToTypeId.get(name); + if (tid != null && tid.equals("ability.cnpc.custom")) { + customEntry = name; + break; + } + } + if (customEntry != null) { + list.remove(customEntry); + list.add(0, customEntry); + } + return list; } private void updateNpcAbilitiesList() { List list = new ArrayList<>(); + rowMapping.clear(); + for (int i = 0; i < npcSlots.size(); i++) { - list.add(getAbilityListEntry(i)); + AbilityAction slot = npcSlots.get(i); + + if (slot.isChain()) { + // Chain header row + list.add(getChainHeaderEntry(i, slot)); + rowMapping.add(new int[]{i, -1}); + + // Chain entry rows + ChainedAbility chain = slot.getChainedAbility(); + if (chain == null && slot.isInlineChain()) { + chain = slot.getInlineChain(); + } + if (chain != null) { + for (int e = 0; e < chain.getEntries().size(); e++) { + ChainedAbilityEntry entry = chain.getEntries().get(e); + list.add(getChainEntryDisplay(entry, e)); + rowMapping.add(new int[]{i, e}); + } + } + } else { + // Regular ability row + list.add(getAbilityListEntry(i)); + rowMapping.add(new int[]{i, -1}); + } } + if (npcAbilitiesScroll != null) { - npcAbilitiesScroll.setList(list); + npcAbilitiesScroll.setUnsortedList(list); } } @@ -488,11 +725,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC * Broken: "[●] 1. > [Missing: id...]" in red */ private String getAbilityListEntry(int index) { - AbilitySlot slot = npcSlots.get(index); + AbilityAction slot = npcSlots.get(index); Ability ability = slot.getAbility(); if (ability == null) { - // Broken reference String refId = slot.getReferenceId(); String shortId = refId != null && refId.length() > 8 ? refId.substring(0, 8) + "..." : refId; return "\u00A7c\u25CF\u00A7r " + (index + 1) + ". \u00A7c> [Missing: " + shortId + "]\u00A7r"; @@ -500,7 +736,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String typeName = getDisplayName(ability.getTypeId()); String customName = ability.getName(); - String colorPrefix = ability.isEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; + String colorPrefix = slot.isSlotEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; String nameDisplay; if (customName != null && !customName.isEmpty() && !customName.equals(typeName)) { @@ -512,9 +748,38 @@ 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; } + private String getChainHeaderEntry(int index, AbilityAction slot) { + ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); + String chainName = chain != null ? chain.getDisplayName() : "???"; + String colorPrefix = slot.isSlotEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; + if (slot.isChainReference()) { + return colorPrefix + (index + 1) + ". \u00A7e> [Chain] " + chainName + "\u00A7r"; + } + return colorPrefix + (index + 1) + ". \u00A7d[Chain] \u00A7r" + chainName; + } + + private String getChainEntryDisplay(ChainedAbilityEntry entry, int entryIndex) { + if (entry.isInline()) { + Ability a = entry.getInlineAbility(); + String name = a != null ? a.getDisplayName() : "???"; + return " \u00A78--- \u00A7r" + name; + } else { + String name = entry.getAbilityReference(); + if (name == null || name.isEmpty()) name = "???"; + Ability resolved = entry.resolve(); + if (resolved != null) { + name = resolved.getDisplayName(); + } + return " \u00A78--- \u00A7e> " + name + "\u00A7r"; + } + } + private void selectAbilityByIndex(int index) { if (index >= 0 && index < npcSlots.size()) { String entry = getAbilityListEntry(index); @@ -538,11 +803,11 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC compound.setInteger("AbilityMinCooldown", minCooldown); compound.setInteger("AbilityMaxCooldown", maxCooldown); - NBTTagList abilityList = new NBTTagList(); - for (AbilitySlot slot : npcSlots) { - abilityList.appendTag(slot.writeNBT()); + NBTTagList actionList = new NBTTagList(); + for (AbilityAction slot : npcSlots) { + actionList.appendTag(slot.writeNBT(false)); } - compound.setTag("Abilities", abilityList); + compound.setTag("AbilityActions", actionList); PacketClient.sendClient(new AbilitiesNpcSavePacket(compound)); } @@ -552,14 +817,27 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC * Adds as an inline slot. */ public void loadAbility(Ability loadedAbility) { + loadAbility(loadedAbility, null); + } + + /** + * Called from SubGuiAbilityLoad when a cloned ability is loaded with a known source. + * Copies scripts server-side from source to the new inline ability. + */ + public void loadAbility(Ability loadedAbility, String sourceAbilityName) { if (loadedAbility != null) { loadedAbility.setId(UUID.randomUUID().toString()); - npcSlots.add(AbilitySlot.inline(loadedAbility)); + npcSlots.add(AbilityAction.inline(loadedAbility)); selectedAbilityIndex = npcSlots.size() - 1; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); updateNpcAbilitiesList(); selectAbilityByIndex(selectedAbilityIndex); initGui(); save(); + // Copy scripts from source ability server-side (scripts are never sent to client) + if (sourceAbilityName != null && !sourceAbilityName.isEmpty()) { + PacketClient.sendClient(new CopyAbilityScriptsPacket(sourceAbilityName, loadedAbility.getId())); + } } } @@ -569,8 +847,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC */ public void loadAbilityReference(String referenceId) { if (referenceId != null && !referenceId.isEmpty()) { - npcSlots.add(AbilitySlot.reference(referenceId)); + npcSlots.add(AbilityAction.abilityReference(referenceId)); selectedAbilityIndex = npcSlots.size() - 1; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); updateNpcAbilitiesList(); selectAbilityByIndex(selectedAbilityIndex); initGui(); @@ -588,21 +867,16 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { if (guiCustomScroll == npcAbilitiesScroll) { - String selected = npcAbilitiesScroll.getSelected(); - if (selected != null) { - // Parse index from "[●] 1. Name" format - strip color codes first - String stripped = selected.replaceAll("\u00A7.", "").trim(); - // Now format is "● 1. Name" - find the number after the circle - int dotIndex = stripped.indexOf("."); - if (dotIndex > 0) { - try { - // Extract just the number portion (skip "● " prefix) - String numPart = stripped.substring(0, dotIndex).replaceAll("[^0-9]", ""); - selectedAbilityIndex = Integer.parseInt(numPart) - 1; - } catch (NumberFormatException e) { - selectedAbilityIndex = -1; - } - } + int scrollIndex = npcAbilitiesScroll.selected; + if (scrollIndex >= 0 && scrollIndex < rowMapping.size()) { + int[] mapping = rowMapping.get(scrollIndex); + selectedSlotIndex = mapping[0]; + selectedEntryIndex = mapping[1]; + selectedAbilityIndex = selectedSlotIndex; + } else { + selectedSlotIndex = -1; + selectedEntryIndex = -1; + selectedAbilityIndex = -1; } initGui(); } @@ -610,22 +884,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { - if (scroll == npcAbilitiesScroll && selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - AbilitySlot slot = npcSlots.get(selectedAbilityIndex); - if (slot.isReference()) { - setSubGui(new SubGuiAbilityEditMode()); - } else { - Ability ability = slot.getAbility(); - if (ability != null) { - setSubGui(ability.createConfigGui(this)); - } + if (scroll == npcAbilitiesScroll && selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size()) { + GuiNpcButton editBtn = getButton(BTN_EDIT); + if (editBtn != null && editBtn.enabled) { + buttonEvent(new GuiNpcButton(BTN_EDIT, 0, 0, 0, 0, "")); } } } @Override public void unFocused(GuiNpcTextField textField) { - if (textField.id == 101) { + if (textField.id == TF_MIN_COOLDOWN) { minCooldown = textField.getInteger(); // Ensure min <= max if (minCooldown > maxCooldown) { @@ -633,7 +902,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC initGui(); } save(); - } else if (textField.id == 102) { + } else if (textField.id == TF_MAX_COOLDOWN) { maxCooldown = textField.getInteger(); // Ensure min <= max if (maxCooldown < minCooldown) { @@ -647,67 +916,299 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void subGuiClosed(SubGuiInterface subgui) { 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; + handleVariantSelectClosed((SubGuiAbilityVariantSelect) subgui); + initGui(); + return; + } + if (subgui instanceof SubGuiChainedAbilityConfig) { + handleChainConfigClosed(); + initGui(); + return; + } + if (subgui instanceof SubGuiAbilityEditMode) { + handleEditModeClosed((SubGuiAbilityEditMode) subgui); + return; + } + if (subgui instanceof SubGuiAbilitySaveConfirm) { + handleSaveConfirmClosed((SubGuiAbilitySaveConfirm) subgui); + initGui(); + return; + } + if (subgui instanceof SubGuiLoadTypeChoice) { + handleLoadTypeChoiceClosed((SubGuiLoadTypeChoice) subgui); + return; + } + if (subgui instanceof SubGuiChainSelect) { + handleChainSelectClosed((SubGuiChainSelect) subgui); + return; + } + if (subgui instanceof SubGuiAbilityConfig) { + handleAbilityConfigClosed(); + return; + } + } + + private void handleVariantSelectClosed(SubGuiAbilityVariantSelect gui) { + int idx = gui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + gui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + npcSlots.add(AbilityAction.inline(newAbility)); + selectedAbilityIndex = npcSlots.size() - 1; + selectedSlotIndex = selectedAbilityIndex; + selectedEntryIndex = -1; + updateNpcAbilitiesList(); + save(); + } + } + pendingTypeId = null; + } + + private void handleChainConfigClosed() { + if (pendingChain != null) { + if (pendingChainSlotIdx < 0) { + // New chain — add to NPC slots + npcSlots.add(AbilityAction.inlineChain(pendingChain)); + selectedSlotIndex = npcSlots.size() - 1; + selectedEntryIndex = -1; + selectedAbilityIndex = selectedSlotIndex; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); + } + // Existing slot (pendingChainSlotIdx >= 0): already updated in-place, nothing to add + pendingChain = null; + pendingChainSlotIdx = -1; + } + updateNpcAbilitiesList(); + save(); + } + + private void handleEditModeClosed(SubGuiAbilityEditMode gui) { + int mode = gui.getResult(); + if (mode < 0) return; // cancelled + + if (selectedSlotIndex < 0 || selectedSlotIndex >= npcSlots.size()) return; + AbilityAction slot = npcSlots.get(selectedSlotIndex); + + if (slot.isChain() && selectedEntryIndex == -1) { + // Chain header (must be CHAIN_REFERENCE) + if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { + String sourceChainName = slot.getReferenceId(); + if (slot.convertToInline()) { + ChainedAbility chain = slot.getInlineChain(); + if (chain != null) { + pendingChain = chain; + pendingChainSlotIdx = selectedSlotIndex; + setSubGui(new SubGuiChainedAbilityConfig(chain, this, true, npcSlots)); + // Copy chain scripts server-side (client never has script handlers) + if (sourceChainName != null && !sourceChainName.isEmpty()) { + PacketClient.sendClient(new CopyAbilityScriptsPacket( + CopyAbilityScriptsPacket.MODE_CHAINED, sourceChainName, chain.getId())); + } + } updateNpcAbilitiesList(); - selectAbilityByIndex(selectedAbilityIndex); save(); } + } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { + ChainedAbility chain = slot.getChainedAbility(); + if (chain != null) { + pendingChain = chain; + pendingChainSlotIdx = selectedSlotIndex; + setSubGui(new SubGuiChainedAbilityConfig(chain, this, true, npcSlots)); + } + } + } else if (slot.isChain() && selectedEntryIndex >= 0) { + // Chain entry reference + // Block all editing for built-in abilities + ChainedAbility resolveChain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); + if (resolveChain != null && selectedEntryIndex < resolveChain.getEntries().size()) { + Ability entryResolved = resolveChain.getEntries().get(selectedEntryIndex).resolve(); + if (entryResolved != null && entryResolved.isBuiltIn()) return; } - pendingTypeId = null; - initGui(); - } else if (subgui instanceof SubGuiAbilityEditMode) { - int mode = ((SubGuiAbilityEditMode) subgui).getResult(); - if (mode < 0) return; // cancelled - if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - AbilitySlot slot = npcSlots.get(selectedAbilityIndex); - if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { - // Convert reference to inline, then edit - if (slot.convertToInline()) { - Ability ability = slot.getAbility(); - if (ability != null) { - ability.setId(UUID.randomUUID().toString()); - setSubGui(ability.createConfigGui(this)); + if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { + if (slot.isChainReference()) { + slot.convertToInline(); + } + ChainedAbility chain = slot.getInlineChain(); + if (chain != null && selectedEntryIndex < chain.getEntries().size()) { + ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); + // Capture source ability reference before convertToInline clears it + String sourceAbilityRef = entry.getAbilityReference(); + if (entry.convertToInline()) { + Ability a = entry.getInlineAbility(); + if (a != null && !a.isBuiltIn()) { + editingChainEntry = true; + editChainSlotIdx = selectedSlotIndex; + editChainEntryIdx = selectedEntryIndex; + a.setNpcInlineEdit(true); + setSubGui(a.createConfigGui(this)); + // Copy ability scripts server-side (client never has script handlers) + if (sourceAbilityRef != null && !sourceAbilityRef.isEmpty()) { + PacketClient.sendClient(new CopyAbilityScriptsPacket(sourceAbilityRef, a.getId())); + } } - updateNpcAbilitiesList(); - save(); } - } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { - // Edit the resolved ability directly (changes propagate to controller) - Ability ability = slot.getAbility(); - if (ability != null) { - setSubGui(ability.createConfigGui(this)); + } + updateNpcAbilitiesList(); + save(); + } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { + ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); + if (chain != null && selectedEntryIndex < chain.getEntries().size()) { + ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); + Ability resolved = entry.resolve(); + if (resolved != null && !resolved.isBuiltIn()) { + editingChainEntryParent = true; + setSubGui(resolved.createConfigGui(this)); } } } - } else if (subgui instanceof SubGuiAbilityConfig) { + } else if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { + // Standalone ability reference → convert to inline + Ability preCheck = slot.getAbility(); + if (preCheck != null && preCheck.isBuiltIn()) return; + // Capture source reference before convertToInline clears it + String sourceAbilityRef = slot.getReferenceId(); + if (slot.convertToInline()) { + Ability ability = slot.getAbility(); + if (ability != null && !ability.isBuiltIn()) { + // UUID already generated by convertToInline() - don't reassign or script handler is orphaned + ability.setNpcInlineEdit(true); + setSubGui(ability.createConfigGui(this)); + // Copy ability scripts server-side (client never has script handlers) + if (sourceAbilityRef != null && !sourceAbilityRef.isEmpty()) { + PacketClient.sendClient(new CopyAbilityScriptsPacket(sourceAbilityRef, ability.getId())); + } + } + updateNpcAbilitiesList(); + save(); + } + } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { + Ability ability = slot.getAbility(); + if (ability != null && !ability.isBuiltIn()) { + setSubGui(ability.createConfigGui(this)); + } + } + } + + private void handleSaveConfirmClosed(SubGuiAbilitySaveConfirm gui) { + if (gui.wasSaved() && pendingSaveSlotIdx >= 0 && pendingSaveSlotIdx < npcSlots.size()) { + if (pendingSaveEntryIdx >= 0) { + // Chain entry: convert inline entry to reference + AbilityAction slot = npcSlots.get(pendingSaveSlotIdx); + ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : null; + if (chain != null && pendingSaveEntryIdx < chain.getEntries().size()) { + ChainedAbilityEntry entry = chain.getEntries().get(pendingSaveEntryIdx); + Ability a = entry.getInlineAbility(); + if (a != null && a.getName() != null && !a.getName().isEmpty()) { + chain.getEntries().set(pendingSaveEntryIdx, + ChainedAbilityEntry.reference(a.getName(), entry.getDelayTicks())); + } + } + } else { + // Standalone: convert inline slot to reference + AbilityAction slot = npcSlots.get(pendingSaveSlotIdx); + Ability a = slot.getAbility(); + if (a != null && a.getName() != null && !a.getName().isEmpty()) { + npcSlots.set(pendingSaveSlotIdx, AbilityAction.abilityReference(a.getName())); + } + } + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); updateNpcAbilitiesList(); save(); } + pendingSaveSlotIdx = -1; + pendingSaveEntryIdx = -1; + } + + private void handleLoadTypeChoiceClosed(SubGuiLoadTypeChoice gui) { + int result = gui.getResult(); + if (result == SubGuiLoadTypeChoice.RESULT_ABILITY) { + setSubGui(new SubGuiAbilityLoad(this)); + } else if (result == SubGuiLoadTypeChoice.RESULT_CHAIN) { + setSubGui(new SubGuiChainSelect()); + } + } + + private void handleChainSelectClosed(SubGuiChainSelect gui) { + String chainName = gui.getSelectedName(); + if (chainName != null) { + loadChainReference(chainName); + } + } + + private void handleAbilityConfigClosed() { + editingChainEntry = false; + editChainSlotIdx = -1; + editChainEntryIdx = -1; + editingChainEntryParent = false; + updateNpcAbilitiesList(); + save(); } /** * Called from SubGuiAbilityConfig when ability is saved. */ public void onAbilitySaved(Ability ability) { + // Editing a global parent ability via "Modify Parent" on a chain entry + if (editingChainEntryParent) { + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); + return; + } + + // Editing an ability inside a chain entry — already same object reference. + // handleAbilityConfigClosed() will call updateNpcAbilitiesList() + save(). + if (editingChainEntry) { + return; + } + if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - AbilitySlot slot = npcSlots.get(selectedAbilityIndex); + AbilityAction slot = npcSlots.get(selectedAbilityIndex); if (slot.isReference()) { - // For reference slots, save back to controller - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + // Modify Parent on standalone reference — save to global preset + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); } else { - // For inline slots, replace with the updated ability - npcSlots.set(selectedAbilityIndex, AbilitySlot.inline(ability)); + // Inline ability — update slot data + npcSlots.set(selectedAbilityIndex, AbilityAction.inline(ability)); } + } + // updateNpcAbilitiesList() + save() deferred to handleAbilityConfigClosed() + } + + @Override + public void onChainedAbilitySaved(ChainedAbility chain) { + // Handled in subGuiClosed — pendingChain tracks the chain being edited + } + + /** + * Called from SubGuiAbilityLoad when a chain reference is loaded. + */ + public void loadChainReference(String referenceId) { + if (referenceId != null && !referenceId.isEmpty()) { + npcSlots.add(AbilityAction.chainReference(referenceId)); + selectedSlotIndex = npcSlots.size() - 1; + selectedEntryIndex = -1; + selectedAbilityIndex = selectedSlotIndex; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); updateNpcAbilitiesList(); + initGui(); + save(); + } + } + + /** + * Called from SubGuiAbilityLoad to load a chain as inline. + */ + public void loadChainInline(ChainedAbility chain) { + if (chain != null) { + npcSlots.add(AbilityAction.inlineChain(chain)); + selectedSlotIndex = npcSlots.size() - 1; + selectedEntryIndex = -1; + selectedAbilityIndex = selectedSlotIndex; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); + updateNpcAbilitiesList(); + initGui(); save(); } } 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 bcfce7687..6d101d3c4 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -1,12 +1,15 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; -import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.controllers.data.AbilityScript; import net.minecraft.client.gui.GuiButton; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.SubGuiTagSelect; +import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.util.GuiMenuTopButton; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; @@ -20,6 +23,8 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; import java.util.List; +import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS; + public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { private static final int DECLARATIVE_ID_START = 1000; @@ -42,6 +47,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi private static final int L_LABEL_X = 5; private static final int ROW_H = 24; + // Condition buttons + private static final int COND_BASE = 50; + private static final int COND_STRIDE = 10; + private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10 + private static final int BTN_ADD_COND = COND_END; + private final Ability ability; private final IAbilityConfigCallback callback; private int activeTab = TAB_GENERAL; @@ -49,7 +60,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi private List fieldDefs; private List customTabNames; - private List conditions; + private List conditions; private int editingConditionIndex = -1; private AbilityFieldBuilder builder; @@ -75,11 +86,11 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi for (FieldDef def : fieldDefs) { String tab = def.getTab(); if (tab != null - && !TAB_NAME_GENERAL.equals(tab) - && !TAB_NAME_TYPE.equals(tab) - && !TAB_NAME_TARGET.equals(tab) - && !TAB_NAME_EFFECTS.equals(tab) - && !customTabNames.contains(tab)) { + && !TAB_NAME_GENERAL.equals(tab) + && !TAB_NAME_TYPE.equals(tab) + && !TAB_NAME_TARGET.equals(tab) + && !TAB_NAME_EFFECTS.equals(tab) + && !customTabNames.contains(tab)) { customTabNames.add(tab); } } @@ -92,6 +103,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi @Override public void initGui() { + // Commit any focused text field before rebuilding + GuiNpcTextField.unfocus(); + // Save scroll position before super clears scroll windows GuiScrollWindow oldSw = getScrollableGui(0); if (oldSw != null && activeTab < tabScrollY.length) { @@ -132,6 +146,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi GuiMenuTopButton closeBtn = new GuiMenuTopButton(-1000, guiLeft + xSize - 22, guiTop - 17, "X"); addTopButton(closeBtn); + GuiMenuTopButton scriptBtn = new GuiMenuTopButton(-999, "script.scripts", closeBtn); + addTopButton(scriptBtn); + // Build scroll window dimensions int swX = guiLeft + 4; int swY = guiTop + 5; @@ -141,9 +158,15 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi int y = 5; int labelCounter = LABEL_ID_START; - // General tab: type label at top — need to reserve space before building + // General tab: type label + optional info labels at top — reserve space if (activeTab == TAB_GENERAL) { y += ROW_H; + if ("ability.cnpc.custom".equals(ability.getTypeId())) { + y += 15; + } + if (ability.isConcurrentCapable()) { + y += 15; + } } // Build declarative fields into an auto-created scroll window @@ -154,10 +177,26 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); - // General tab: add type label at top of scroll window + // General tab: add type label + optional info labels at top of scroll window if (activeTab == TAB_GENERAL) { - sw.addLabel(new GuiNpcLabel(builder.getNextLabelId(), "gui.type", 5, 5 + 5, 0xFFFFFF)); - sw.addLabel(new GuiNpcLabel(builder.getNextLabelId() + 1, ability.getTypeId(), 55, 5 + 5, 0xFFFFFF)); + int baseId = builder.getNextLabelId(); + int infoY = 25; + sw.addLabel(new GuiNpcLabel(baseId, "gui.type", 5, 10, 0xFFFFFF)); + sw.addLabel(new GuiNpcLabel(baseId + 1, ability.getTypeId(), 55, 10, 0xFFFFFF)); + if ("ability.cnpc.custom".equals(ability.getTypeId())) { + sw.addLabel(new GuiNpcLabel(baseId + 2, + StatCollector.translateToLocal("ability.customScriptInfo"), 5, infoY, 0xFF55FF)); + infoY += 15; + } + if (ability.isConcurrentCapable()) { + sw.addLabel(new GuiNpcLabel(baseId + 3, + StatCollector.translateToLocal("ability.concurrentInfo"), 5, infoY, 0x55FFFF)); + } + } + + // Tags button on general tab + if (activeTab == TAB_GENERAL) { + sw.addButton(new GuiNpcButton(40, sw.clipWidth - 95, 5, 80, 20, "gui.tags")); } // Conditions on target tab — appended after field defs @@ -187,11 +226,21 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } } else { switch (tabIndex) { - case TAB_GENERAL: tabName = TAB_NAME_GENERAL; break; - case TAB_TYPE: tabName = TAB_NAME_TYPE; break; - case TAB_TARGET: tabName = TAB_NAME_TARGET; break; - case TAB_EFFECTS: tabName = TAB_NAME_EFFECTS; break; - default: tabName = TAB_NAME_TYPE; break; + case TAB_GENERAL: + tabName = TAB_NAME_GENERAL; + break; + case TAB_TYPE: + tabName = TAB_NAME_TYPE; + break; + case TAB_TARGET: + tabName = TAB_NAME_TARGET; + break; + case TAB_EFFECTS: + tabName = TAB_NAME_EFFECTS; + break; + default: + tabName = TAB_NAME_TYPE; + break; } } @@ -213,46 +262,29 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); y += 15; - for (int i = 0; i < conditions.size() && i < 3; i++) { - Condition cond = conditions.get(i); + for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { + AbilityCondition cond = conditions.get(i); String condName = getConditionDisplayName(cond); - sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); - sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); - sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); + GuiNpcButton condBtn = new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName); + condBtn.hoverableText = cond.getConditionSummary(); + sw.addButton(condBtn); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); y += 22; } - if (conditions.size() < 3) { - sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); + if (conditions.size() < MAX_CONDITIONS) { + sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); y += ROW_H; } return y; } - private String getConditionDisplayName(Condition cond) { + private String getConditionDisplayName(AbilityCondition cond) { if (cond == null) return "None"; - String typeId = cond.getTypeId(); - switch (typeId) { - case "hp_above": - return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hp_below": - return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_above": - return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_below": - return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hit_count": - Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; - return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; - default: - return typeId; - } - } - - private float getConditionThreshold(Condition cond) { - NBTTagCompound nbt = cond.writeNBT(); - return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; + String name = cond.getName(); + return StatCollector.translateToLocal(name); } // ═══════════════════════════════════════════════════════════════════════════ @@ -264,17 +296,47 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi int id = guibutton.id; // Tab switching — fixed tabs - if (id == 90) { activeTab = TAB_GENERAL; initGui(); return; } - if (id == 91) { activeTab = TAB_TYPE; initGui(); return; } - if (id == 92) { activeTab = TAB_TARGET; initGui(); return; } - if (id == 93) { activeTab = TAB_EFFECTS; initGui(); return; } + if (id == 90) { + activeTab = TAB_GENERAL; + initGui(); + return; + } + if (id == 91) { + activeTab = TAB_TYPE; + initGui(); + return; + } + if (id == 92) { + activeTab = TAB_TARGET; + initGui(); + return; + } + if (id == 93) { + activeTab = TAB_EFFECTS; + initGui(); + return; + } // Custom tabs (94+) if (id >= 94 && id < 94 + customTabNames.size()) { activeTab = 4 + (id - 94); initGui(); return; } - if (id == -1000) { close(); return; } + if (id == -999) { + GuiNpcTextField.unfocus(); + applyToAbility(); + callback.onAbilitySaved(ability); + GuiScriptInterface.open(parent, new AbilityScript(ability.getId())); + return; + } + if (id == 40) { + setSubGui(new SubGuiTagSelect(ability.getTagUUIDs())); + return; + } + if (id == -1000) { + close(); + return; + } // Condition buttons (50-80) if (handleConditionButton(id)) return; @@ -291,9 +353,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } private boolean handleConditionButton(int id) { - if (id >= 50 && id < 80) { - int condIndex = (id - 50) / 10; - int action = (id - 50) % 10; + if (id >= COND_BASE && id < COND_END) { + int condIndex = (id - COND_BASE) / COND_STRIDE; + int action = (id - COND_BASE) % COND_STRIDE; if (action == 0 || action == 1) { if (condIndex < conditions.size()) { editingConditionIndex = condIndex; @@ -307,8 +369,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } return true; } - if (id == 80) { - if (conditions.size() < 3) { + if (id == BTN_ADD_COND) { + if (conditions.size() < MAX_CONDITIONS) { editingConditionIndex = conditions.size(); setSubGui(new SubGuiConditionEdit(null)); } @@ -342,7 +404,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi if (subgui instanceof SubGuiConditionEdit) { SubGuiConditionEdit condEdit = (SubGuiConditionEdit) subgui; - Condition result = condEdit.getResult(); + AbilityCondition result = condEdit.getResult(); if (result != null && editingConditionIndex >= 0) { if (editingConditionIndex < conditions.size()) { conditions.set(editingConditionIndex, result); @@ -369,12 +431,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi protected void applyToAbility() { ability.getConditions().clear(); - for (Condition c : conditions) ability.addCondition(c); + for (AbilityCondition c : conditions) ability.addCondition(c); } public void loadAbility(Ability loadedAbility) { if (loadedAbility == null) return; - NBTTagCompound nbt = loadedAbility.writeNBT(); + NBTTagCompound nbt = loadedAbility.writeNBT(false); nbt.setString("typeId", ability.getTypeId()); ability.readNBT(nbt); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java index 4d21f12ca..9e3856a14 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java @@ -3,18 +3,15 @@ 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; /** * Dialog asking the user whether to clone-and-modify (convert to inline) or modify the parent ability. */ -public class SubGuiAbilityEditMode extends SubGuiInterface { +public class SubGuiAbilityEditMode extends SubGuiSimpleChoice { public static final int MODE_CLONE_MODIFY = 0; public static final int MODE_MODIFY_PARENT = 1; - private int result = -1; - public SubGuiAbilityEditMode() { setBackground("menubg.png"); xSize = 220; @@ -39,18 +36,13 @@ public class SubGuiAbilityEditMode extends SubGuiInterface { @Override public void buttonEvent(GuiButton guibutton) { if (guibutton.id == 0) { - result = MODE_CLONE_MODIFY; + setResult(MODE_CLONE_MODIFY); close(); } else if (guibutton.id == 1) { - result = MODE_MODIFY_PARENT; + setResult(MODE_MODIFY_PARENT); close(); } else if (guibutton.id == 2) { - result = -1; close(); } } - - public int getResult() { - return result; - } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java index 103d446fc..b0fc0f629 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java @@ -1,7 +1,8 @@ package noppes.npcs.client.gui.advanced; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.data.ability.enums.UserType; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; @@ -21,7 +22,7 @@ import noppes.npcs.constants.EnumScrollData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.UUID; +import java.util.Map; import java.util.Vector; /** @@ -33,10 +34,8 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL private final SubGuiAbilityConfig parentConfig; private final GuiNPCAbilities parentAbilities; private String selectedDisplayName = null; - private String selectedUuid = null; + private String selectedName = null; - /** Maps display name -> UUID for custom abilities. */ - private final HashMap displayToUuid = new HashMap<>(); private HashMap rawData = new HashMap<>(); private GuiCustomScroll scroll; @@ -97,18 +96,22 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.load")); addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel")); - getButton(0).setEnabled(selectedUuid != null); + getButton(0).setEnabled(selectedName != null); } private List getFilteredList() { - 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); + for (Map.Entry entry : rawData.entrySet()) { + String name = entry.getKey(); + + // Only show NPC-valid abilities (NPC_ONLY or BOTH) + UserType ut = UserType.fromOrdinal(entry.getValue()); + if (!ut.allowsNpc()) continue; + + if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) { + continue; } + list.add(name); } return list; } @@ -117,7 +120,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - if (id == 0 && selectedUuid != null) { + if (id == 0 && selectedName != null) { if (parentAbilities != null) { // From NPC abilities GUI - ask clone/reference setSubGui(new SubGuiAbilityLoadMode()); @@ -125,7 +128,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL // From config GUI - always clone waitingForLoad = true; pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE; - PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); + PacketClient.sendClient(new CustomAbilityGetPacket(selectedName)); } } else if (id == 2) { close(); @@ -152,16 +155,16 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL if (mode < 0) return; // cancelled if (mode == SubGuiAbilityLoadMode.MODE_REFERENCE) { - // Reference mode - just pass the reference ID - if (parentAbilities != null && selectedUuid != null) { - parentAbilities.loadAbilityReference(selectedUuid); + // Reference mode - just pass the reference name + if (parentAbilities != null && selectedName != null) { + parentAbilities.loadAbilityReference(selectedName); } close(); } else { // Clone mode - request full data waitingForLoad = true; pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE; - PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); + PacketClient.sendClient(new CustomAbilityGetPacket(selectedName)); } } } @@ -170,9 +173,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { if (scroll.id == 0) { selectedDisplayName = scroll.getSelected(); - if (selectedDisplayName != null) { - selectedUuid = displayToUuid.get(selectedDisplayName); - } + selectedName = selectedDisplayName; initGui(); } } @@ -181,15 +182,13 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { if (scroll.id == 0 && selection != null && !selection.isEmpty()) { selectedDisplayName = selection; - selectedUuid = displayToUuid.get(selectedDisplayName); - if (selectedUuid != null) { - if (parentAbilities != null) { - setSubGui(new SubGuiAbilityLoadMode()); - } else { - waitingForLoad = true; - pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE; - PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); - } + selectedName = selection; + if (parentAbilities != null) { + setSubGui(new SubGuiAbilityLoadMode()); + } else { + waitingForLoad = true; + pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE; + PacketClient.sendClient(new CustomAbilityGetPacket(selectedName)); } } } @@ -197,22 +196,10 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL @Override public void setData(Vector list, HashMap data, EnumScrollData type) { if (type == EnumScrollData.CUSTOM_ABILITIES) { - displayToUuid.clear(); rawData = data; - for (String key : data.keySet()) { - // key format: "displayName\tUUID" - int tabIndex = key.indexOf('\t'); - if (tabIndex > 0) { - String displayName = key.substring(0, tabIndex); - String uuid = key.substring(tabIndex + 1); - displayToUuid.put(displayName, uuid); - } else { - displayToUuid.put(key, key); - } - } if (scroll != null) { scroll.setList(getFilteredList()); - if (selectedDisplayName != null && displayToUuid.containsKey(selectedDisplayName)) { + if (selectedDisplayName != null && rawData.containsKey(selectedDisplayName)) { scroll.setSelected(selectedDisplayName); } } @@ -226,15 +213,10 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL waitingForLoad = false; Ability loaded = AbilityController.Instance.fromNBT(compound); if (loaded != null) { - if (pendingLoadMode == SubGuiAbilityLoadMode.MODE_CLONE) { - // Give it a new UUID so it's a unique inline copy - loaded.setId(UUID.randomUUID().toString()); - } - if (parentConfig != null) { parentConfig.loadAbility(loaded); } else if (parentAbilities != null) { - parentAbilities.loadAbility(loaded); + parentAbilities.loadAbility(loaded, selectedName); } } close(); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java index 28a7bd0bb..5995c0e9e 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java @@ -3,18 +3,15 @@ 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; /** * Dialog asking the user whether to Clone (inline copy) or Reference the loaded ability. */ -public class SubGuiAbilityLoadMode extends SubGuiInterface { +public class SubGuiAbilityLoadMode extends SubGuiSimpleChoice { public static final int MODE_CLONE = 0; public static final int MODE_REFERENCE = 1; - private int result = -1; - public SubGuiAbilityLoadMode() { setBackground("menubg.png"); xSize = 200; @@ -39,18 +36,13 @@ public class SubGuiAbilityLoadMode extends SubGuiInterface { @Override public void buttonEvent(GuiButton guibutton) { if (guibutton.id == 0) { - result = MODE_CLONE; + setResult(MODE_CLONE); close(); } else if (guibutton.id == 1) { - result = MODE_REFERENCE; + setResult(MODE_REFERENCE); close(); } else if (guibutton.id == 2) { - result = -1; close(); } } - - public int getResult() { - return result; - } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityMagic.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityMagic.java new file mode 100644 index 000000000..8f555017a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityMagic.java @@ -0,0 +1,277 @@ +package noppes.npcs.client.gui.advanced; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +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 noppes.npcs.controllers.MagicController; +import noppes.npcs.controllers.data.Magic; +import noppes.npcs.controllers.data.MagicData; +import noppes.npcs.controllers.data.MagicEntry; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Sub-GUI for editing magic splits on an Ability. + * Dual-scroll layout: available magics on left, assigned magics on right. + * Only split values (no flat damage) are editable. + */ +public class SubGuiAbilityMagic extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + + public MagicData magicData; + + private GuiCustomScroll availableScroll; + private GuiCustomScroll assignedScroll; + + /** Maps display name → magic ID for all available magics. */ + private final HashMap allMagic = new HashMap<>(); + /** Maps formatted display string (right scroll) → base display name. */ + private final HashMap assignedDisplayToName = new HashMap<>(); + private String search = ""; + + private GuiNpcTextField splitField; + + /** + * Builds the ability editor's magic field. + *

+ * This lives here rather than in Ability because the lambdas below carry this class in + * their method descriptors. Ability is a both-side class, and anything reflecting over its + * declared methods on a server - Nashorn's adapter generator, for one - would resolve those + * descriptors and fail to find this client-only type. + */ + public static FieldDef createMagicField(MagicData magicData) { + return FieldDef.subGuiField("ability.magic.editor", + () -> new SubGuiAbilityMagic(magicData.copy()), + gui -> { + MagicData result = ((SubGuiAbilityMagic) gui).magicData; + magicData.getMagics().clear(); + for (Map.Entry e : result.getMagics().entrySet()) { + magicData.getMagics().put(e.getKey(), e.getValue()); + } + }) + .buttonLabel(() -> magicData.isEmpty() + ? StatCollector.translateToLocal("ability.magic.usesCaster") + : magicData.getMagics().size() + " Magic(s)") + .tab("General"); + } + + public SubGuiAbilityMagic(MagicData data) { + this.magicData = data; + setBackground("menubg.png"); + xSize = 420; + ySize = 222; + + // Load all available magics from the controller + MagicController controller = MagicController.getInstance(); + for (Map.Entry entry : controller.magics.entrySet()) { + allMagic.put(entry.getValue().getDisplayName(), entry.getKey()); + } + } + + @Override + public void initGui() { + super.initGui(); + + int scrollW = 150; + int scrollH = 140; + int leftX = guiLeft + 10; + int rightX = guiLeft + 250; + int topY = guiTop + 20; + + // Title + addLabel(new GuiNpcLabel(0, "ability.magic.editor", guiLeft + 10, guiTop + 5)); + + // Left scroll: available magics + if (availableScroll == null) { + availableScroll = new GuiCustomScroll(this, 0); + availableScroll.setSize(scrollW, scrollH); + } + availableScroll.guiLeft = leftX; + availableScroll.guiTop = topY; + availableScroll.setList(getSearchList()); + addScroll(availableScroll); + + // Search field below left scroll + addTextField(new GuiNpcTextField(4, this, fontRendererObj, leftX, topY + scrollH + 5, scrollW, 20, search)); + + // Right scroll: assigned magics + if (assignedScroll == null) { + assignedScroll = new GuiCustomScroll(this, 1); + assignedScroll.setSize(scrollW, scrollH); + } + assignedScroll.guiLeft = rightX; + assignedScroll.guiTop = topY; + updateAssignedList(); + addScroll(assignedScroll); + + // Arrow buttons between scrolls + int midX = guiLeft + 175; + addButton(new GuiNpcButton(70, midX, topY + 40, 55, 20, ">")); + addButton(new GuiNpcButton(71, midX, topY + 62, 55, 20, "<")); + + // Standardize button + addButton(new GuiNpcButton(72, midX, topY + 90, 55, 20, "magic.dist")); + getButton(72).setHoverText("magic.distInfo"); + + // Split field below right scroll + int tfY = topY + scrollH + 5; + addLabel(new GuiNpcLabel(5002, "magic.split", rightX - 57, tfY + 5)); + splitField = new GuiNpcTextField(73, this, fontRendererObj, rightX, tfY, 60, 20, ""); + splitField.setFloatsOnly(); + splitField.setMinMaxDefaultFloat(0, 1, 0); + splitField.enabled = false; + addTextField(splitField); + + // Done button + addButton(new GuiNpcButton(80, guiLeft + xSize / 2 - 40, guiTop + ySize - 34, 80, 20, "gui.done")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + // Add magic + if (guibutton.id == 70) { + if (availableScroll.hasSelected()) { + String selected = availableScroll.getSelected(); + Integer id = allMagic.get(selected); + if (id != null && !magicData.hasMagic(id)) { + magicData.addMagic(id, 0, 0); + } + } + updateAssignedList(); + return; + } + // Remove magic + if (guibutton.id == 71) { + if (assignedScroll.hasSelected()) { + Integer id = resolveAssignedId(assignedScroll.getSelected()); + if (id != null && magicData.hasMagic(id)) { + magicData.removeMagic(id); + } + } + updateAssignedList(); + if (splitField != null) { + splitField.setText(""); + splitField.enabled = false; + } + return; + } + // Standardize splits + if (guibutton.id == 72) { + if (magicData.getMagics().size() > 0) { + int count = magicData.getMagics().size(); + float stdSplit = 1.0f / count; + for (Integer key : magicData.getMagics().keySet()) { + magicData.getMagic(key).split = stdSplit; + } + // Update field if something is selected + if (assignedScroll.getSelected() != null && splitField != null) { + Integer id = resolveAssignedId(assignedScroll.getSelected()); + if (id != null && magicData.hasMagic(id)) { + splitField.setText(magicData.getMagic(id).split + ""); + } + } + updateAssignedList(); + } + return; + } + // Done + if (guibutton.id == 80) { + close(); + return; + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(4) != null && getTextField(4).isFocused()) { + if (search.equals(getTextField(4).getText())) + return; + search = getTextField(4).getText().toLowerCase(); + availableScroll.setList(getSearchList()); + availableScroll.resetScroll(); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll == assignedScroll) { + if (assignedScroll.getSelected() != null) { + Integer id = resolveAssignedId(assignedScroll.getSelected()); + if (id != null && magicData.hasMagic(id)) { + if (splitField != null) { + splitField.setText(magicData.getMagic(id).split + ""); + splitField.enabled = true; + } + } + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + } + + @Override + public void unFocused(GuiNpcTextField textField) { + if (textField.id == 73) { + if (assignedScroll != null && assignedScroll.getSelected() != null) { + Integer id = resolveAssignedId(assignedScroll.getSelected()); + if (id != null && magicData.hasMagic(id)) { + try { + float split = Float.parseFloat(textField.getText()); + magicData.getMagic(id).split = split; + updateAssignedList(); + } catch (NumberFormatException e) { + } + } + } + } + } + + private List getSearchList() { + if (search.isEmpty()) { + return new ArrayList<>(allMagic.keySet()); + } + List list = new ArrayList<>(); + for (String name : allMagic.keySet()) { + if (name.toLowerCase().contains(search)) + list.add(name); + } + return list; + } + + /** + * Resolves the magic ID from a right-scroll selection (which may be formatted as "Name - XX%"). + */ + private Integer resolveAssignedId(String selection) { + if (selection == null) return null; + String baseName = assignedDisplayToName.get(selection); + if (baseName == null) baseName = selection; + return allMagic.get(baseName); + } + + private void updateAssignedList() { + assignedDisplayToName.clear(); + List selected = new ArrayList<>(); + for (Map.Entry entry : allMagic.entrySet()) { + if (magicData.hasMagic(entry.getValue())) { + float split = magicData.getMagic(entry.getValue()).split; + String display = entry.getKey() + " - " + Math.round(split * 100) + "%"; + assignedDisplayToName.put(display, entry.getKey()); + selected.add(display); + } + } + if (assignedScroll != null) { + assignedScroll.setList(selected); + } + } +} 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 b8a4e0e66..7f51b15e0 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java @@ -21,6 +21,7 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui private final Ability ability; private final IAbilityConfigCallback callback; private final Set existingNames; + private boolean saved = false; public SubGuiAbilitySaveConfirm(Ability ability) { this(ability, null, null); @@ -68,18 +69,27 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui } private void doSave() { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + saved = true; + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); if (callback != null) { callback.onAbilitySaved(ability); } close(); } + public boolean wasSaved() { + return saved; + } + @Override public void subGuiClosed(SubGuiInterface subgui) { if (subgui instanceof SubGuiDuplicateNameConfirm) { - if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) { + SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui; + if (confirm.isConfirmed()) { doSave(); + } else if (confirm.isBack()) { + // Keep this save-confirm dialog open. + return; } else { close(); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java new file mode 100644 index 000000000..8cab092a2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java @@ -0,0 +1,186 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; +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.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.IScrollData; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumScrollData; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +/** + * Simple ability name picker with optional filter mode. + * Shows custom, built-in, or all abilities in a scroll list with search. + * Returns the selected ability name. + */ +public class SubGuiAbilitySelect extends SubGuiInterface implements ICustomScrollListener, IScrollData { + + /** Show all abilities (custom + built-in). */ + public static final int FILTER_ALL = 0; + /** Show only custom abilities. */ + public static final int FILTER_CUSTOM_ONLY = 1; + /** Show only built-in abilities. */ + public static final int FILTER_BUILTIN_ONLY = 2; + + private GuiCustomScroll scroll; + private HashMap customData = new HashMap<>(); + private HashMap builtInData = new HashMap<>(); + private String selectedName = null; + private String search = ""; + private final int filterMode; + + public SubGuiAbilitySelect() { + this(FILTER_ALL); + } + + public SubGuiAbilitySelect(int filterMode) { + this.filterMode = filterMode; + setBackground("menubg.png"); + xSize = 220; + ySize = 216; + + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 5; + + addLabel(new GuiNpcLabel(0, "ability.select", guiLeft + 10, y)); + y += 14; + + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + scroll.setSize(200, 140); + } + scroll.guiLeft = guiLeft + 10; + scroll.guiTop = y; + scroll.setList(getFilteredList()); + if (selectedName != null) { + scroll.setSelected(selectedName); + } + addScroll(scroll); + + y += 143; + + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 10, y, 200, 20, search)); + + y += 24; + + addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.select")); + addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel")); + + getButton(0).setEnabled(selectedName != null); + } + + private List getFilteredList() { + HashMap merged = new HashMap<>(); + if (filterMode != FILTER_BUILTIN_ONLY) { + merged.putAll(customData); + } + if (filterMode != FILTER_CUSTOM_ONLY) { + merged.putAll(builtInData); + } + + List list = new ArrayList<>(); + for (Map.Entry entry : merged.entrySet()) { + String name = entry.getKey(); + + // Only show NPC-valid abilities (NPC_ONLY or BOTH) + UserType ut = UserType.fromOrdinal(entry.getValue()); + if (!ut.allowsNpc()) continue; + + if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) { + continue; + } + list.add(name); + } + return list; + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + + if (id == 0 && selectedName != null) { + close(); + } else if (id == 2) { + selectedName = null; + close(); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + String newSearch = getTextField(10).getText(); + if (!search.equals(newSearch)) { + search = newSearch; + scroll.resetScroll(); + scroll.setList(getFilteredList()); + } + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0) { + selectedName = scroll.getSelected(); + initGui(); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (scroll.id == 0 && selection != null && !selection.isEmpty()) { + selectedName = selection; + close(); + } + } + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.CUSTOM_ABILITIES) { + customData = data; + } else if (type == EnumScrollData.BUILTIN_ABILITIES) { + builtInData = data; + } + if (scroll != null) { + scroll.setList(getFilteredList()); + if (selectedName != null) { + scroll.setSelected(selectedName); + } + } + initGui(); + } + + @Override + public void setSelected(String selected) { + this.selectedName = selected; + if (scroll != null) { + scroll.setSelected(selected); + } + } + + /** + * Get the selected ability name after the dialog closes. + * Returns null if cancelled. + */ + public String getSelectedName() { + return selectedName; + } +} 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 5d810862f..46975f289 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -1,6 +1,7 @@ package noppes.npcs.client.gui.advanced; -import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import noppes.npcs.client.gui.util.GuiCustomScroll; @@ -11,6 +12,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -20,6 +22,11 @@ import java.util.Map; */ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + private static final int BTN_ADD = 0; + private static final int BTN_CANCEL = 1; + private static final int BTN_SCROLL_TYPE = 2; + private static final int TF_SEARCH = 10; + private GuiCustomScroll scroll; private final HashMap displayNameToTypeId = new HashMap<>(); private final HashMap allDisplayNameToTypeId = new HashMap<>(); @@ -36,62 +43,152 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS public void initGui() { super.initGui(); - addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); + int y = guiTop + 5; + // Scroll type filter button + addButton(new GuiNpcButton(BTN_SCROLL_TYPE, guiLeft + 5, y, 190, 20, GuiNPCAbilities.scrollType.toString())); + y += 24; + + // Search bar + addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 5, y, 190, 18, search)); + y += 20; + + // Scroll list (shortened to fit filter button within original ySize) if (scroll == null) { scroll = new GuiCustomScroll(this, 0); - scroll.setSize(190, 145); + scroll.setSize(190, 121); } scroll.guiLeft = guiLeft + 5; - scroll.guiTop = guiTop + 26; + scroll.guiTop = y; addScroll(scroll); buildAllTypes(); - scroll.setList(getFilteredTypeList()); + scroll.setUnsortedList(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")); + addButton(new GuiNpcButton(BTN_ADD, guiLeft + 5, guiTop + 188, 90, 20, "gui.add")); + getButton(BTN_ADD).setEnabled(scroll.hasSelected()); + addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); } private void buildAllTypes() { allDisplayNameToTypeId.clear(); String[] types = AbilityController.Instance.getTypes(); for (String typeId : types) { + // Never show built-in types — they are immutable and cannot be created + if (AbilityController.Instance.isBuiltInType(typeId)) + continue; + + // Apply scroll type filter + if (!matchesScrollType(typeId)) + continue; + String displayName = I18n.format(typeId); + if (typeId.equals("ability.cnpc.custom")) { + displayName = "\u00A7d" + displayName; + } else if (AbilityController.Instance.isConcurrentCapableType(typeId)) { + displayName = "\u00A7b" + displayName; + } allDisplayNameToTypeId.put(displayName, typeId); } } + private boolean matchesScrollType(String typeId) { + GuiNPCAbilities.ScrollType type = GuiNPCAbilities.scrollType; + if (type == GuiNPCAbilities.ScrollType.ALL) { + return true; + } else if (type == GuiNPCAbilities.ScrollType.CNPC) { + return typeId.startsWith("ability.cnpc."); + } else if (type == GuiNPCAbilities.ScrollType.MODDED) { + if (!Register.isEmpty("ability")) { + List registerList = Register.REGISTERED_NAMESPACES.get("ability"); + if (!registerList.isEmpty()) { + String namespace = registerList.get(GuiNPCAbilities.modIndex); + return typeId.startsWith("ability." + namespace + "."); + } + } + return false; + } + return true; + } + 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)) { + String stripped = displayName.replaceAll("\u00A7.", ""); + if (search.isEmpty() || stripped.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) { list.add(displayName); displayNameToTypeId.put(displayName, entry.getValue()); } } + Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare( + a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", ""))); + + // Pin Custom Ability to top of list + String customEntry = null; + for (String name : list) { + String tid = displayNameToTypeId.get(name); + if (tid != null && tid.equals("ability.cnpc.custom")) { + customEntry = name; + break; + } + } + if (customEntry != null) { + list.remove(customEntry); + list.add(0, customEntry); + } + return list; } @Override public void buttonEvent(GuiButton guibutton) { - if (guibutton.id == 0 && scroll.hasSelected()) { + int id = guibutton.id; + + if (id == BTN_ADD && scroll.hasSelected()) { String displayName = scroll.getSelected(); selectedTypeId = displayNameToTypeId.get(displayName); close(); - } else if (guibutton.id == 1) { + } else if (id == BTN_CANCEL) { selectedTypeId = null; close(); + } else if (id == BTN_SCROLL_TYPE) { + cycleScrollType(); + if (scroll != null) { + scroll.resetScroll(); + } + initGui(); + } + } + + private void cycleScrollType() { + if (GuiNPCAbilities.scrollType != GuiNPCAbilities.ScrollType.MODDED) { + GuiNPCAbilities.ScrollType[] values = GuiNPCAbilities.ScrollType.values(); + GuiNPCAbilities.ScrollType next = values[(GuiNPCAbilities.scrollType.ordinal() + 1) % values.length]; + if (next == GuiNPCAbilities.ScrollType.MODDED && Register.isEmpty("ability")) { + next = GuiNPCAbilities.ScrollType.ALL; + } + GuiNPCAbilities.scrollType = next; + } else { + List list = Register.REGISTERED_NAMESPACES.get("ability"); + if (list != null && !list.isEmpty()) { + if (GuiNPCAbilities.modIndex == list.size() - 1) { + GuiNPCAbilities.scrollType = GuiNPCAbilities.ScrollType.ALL; + } else { + GuiNPCAbilities.modIndex = (GuiNPCAbilities.modIndex + 1) % list.size(); + } + } else { + GuiNPCAbilities.modIndex = 0; + GuiNPCAbilities.scrollType = GuiNPCAbilities.ScrollType.ALL; + } } } @Override public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { if (guiCustomScroll.id == 0) { - getButton(0).setEnabled(scroll.hasSelected()); + getButton(BTN_ADD).setEnabled(scroll.hasSelected()); } } @@ -106,9 +203,9 @@ 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(); + if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) { + if (!search.equals(getTextField(TF_SEARCH).getText())) { + search = getTextField(TF_SEARCH).getText().toLowerCase(); scroll.setList(getFilteredTypeList()); scroll.resetScroll(); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java index 1c65d0dc6..be7ba5645 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java @@ -88,12 +88,15 @@ public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICust scroll.setSize(190, 155); // Mark blank separators and group headers as non-interactive colored entries + scroll.nonInteractive.add(""); scroll.colors.put("", 0x000000); if (lastGroup != null) { for (int i = 0; i < variants.size(); i++) { String group = variants.get(i).getGroup(); - if (group != null) + if (group != null) { + scroll.nonInteractive.add(group); scroll.colors.put(group, 0xFFFF00); // Yellow + } } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainSelect.java new file mode 100644 index 000000000..f2d858551 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainSelect.java @@ -0,0 +1,92 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.AbilityController; +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; +import java.util.Set; + +/** + * Selector for chained ability presets. Lists chain names from synced data. + * Returns the selected chain name via {@link #getSelectedName()}. + */ +public class SubGuiChainSelect extends SubGuiInterface implements ICustomScrollListener { + + private GuiCustomScroll scroll; + private String selectedName = null; + + public SubGuiChainSelect() { + setBackground("menubg.png"); + xSize = 220; + ySize = 200; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 5; + addLabel(new GuiNpcLabel(0, "ability.loadChain", guiLeft + 10, y)); + y += 14; + + List names = getChainNames(); + + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + scroll.setSize(200, 130); + } + scroll.guiLeft = guiLeft + 10; + scroll.guiTop = y; + scroll.setList(names); + if (selectedName != null) { + scroll.setSelected(selectedName); + } + addScroll(scroll); + + y += 133; + addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.select")); + addButton(new GuiNpcButton(1, guiLeft + 115, y, 95, 20, "gui.cancel")); + getButton(0).setEnabled(selectedName != null); + } + + private List getChainNames() { + Set names = AbilityController.Instance.getChainedAbilityNamesSet(); + return new ArrayList<>(names); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0 && selectedName != null) { + close(); + } else if (guibutton.id == 1) { + selectedName = null; + close(); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0) { + selectedName = guiCustomScroll.getSelected(); + initGui(); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && selection != null && !selection.isEmpty()) { + selectedName = selection; + close(); + } + } + + public String getSelectedName() { + return selectedName; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java new file mode 100644 index 000000000..2ffec82c9 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -0,0 +1,945 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityAction; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; +import kamkeel.npcs.controllers.data.ability.data.AbilityIconData; +import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.builder.GuiFieldBuilder; +import noppes.npcs.client.gui.util.GuiMenuTopButton; +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.GuiScrollWindow; +import noppes.npcs.client.gui.util.*; + +import java.util.ArrayList; +import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; + + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BooleanSupplier; + +import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS; + +/** + * SubGui for editing a {@link ChainedAbility}. + * Core tabs: General, Entries, Conditions. + * Additional tabs are injected dynamically by {@link IChainedAbilityFieldProvider}s. + */ +public class SubGuiChainedAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, IAbilityConfigCallback { + + // ── Declarative field ID ranges ────────────────────────────────────────── + private static final int DECLARATIVE_ID_START = 1000; + private static final int CLEAR_ID_START = 2000; + private static final int LABEL_ID_START = 3000; + + // ── Tab constants (core tabs) ──────────────────────────────────────────── + private static final int TAB_GENERAL = 0; + private static final int TAB_ENTRIES = 1; + private static final int TAB_TARGET = 2; + private static final int CORE_TAB_COUNT = 3; + + // ── Tab button IDs ──────────────────────────────────────────────────────── + private static final int BTN_TAB_GENERAL = 90; + private static final int BTN_TAB_ENTRIES = 91; + private static final int BTN_TAB_TARGET = 92; + private static final int BTN_TAB_EXTRA_BASE = 93; + private static final int BTN_SCRIPT = -999; + private static final int BTN_CLOSE = -1000; + + // ── Entries tab: per-entry ID encoding ───────────────────────────────────── + // Actual ID = ENTRY_BASE + i * ENTRY_STRIDE + offset + // offset 0 = name/select button, 1 = delay text field, 2 = up, 3 = down, 4 = delete + private static final int ENTRY_BASE = 100; + private static final int ENTRY_END = 200; + private static final int ENTRY_STRIDE = 10; + private static final int BTN_ADD_ENTRY = 200; + + // ── Conditions tab: per-condition ID encoding ───────────────────────────── + // Actual ID = COND_BASE + i * COND_STRIDE + offset + // offset 0 = name/click, 1 = edit, 2 = delete + private static final int COND_BASE = 50; + private static final int COND_STRIDE = 10; + private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10 + private static final int BTN_ADD_COND = COND_END; + + // ── Layout constants ────────────────────────────────────────────────────── + private static final int L_LABEL_X = 5; + private static final int ROW_H = 24; + private static final int MAX_ENTRIES = 10; + + private final ChainedAbility chain; + private final IChainedAbilityConfigCallback callback; + private final boolean npcContext; + private final boolean readOnlyEntries; + private final List npcSlots; + private int activeTab = TAB_GENERAL; + + private List fieldDefs; + private List entries; + private List conditions; + + // Dynamic tabs injected by field providers (e.g., "Icon") + private List extraTabs = new ArrayList<>(); + + private GuiFieldBuilder builder; + private float[] tabScrollY; + + // Entry editing + private int editingEntryIndex = -1; + private String pendingTypeId; + private boolean editingParentAbility = false; + + // Condition editing + private int editingConditionIndex = -1; + + // Save only on explicit X button, not ESC + private boolean saveOnClose = false; + + // Track consumed NPC slot indices for deferred removal on save + private final List consumedSlotIndices = new ArrayList<>(); + + public SubGuiChainedAbilityConfig(ChainedAbility chain, IChainedAbilityConfigCallback callback) { + this(chain, callback, false, null, false); + } + + public SubGuiChainedAbilityConfig(ChainedAbility chain, IChainedAbilityConfigCallback callback, + boolean npcContext, List npcSlots) { + this(chain, callback, npcContext, npcSlots, false); + } + + public SubGuiChainedAbilityConfig(ChainedAbility chain, IChainedAbilityConfigCallback callback, + boolean npcContext, List npcSlots, boolean readOnlyEntries) { + this.chain = chain; + this.callback = callback; + this.npcContext = npcContext; + this.readOnlyEntries = readOnlyEntries; + this.npcSlots = npcSlots; + this.entries = new ArrayList<>(chain.getEntries()); + this.conditions = new ArrayList<>(chain.getConditions()); + + buildFieldDefs(); + + setBackground("menubg.png", 217); + xSize = 356; + ySize = 200; + } + + private void buildFieldDefs() { + fieldDefs = new ArrayList<>(); + + fieldDefs.add(FieldDef.stringField("gui.name", chain::getName, chain::setName).tab("General")); + fieldDefs.add(FieldDef.stringField("gui.displayName", chain::getRawDisplayName, chain::setDisplayName).tab("General")); + // Computed "Valid For" label (derived from child abilities) + fieldDefs.add(FieldDef.labelField("ability.validFor", () -> { + UserType ut = computeAllowedBy(); + return "\u00A7e" + StatCollector.translateToLocal("ability.userType." + ut.name()); + }).tab("General")); + fieldDefs.add(FieldDef.boolField("gui.enabled", chain::isEnabled, chain::setEnabled).tab("General")); + fieldDefs.add(FieldDef.intField("ability.weight", chain::getWeight, chain::setWeight).range(1, 100).tab("General")); + fieldDefs.add(FieldDef.boolField("ability.windUpAll", chain::isWindUpAll, chain::setWindUpAll).tab("General")); + fieldDefs.add(FieldDef.row( + FieldDef.intField("ability.cooldown", chain::getCooldownTicks, chain::setCooldownTicks).range(0, 12000), + FieldDef.boolField("ability.perAbilityCooldown", chain::isPerAbilityCooldown, chain::setPerAbilityCooldown) + ).tab("General")); + fieldDefs.add(FieldDef.boolField("ability.ignoreCooldown", chain::isIgnoreCooldown, chain::setIgnoreCooldown).tab("General")); + + // ── Target tab ─────────────────────────────────────────────── + fieldDefs.add(FieldDef.row( + FieldDef.floatField("ability.minRange", chain::getMinRange, chain::setMinRange).range(0, 64), + FieldDef.floatField("ability.maxRange", chain::getMaxRange, chain::setMaxRange).range(0, 64) + ).tab("Target")); + + // ── Icon tab ────────────────────────────────────────────── + AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain); + BooleanSupplier isCustomIcon = chainIcon::isEnabled; + + fieldDefs.add(FieldDef.section("ability.section.icon").tab("Icon")); + fieldDefs.add(FieldDef.boolField("ability.hasIcon", chainIcon::isEnabled, chainIcon::setEnabled).tab("Icon")); + fieldDefs.add(FieldDef.row( + FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).range(1, 256), + FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).range(1, 256) + ).tab("Icon").visibleWhen(isCustomIcon)); + fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f).visibleWhen(isCustomIcon)); + fieldDefs.add(FieldDef.intField("ability.icon.layers", chainIcon::getLayerCount, chainIcon::setLayerCount) + .tab("Icon").range(1, AbilityIconData.MAX_LAYERS).visibleWhen(isCustomIcon)); + for (int i = 0; i < AbilityIconData.MAX_LAYERS; i++) { + final int idx = i; + java.util.function.BooleanSupplier layerVisible = () -> isCustomIcon.getAsBoolean() && chainIcon.getLayerCount() > idx; + String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1); + fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.textureSubGui("gui.texture", + () -> chainIcon.getLayer(idx).texture, + t -> chainIcon.setLayerTexture(idx, t)) + .tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.row( + FieldDef.intField("ability.icon.x", + () -> chainIcon.getLayer(idx).iconX, + x -> chainIcon.setLayerIconX(idx, x)).range(0, 4096), + FieldDef.intField("ability.icon.y", + () -> chainIcon.getLayer(idx).iconY, + y -> chainIcon.setLayerIconY(idx, y)).range(0, 4096) + ).tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.colorSubGui("ability.icon.tint", + () -> chainIcon.getLayer(idx).tintColor, + c -> chainIcon.setLayerTintColor(idx, c)) + .tab("Icon").visibleWhen(layerVisible)); + } + + // Animation + fieldDefs.add(FieldDef.section("Animation").tab("Icon").visibleWhen(isCustomIcon)); + fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover").visibleWhen(isCustomIcon)); + fieldDefs.add(FieldDef.intField("gui.frameCount", chainIcon::getFrameCount, chainIcon::setFrameCount) + .tab("Icon").range(1, 256).visibleWhen(() -> isCustomIcon.getAsBoolean() && chainIcon.isAnimated())); + fieldDefs.add(FieldDef.intField("gui.frameTime", chainIcon::getFrameTime, chainIcon::setFrameTime) + .tab("Icon").range(1, 100).visibleWhen(() -> isCustomIcon.getAsBoolean() && chainIcon.isAnimated())); + + // External field providers (e.g., DBC Addon injecting a "DBC" tab) + if (AbilityController.Instance != null) { + for (IChainedAbilityFieldProvider provider : AbilityController.Instance.getChainedFieldProviders()) { + provider.addFieldDefinitions(chain, fieldDefs); + } + } + + // Collect extra tab names from provider-injected fields + Set tabNames = new LinkedHashSet<>(); + for (FieldDef def : fieldDefs) { + String tab = def.getTab(); + if (tab != null && !tab.isEmpty() && !"General".equals(tab) && !"Target".equals(tab)) { + tabNames.add(tab); + } + } + extraTabs = new ArrayList<>(tabNames); + + // Size scroll array for all tabs + tabScrollY = new float[CORE_TAB_COUNT + extraTabs.size()]; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // COMPUTED USERTYPE + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Compute the allowed UserType from the current (possibly modified) entries list. + * Mirrors ChainedAbility.getAllowedBy() but uses the local entries. + */ + private UserType computeAllowedBy() { + if (entries.isEmpty()) return UserType.BOTH; + boolean allAllowPlayer = true; + boolean allAllowNpc = true; + for (ChainedAbilityEntry entry : entries) { + Ability a = entry.resolve(); + if (a == null) continue; + UserType ut = a.getAllowedBy(); + if (!ut.allowsPlayer()) allAllowPlayer = false; + if (!ut.allowsNpc()) allAllowNpc = false; + } + if (allAllowPlayer && allAllowNpc) return UserType.BOTH; + if (allAllowPlayer) return UserType.PLAYER_ONLY; + if (allAllowNpc) return UserType.NPC_ONLY; + return UserType.NONE; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // INIT GUI + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void initGui() { + // Commit any focused text field before rebuilding + GuiNpcTextField.unfocus(); + + // Save scroll position + GuiScrollWindow oldSw = getScrollableGui(0); + if (oldSw != null && activeTab < tabScrollY.length) { + tabScrollY[activeTab] = oldSw.nextScrollY; + } + + super.initGui(); + + // Tab buttons — core tabs + GuiMenuTopButton generalTab = new GuiMenuTopButton(BTN_TAB_GENERAL, guiLeft + 4, guiTop - 17, "menu.general"); + generalTab.active = (activeTab == TAB_GENERAL); + addTopButton(generalTab); + + GuiMenuTopButton entriesTab = new GuiMenuTopButton(BTN_TAB_ENTRIES, generalTab, "ability.entries"); + entriesTab.active = (activeTab == TAB_ENTRIES); + addTopButton(entriesTab); + + GuiMenuTopButton targetTab = new GuiMenuTopButton(BTN_TAB_TARGET, entriesTab, "script.target"); + targetTab.active = (activeTab == TAB_TARGET); + addTopButton(targetTab); + + // Dynamic extra tabs from field providers + GuiMenuTopButton prevTab = targetTab; + for (int i = 0; i < extraTabs.size(); i++) { + int tabIndex = CORE_TAB_COUNT + i; + GuiMenuTopButton extraTab = new GuiMenuTopButton(BTN_TAB_EXTRA_BASE + i, prevTab, extraTabs.get(i)); + extraTab.active = (activeTab == tabIndex); + addTopButton(extraTab); + prevTab = extraTab; + } + + GuiMenuTopButton closeBtn = new GuiMenuTopButton(BTN_CLOSE, guiLeft + xSize - 22, guiTop - 17, "X"); + addTopButton(closeBtn); + + GuiMenuTopButton scriptBtn = new GuiMenuTopButton(BTN_SCRIPT, "script.scripts", closeBtn); + addTopButton(scriptBtn); + + // Scroll window dimensions + int swX = guiLeft + 4; + int swY = guiTop + 5; + int swW = xSize - 8; + int swH = ySize - 10; + + if (activeTab == TAB_GENERAL) { + buildFieldDefTab("General", swX, swY, swW, swH); + } else if (activeTab == TAB_ENTRIES) { + buildEntriesTab(swX, swY, swW, swH); + } else if (activeTab == TAB_TARGET) { + buildTargetTab(swX, swY, swW, swH); + } else if (activeTab >= CORE_TAB_COUNT) { + int extraIndex = activeTab - CORE_TAB_COUNT; + if (extraIndex < extraTabs.size()) { + buildFieldDefTab(extraTabs.get(extraIndex), swX, swY, swW, swH); + } + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // FIELDDEF-BASED TAB (General + dynamic provider tabs) + // ═══════════════════════════════════════════════════════════════════════════ + + private void buildFieldDefTab(String tabName, int swX, int swY, int swW, int swH) { + List tabFields = new ArrayList<>(); + for (FieldDef def : fieldDefs) { + if (tabName.equals(def.getTab()) && def.isVisible()) { + tabFields.add(def); + } + } + + builder = new GuiFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); + builder.startY(5); + + GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); + restoreScroll(sw); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // ENTRIES TAB + // ═══════════════════════════════════════════════════════════════════════════ + + private void buildEntriesTab(int swX, int swY, int swW, int swH) { + GuiScrollWindow sw = new GuiScrollWindow(this, swX, swY, swW, swH, 0); + sw.backgroundColor = 0x88000000; + addScrollableGui(0, sw); + + int y = 5; + int labelCounter = 0; + + for (int i = 0; i < entries.size() && i < MAX_ENTRIES; i++) { + ChainedAbilityEntry entry = entries.get(i); + + // Index label + sw.addLabel(new GuiNpcLabel(labelCounter++, (i + 1) + ".", L_LABEL_X, y + 5, 0xFFFFFF)); + + // Ability reference/inline button + String btnLabel; + if (entry.isInline()) { + Ability a = entry.getInlineAbility(); + btnLabel = a != null ? a.getDisplayName() : "\u00A7cEmpty"; + } else { + String refName = entry.getAbilityReference(); + if (refName == null || refName.isEmpty()) { + btnLabel = StatCollector.translateToLocal("gui.select") + "..."; + } else { + Ability resolved = entry.resolve(); + btnLabel = "\u00A7e> " + (resolved != null ? resolved.getDisplayName() : refName); + } + } + GuiNpcButton entryBtn = new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE, L_LABEL_X + 15, y, 140, 20, btnLabel); + if (readOnlyEntries) { + entryBtn.setEnabled(false); + } + sw.addButton(entryBtn); + + if (!readOnlyEntries) { + // Check if this entry is concurrent-active (delay disabled) + Ability resolvedAbility = entry.resolve(); + boolean isConcurrentActive = resolvedAbility != null + && resolvedAbility.isConcurrentCapable() + && entry.isConcurrentEnabled(); + + // Delay label + field + sw.addLabel(new GuiNpcLabel(labelCounter++, "ability.delay", L_LABEL_X + 160, y + 5, + isConcurrentActive ? 0x555555 : 0xAAAAAA)); + GuiNpcTextField delayField = new GuiNpcTextField(ENTRY_BASE + i * ENTRY_STRIDE + 1, this, fontRendererObj, + L_LABEL_X + 195, y, 40, 20, String.valueOf(entry.getDelayTicks())); + delayField.setIntegersOnly(); + delayField.setMinMaxDefault(0, 6000, 0); + if (isConcurrentActive) { + delayField.setEnabled(false); + } + sw.addTextField(delayField); + + // Up button + if (i > 0) { + sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 2, L_LABEL_X + 240, y, 20, 20, "\u2191")); + } + + // Down button + if (i < entries.size() - 1) { + sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 3, L_LABEL_X + 263, y, 20, 20, "\u2193")); + } + + // Concurrent toggle (only shown if resolved ability is concurrent-capable, never for first entry) + if (i > 0 && resolvedAbility != null && resolvedAbility.isConcurrentCapable()) { + String cLabel = entry.isConcurrentEnabled() ? "\u00A7bC" : "\u00A77C"; + GuiNpcButton cBtn = new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 5, L_LABEL_X + 288, y, 20, 20, cLabel); + cBtn.setHoverText("ability.hover.concurrent"); + sw.addButton(cBtn); + } + + // Delete button + sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 4, L_LABEL_X + 313, y, 20, 20, "X")); + } else { + // Read-only: show delay as label only + int delay = entry.getDelayTicks(); + if (delay > 0) { + sw.addLabel(new GuiNpcLabel(labelCounter++, delay + "t", L_LABEL_X + 165, y + 5, 0x888888)); + } + } + + y += ROW_H; + } + + // Add entry button (hidden in read-only mode) + if (!readOnlyEntries && entries.size() < MAX_ENTRIES) { + sw.addButton(new GuiNpcButton(BTN_ADD_ENTRY, L_LABEL_X, y, 80, 20, "gui.add")); + y += ROW_H; + } + + sw.maxScrollY = Math.max(y - swH, 0); + restoreScroll(sw); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // TARGET TAB (FieldDef fields + conditions list) + // ═══════════════════════════════════════════════════════════════════════════ + + private void buildTargetTab(int swX, int swY, int swW, int swH) { + // Build FieldDef fields (ranges, Valid For) first + List tabFields = new ArrayList<>(); + for (FieldDef def : fieldDefs) { + if ("Target".equals(def.getTab()) && def.isVisible()) { + tabFields.add(def); + } + } + + builder = new GuiFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); + builder.startY(5); + + GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); + + // Append conditions list below the FieldDef fields + int y = builder.getLastBuildY(); + int condY = renderConditions(sw, y, builder.getNextLabelId()); + sw.maxScrollY = Math.max(condY - swH, 0); + + restoreScroll(sw); + } + + private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) { + y += 3; + sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); + y += 15; + + for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { + AbilityCondition cond = conditions.get(i); + String condName = getConditionDisplayName(cond); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); + y += 22; + } + + if (conditions.size() < MAX_CONDITIONS) { + sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); + y += ROW_H; + } + + return y; + } + + private String getConditionDisplayName(AbilityCondition cond) { + if (cond == null) return "None"; + String name = cond.getName(); + return StatCollector.translateToLocal(name); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // SCROLL RESTORE + // ═══════════════════════════════════════════════════════════════════════════ + + private void restoreScroll(GuiScrollWindow sw) { + if (activeTab < tabScrollY.length) { + float restored = Math.min(tabScrollY[activeTab], sw.maxScrollY); + sw.nextScrollY = restored; + sw.scrollY = restored; + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // BUTTON EVENTS + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + + // Tab switching — core tabs + if (id == BTN_TAB_GENERAL) { + activeTab = TAB_GENERAL; + initGui(); + return; + } + if (id == BTN_TAB_ENTRIES) { + activeTab = TAB_ENTRIES; + initGui(); + return; + } + if (id == BTN_TAB_TARGET) { + activeTab = TAB_TARGET; + initGui(); + return; + } + if (id == BTN_SCRIPT) { + GuiScriptInterface.open(parent, new ChainedAbilityScript(chain.getId())); + return; + } + if (id == BTN_CLOSE) { + saveOnClose = true; + close(); + return; + } + + // Tab switching — extra tabs + if (id >= BTN_TAB_EXTRA_BASE && id < BTN_TAB_EXTRA_BASE + extraTabs.size()) { + activeTab = CORE_TAB_COUNT + (id - BTN_TAB_EXTRA_BASE); + initGui(); + return; + } + + // Entries tab + if (activeTab == TAB_ENTRIES) { + if (handleEntryButton(id)) return; + } + + // Target tab (includes conditions) + if (activeTab == TAB_TARGET) { + if (handleConditionButton(id)) return; + } + + // FieldDef-based tabs (General + extra tabs) — declarative field handling + if (isFieldDefTab() && builder != null) { + if (builder.handleButtonEvent(id, guibutton)) { + if (!hasSubGui()) { + initGui(); + } + return; + } + } + } + + /** + * Whether the current active tab uses the declarative FieldDef system. + */ + private boolean isFieldDefTab() { + return activeTab == TAB_GENERAL || activeTab == TAB_TARGET || activeTab >= CORE_TAB_COUNT; + } + + private boolean handleEntryButton(int id) { + // Add entry + if (id == BTN_ADD_ENTRY) { + if (entries.size() < MAX_ENTRIES) { + // Both contexts use entry source selector; hide NPC option in global context + setSubGui(new SubGuiChainedEntrySource(npcContext)); + } + return true; + } + + // Per-entry buttons (ENTRY_BASE to ENTRY_END) + if (id >= ENTRY_BASE && id < ENTRY_END) { + int entryIndex = (id - ENTRY_BASE) / ENTRY_STRIDE; + int action = (id - ENTRY_BASE) % ENTRY_STRIDE; + + if (entryIndex < 0 || entryIndex >= entries.size()) return false; + + switch (action) { + case 0: // Entry name button — reference: clone/modify dialog; inline: edit config + ChainedAbilityEntry clickedEntry = entries.get(entryIndex); + if (clickedEntry.isReference()) { + // Built-in abilities are always references — no editing allowed + Ability refResolved = clickedEntry.resolve(); + if (refResolved != null && refResolved.isBuiltIn()) return true; + editingEntryIndex = entryIndex; + setSubGui(new SubGuiAbilityEditMode()); + } else if (clickedEntry.isInline() && clickedEntry.getInlineAbility() != null) { + Ability inlineAbility = clickedEntry.getInlineAbility(); + if (inlineAbility.isBuiltIn()) return true; + editingEntryIndex = entryIndex; + setSubGui(new SubGuiAbilityConfig(inlineAbility, this)); + } + return true; + case 2: // Up + if (entryIndex > 0) { + // Commit any focused delay field before reordering + GuiNpcTextField.unfocus(); + ChainedAbilityEntry entry = entries.remove(entryIndex); + entries.add(entryIndex - 1, entry); + // Can't be concurrent at position 0 + if (entryIndex - 1 == 0) { + entry.setConcurrentEnabled(false); + } + initGui(); + } + return true; + case 3: // Down + if (entryIndex < entries.size() - 1) { + // Commit any focused delay field before reordering + GuiNpcTextField.unfocus(); + ChainedAbilityEntry entry = entries.remove(entryIndex); + entries.add(entryIndex + 1, entry); + initGui(); + } + return true; + case 4: // Delete + // Commit any focused delay field before removing + GuiNpcTextField.unfocus(); + entries.remove(entryIndex); + initGui(); + return true; + case 5: // Concurrent toggle + ChainedAbilityEntry toggleEntry = entries.get(entryIndex); + boolean newState = !toggleEntry.isConcurrentEnabled(); + toggleEntry.setConcurrentEnabled(newState); + if (newState) { + toggleEntry.setDelayTicks(0); + } + initGui(); + return true; + } + } + + return false; + } + + private boolean handleConditionButton(int id) { + if (id >= COND_BASE && id < COND_END) { + int condIndex = (id - COND_BASE) / COND_STRIDE; + int action = (id - COND_BASE) % COND_STRIDE; + if (action == 0 || action == 1) { + if (condIndex < conditions.size()) { + editingConditionIndex = condIndex; + setSubGui(new SubGuiConditionEdit(conditions.get(condIndex))); + } + } else if (action == 2) { + if (condIndex < conditions.size()) { + conditions.remove(condIndex); + initGui(); + } + } + return true; + } + if (id == BTN_ADD_COND) { + if (conditions.size() < MAX_CONDITIONS) { + editingConditionIndex = conditions.size(); + setSubGui(new SubGuiConditionEdit(null)); + } + return true; + } + return false; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // TEXT FIELD EVENTS + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void unFocused(GuiNpcTextField textField) { + int id = textField.id; + + // FieldDef-based tabs — declarative fields + if (isFieldDefTab() && builder != null && id >= DECLARATIVE_ID_START) { + if (builder.handleTextFieldEvent(id, textField)) { + initGui(); + } + return; + } + + // Entries tab - delay fields (ENTRY_BASE + i * ENTRY_STRIDE + 1) + if (activeTab == TAB_ENTRIES && id >= ENTRY_BASE + 1 && id < ENTRY_END) { + int entryIndex = (id - ENTRY_BASE - 1) / ENTRY_STRIDE; + if (entryIndex >= 0 && entryIndex < entries.size()) { + entries.get(entryIndex).setDelayTicks(textField.getInteger()); + } + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // SUB GUI CLOSED + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + // FieldDef-based tabs — declarative sub-gui handling + if (isFieldDefTab() && builder != null) { + if (builder.handleSubGuiClosed(subgui)) { + initGui(); + return; + } + } + + if (subgui instanceof SubGuiAbilitySelect) { + handleAbilitySelectClosed((SubGuiAbilitySelect) subgui); + initGui(); + return; + } + if (subgui instanceof SubGuiChainedEntrySource) { + handleEntrySourceClosed((SubGuiChainedEntrySource) subgui); + return; + } + if (subgui instanceof SubGuiNpcSlotPicker) { + handleSlotPickerClosed((SubGuiNpcSlotPicker) subgui); + initGui(); + return; + } + if (subgui instanceof SubGuiAbilityVariantSelect) { + handleVariantSelectClosed((SubGuiAbilityVariantSelect) subgui); + if (!hasSubGui()) initGui(); + return; + } + if (subgui instanceof SubGuiAbilityTypeSelect) { + handleTypeSelectClosed((SubGuiAbilityTypeSelect) subgui); + if (!hasSubGui()) initGui(); + return; + } + if (subgui instanceof SubGuiAbilityEditMode) { + handleEditModeClosed((SubGuiAbilityEditMode) subgui); + if (!hasSubGui()) initGui(); + return; + } + if (subgui instanceof SubGuiAbilityConfig) { + editingEntryIndex = -1; + editingParentAbility = false; + initGui(); + return; + } + if (subgui instanceof SubGuiConditionEdit) { + handleConditionEditClosed((SubGuiConditionEdit) subgui); + initGui(); + return; + } + } + + private void handleAbilitySelectClosed(SubGuiAbilitySelect gui) { + String selectedName = gui.getSelectedName(); + if (selectedName != null) { + if (editingEntryIndex >= 0 && editingEntryIndex < entries.size()) { + int delay = entries.get(editingEntryIndex).getDelayTicks(); + entries.set(editingEntryIndex, ChainedAbilityEntry.reference(selectedName, delay)); + } else { + entries.add(ChainedAbilityEntry.reference(selectedName, 0)); + } + } + editingEntryIndex = -1; + } + + private void handleEntrySourceClosed(SubGuiChainedEntrySource gui) { + int source = gui.getResult(); + if (source == SubGuiChainedEntrySource.SOURCE_NPC_SLOTS) { + setSubGui(new SubGuiNpcSlotPicker(npcSlots)); + } else if (source == SubGuiChainedEntrySource.SOURCE_LOAD_PRESET) { + setSubGui(new SubGuiAbilitySelect(SubGuiAbilitySelect.FILTER_CUSTOM_ONLY)); + } else if (source == SubGuiChainedEntrySource.SOURCE_CREATE_NEW) { + setSubGui(new SubGuiAbilityTypeSelect()); + } else if (source == SubGuiChainedEntrySource.SOURCE_BUILT_IN) { + setSubGui(new SubGuiAbilitySelect(SubGuiAbilitySelect.FILTER_BUILTIN_ONLY)); + } + // Don't initGui — we're opening another SubGui + } + + private void handleSlotPickerClosed(SubGuiNpcSlotPicker gui) { + int slotIndex = gui.getSelectedIndex(); + if (slotIndex >= 0 && npcSlots != null && slotIndex < npcSlots.size()) { + AbilityAction consumed = npcSlots.get(slotIndex); + Ability ability = consumed.getAbility(); + if (ability != null) { + if (consumed.getSlotType() == AbilityAction.SlotType.INLINE_ABILITY) { + entries.add(ChainedAbilityEntry.inline(ability, 0)); + } else { + entries.add(ChainedAbilityEntry.reference(consumed.getReferenceId(), 0)); + } + if (!consumedSlotIndices.contains(slotIndex)) { + consumedSlotIndices.add(slotIndex); + } + } + } + } + + private void handleTypeSelectClosed(SubGuiAbilityTypeSelect gui) { + String typeId = gui.getSelectedTypeId(); + if (typeId != null) { + 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 && !newAbility.isBuiltIn()) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } + newAbility.setId(java.util.UUID.randomUUID().toString()); + entries.add(ChainedAbilityEntry.inline(newAbility, 0)); + editingEntryIndex = entries.size() - 1; + setSubGui(new SubGuiAbilityConfig(newAbility, this)); + } + } + } + + private void handleVariantSelectClosed(SubGuiAbilityVariantSelect gui) { + int idx = gui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null && !newAbility.isBuiltIn()) { + gui.getVariants().get(idx).apply(newAbility); + newAbility.setId(java.util.UUID.randomUUID().toString()); + entries.add(ChainedAbilityEntry.inline(newAbility, 0)); + editingEntryIndex = entries.size() - 1; + pendingTypeId = null; + setSubGui(new SubGuiAbilityConfig(newAbility, this)); + return; + } + } + pendingTypeId = null; + } + + private void handleEditModeClosed(SubGuiAbilityEditMode gui) { + int mode = gui.getResult(); + if (mode < 0 || editingEntryIndex < 0 || editingEntryIndex >= entries.size()) { + editingEntryIndex = -1; + return; + } + + ChainedAbilityEntry entry = entries.get(editingEntryIndex); + + // Block all editing for built-in abilities + Ability preCheck = entry.resolve(); + if (preCheck != null && preCheck.isBuiltIn()) { + editingEntryIndex = -1; + return; + } + + if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { + if (entry.convertToInline()) { + Ability a = entry.getInlineAbility(); + if (a != null && !a.isBuiltIn()) { + a.setId(java.util.UUID.randomUUID().toString()); + setSubGui(new SubGuiAbilityConfig(a, this)); + return; + } + } + editingEntryIndex = -1; + } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { + Ability resolved = entry.resolve(); + if (resolved != null && !resolved.isBuiltIn()) { + editingParentAbility = true; + setSubGui(resolved.createConfigGui(this)); + return; + } + editingEntryIndex = -1; + } + } + + private void handleConditionEditClosed(SubGuiConditionEdit gui) { + AbilityCondition result = gui.getResult(); + if (result != null && editingConditionIndex >= 0) { + if (editingConditionIndex < conditions.size()) { + conditions.set(editingConditionIndex, result); + } else { + conditions.add(result); + } + } + editingConditionIndex = -1; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CLOSE / APPLY + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void onAbilitySaved(Ability ability) { + if (editingParentAbility) { + // Persist the global parent ability to the server + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); + editingParentAbility = false; + return; + } + // Inline ability mutated in-place; entry already holds the reference + } + + @Override + public void close() { + if (saveOnClose) { + GuiNpcTextField.unfocus(); + applyToChain(); + callback.onChainedAbilitySaved(chain); + } + super.close(); + } + + + private void applyToChain() { + // Entries + chain.getEntries().clear(); + for (ChainedAbilityEntry entry : entries) { + chain.addEntry(entry); + } + + // Conditions + chain.getConditions().clear(); + for (AbilityCondition c : conditions) { + chain.getConditions().add(c); + } + + // Remove consumed NPC slots (descending order to preserve indices) + if (npcSlots != null && !consumedSlotIndices.isEmpty()) { + Collections.sort(consumedSlotIndices, Collections.reverseOrder()); + for (int idx : consumedSlotIndices) { + if (idx < npcSlots.size()) { + npcSlots.remove(idx); + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java new file mode 100644 index 000000000..b40753410 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java @@ -0,0 +1,62 @@ +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; + +/** + * Choice dialog for adding an entry to a chain. + * Options: By Reference, Create New, Built-in, From NPC Slots (optional). + */ +public class SubGuiChainedEntrySource extends SubGuiSimpleChoice { + + public static final int SOURCE_NONE = -1; + public static final int SOURCE_NPC_SLOTS = 0; + public static final int SOURCE_LOAD_PRESET = 1; + public static final int SOURCE_CREATE_NEW = 2; + public static final int SOURCE_BUILT_IN = 3; + + private final boolean showNpcOption; + + public SubGuiChainedEntrySource() { + this(true); + } + + public SubGuiChainedEntrySource(boolean showNpcOption) { + this.showNpcOption = showNpcOption; + setBackground("menubg.png"); + xSize = 200; + ySize = showNpcOption ? 132 : 110; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.entrySource", guiLeft + 10, y)); + + y += 20; + addButton(new GuiNpcButton(SOURCE_LOAD_PRESET, guiLeft + 10, y, 180, 20, "ability.byReference")); + + y += 22; + addButton(new GuiNpcButton(SOURCE_CREATE_NEW, guiLeft + 10, y, 180, 20, "ability.createNew")); + + y += 22; + addButton(new GuiNpcButton(SOURCE_BUILT_IN, guiLeft + 10, y, 180, 20, "gui.builtin")); + + if (showNpcOption) { + y += 22; + addButton(new GuiNpcButton(SOURCE_NPC_SLOTS, guiLeft + 10, y, 180, 20, "ability.fromNpc")); + } + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + if (id >= 0 && id <= 3) { + setResult(id); + close(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java index d941f19ec..b0ed1d635 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java @@ -1,190 +1,310 @@ package noppes.npcs.client.gui.advanced; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.util.Register; 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.GuiNpcTextField; -import noppes.npcs.client.gui.util.ITextfieldListener; -import noppes.npcs.client.gui.util.SubGuiInterface; +import net.minecraft.client.resources.I18n; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.util.*; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; /** - * SubGui for editing a single ability condition. - * Allows selecting condition type and configuring its parameters. + * SubGui for editing a single AbilityCondition. + * + * Split-panel layout: + * Left – Mod namespace filter + scrollable condition type list + * Right – FieldDef configuration for the selected condition */ -public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener { +public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, ICustomScrollListener { - // Condition types - private static final String[] CONDITION_TYPES = { - "condition.hp_above", - "condition.hp_below", - "condition.target_hp_above", - "condition.target_hp_below", - "condition.hit_count" - }; + private static final int DECLARATIVE_ID_START = 1000; + private static final int CLEAR_ID_START = 2000; + private static final int LABEL_ID_START = 3000; - private static final String[] CONDITION_TYPE_IDS = { - "hp_above", - "hp_below", - "target_hp_above", - "target_hp_below", - "hit_count" - }; + private static final int BTN_NAMESPACE = 1; + private static final int BTN_CANCEL = 10; + private static final int BTN_DONE = 11; + private static final int TF_SEARCH = 12; - // Current condition being edited - private Condition condition; - private Condition result; + // Left panel + private static final int LEFT_WIDTH = 110; + private static final int LEFT_MARGIN = 5; - // State - private int selectedTypeIndex = 0; - private float threshold = 0.5f; // For HP conditions (0.0-1.0) - private int requiredHits = 3; // For hit_count - private int withinTicks = 60; // For hit_count + // Right panel + private static final int RIGHT_GAP = 5; - public SubGuiConditionEdit(Condition existing) { - this.condition = existing; + private String searchText = ""; + + private AbilityCondition condition; + private AbilityCondition result; + private String selectedTypeId; + + // Namespace filter + private int namespaceFilter = 0; // 0 = ALL, 1 = cnpc, 2+ = modded namespaces + private List modNamespaces; + + // Type list + private GuiCustomScroll scroll; + private final HashMap displayNameToTypeId = new HashMap<>(); + private String[] filteredTypeIds; + + private AbilityFieldBuilder builder; + + public SubGuiConditionEdit(AbilityCondition existing) { this.result = null; + this.modNamespaces = getModNamespaces(); if (existing != null) { - String typeId = existing.getTypeId(); - for (int i = 0; i < CONDITION_TYPE_IDS.length; i++) { - if (CONDITION_TYPE_IDS[i].equals(typeId)) { - selectedTypeIndex = i; - break; - } + this.condition = existing; + this.selectedTypeId = existing.getTypeId(); + // Set namespace filter to match existing condition + setNamespaceForTypeId(selectedTypeId); + } else { + // Default to first available condition + String[] allTypes = AbilityController.Instance.getConditionTypes(); + if (allTypes.length > 0) { + this.selectedTypeId = allTypes[0]; + this.condition = spawnCondition(selectedTypeId); } - loadFromCondition(existing); } - setBackground("menubg.png"); - xSize = 220; - ySize = 140; + setBackground("menubg.png", 217); + xSize = 356; + ySize = 200; } - private void loadFromCondition(Condition cond) { - String typeId = cond.getTypeId(); - if (typeId.equals("hit_count")) { - Condition.ConditionHitCount hitCount = (Condition.ConditionHitCount) cond; - requiredHits = hitCount.getRequiredHits(); - withinTicks = hitCount.getWithinTicks(); - } else { - // HP-based conditions - net.minecraft.nbt.NBTTagCompound nbt = cond.writeNBT(); - threshold = nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; + private List getModNamespaces() { + List result = new ArrayList<>(); + List registered = Register.REGISTERED_NAMESPACES.get("condition"); + if (registered != null) { + result.addAll(registered); } + return result; + } + + private void setNamespaceForTypeId(String typeId) { + if (typeId == null) return; + String[] parts = typeId.split("\\.", 3); + if (parts.length < 2) return; + String ns = parts[1]; + + if ("cnpc".equals(ns)) { + namespaceFilter = 1; + } else { + for (int i = 0; i < modNamespaces.size(); i++) { + if (modNamespaces.get(i).equals(ns)) { + namespaceFilter = 2 + i; + return; + } + } + namespaceFilter = 0; // Fallback to ALL + } + } + + private String getNamespaceFilterLabel() { + if (namespaceFilter == 0) return "ALL"; + if (namespaceFilter == 1) return "CNPC"; + int modIdx = namespaceFilter - 2; + if (modIdx >= 0 && modIdx < modNamespaces.size()) { + String ns = modNamespaces.get(modIdx); + String display = Register.NAMESPACE_DISPLAY_NAMES.get(ns); + return display != null ? display : ns.toUpperCase(); + } + return "ALL"; + } + + private void cycleNamespaceFilter() { + namespaceFilter++; + // 0=ALL, 1=CNPC, 2..2+N-1=mod namespaces, then wrap + int max = 2 + modNamespaces.size(); + if (namespaceFilter >= max) { + namespaceFilter = 0; + } + // Skip empty mod namespace slots + if (namespaceFilter >= 2) { + int modIdx = namespaceFilter - 2; + if (modIdx >= modNamespaces.size()) { + namespaceFilter = 0; + } + } + } + + private String[] getFilteredTypes() { + if (namespaceFilter == 0) { + return AbilityController.Instance.getConditionTypes(); + } else if (namespaceFilter == 1) { + return AbilityController.Instance.getConditionTypesByNamespace("cnpc"); + } else { + int modIdx = namespaceFilter - 2; + if (modIdx >= 0 && modIdx < modNamespaces.size()) { + return AbilityController.Instance.getConditionTypesByNamespace(modNamespaces.get(modIdx)); + } + return AbilityController.Instance.getConditionTypes(); + } + } + + private AbilityCondition spawnCondition(String typeId) { + if (typeId == null) return null; + Supplier factory = AbilityController.Instance.getConditionType(typeId); + return factory != null ? factory.get() : null; } @Override public void initGui() { + GuiNpcTextField.unfocus(); super.initGui(); - int y = guiTop + 8; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 90; + int leftX = guiLeft + LEFT_MARGIN; + int btnY = guiTop + ySize - 26; - // Title - addLabel(new GuiNpcLabel(0, "condition.edit", labelX, y)); - y += 18; + // Namespace filter button (above left scroll only) + addButton(new GuiNpcButton(BTN_NAMESPACE, leftX, guiTop + 5, LEFT_WIDTH, 20, getNamespaceFilterLabel())); - // Condition Type selector - addLabel(new GuiNpcLabel(1, "gui.type", labelX, y + 5)); - GuiNpcButton typeBtn = new GuiNpcButton(1, fieldX, y, 115, 20, CONDITION_TYPES, selectedTypeIndex); - typeBtn.setHoverText("condition.hover.type"); - addButton(typeBtn); - y += 26; - - // Type-specific fields - String typeId = CONDITION_TYPE_IDS[selectedTypeIndex]; - if (typeId.equals("hit_count")) { - // Hit count fields - addLabel(new GuiNpcLabel(2, "condition.hits", labelX, y + 5)); - GuiNpcTextField hitsField = new GuiNpcTextField(2, this, fontRendererObj, fieldX, y, 40, 20, "" + requiredHits); - hitsField.setIntegersOnly(); - hitsField.setMinMaxDefault(1, 100, 3); - hitsField.setHoverText("condition.hover.hits"); - addTextField(hitsField); - y += 24; - - addLabel(new GuiNpcLabel(3, "condition.within", labelX, y + 5)); - GuiNpcTextField ticksField = new GuiNpcTextField(3, this, fontRendererObj, fieldX, y, 40, 20, "" + withinTicks); - ticksField.setIntegersOnly(); - ticksField.setMinMaxDefault(1, 1200, 60); - ticksField.setHoverText("condition.hover.within"); - addTextField(ticksField); - } else { - // HP threshold field (as percentage) - addLabel(new GuiNpcLabel(2, "condition.percent", labelX, y + 5)); - int percent = (int) (threshold * 100); - GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, "" + percent); - thresholdField.setIntegersOnly(); - thresholdField.setMinMaxDefault(1, 99, 50); - thresholdField.setHoverText("condition.hover.threshold"); - addTextField(thresholdField); - addLabel(new GuiNpcLabel(4, "%", fieldX + 45, y + 5)); + // Build filtered type list + filteredTypeIds = getFilteredTypes(); + displayNameToTypeId.clear(); + List scrollList = new ArrayList<>(); + for (String typeId : filteredTypeIds) { + Supplier factory = AbilityController.Instance.getConditionType(typeId); + String displayName = factory != null ? I18n.format(factory.get().getName()) : typeId; + if (!searchText.isEmpty() && !displayName.toLowerCase().contains(searchText.toLowerCase())) continue; + scrollList.add(displayName); + displayNameToTypeId.put(displayName, typeId); } + // Left panel: condition type scroll list (between namespace button and search bar) + int scrollTop = guiTop + 29; + int scrollBottom = btnY - 24; + int scrollHeight = scrollBottom - scrollTop; + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + } + scroll.guiLeft = leftX; + scroll.guiTop = scrollTop; + scroll.setSize(LEFT_WIDTH, scrollHeight); + scroll.setUnsortedList(scrollList); + + // Pre-select current condition type in scroll + if (selectedTypeId != null) { + for (int i = 0; i < scrollList.size(); i++) { + String typeId = displayNameToTypeId.get(scrollList.get(i)); + if (typeId != null && typeId.equals(selectedTypeId)) { + scroll.selected = i; + break; + } + } + } + addScroll(scroll); + + // Search text field (below left scroll) + GuiNpcTextField searchField = new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, leftX, scrollBottom + 2, LEFT_WIDTH, 20, searchText); + searchField.setHoverText("gui.search"); + addTextField(searchField); + + // Right panel: condition config via FieldDef (full height from top to buttons) + int rightX = leftX + LEFT_WIDTH + RIGHT_GAP; + int rightW = xSize - LEFT_MARGIN * 2 - LEFT_WIDTH - RIGHT_GAP; + int rightTop = guiTop + 5; + int rightHeight = btnY - rightTop - 4; + + List fields = new ArrayList<>(); + if (condition != null) { + fields = condition.getAllDefinitions(); + } + + builder = new AbilityFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); + builder.contentRight(rightW); + builder.startY(5); + builder.buildScrollWindow(fields, rightX, rightTop, rightW, rightHeight); + // Bottom buttons - addButton(new GuiNpcButton(10, guiLeft + 8, guiTop + ySize - 28, 60, 20, "gui.cancel")); - addButton(new GuiNpcButton(11, guiLeft + xSize - 68, guiTop + ySize - 28, 60, 20, "gui.done")); + addButton(new GuiNpcButton(BTN_CANCEL, leftX, btnY, 60, 20, "gui.cancel")); + GuiNpcButton doneBtn = new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done"); + if (condition == null || !condition.isConfigured()) { + doneBtn.setEnabled(false); + } + addButton(doneBtn); } @Override public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - if (id == 1) { - // Type changed - selectedTypeIndex = ((GuiNpcButton) guibutton).getValue(); + if (id == BTN_NAMESPACE) { + cycleNamespaceFilter(); initGui(); - } else if (id == 10) { - // Cancel - close without saving + return; + } + + if (id == BTN_CANCEL) { result = null; close(); - } else if (id == 11) { - // Done - create condition and close - result = createCondition(); + return; + } + + if (id == BTN_DONE) { + result = condition; close(); + return; + } + + if (builder != null && builder.handleButtonEvent(id, guibutton)) { + if (!hasSubGui()) { + initGui(); + } } } + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && scroll.hasSelected()) { + String displayName = scroll.getSelected(); + String typeId = displayNameToTypeId.get(displayName); + if (typeId != null && !typeId.equals(selectedTypeId)) { + selectedTypeId = typeId; + condition = spawnCondition(selectedTypeId); + initGui(); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + // Same as single click — user still needs to configure fields + } + @Override public void unFocused(GuiNpcTextField textField) { - int id = textField.id; - - if (id == 2) { - requiredHits = textField.getInteger(); - } else if (id == 3) { - withinTicks = textField.getInteger(); - } else if (id == 4) { - int percent = textField.getInteger(); - threshold = percent / 100.0f; + if (textField.id == TF_SEARCH) { + String newText = textField.getText(); + if (!newText.equals(searchText)) { + searchText = newText; + initGui(); + } + return; + } + if (textField.id < DECLARATIVE_ID_START) return; + if (builder != null && builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); } } - private Condition createCondition() { - String typeId = CONDITION_TYPE_IDS[selectedTypeIndex]; - - switch (typeId) { - case "hp_above": - return new Condition.ConditionHPAbove(threshold); - case "hp_below": - return new Condition.ConditionHPBelow(threshold); - case "target_hp_above": - return new Condition.ConditionTargetHPAbove(threshold); - case "target_hp_below": - return new Condition.ConditionTargetHPBelow(threshold); - case "hit_count": - return new Condition.ConditionHitCount(requiredHits, withinTicks); - default: - return null; + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (builder != null && builder.handleSubGuiClosed(subgui)) { + initGui(); } } - /** - * Get the resulting condition after dialog closes. - * Returns null if cancelled or no valid condition. - */ - public Condition getResult() { + public AbilityCondition getResult() { return result; } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java new file mode 100644 index 000000000..233ad8ece --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java @@ -0,0 +1,247 @@ +package noppes.npcs.client.gui.advanced; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * SubGui for selecting a custom effect from CustomEffectController. + * Supports switching between effect maps (index 0 = custom, addon indices via toggle button). + */ +@SideOnly(Side.CLIENT) +public class SubGuiCustomEffectSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + + /** + * Builds the condition editor's effect-select field. + *

+ * This lives here rather than in ConditionHasEffect because the lambdas below carry this + * class in their method descriptors. The condition is a both-side class, and @SideOnly does + * not strip the synthetic lambda methods it generates - so anything reflecting over its + * declared methods on a server would resolve those descriptors and fail to find this type. + */ + public static FieldDef createSelectField(ConditionHasEffect condition) { + return FieldDef.subGuiField("condition.select_effect", + () -> new SubGuiCustomEffectSelect(condition.getEffectId(), condition.getEffectIndex()), + gui -> { + SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui; + if (sel.getSelectedEffectId() >= 0) { + condition.setEffect(sel.getSelectedEffectId(), sel.getSelectedIndex()); + } + }) + .buttonLabel(() -> { + if (condition.getEffectId() < 0) return "None"; + CustomEffect effect = condition.getEffect(); + return effect != null ? effect.getName() : "ID:" + condition.getEffectId(); + }) + .clearable(() -> condition.setEffect(-1, 0)); + } + + private GuiCustomScroll scroll; + private final HashMap displayNameToId = new HashMap<>(); + private final HashMap allDisplayNameToId = new HashMap<>(); + private int selectedEffectId = -1; + private int selectedIndex = 0; + private String search = ""; + private final int preselectedId; + private final int preselectedIndex; + + /** The effect map index currently being viewed */ + private int viewIndex = 0; + + /** Ordered list of available indices for toggling */ + private List availableIndices; + + public SubGuiCustomEffectSelect(int preselectedId) { + this(preselectedId, 0); + } + + public SubGuiCustomEffectSelect(int preselectedId, int preselectedIndex) { + this.preselectedId = preselectedId; + this.preselectedIndex = preselectedIndex; + this.viewIndex = preselectedIndex; + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + buildAvailableIndices(); + + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); + + // Toggle button for switching between effect lists (only if addon indices exist) + if (availableIndices.size() > 1) { + String label = getViewLabel(); + addButton(new GuiNpcButton(2, guiLeft + 5, guiTop + 26, 190, 20, label)); + } + + int scrollTop = availableIndices.size() > 1 ? guiTop + 49 : guiTop + 26; + int scrollHeight = availableIndices.size() > 1 ? 122 : 145; + + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + } + scroll.setSize(190, scrollHeight); + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = scrollTop; + addScroll(scroll); + + buildAllEffects(); + List filtered = getFilteredList(); + scroll.setUnsortedList(filtered); + + // Pre-select current effect (only if viewing the same index) + if (preselectedId >= 0 && viewIndex == preselectedIndex && !scroll.hasSelected()) { + for (String name : filtered) { + Integer id = displayNameToId.get(name); + if (id != null && id == preselectedId) { + scroll.setSelected(name); + break; + } + } + } + + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); + getButton(0).setEnabled(scroll.hasSelected()); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + private void buildAvailableIndices() { + availableIndices = new ArrayList<>(); + CustomEffectController controller = CustomEffectController.getInstance(); + + // Always include index 0 + availableIndices.add(0); + + // Add any addon indices that have registered labels + HashMap labels = controller.getIndexLabels(); + for (int idx : labels.keySet()) { + if (idx != 0 && controller.getEffectMap(idx) != null) { + availableIndices.add(idx); + } + } + Collections.sort(availableIndices); + + // Ensure viewIndex is valid + if (!availableIndices.contains(viewIndex)) { + viewIndex = 0; + } + } + + private String getViewLabel() { + if (viewIndex == 0) { + return "Custom Effects"; + } + HashMap labels = CustomEffectController.getInstance().getIndexLabels(); + String label = labels.get(viewIndex); + return label != null ? label : "Index " + viewIndex; + } + + private void buildAllEffects() { + allDisplayNameToId.clear(); + HashMap effects = CustomEffectController.getInstance().getEffectMap(viewIndex); + if (effects == null) return; + for (CustomEffect ce : effects.values()) { + if (ce.getName() != null && !ce.getName().isEmpty()) { + allDisplayNameToId.put(ce.getName(), ce.id); + } + } + } + + private List getFilteredList() { + List list = new ArrayList<>(); + displayNameToId.clear(); + for (Map.Entry entry : allDisplayNameToId.entrySet()) { + String name = entry.getKey(); + if (search.isEmpty() || name.toLowerCase().contains(search)) { + list.add(name); + displayNameToId.put(name, entry.getValue()); + } + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0 && scroll.hasSelected()) { + String name = scroll.getSelected(); + Integer id = displayNameToId.get(name); + selectedEffectId = id != null ? id : -1; + selectedIndex = viewIndex; + close(); + } else if (guibutton.id == 1) { + selectedEffectId = -1; + close(); + } else if (guibutton.id == 2) { + // Toggle to next available index + int currentPos = availableIndices.indexOf(viewIndex); + int nextPos = (currentPos + 1) % availableIndices.size(); + viewIndex = availableIndices.get(nextPos); + search = ""; + scroll = null; + initGui(); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0) { + getButton(0).setEnabled(scroll.hasSelected()); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && selection != null) { + Integer id = displayNameToId.get(selection); + selectedEffectId = id != null ? id : -1; + selectedIndex = viewIndex; + close(); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + String newSearch = getTextField(10).getText().toLowerCase(); + if (!search.equals(newSearch)) { + search = newSearch; + scroll.setUnsortedList(getFilteredList()); + scroll.resetScroll(); + } + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + } + + public int getSelectedEffectId() { + return selectedEffectId; + } + + public int getSelectedIndex() { + return selectedIndex; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java index b16386c32..5d316f416 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java @@ -10,7 +10,13 @@ import noppes.npcs.client.gui.util.SubGuiInterface; */ public class SubGuiDuplicateNameConfirm extends SubGuiInterface { - private boolean confirmed = false; + public enum Result { + CONTINUE, + BACK, + CANCEL + } + + private Result result = Result.CANCEL; public SubGuiDuplicateNameConfirm() { setBackground("menubg.png"); @@ -26,22 +32,38 @@ public class SubGuiDuplicateNameConfirm extends SubGuiInterface { 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")); + addButton(new GuiNpcButton(0, guiLeft + 10, y, 65, 20, "gui.continue")); + addButton(new GuiNpcButton(1, guiLeft + 78, y, 65, 20, "gui.back")); + addButton(new GuiNpcButton(2, guiLeft + 146, y, 65, 20, "gui.cancel")); } @Override public void buttonEvent(GuiButton guibutton) { if (guibutton.id == 0) { - confirmed = true; + result = Result.CONTINUE; close(); } else if (guibutton.id == 1) { - confirmed = false; + result = Result.BACK; + close(); + } else if (guibutton.id == 2) { + result = Result.CANCEL; close(); } } + public Result getResult() { + return result; + } + public boolean isConfirmed() { - return confirmed; + return result == Result.CONTINUE; + } + + public boolean isBack() { + return result == Result.BACK; + } + + public boolean isCancelled() { + return result == Result.CANCEL; } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiLoadTypeChoice.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiLoadTypeChoice.java new file mode 100644 index 000000000..cb3fd4cb3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiLoadTypeChoice.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; + +/** + * Choice dialog for the Load button: Load Ability or Load Chain. + */ +public class SubGuiLoadTypeChoice extends SubGuiSimpleChoice { + + public static final int RESULT_NONE = -1; + public static final int RESULT_ABILITY = 0; + public static final int RESULT_CHAIN = 1; + + public SubGuiLoadTypeChoice() { + setBackground("menubg.png"); + xSize = 200; + ySize = 80; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.loadType", guiLeft + 10, y)); + + y += 20; + addButton(new GuiNpcButton(0, guiLeft + 10, y, 85, 20, "ability.loadAbility")); + addButton(new GuiNpcButton(1, guiLeft + 105, y, 85, 20, "ability.loadChain")); + + y += 24; + addButton(new GuiNpcButton(2, guiLeft + 55, y, 90, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + if (id == 0 || id == 1) { + setResult(id); + close(); + } else if (id == 2) { + close(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiNpcSlotPicker.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiNpcSlotPicker.java new file mode 100644 index 000000000..90086857f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiNpcSlotPicker.java @@ -0,0 +1,113 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityAction; +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.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +/** + * Picker for selecting an NPC ability slot to consume into a chain entry. + * Shows standalone (non-chain) ability slots from the NPC's current list. + */ +public class SubGuiNpcSlotPicker extends SubGuiInterface implements ICustomScrollListener { + + private final List npcSlots; + private final List validIndices = new ArrayList<>(); + private GuiCustomScroll scroll; + private int selectedIndex = -1; + + public SubGuiNpcSlotPicker(List npcSlots) { + this.npcSlots = npcSlots; + setBackground("menubg.png"); + xSize = 220; + ySize = 200; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 5; + addLabel(new GuiNpcLabel(0, "ability.selectSlot", guiLeft + 10, y)); + y += 14; + + List displayList = new ArrayList<>(); + validIndices.clear(); + + for (int i = 0; i < npcSlots.size(); i++) { + AbilityAction slot = npcSlots.get(i); + // Only show standalone abilities (not chains) + if (slot.isChain()) continue; + + Ability ability = slot.getAbility(); + if (ability == null) continue; + + String typeName = I18n.format(ability.getTypeId()); + String customName = ability.getName(); + String display; + if (customName != null && !customName.isEmpty() && !customName.equals(typeName)) { + display = (i + 1) + ". " + customName + " (" + typeName + ")"; + } else { + display = (i + 1) + ". " + typeName; + } + + if (slot.isReference()) { + display = "\u00A7e" + display + " (Ref)"; + } + + displayList.add(display); + validIndices.add(i); + } + + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + scroll.setSize(200, 130); + } + scroll.guiLeft = guiLeft + 10; + scroll.guiTop = y; + scroll.setList(displayList); + addScroll(scroll); + + y += 133; + addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.select")); + addButton(new GuiNpcButton(1, guiLeft + 115, y, 95, 20, "gui.cancel")); + getButton(0).setEnabled(selectedIndex >= 0); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0 && selectedIndex >= 0) { + close(); + } else if (guibutton.id == 1) { + selectedIndex = -1; + close(); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && guiCustomScroll.selected >= 0 && guiCustomScroll.selected < validIndices.size()) { + selectedIndex = validIndices.get(guiCustomScroll.selected); + initGui(); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && selectedIndex >= 0) { + close(); + } + } + + public int getSelectedIndex() { + return selectedIndex; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiSimpleChoice.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiSimpleChoice.java new file mode 100644 index 000000000..1fb3e8fe8 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiSimpleChoice.java @@ -0,0 +1,23 @@ +package noppes.npcs.client.gui.advanced; + +import noppes.npcs.client.gui.util.SubGuiInterface; + +/** + * Base class for simple choice dialogs that present a few buttons and return an int result. + * Subclasses define their own layout in {@code initGui()} and call {@code setResult()} from {@code buttonEvent()}. + * The parent reads the result via {@code getResult()} in {@code subGuiClosed()}. + * + *

Result is -1 by default (cancelled / no selection).

+ */ +public abstract class SubGuiSimpleChoice extends SubGuiInterface { + + private int result = -1; + + protected final void setResult(int result) { + this.result = result; + } + + public int getResult() { + return result; + } +} 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..a2b523ec6 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -2,12 +2,13 @@ package noppes.npcs.client.gui.builder; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.data.Animation; import noppes.npcs.client.gui.SubGuiColorSelector; import noppes.npcs.client.gui.select.GuiAnimationSelection; import noppes.npcs.client.gui.select.GuiSoundSelection; +import noppes.npcs.client.gui.select.GuiTexturePathSelection; import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.Animation; import java.util.List; import java.util.function.BooleanSupplier; @@ -32,8 +33,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; @@ -118,10 +119,11 @@ public class FieldDef { return def; } - public static FieldDef subGuiField(String label, Supplier factory, Consumer resultHandler) { + @SuppressWarnings("unchecked") + public static FieldDef subGuiField(String label, Supplier factory, Consumer resultHandler) { FieldDef def = new FieldDef(label, FieldType.SUB_GUI); - def.subGuiFactory = factory; - def.subGuiResultHandler = resultHandler; + def.subGuiFactory = (Supplier) (Supplier) factory; + def.subGuiResultHandler = (Consumer) (Consumer) resultHandler; return def; } @@ -154,8 +156,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); } @@ -174,9 +176,21 @@ public class FieldDef { .clearable(() -> setter.accept("")); } + public static FieldDef textureSubGui(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.STRING_BROWSE); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept(v != null ? v.toString() : ""); + def.subGuiFactory = () -> new GuiTexturePathSelection(getter.get()); + def.subGuiResultHandler = gui -> { + GuiTexturePathSelection t = (GuiTexturePathSelection) gui; + if (t.selectedResource != null) setter.accept(t.selectedResource.toString()); + }; + return def; + } + public static FieldDef animSubGui(String label, - Supplier idGetter, Consumer idSetter, - Supplier nameGetter, Consumer nameSetter) { + Supplier idGetter, Consumer idSetter, + Supplier nameGetter, Consumer nameSetter) { return subGuiField(label, () -> new GuiAnimationSelection(idGetter.get(), nameGetter.get()), gui -> { @@ -186,23 +200,34 @@ public class FieldDef { idSetter.accept(-1); } else { idSetter.accept(sel.selectedAnimationId); - nameSetter.accept(""); + String customName = sel.getSelectedName(); + nameSetter.accept(customName != null ? customName : ""); } }) .buttonLabel(() -> { String name = nameGetter.get(); - if (name != null && !name.isEmpty()) return name; int id = idGetter.get(); + if (id < 0 && name != null && !name.isEmpty()) { + // Built-in animation: show just the name + return name; + } if (id >= 0) { + // Custom animation: show (X) Name + if (name != null && !name.isEmpty()) { + return "(" + id + ") " + name; + } Animation anim = AnimationController.Instance != null ? (Animation) AnimationController.Instance.get(id) : null; String animName = anim != null ? anim.getName() : ""; return animName != null && !animName.isEmpty() - ? "(ID: " + id + ") " + animName : "ID: " + id; + ? "(" + id + ") " + animName : String.valueOf(id); } return "gui.none"; }) - .clearable(() -> { idSetter.accept(-1); nameSetter.accept(""); }); + .clearable(() -> { + idSetter.accept(-1); + nameSetter.accept(""); + }); } // ═══════════════════════════════════════════════════════════════════ @@ -264,21 +289,65 @@ public class FieldDef { // GETTERS // ═══════════════════════════════════════════════════════════════════ - public String getLabel() { return label; } - public FieldType getType() { return type; } - public String getTab() { return tab; } - public boolean isVisible() { return visibleWhen.getAsBoolean(); } - public boolean isEnabled() { return enabledWhen.getAsBoolean(); } - 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 Class> getEnumClass() { return enumClass; } - public String[] getStringEnumValues() { return stringEnumValues; } - public Supplier getSubGuiFactory() { return subGuiFactory; } - public Consumer getSubGuiResultHandler() { return subGuiResultHandler; } - public boolean hasClearAction() { return clearAction != null; } - public Runnable getClearAction() { return clearAction; } + public String getLabel() { + return label; + } + + public FieldType getType() { + return type; + } + + public String getTab() { + return tab; + } + + public boolean isVisible() { + return visibleWhen.getAsBoolean(); + } + + public boolean isEnabled() { + return enabledWhen.getAsBoolean(); + } + + public String getHoverText() { + return hoverText; + } + + public float getMin() { + return min; + } + + public float getMax() { + return max; + } + + public boolean hasRange() { + return min != 0 || max != Float.POSITIVE_INFINITY; + } + + public Class> getEnumClass() { + return enumClass; + } + + public String[] getStringEnumValues() { + return stringEnumValues; + } + + public Supplier getSubGuiFactory() { + return subGuiFactory; + } + + public Consumer getSubGuiResultHandler() { + return subGuiResultHandler; + } + + public boolean hasClearAction() { + return clearAction != null; + } + + public Runnable getClearAction() { + return clearAction; + } public Object getValue() { return getter != null ? getter.get() : null; @@ -305,8 +374,13 @@ public class FieldDef { return buttonTextColorSupplier != null ? buttonTextColorSupplier.get() : null; } - public FieldDef getLeftChild() { return leftChild; } - public FieldDef getRightChild() { return rightChild; } + public FieldDef getLeftChild() { + return leftChild; + } + + public FieldDef getRightChild() { + return rightChild; + } // ═══════════════════════════════════════════════════════════════════ // LIST MANIPULATION (for mod injection) @@ -356,7 +430,7 @@ public class FieldDef { * * @param fields The field list to modify * @param targetLabel The label of the field to modify - * @param condition The condition to replace + * @param condition The condition to replace * @return true if the target was found and the condition was modified */ public static boolean modifyVisibility(List fields, String targetLabel, BooleanSupplier condition) { diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldType.java b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java index 052e2f4cd..347086b78 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldType.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java @@ -15,5 +15,8 @@ public enum FieldType { SECTION_HEADER, LABEL, EFFECTS_LIST, - ROW + CUSTOM_EFFECTS_LIST, + EFFECT_ACTIONS_LIST, + ROW, + STRING_BROWSE } 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 b1f123956..3f1d06b89 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -69,13 +69,32 @@ public class GuiFieldBuilder { // CONFIG CHAINING // ═══════════════════════════════════════════════════════════════════ - public GuiFieldBuilder scrollWindowId(int id) { this.scrollWindowId = id; return this; } - public GuiFieldBuilder contentRight(int v) { this.contentRight = v; return this; } - public GuiFieldBuilder startIds(int widget, int clear, int label) { - this.widgetId = widget; this.clearId = clear; this.labelId = label; return this; + public GuiFieldBuilder scrollWindowId(int id) { + this.scrollWindowId = id; + return this; + } + + public GuiFieldBuilder contentRight(int v) { + this.contentRight = v; + return this; + } + + public GuiFieldBuilder startIds(int widget, int clear, int label) { + this.widgetId = widget; + this.clearId = clear; + this.labelId = label; + return this; + } + + public GuiFieldBuilder startY(int y) { + this.startY = y; + return this; + } + + public GuiFieldBuilder rowHeight(int h) { + this.rowHeight = h; + return this; } - public GuiFieldBuilder startY(int y) { this.startY = y; return this; } - public GuiFieldBuilder rowHeight(int h) { this.rowHeight = h; return this; } // ═══════════════════════════════════════════════════════════════════ // BUILD @@ -98,6 +117,7 @@ public class GuiFieldBuilder { /** * Processes all fields and adds widgets to the scroll window. + * * @return the final Y position after all fields */ protected int build(List fields) { @@ -173,8 +193,14 @@ public class GuiFieldBuilder { } private int lastHandledIndex = -1; - protected void setLastHandledIndex(int index) { this.lastHandledIndex = index; } - protected int getLastHandledIndex() { return lastHandledIndex; } + + protected void setLastHandledIndex(int index) { + this.lastHandledIndex = index; + } + + protected int getLastHandledIndex() { + return lastHandledIndex; + } // ═══════════════════════════════════════════════════════════════════ // FIELD RENDERING @@ -194,7 +220,7 @@ public class GuiFieldBuilder { float fVal = def.getValue() instanceof Number ? ((Number) def.getValue()).floatValue() : 0f; GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, String.valueOf(fVal)); tf.setFloatsOnly(); - if (def.hasRange()) tf.setMinMaxDefaultFloat(def.getMin(), def.getMax(), fVal); + tf.setMinMaxDefaultFloat(def.getMin(), def.getMax(), fVal); if (!def.isEnabled()) tf.setEnabled(false); if (hover != null) tf.setHoverText(hover); sw.addTextField(tf); @@ -207,7 +233,7 @@ public class GuiFieldBuilder { int iVal = def.getValue() instanceof Number ? ((Number) def.getValue()).intValue() : 0; GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, String.valueOf(iVal)); tf.setIntegersOnly(); - if (def.hasRange()) tf.setMinMaxDefault((int) def.getMin(), (int) def.getMax(), iVal); + tf.setMinMaxDefault((int) def.getMin(), (int) def.getMax(), iVal); if (!def.isEnabled()) tf.setEnabled(false); if (hover != null) tf.setHoverText(hover); sw.addTextField(tf); @@ -219,6 +245,9 @@ public class GuiFieldBuilder { case STRING: { String sVal = def.getValue() != null ? def.getValue().toString() : ""; GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, sVal); + if ("gui.name".equals(def.getLabel())) { + tf.setFileNameSafe(); + } if (!def.isEnabled()) tf.setEnabled(false); if (hover != null) tf.setHoverText(hover); sw.addTextField(tf); @@ -268,7 +297,10 @@ public class GuiFieldBuilder { String curVal = def.getStringEnumValue(); int selected = 0; for (int i = 0; i < values.length; i++) { - if (values[i].equals(curVal)) { selected = i; break; } + if (values[i].equals(curVal)) { + selected = i; + break; + } } GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, fieldW, 20, values, selected); if (!def.isEnabled()) btn.setEnabled(false); @@ -284,12 +316,12 @@ public class GuiFieldBuilder { String btnText = def.getButtonLabel(); int btnW; if (def.hasClearAction()) { - btnW = contentRight - 22 - fieldX; - GuiNpcButton clearBtn = new GuiNpcButton(clearId, contentRight - 20, y, 20, 20, "X"); + btnW = fieldW - 22; + GuiNpcButton clearBtn = new GuiNpcButton(clearId, fieldX + fieldW - 20, y, 20, 20, "X"); sw.addButton(clearBtn); clearFieldMap.put(clearId, def); } else { - btnW = contentRight - fieldX; + btnW = fieldW; } GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, btnW, 20, btnText); Integer textColor = def.getButtonTextColor(); @@ -302,6 +334,25 @@ public class GuiFieldBuilder { clearId++; break; } + case STRING_BROWSE: { + // Text field for manual input (URLs, paths) + browse button + int btnW = 20; + int tfW = fieldW - btnW - 2; + String sVal = def.getValue() != null ? def.getValue().toString() : ""; + GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, tfW, 20, sVal); + if (!def.isEnabled()) tf.setEnabled(false); + if (hover != null) tf.setHoverText(hover); + sw.addTextField(tf); + textFieldMap.put(widgetId, def); + widgetId++; + // Browse button + GuiNpcButton browseBtn = new GuiNpcButton(clearId, fieldX + tfW + 2, y, btnW, 20, "..."); + if (!def.isEnabled()) browseBtn.setEnabled(false); + sw.addButton(browseBtn); + buttonFieldMap.put(clearId, def); + clearId++; + break; + } default: // Unknown type — skip, incrementing IDs to stay in sync widgetId++; @@ -315,20 +366,37 @@ public class GuiFieldBuilder { String translated = StatCollector.translateToLocal(def.getLabel()); int labelW = fontRenderer.getStringWidth(translated); int fieldX = colLLabel + labelW + labelPadding; + // Available width before the scrollbar + int maxW = contentRight - fieldX - 15; + if ((def.getType() == FieldType.SUB_GUI || def.getType() == FieldType.STRING_BROWSE) && maxW > 0) { + // SUB_GUI fields fill all available width up to the scrollbar + fieldW = maxW; + } else if (maxW > 0 && fieldW > maxW) { + fieldW = maxW; + } renderFieldAt(def, colLLabel, fieldX, fieldW, y); } protected int getFullFieldWidth(FieldDef def) { switch (def.getType()) { case FLOAT: - case INT: return 60; - case STRING: return 200; - case BOOLEAN: return 50; - case LABEL: return 60; + case INT: + return 60; + case STRING: + return 200; + case BOOLEAN: + return 50; + case LABEL: + return 60; case ENUM: - case STRING_ENUM: return 120; - case SUB_GUI: return def.hasClearAction() ? 175 : 200; - default: return 80; + case STRING_ENUM: + return 120; + case SUB_GUI: + return def.hasClearAction() ? 175 : 200; + case STRING_BROWSE: + return 200; + default: + return 80; } } @@ -387,6 +455,15 @@ public class GuiFieldBuilder { }); } return true; + case STRING_BROWSE: + if (def.getSubGuiFactory() != null) { + parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> { + if (def.getSubGuiResultHandler() != null) { + def.getSubGuiResultHandler().accept(sub); + } + }); + } + return true; default: return false; } @@ -410,7 +487,8 @@ public class GuiFieldBuilder { def.setValue(newVal); return true; } - } catch (NumberFormatException ignored) {} + } catch (NumberFormatException ignored) { + } return false; case INT: try { @@ -421,9 +499,11 @@ public class GuiFieldBuilder { def.setValue(newVal); return true; } - } catch (NumberFormatException ignored) {} + } catch (NumberFormatException ignored) { + } return false; case STRING: + case STRING_BROWSE: String newVal = field.getText(); Object old = def.getValue(); String oldVal = old != null ? old.toString() : ""; @@ -453,10 +533,27 @@ public class GuiFieldBuilder { // GETTERS // ═══════════════════════════════════════════════════════════════════ - public Map getButtonFieldMap() { return buttonFieldMap; } - public Map getTextFieldMap() { return textFieldMap; } - public Map getClearFieldMap() { return clearFieldMap; } - public GuiScrollWindow getScrollWindow() { return sw; } - public int getLastBuildY() { return lastBuildY; } - public int getNextLabelId() { return labelId; } + public Map getButtonFieldMap() { + return buttonFieldMap; + } + + public Map getTextFieldMap() { + return textFieldMap; + } + + public Map getClearFieldMap() { + return clearFieldMap; + } + + public GuiScrollWindow getScrollWindow() { + return sw; + } + + public int getLastBuildY() { + return lastBuildY; + } + + public int getNextLabelId() { + return labelId; + } } diff --git a/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java b/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java index 58303db63..021323329 100644 --- a/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java +++ b/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java @@ -7,6 +7,7 @@ import noppes.npcs.api.gui.ICustomGuiComponent; import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.client.gui.custom.GuiCustom; import noppes.npcs.client.gui.custom.interfaces.IGuiComponent; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.scripted.gui.ScriptGuiTexturedRect; import org.lwjgl.opengl.GL11; @@ -30,6 +31,11 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { float alpha; float rotation; + // Animation + boolean animated; + int frameCount = 1; + int frametime = 2; + public CustomGuiTexturedRect(int id, String texture, int x, int y, int width, int height) { this(id, texture, x, y, width, height, 0, 0); } @@ -64,10 +70,18 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { int totalWidth = this.imageData.getTotalWidth(); int totalHeight = this.imageData.getTotalHeight(); + // Animation V offset + float vOff = 0f; + if (this.imageData.isAnimated()) { + vOff = this.imageData.getCurrentFrameVOffset(); + } else if (this.animated && this.frameCount > 1) { + vOff = AnimationHelper.getFrameVOffset(totalHeight, this.frameCount, this.frametime); + } + float u1 = (float) textureX / (float) totalWidth; float u2 = u1 + (float) width / (float) totalWidth; - float v1 = (float) textureY / (float) totalHeight; - float v2 = v1 + (float) height / (float) totalHeight; + float v1 = vOff + (float) textureY / (float) totalHeight; + float v2 = vOff + ((float) textureY + (float) height) / (float) totalHeight; GL11.glPushMatrix(); float red = (color >> 16 & 255) / 255f; @@ -104,6 +118,9 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { component.setColor(color); component.setAlpha(alpha); component.setRotation(rotation); + if (this.animated && this.frameCount > 1) { + component.setAnimation(this.frameCount, this.frametime); + } return component; } @@ -124,6 +141,12 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { rect.alpha = component.getAlpha(); rect.rotation = component.getRotation(); + if (component.isAnimated()) { + rect.animated = true; + rect.frameCount = component.getFrameCount(); + rect.frametime = component.getFrameTime(); + } + return rect; } } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiAbilityDirectory.java b/src/main/java/noppes/npcs/client/gui/global/GuiAbilityDirectory.java new file mode 100644 index 000000000..0684218c2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiAbilityDirectory.java @@ -0,0 +1,1027 @@ +package noppes.npcs.client.gui.global; + +import kamkeel.npcs.client.renderer.TelegraphRenderer; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.preview.AbilityPreviewExecutor; +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.ChainedAbilityGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityClonePacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityRemovePacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilitySavePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilityClonePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; +import kamkeel.npcs.network.packets.request.category.AbilityCategoryMovePacket; +import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket; +import kamkeel.npcs.network.packets.request.category.CategorySavePacket; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiYesNo; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientEventHandler; +import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect; +import noppes.npcs.client.gui.advanced.SubGuiAbilityVariantSelect; +import noppes.npcs.client.gui.advanced.SubGuiChainedAbilityConfig; +import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiDirectoryCategorized; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiTexturedButton; +import noppes.npcs.client.gui.util.GuiUtil; +import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.data.AnimationData; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.controllers.data.Category; +import noppes.npcs.entity.EntityCustomNpc; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.Vector; + +public class GuiAbilityDirectory extends GuiDirectoryCategorized + implements IAbilityConfigCallback, IChainedAbilityConfigCallback { + + private EntityNPCInterface npc; + private EntityNPCInterface originalNpc; + + // View mode: 0=Built-In, 1=Custom, 2=Chained + private int viewMode = 1; + private boolean currentIsBuiltIn = false; + + // Data caches + private HashMap builtInData = new HashMap<>(); + private Ability selectedAbility = null; + private ChainedAbility selectedChain = null; + + // User type filter: 0=Both, 1=NPC Only, 2=Player Only + private int userTypeFilter = 0; + private static final String[] FILTER_LABELS = {"gui.both", "gui.npcs", "gui.players"}; + + // Pending save state + private Ability pendingSaveAbility = null; + private ChainedAbility pendingSaveChain = null; + private String pendingTypeId = null; + + // Preview playback + private AbilityPreviewExecutor previewExecutor; + private long prevTick = 0; + private double npcStartX, npcStartY, npcStartZ; + private boolean trackingMovement = false; + + // Fixed camera settings (matching GuiAbilityInterface) + private static final float NPC_FACING_YAW = 310f; + private static final float CAMERA_PITCH = 5f; + + public GuiAbilityDirectory(EntityNPCInterface npc) { + super(); + this.originalNpc = npc; + this.npc = createFakeNPC(npc); + rightPanelPercent = 0.38f; + minRightPanelW = 200; + zoomed = 50; + + // Initialize preview executor + previewExecutor = new AbilityPreviewExecutor(); + + // Re-request categories — viewMode was 0 during super() call + requestCategoryList(); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } + + private static EntityNPCInterface createFakeNPC(EntityNPCInterface original) { + EntityCustomNpc fake = new EntityCustomNpc(Minecraft.getMinecraft().theWorld); + fake.display.readToNBT(original.display.writeToNBT(new NBTTagCompound())); + fake.display.name = "ability preview"; + fake.height = original.height; + fake.width = original.width; + fake.display.animationData.setEnabled(true); + return fake; + } + + private boolean isBuiltInMode() { return viewMode == 0; } + private boolean isCustomMode() { return viewMode == 1; } + private boolean isChainedMode() { return viewMode == 2; } + + private int getCategoryType() { + return isChainedMode() ? EnumCategoryType.CHAINED_ABILITY : EnumCategoryType.ABILITY; + } + + // ========== Layout Overrides ========== + + @Override + protected boolean hasCategories() { return !isBuiltInMode(); } + + @Override + protected void computeLayout() { + if (isBuiltInMode()) { + leftPanelPercent = 0.0f; + minLeftPanelW = 0; + } else { + leftPanelPercent = 0.15f; + minLeftPanelW = 120; + } + super.computeLayout(); + } + + @Override + protected void drawPanels() { + if (isBuiltInMode()) { + // No left panel border + if (rightPanelW > 0) { + GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder); + } + } else { + super.drawPanels(); + } + } + + @Override + protected void initLeftPanel() { + if (isBuiltInMode()) return; + super.initLeftPanel(); + } + + // ========== Title ========== + + @Override + protected String getTitle() { + if (isBuiltInMode()) return "Abilities (Built-in)"; + if (isChainedMode()) return "Chained Abilities"; + return "Abilities"; + } + + // ========== Top Bar ========== + + @Override + protected int initExtraTopBarButtons(int x, int topBtnY) { + int topBtnW = 55; + + // View mode toggle: Built-In / Custom / Chained + String[] labels = {"gui.builtin", "gui.custom", "gui.chained"}; + int[] colors = {0x55FFFF, 0xFFFFFF, 0xFFFF55}; + GuiNpcButton viewBtn = new GuiNpcButton(60, x, topBtnY, topBtnW, btnH, labels[viewMode]); + viewBtn.setTextColor(colors[viewMode]); + addButton(viewBtn); + x += topBtnW + 2; + + // User type filter (only for Custom and Built-in, not Chained) + if (!isChainedMode()) { + addButton(new GuiNpcButton(61, x, topBtnY, topBtnW, btnH, FILTER_LABELS[userTypeFilter])); + x += topBtnW + 2; + } + + return x; + } + + @Override + protected void initTopBar(int topBtnY) { + super.initTopBar(topBtnY); + + // Disable category-dependent buttons in built-in mode + if (isBuiltInMode()) { + if (getButton(50) != null) getButton(50).enabled = false; // Add + if (getButton(54) != null) getButton(54).enabled = false; // Move + } + } + + // ========== Category Requests ========== + + @Override + protected void requestCategoryList() { + if (isBuiltInMode()) return; + PacketClient.sendClient(new CategoryListRequestPacket(getCategoryType())); + } + + @Override + protected void requestItemsInCategory(int catId) { + if (isBuiltInMode()) return; + PacketClient.sendClient(new CategoryItemsRequestPacket(getCategoryType(), catId)); + } + + @Override + protected void requestItemData(int itemId) { + // Not used — we override customScrollClicked for name-based requests + } + + @Override + protected void onSaveCategory(Category cat) { + PacketClient.sendClient(new CategorySavePacket(getCategoryType(), cat.writeNBT(new NBTTagCompound()))); + } + + @Override + protected void onRemoveCategory(int catId) { + PacketClient.sendClient(new CategoryRemovePacket(getCategoryType(), catId)); + } + + @Override + protected void onAddItem(int catId) { + if (isBuiltInMode()) return; + if (isChainedMode()) { + ChainedAbility newChain = new ChainedAbility("New Chain"); + setSubGui(new SubGuiChainedAbilityConfig(newChain, this)); + } else { + setSubGui(new SubGuiAbilityTypeSelect()); + } + } + + @Override + protected void onRemoveItem(int itemId) { + // Handled via confirmClicked with name-based packets + } + + @Override + protected void onEditItem() { + stopPreviewPlayback(); + if (isChainedMode() && selectedChain != null) { + setSubGui(new SubGuiChainedAbilityConfig(selectedChain, this)); + } else if (!currentIsBuiltIn && selectedAbility != null) { + setSubGui(selectedAbility.createConfigGui(this)); + } + } + + @Override + protected void onCloneItem() { + if (currentIsBuiltIn) return; + if (isChainedMode() && selectedChain != null) { + PacketClient.sendClient(new ChainedAbilityClonePacket(selectedChain.getName())); + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + } else if (selectedAbility != null) { + PacketClient.sendClient(new CustomAbilityClonePacket(selectedAbility.getName())); + if (selectedCatId >= 0 && isCustomMode()) requestItemsInCategory(selectedCatId); + } + } + + @Override + protected void onItemReceived(NBTTagCompound compound) { + if (isChainedMode() && compound.hasKey("Entries")) { + selectedChain = new ChainedAbility(); + selectedChain.readNBT(compound); + setPrevItemName(selectedChain.getName()); + } else { + currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn"); + selectedAbility = AbilityController.Instance.fromNBT(compound); + if (selectedAbility != null) { + setPrevItemName(selectedAbility.getName()); + } + } + } + + @Override + protected boolean hasSelectedItem() { + if (isChainedMode()) return selectedChain != null; + if (currentIsBuiltIn) return selectedAbility != null; + return selectedAbility != null; + } + + @Override + protected int getSelectedItemId() { + return -1; // Abilities use names, not IDs + } + + @Override + protected void sendMovePacket(int itemId, int destCatId) { + // Not used — we override executeMoveItems for name-based moves + } + + @Override + protected void onMoveNewItem(int catId) { + String name = prevItemName; + if (name != null && !name.isEmpty()) { + PacketClient.sendClient(new AbilityCategoryMovePacket(getCategoryType(), name, catId)); + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + } + } + + @Override + protected GuiScreen getWindowedVariant() { + return new GuiNpcManageAbilities(originalNpc, false); + } + + @Override + protected void saveCurrentItem() { + // Abilities are saved via SubGui callbacks, not on close + } + + // ========== Move Override (name-based) ========== + + @Override + protected void executeMoveItems(int destCatId) { + for (String name : moveSelection) { + PacketClient.sendClient(new AbilityCategoryMovePacket(getCategoryType(), name, destCatId)); + } + movePhase = 0; + moveSelection.clear(); + if (selectedCatId >= 0) { + requestItemsInCategory(selectedCatId); + } + initGui(); + } + + // ========== Scroll Events (name-based) ========== + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0) { + if (isBuiltInMode()) { + // Built-in: name-based request + String selected = itemScroll.getSelected(); + if (selected != null && !selected.equals(prevItemName)) { + stopPreviewPlayback(); + currentIsBuiltIn = true; + PacketClient.sendClient(new BuiltInAbilityGetPacket(selected)); + prevItemName = selected; + } + return; + } + + if (movePhase == 1) { + // Move phase 1: selecting items + if (moveSelection.size() > MAX_MOVE_ITEMS) { + java.util.HashSet trimmed = new java.util.HashSet<>(); + int count = 0; + for (String s : moveSelection) { + if (count++ >= MAX_MOVE_ITEMS) break; + trimmed.add(s); + } + moveSelection.clear(); + moveSelection.addAll(trimmed); + itemScroll.setSelectedList(moveSelection); + } + if (getButton(55) != null) { + getButton(55).enabled = !moveSelection.isEmpty(); + } + return; + } + + // Normal click: name-based request + String selected = itemScroll.getSelected(); + if (selected != null && !selected.equals(prevItemName)) { + stopPreviewPlayback(); + prevItemName = selected; + currentIsBuiltIn = false; + if (isChainedMode()) { + PacketClient.sendClient(new ChainedAbilityGetPacket(selected)); + } else { + PacketClient.sendClient(new CustomAbilityGetPacket(selected)); + } + } + return; + } + + // Category scroll — delegate to parent + super.customScrollClicked(i, j, k, scroll); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (scroll.id == 0 && hasSelectedItem() && movePhase == 0) { + onEditItem(); + } + } + + // ========== Search with User Type Filtering ========== + + @Override + protected List getItemSearchList() { + if (selectedCatId < 0 && !isBuiltInMode()) return new ArrayList<>(); + List list = new ArrayList<>(); + HashMap data = isBuiltInMode() ? builtInData : itemData; + for (Map.Entry entry : data.entrySet()) { + String name = entry.getKey(); + if (!itemSearch.isEmpty() && !name.toLowerCase().contains(itemSearch)) continue; + if (!isChainedMode() && userTypeFilter != 0) { + UserType ut = UserType.fromOrdinal(entry.getValue()); + if (userTypeFilter == 1 && !ut.allowsNpc()) continue; + if (userTypeFilter == 2 && !ut.allowsPlayer()) continue; + } + list.add(name); + } + return list; + } + + // ========== Data from Server ========== + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.BUILTIN_ABILITIES) { + builtInData = data; + if (isBuiltInMode()) { + itemScroll.setList(getItemSearchList()); + initGui(); + } + return; + } + if (type == EnumScrollData.CUSTOM_ABILITIES) { + // Received flat list — used only for built-in data alongside it + // Category mode uses CATEGORY_GROUP instead + return; + } + if (type == EnumScrollData.CHAINED_ABILITIES) { + // Flat list — not used in category mode + return; + } + super.setData(list, data, type); + } + + // ========== Actions ========== + + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + + // View mode toggle + if (id == 60) { + viewMode = (viewMode + 1) % 3; + stopPreviewPlayback(); + clearSelection(); + if (isBuiltInMode()) { + selectedCatId = 0; + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } else { + selectedCatId = -1; + requestCategoryList(); + } + initGui(); + return; + } + + // User type filter + if (id == 61) { + userTypeFilter = (userTypeFilter + 1) % 3; + itemScroll.setList(getItemSearchList()); + initGui(); + return; + } + + // Preview controls + if (id == 91) { // Play + if (previewExecutor.isPaused()) { + previewExecutor.play(); + } else { + startPreviewPlayback(); + } + initGui(); + return; + } else if (id == 92) { // Pause + previewExecutor.pause(); + initGui(); + return; + } else if (id == 93) { // Stop + stopPreviewPlayback(); + initGui(); + return; + } + + // Remove — need custom handling for name-based remove + if (id == 53 && prevItemName != null && !prevItemName.isEmpty() && movePhase == 0) { + int confirmId = isChainedMode() ? 3 : 2; + GuiYesNo guiyesno = new GuiYesNo(this, prevItemName, StatCollector.translateToLocal("gui.delete"), confirmId); + displayGuiScreen(guiyesno); + return; + } + + super.actionPerformed(guibutton); + } + + private void clearSelection() { + prevItemName = ""; + selectedAbility = null; + selectedChain = null; + currentIsBuiltIn = false; + itemSearch = ""; + movePhase = 0; + moveSelection.clear(); + trackingMovement = false; + } + + // ========== Confirm Dialog ========== + + @Override + public void confirmClicked(boolean result, int id) { + NoppesUtil.openGUI(player, this); + if (!result) return; + + // Remove custom ability + if (id == 2 && prevItemName != null && !prevItemName.isEmpty()) { + PacketClient.sendClient(new CustomAbilityRemovePacket(prevItemName)); + selectedAbility = null; + prevItemName = ""; + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + initGui(); + return; + } + + // Remove chained ability + if (id == 3 && prevItemName != null && !prevItemName.isEmpty()) { + PacketClient.sendClient(new ChainedAbilityRemovePacket(prevItemName)); + selectedChain = null; + prevItemName = ""; + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + initGui(); + return; + } + + // Category remove (id == 5) handled by parent + super.confirmClicked(result, id); + } + + // ========== SubGui Callbacks ========== + + @Override + protected void onSubGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiChainedAbilityConfig) { + if (pendingSaveChain != null) { + PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT(false))); + prevItemName = pendingSaveChain.getName(); + pendingSaveChain = null; + if (selectedCatId >= 0 && isChainedMode()) requestItemsInCategory(selectedCatId); + } + initGui(); + return; + } + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect gui = (SubGuiAbilityVariantSelect) subgui; + int idx = gui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + gui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + pendingTypeId = null; + selectedAbility = newAbility; + prevItemName = newAbility.getName(); + setSubGui(newAbility.createConfigGui(this)); + return; + } + } + pendingTypeId = null; + } else if (subgui instanceof SubGuiAbilityTypeSelect) { + String typeId = ((SubGuiAbilityTypeSelect) subgui).getSelectedTypeId(); + if (typeId != null) { + 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()); + selectedAbility = newAbility; + prevItemName = newAbility.getName(); + setSubGui(newAbility.createConfigGui(this)); + return; + } + } + } else if (subgui instanceof SubGuiDuplicateNameConfirm) { + SubGuiDuplicateNameConfirm gui = (SubGuiDuplicateNameConfirm) subgui; + if (pendingSaveAbility != null) { + if (gui.isConfirmed()) { + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false))); + prevItemName = pendingSaveAbility.getName(); + pendingSaveAbility = null; + if (selectedCatId >= 0 && isCustomMode()) requestItemsInCategory(selectedCatId); + } else if (gui.isBack()) { + Ability ability = pendingSaveAbility; + pendingSaveAbility = null; + setSubGui(ability.createConfigGui(this)); + return; + } else { + pendingSaveAbility = null; + } + } + } else if (pendingSaveAbility != null) { + if (hasDuplicateName(pendingSaveAbility)) { + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false))); + prevItemName = pendingSaveAbility.getName(); + pendingSaveAbility = null; + if (selectedCatId >= 0 && isCustomMode()) requestItemsInCategory(selectedCatId); + } + initGui(); + } + + private boolean hasDuplicateName(Ability ability) { + String name = ability.getName(); + if (name == null || name.isEmpty()) return false; + if (!itemData.containsKey(name)) return false; + String uuid = ability.getId(); + if (uuid == null || uuid.isEmpty()) return true; + Ability existing = AbilityController.Instance.getCustomAbilityByName(name); + return existing == null || !uuid.equals(existing.getId()); + } + + @Override + public void onAbilitySaved(Ability ability) { + pendingSaveAbility = ability; + } + + @Override + public void onChainedAbilitySaved(ChainedAbility chain) { + pendingSaveChain = chain; + } + + // ========== Right Panel ========== + + @Override + protected void initRightPanel(int startY) { + // Calculate layout: playback row + edit + remove rows + int bottomRows = 2; // edit, remove + boolean hasPlayback = hasSelectedItem(); + if (hasPlayback) bottomRows++; // playback row + int bottomH = bottomRows * (btnH + gap) + 14; + + previewX = rightX; + previewY = contentY; + previewW = rightPanelW; + previewH = contentH - bottomH - gap; + + // Playback controls + if (hasPlayback) { + int playY = contentY + previewH + gap; + String animTexture = "customnpcs:textures/gui/animation.png"; + int btnX = rightX + 4; + + boolean isPlaying = previewExecutor.isPlaying() && !previewExecutor.isPaused(); + boolean isPaused = previewExecutor.isPaused(); + boolean isActive = previewExecutor.isActive(); + + if (!isPlaying || isPaused) { + String statusKey = isPaused ? "animation.paused" : "animation.stopped"; + addLabel(new GuiNpcLabel(90, statusKey, btnX, playY + 5, 0xFFFFFF)); + addButton(new GuiTexturedButton(91, "", btnX + 65, playY, 11, 20, animTexture, 18, 71)); + } else { + addLabel(new GuiNpcLabel(90, "animation.playing", btnX, playY + 5, 0xFFFFFF)); + addButton(new GuiTexturedButton(92, "", btnX + 65, playY, 14, 20, animTexture, 0, 71)); + } + if (isActive) { + addButton(new GuiTexturedButton(93, "", btnX + 85, playY, 14, 20, animTexture, 33, 71)); + } + } + + // Edit + Copy on one row, Remove below + int btnY = contentY + contentH - btnH * 2 - gap; + int halfW = (rightPanelW - gap) / 2; + + GuiNpcButton editBtn = new GuiNpcButton(51, rightX, btnY, halfW, btnH, "gui.edit"); + editBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn; + addButton(editBtn); + + GuiNpcButton cloneBtn = new GuiNpcButton(52, rightX + halfW + gap, btnY, halfW, btnH, "gui.copy"); + cloneBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn; + addButton(cloneBtn); + + int removeY = btnY + btnH + gap; + GuiNpcButton removeBtn = new GuiNpcButton(53, rightX, removeY, rightPanelW, btnH, "gui.remove"); + removeBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn; + removeBtn.setTextColor(0xFF5555); + addButton(removeBtn); + } + + // ========== Preview Rendering ========== + + @Override + protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) { + if (selectedAbility == null && selectedChain == null) return; + + boolean previewing = previewExecutor.isActive(); + + // When preview is active, use fixed camera like GuiAbilityInterface + // Otherwise use the standard mouse-follow rotation + if (previewing) { + drawAbilityPreview(partialTicks); + } else { + drawStaticNpcPreview(centerX, centerY, mouseX, mouseY); + } + } + + /** + * Renders the full ability preview with fixed camera, preview entities, and telegraph. + * Matches GuiAbilityInterface's rendering pipeline. + */ + private void drawAbilityPreview(float partialTicks) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Set NPC facing direction + npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; + npc.prevRotationYaw = npc.rotationYaw = NPC_FACING_YAW; + npc.prevRotationYawHead = npc.rotationYawHead = NPC_FACING_YAW; + npc.rotationPitch = 0; + + // Calculate NPC position delta for movement rendering + double npcDeltaX = 0, npcDeltaY = 0, npcDeltaZ = 0; + if (trackingMovement) { + double interpX = npc.prevPosX + (npc.posX - npc.prevPosX) * partialTicks; + double interpY = npc.prevPosY + (npc.posY - npc.prevPosY) * partialTicks; + double interpZ = npc.prevPosZ + (npc.posZ - npc.prevPosZ) * partialTicks; + npcDeltaX = interpX - npcStartX; + npcDeltaY = interpY - npcStartY; + npcDeltaZ = interpZ - npcStartZ; + } + + // NPC render position: left-center of preview area + int npcScreenX = previewX + (int)(previewW * 0.33f); + int npcScreenY = previewY + (int)(previewH * 0.80f); + + // Scale camera zoom based on panel size + float scale = Math.min(previewW, previewH) / 200f; + float renderZoom = zoomed * scale; + + // Enable scissor to clip rendering to preview area + GL11.glEnable(GL11.GL_SCISSOR_TEST); + setScissorClip(previewX, previewY, previewW, previewH); + + try { + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glPushMatrix(); + + GL11.glTranslatef(npcScreenX, npcScreenY, 500F); + GL11.glScalef(-renderZoom, renderZoom, renderZoom); + GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F); + GL11.glRotatef(CAMERA_PITCH, 1.0F, 0.0F, 0.0F); + GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F); + + GL11.glRotatef(135F, 0.0F, 1.0F, 0.0F); + RenderHelper.enableStandardItemLighting(); + GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F); + + GL11.glTranslatef(0.0F, npc.yOffset, 0.0F); + RenderManager.instance.playerViewY = 180F; + ClientEventHandler.renderingEntityInGUI = true; + + // Render NPC at its position delta + try { + RenderManager.instance.renderEntityWithPosYaw(npc, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); + } catch (Exception ignored) {} + + // Render preview entities + renderPreviewEntities(partialTicks); + + // Render telegraph + renderPreviewTelegraph(partialTicks); + + ClientEventHandler.renderingEntityInGUI = false; + GL11.glPopMatrix(); + + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + } finally { + ClientEventHandler.renderingEntityInGUI = false; + GL11.glDisable(GL11.GL_SCISSOR_TEST); + } + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + } + + /** + * Standard static NPC preview with mouse-follow rotation (when not previewing an ability). + */ + private void drawStaticNpcPreview(int centerX, int centerY, int mouseX, int mouseY) { + float scale = Math.min(previewW, previewH) / 200f; + float renderZoom = zoomed * scale; + + GL11.glColor4f(1, 1, 1, 1); + EntityLivingBase entity = this.npc; + + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glPushMatrix(); + GL11.glTranslatef(centerX, centerY, 60F); + GL11.glScalef(-renderZoom, renderZoom, renderZoom); + GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F); + + float f2 = entity.renderYawOffset; + float f3 = entity.rotationYaw; + float f4 = entity.rotationPitch; + float f7 = entity.rotationYawHead; + float f5 = (float) centerX - mouseX; + float f6 = (float) (centerY - 50) - mouseY; + + GL11.glRotatef(135F, 0.0F, 1.0F, 0.0F); + RenderHelper.enableStandardItemLighting(); + GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(-(float) Math.atan(f6 / 800F) * 20F, 1.0F, 0.0F, 0.0F); + entity.prevRenderYawOffset = entity.renderYawOffset = rotation; + entity.prevRotationYaw = entity.rotationYaw = (float) Math.atan(f5 / 80F) * 40F + rotation; + entity.rotationPitch = -(float) Math.atan(f6 / 80F) * 20F; + entity.prevRotationYawHead = entity.rotationYawHead = entity.rotationYaw; + GL11.glTranslatef(0.0F, entity.yOffset, 1F); + RenderManager.instance.playerViewY = 180F; + + ClientEventHandler.renderingEntityInGUI = true; + try { + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0, 0.0, 0.0, 0.0F, 1.0F); + } catch (Exception ignored) {} + ClientEventHandler.renderingEntityInGUI = false; + + entity.prevRenderYawOffset = entity.renderYawOffset = f2; + entity.prevRotationYaw = entity.rotationYaw = f3; + entity.rotationPitch = f4; + entity.prevRotationYawHead = entity.rotationYawHead = f7; + GL11.glPopMatrix(); + + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + } + + private void renderPreviewEntities(float partialTicks) { + List entities = previewExecutor.getPreviewEntities(); + if (entities.isEmpty()) return; + + boolean lightingWasEnabled = GL11.glIsEnabled(GL11.GL_LIGHTING); + double refX = trackingMovement ? npcStartX : npc.posX; + double refY = trackingMovement ? npcStartY : npc.posY; + double refZ = trackingMovement ? npcStartZ : npc.posZ; + + for (Entity entity : entities) { + if (entity == null || entity.isDead) continue; + double offsetX = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - refX; + double offsetY = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - refY - npc.yOffset; + double offsetZ = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - refZ; + + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GL11.glDisable(GL11.GL_LIGHTING); + try { + RenderManager.instance.renderEntityWithPosYaw(entity, offsetX, offsetY, offsetZ, entity.rotationYaw, partialTicks); + } catch (Exception ignored) {} + } + + if (lightingWasEnabled) GL11.glEnable(GL11.GL_LIGHTING); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + private void renderPreviewTelegraph(float partialTicks) { + TelegraphInstance telegraph = previewExecutor.getTelegraph(); + if (telegraph == null || TelegraphRenderer.Instance == null) return; + + double refX = trackingMovement ? npcStartX : npc.posX; + double refY = trackingMovement ? npcStartY : npc.posY; + double refZ = trackingMovement ? npcStartZ : npc.posZ; + + double offsetX = telegraph.getInterpolatedX(partialTicks) - refX; + double offsetY = telegraph.getInterpolatedY(partialTicks) - refY - npc.yOffset; + double offsetZ = telegraph.getInterpolatedZ(partialTicks) - refZ; + + TelegraphRenderer.Instance.renderTelegraphInGUI(telegraph, offsetX, offsetY, offsetZ, 1.0f, partialTicks); + } + + private void setScissorClip(int x, int y, int w, int h) { + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scale = sr.getScaleFactor(); + int scaledY = mc.displayHeight - (y + h) * scale; + GL11.glScissor(x * scale, scaledY, w * scale, h * scale); + } + + // ========== Preview Tick ========== + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + // Set NPC rotation BEFORE ticking for correct anchor points + if (previewExecutor.isActive()) { + npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; + npc.prevRotationYaw = npc.rotationYaw = NPC_FACING_YAW; + npc.prevRotationYawHead = npc.rotationYawHead = NPC_FACING_YAW; + } + + tickPreview(); + super.drawScreen(mouseX, mouseY, partialTicks); + } + + private void tickPreview() { + if (previewExecutor.isPlaying() && !previewExecutor.isPaused()) { + long time = mc.theWorld != null ? mc.theWorld.getTotalWorldTime() : System.currentTimeMillis() / 50; + if (time != prevTick) { + npc.display.animationData.increaseTime(); + previewExecutor.tick(); + prevTick = time; + + if (!previewExecutor.isActive()) { + trackingMovement = false; + initGui(); + } + } + } + } + + private void startPreviewPlayback() { + // Save NPC start position for movement tracking + npcStartX = npc.posX; + npcStartY = npc.posY; + npcStartZ = npc.posZ; + trackingMovement = true; + + if (isChainedMode() && selectedChain != null) { + previewExecutor.startChainPreview(selectedChain, npc); + } else if (selectedAbility != null) { + previewExecutor.startPreview(selectedAbility, npc); + } + } + + private void stopPreviewPlayback() { + previewExecutor.stop(); + trackingMovement = false; + // Reset NPC animation + AnimationData data = npc.display.animationData; + data.setAnimation(new Animation()); + } + + // ========== Preview Status Drawing ========== + + @Override + protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { + super.drawOverlay(mouseX, mouseY, partialTicks); + + // Draw preview status text inside the preview area + if (previewExecutor.isActive() && !hasSubGui()) { + String status = previewExecutor.getStatusString(); + fontRendererObj.drawString(status, previewX + 4, previewY + previewH - 12, 0xFFFFFF, true); + } + } + + @Override + protected void drawItemDetails(int x, int y, int w) { + if (isChainedMode() && selectedChain != null) { + fontRendererObj.drawString(selectedChain.getDisplayName(), x, y, 0xFFFFFF, true); + y += 14; + fontRendererObj.drawString(StatCollector.translateToLocal("ability.entries") + ": " + selectedChain.getEntries().size(), x, y, 0xB5B5B5, false); + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("ability.cooldown") + ": " + selectedChain.getCooldownTicks() + "t", x, y, 0xB5B5B5, false); + y += 12; + UserType ut = selectedChain.getAllowedBy(); + fontRendererObj.drawString(StatCollector.translateToLocal("ability.allowed") + ": " + ut.name(), x, y, 0xB5B5B5, false); + } else if (selectedAbility != null) { + fontRendererObj.drawString(selectedAbility.getDisplayName(), x, y, 0xFFFFFF, true); + y += 14; + String typeId = selectedAbility.getTypeId(); + String typeName = StatCollector.translateToLocal(typeId); + fontRendererObj.drawString(StatCollector.translateToLocal("gui.type") + ": " + typeName, x, y, 0xFFAE0D, false); + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("ability.cooldown") + ": " + selectedAbility.getCooldownTicks() + "t", x, y, 0xB5B5B5, false); + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("ability.windup") + ": " + selectedAbility.getWindUpTicks() + "t", x, y, 0xB5B5B5, false); + y += 12; + UserType ut = selectedAbility.getAllowedBy(); + fontRendererObj.drawString(StatCollector.translateToLocal("ability.allowed") + ": " + ut.name(), x, y, 0xB5B5B5, false); + if (selectedAbility.hasDamage()) { + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("ability.damage") + ": " + selectedAbility.getDisplayDamage(), x, y, 0xFF5555, false); + } + if (currentIsBuiltIn) { + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("gui.builtin.tag"), x, y, 0x55FF55, false); + } + } + } + + // ========== Cleanup ========== + + @Override + public void onGuiClosed() { + stopPreviewPlayback(); + if (npc != null) { + npc.display.animationData.setEnabled(false); + } + super.onGuiClosed(); + } + + @Override + public void save() {} +} diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiAnimationDirectory.java b/src/main/java/noppes/npcs/client/gui/global/GuiAnimationDirectory.java new file mode 100644 index 000000000..15f3ec9ff --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiAnimationDirectory.java @@ -0,0 +1,529 @@ +package noppes.npcs.client.gui.global; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket; +import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket; +import kamkeel.npcs.network.packets.request.animation.AnimationClonePacket; +import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket; +import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket; +import kamkeel.npcs.network.packets.request.animation.BuiltInAnimationGetPacket; +import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket; +import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket; +import kamkeel.npcs.network.packets.request.category.CategorySavePacket; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiDirectoryCategorized; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiUtil; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiTexturedButton; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.controllers.data.AnimationData; +import noppes.npcs.controllers.data.Category; +import noppes.npcs.controllers.data.Frame; +import noppes.npcs.controllers.data.FramePart; +import noppes.npcs.client.ClientEventHandler; +import noppes.npcs.entity.EntityCustomNpc; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import java.util.HashMap; +import java.util.Vector; + +public class GuiAnimationDirectory extends GuiDirectoryCategorized { + public Animation animation = new Animation(); + public EntityNPCInterface npc; + private EntityNPCInterface originalNpc; + + // Animation playback + public boolean playingAnimation = false; + private long prevTick; + + // Built-in mode + private boolean showingBuiltIn = false; + private boolean currentIsBuiltIn = false; + private HashMap builtInData = new HashMap<>(); + + public GuiAnimationDirectory(EntityNPCInterface npc) { + super(); + this.originalNpc = npc; + this.npc = createFakeNPC(npc); + zoomed = 70; + PacketClient.sendClient(new AnimationsGetPacket()); + } + + private static EntityNPCInterface createFakeNPC(EntityNPCInterface original) { + EntityCustomNpc fake = new EntityCustomNpc(Minecraft.getMinecraft().theWorld); + fake.display.readToNBT(original.display.writeToNBT(new NBTTagCompound())); + fake.display.name = "anim preview"; + fake.height = original.height; + fake.width = original.width; + fake.display.animationData.setEnabled(true); + return fake; + } + + @Override + protected boolean hasCategories() { return !showingBuiltIn; } + + @Override + protected void computeLayout() { + if (showingBuiltIn) { + leftPanelPercent = 0.0f; + minLeftPanelW = 0; + } else { + leftPanelPercent = 0.15f; + minLeftPanelW = 120; + } + super.computeLayout(); + } + + @Override + protected void drawPanels() { + if (showingBuiltIn) { + if (rightPanelW > 0) { + GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder); + } + } else { + super.drawPanels(); + } + } + + @Override + protected void initLeftPanel() { + if (showingBuiltIn) return; + super.initLeftPanel(); + } + + @Override + protected String getTitle() { + return showingBuiltIn ? "Animations (Built-in)" : "Animations"; + } + + @Override + protected void requestCategoryList() { + if (!showingBuiltIn) { + PacketClient.sendClient(new CategoryListRequestPacket(EnumCategoryType.ANIMATION)); + } + } + + @Override + protected void requestItemsInCategory(int catId) { + if (!showingBuiltIn) { + PacketClient.sendClient(new CategoryItemsRequestPacket(EnumCategoryType.ANIMATION, catId)); + } + } + + @Override + protected void requestItemData(int itemId) { + PacketClient.sendClient(new AnimationGetPacket(itemId)); + } + + @Override + protected void onSaveCategory(Category cat) { + PacketClient.sendClient(new CategorySavePacket(EnumCategoryType.ANIMATION, cat.writeNBT(new NBTTagCompound()))); + } + + @Override + protected void onRemoveCategory(int catId) { + PacketClient.sendClient(new CategoryRemovePacket(EnumCategoryType.ANIMATION, catId)); + } + + @Override + protected void onAddItem(int catId) { + if (showingBuiltIn) return; + String name = "New"; + while (itemData.containsKey(name)) name += "_"; + Animation newAnim = new Animation(-1, name); + PacketClient.sendClient(new AnimationSavePacket(newAnim.writeToNBT())); + } + + @Override + protected void onRemoveItem(int itemId) { + if (showingBuiltIn) return; + PacketClient.sendClient(new AnimationRemovePacket(itemId)); + animation = new Animation(); + } + + @Override + protected void onEditItem() { + if (animation != null && animation.id >= 0 && !currentIsBuiltIn) { + NoppesUtil.openGUI(player, new GuiNPCEditAnimation(this, animation, npc)); + } + } + + @Override + protected void onCloneItem() { + if (showingBuiltIn || currentIsBuiltIn) return; + if (animation != null && animation.id >= 0) { + PacketClient.sendClient(new AnimationClonePacket(animation.id)); + } + } + + @Override + protected void onItemReceived(NBTTagCompound compound) { + animation = new Animation(); + animation.readFromNBT(compound); + setPrevItemName(animation.name); + + currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn"); + + playingAnimation = false; + showFirstFrame(); + } + + private void showFirstFrame() { + if (animation.id != -1 || currentIsBuiltIn) { + AnimationData data = npc.display.animationData; + data.setAnimation(new Animation()); + data.animation.smooth = animation.smooth; + data.animation.loop = 0; + if (!animation.frames.isEmpty()) { + Frame firstFrame = new Frame(); + firstFrame.parent = data.animation; + firstFrame.readFromNBT(animation.frames.get(0).writeToNBT()); + data.animation.addFrame(firstFrame); + } + } + } + + @Override + protected boolean hasSelectedItem() { + if (currentIsBuiltIn) return true; + return animation != null && animation.id >= 0; + } + + @Override + protected int getSelectedItemId() { + return animation != null ? animation.id : -1; + } + + @Override + protected void sendMovePacket(int itemId, int destCatId) { + PacketClient.sendClient(new CategoryMoveItemPacket(EnumCategoryType.ANIMATION, itemId, destCatId)); + } + + @Override + protected GuiScreen getWindowedVariant() { + return new GuiNPCManageAnimations(originalNpc, false, false); + } + + @Override + protected void saveCurrentItem() { + if (!currentIsBuiltIn && animation != null && animation.id >= 0 && prevItemName != null && !prevItemName.isEmpty()) { + PacketClient.sendClient(new AnimationSavePacket(animation.writeToNBT())); + prevItemName = animation.name; + } + } + + @Override + protected void onSubGuiClosed(SubGuiInterface subgui) { + if (animation != null && animation.id >= 0) { + setPrevItemName(animation.name); + if (selectedCatId >= 0 && !showingBuiltIn) requestItemsInCategory(selectedCatId); + } + } + + // ========== Built-in Toggle ========== + + @Override + protected int initExtraTopBarButtons(int x, int topBtnY) { + String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; + GuiNpcButton toggleBtn = new GuiNpcButton(60, x, topBtnY, 55, btnH, toggleLabel); + toggleBtn.setTextColor(showingBuiltIn ? 0x55FFFF : 0xFFFFFF); + addButton(toggleBtn); + return x + 55 + 2; + } + + @Override + protected void initTopBar(int topBtnY) { + super.initTopBar(topBtnY); + + // Disable item operations in built-in mode + if (showingBuiltIn) { + if (getButton(50) != null) getButton(50).enabled = false; // Add + if (getButton(54) != null) getButton(54).enabled = false; // Move + } + } + + @Override + protected void initRightPanel(int startY) { + // Calculate layout: playback rows + edit/copy + remove rows + int bottomRows = 2; // edit+copy, remove + boolean hasPlayback = animation != null && !animation.frames.isEmpty() && hasSelectedItem(); + if (hasPlayback) { + bottomRows++; // playback controls row + if (playingAnimation) bottomRows++; // frame info row + } + int bottomH = bottomRows * (btnH + gap) + 14; + + previewX = rightX; + previewY = contentY; + previewW = rightPanelW; + previewH = contentH - bottomH - gap; + + // Playback controls + if (hasPlayback) { + int playY = contentY + previewH + gap; + String animTexture = "customnpcs:textures/gui/animation.png"; + AnimationData data = npc.display.animationData; + int btnX = rightX + 4; + + if (!playingAnimation || (data.animation != null && data.animation.paused)) { + String statusKey = (data.animation != null && data.animation.paused) ? "animation.paused" : "animation.stopped"; + addLabel(new GuiNpcLabel(90, statusKey, btnX, playY + 5, 0xFFFFFF)); + addButton(new GuiTexturedButton(91, "", btnX + 65, playY, 11, 20, animTexture, 18, 71)); + } else { + addLabel(new GuiNpcLabel(90, "animation.playing", btnX, playY + 5, 0xFFFFFF)); + addButton(new GuiTexturedButton(92, "", btnX + 65, playY, 14, 20, animTexture, 0, 71)); + } + if (playingAnimation) { + addButton(new GuiTexturedButton(93, "", btnX + 85, playY, 14, 20, animTexture, 33, 71)); + // Frame info on its own line below playback controls + int frameInfoY = playY + btnH + gap; + addLabel(new GuiNpcLabel(94, "", btnX, frameInfoY + 5, 0xFFFFFF)); + } + } + + // Edit + Copy on one row, Remove below + int btnY = contentY + contentH - btnH * 2 - gap; + int halfW = (rightPanelW - gap) / 2; + + GuiNpcButton editBtn = new GuiNpcButton(51, rightX, btnY, halfW, btnH, "gui.edit"); + editBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn; + addButton(editBtn); + + GuiNpcButton cloneBtn = new GuiNpcButton(52, rightX + halfW + gap, btnY, halfW, btnH, "gui.copy"); + cloneBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn; + addButton(cloneBtn); + + int removeY = btnY + btnH + gap; + GuiNpcButton removeBtn = new GuiNpcButton(53, rightX, removeY, rightPanelW, btnH, "gui.remove"); + removeBtn.enabled = hasSelectedItem() && movePhase == 0 && !currentIsBuiltIn; + removeBtn.setTextColor(0xFF5555); + addButton(removeBtn); + } + + // ========== Scroll Events Override for Built-in ========== + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0 && showingBuiltIn) { + String selected = itemScroll.getSelected(); + if (selected != null && !selected.equals(prevItemName)) { + PacketClient.sendClient(new BuiltInAnimationGetPacket(selected)); + prevItemName = selected; + } + return; + } + super.customScrollClicked(i, j, k, scroll); + } + + // ========== Data ========== + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.BUILTIN_ANIMATIONS) { + this.builtInData = data; + if (showingBuiltIn) { + this.itemData = data; + itemScroll.setList(getItemSearchList()); + initGui(); + } + return; + } + super.setData(list, data, type); + } + + // ========== Animation Tick ========== + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + AnimationData data = npc.display.animationData; + if (!data.isActive() && playingAnimation) { + playingAnimation = false; + initGui(); + } else if (data.isActive()) { + long time = mc.theWorld.getTotalWorldTime(); + if (time != prevTick) { + npc.display.animationData.increaseTime(); + GuiNpcLabel label = getLabel(94); + if (label != null && data.animation != null) { + int frameIdx = data.animation.currentFrame; + int frameTime = data.animation.currentFrameTime; + int totalFrames = data.animation.frames.size(); + Frame curFrame = (Frame) data.animation.currentFrame(); + int duration = curFrame != null ? curFrame.getDuration() : 0; + label.label = (frameIdx + 1) + "/" + totalFrames + " (" + frameTime + "/" + duration + "t)"; + } + } + prevTick = time; + } + super.drawScreen(mouseX, mouseY, partialTicks); + } + + // ========== Actions ========== + + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + + // Toggle built-in / custom + if (id == 60) { + showingBuiltIn = !showingBuiltIn; + animation = new Animation(); + currentIsBuiltIn = false; + playingAnimation = false; + prevItemName = ""; + itemSearch = ""; + + if (showingBuiltIn) { + // Show built-in flat list + this.itemData = builtInData; + selectedCatId = 0; // Ensure list is visible + } else { + // Re-enter category mode + this.itemData = new HashMap<>(); + selectedCatId = -1; + requestCategoryList(); + } + initGui(); + return; + } + + // Playback controls + AnimationData data = npc.display.animationData; + if (id == 91) { + if (!playingAnimation || !data.isActive()) { + animation.currentFrame = 0; + animation.currentFrameTime = 0; + for (Frame frame : animation.frames) { + for (FramePart framePart : frame.frameParts.values()) { + framePart.prevRotations = new float[]{0, 0, 0}; + framePart.prevPivots = new float[]{0, 0, 0}; + } + } + } + playingAnimation = true; + data.setAnimation(this.animation); + data.animation.paused = false; + initGui(); + return; + } else if (id == 92) { + data.animation.paused = true; + initGui(); + return; + } else if (id == 93) { + playingAnimation = false; + data.animation.paused = false; + showFirstFrame(); + initGui(); + return; + } + + super.actionPerformed(guibutton); + } + + // ========== Preview Rendering ========== + + @Override + protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) { + if (animation == null) return; + if (!currentIsBuiltIn && animation.id == -1) return; + + // Scale NPC with panel size + float scale = Math.min(previewW, previewH) / 200f; + float renderZoom = zoomed * scale; + + GL11.glColor4f(1, 1, 1, 1); + EntityLivingBase entity = this.npc; + + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glPushMatrix(); + GL11.glTranslatef(centerX, centerY, 60F); + GL11.glScalef(-renderZoom, renderZoom, renderZoom); + GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F); + + float f2 = entity.renderYawOffset; + float f3 = entity.rotationYaw; + float f4 = entity.rotationPitch; + float f7 = entity.rotationYawHead; + float f5 = (float) centerX - mouseX; + float f6 = (float) (centerY - 50) - mouseY; + + GL11.glRotatef(135F, 0.0F, 1.0F, 0.0F); + RenderHelper.enableStandardItemLighting(); + GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(-(float) Math.atan(f6 / 800F) * 20F, 1.0F, 0.0F, 0.0F); + entity.prevRenderYawOffset = entity.renderYawOffset = rotation; + entity.prevRotationYaw = entity.rotationYaw = (float) Math.atan(f5 / 80F) * 40F + rotation; + entity.rotationPitch = -(float) Math.atan(f6 / 80F) * 20F; + entity.prevRotationYawHead = entity.rotationYawHead = entity.rotationYaw; + GL11.glTranslatef(0.0F, entity.yOffset, 1F); + RenderManager.instance.playerViewY = 180F; + + ClientEventHandler.renderingEntityInGUI = true; + try { + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0, 0.0, 0.0, 0.0F, 1.0F); + } catch (Exception ignored) { + } + ClientEventHandler.renderingEntityInGUI = false; + + entity.prevRenderYawOffset = entity.renderYawOffset = f2; + entity.prevRotationYaw = entity.rotationYaw = f3; + entity.rotationPitch = f4; + entity.prevRotationYawHead = entity.rotationYawHead = f7; + GL11.glPopMatrix(); + + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + } + + @Override + protected void drawItemDetails(int x, int y, int w) { + if (animation == null) return; + if (!currentIsBuiltIn && animation.id == -1) return; + + fontRendererObj.drawString(animation.name, x, y, 0xFFFFFF, true); + y += 14; + fontRendererObj.drawString(StatCollector.translateToLocal("animation.frames") + ": " + animation.frames.size(), x, y, 0xB5B5B5, false); + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("stats.speed") + ": " + animation.speed, x, y, 0xB5B5B5, false); + y += 12; + String loopStr = animation.loop == 0 ? StatCollector.translateToLocal("gui.none") : animation.loop == 1 ? StatCollector.translateToLocal("animation.loop") : StatCollector.translateToLocal("animation.mirror"); + fontRendererObj.drawString(StatCollector.translateToLocal("animation.loop") + ": " + loopStr, x, y, 0xB5B5B5, false); + if (currentIsBuiltIn) { + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("gui.builtin.tag"), x, y, 0x55FF55, false); + } + } + + // ========== Cleanup ========== + + @Override + public void onGuiClosed() { + if (npc != null) { + npc.display.animationData.setEnabled(false); + } + super.onGuiClosed(); + } + +} diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiEffectDirectory.java b/src/main/java/noppes/npcs/client/gui/global/GuiEffectDirectory.java new file mode 100644 index 000000000..4133082d0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiEffectDirectory.java @@ -0,0 +1,191 @@ +package noppes.npcs.client.gui.global; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket; +import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket; +import kamkeel.npcs.network.packets.request.category.CategorySavePacket; +import kamkeel.npcs.network.packets.request.effects.EffectGetPacket; +import kamkeel.npcs.network.packets.request.effects.EffectRemovePacket; +import kamkeel.npcs.network.packets.request.effects.EffectClonePacket; +import kamkeel.npcs.network.packets.request.effects.EffectSavePacket; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.SubGuiEffectGeneral; +import noppes.npcs.client.gui.util.GuiDirectoryCategorized; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.client.renderer.ImageData; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.Category; +import noppes.npcs.controllers.data.CustomEffect; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; + +import static noppes.npcs.client.gui.player.inventory.GuiCNPCInventory.specialIcons; + +public class GuiEffectDirectory extends GuiDirectoryCategorized { + public CustomEffect effect = new CustomEffect(); + public EntityNPCInterface npc; + + public GuiEffectDirectory(EntityNPCInterface npc) { + super(); + this.npc = npc; + } + + @Override + protected String getTitle() { return "Effects"; } + + @Override + protected void requestCategoryList() { + PacketClient.sendClient(new CategoryListRequestPacket(EnumCategoryType.EFFECT)); + } + + @Override + protected void requestItemsInCategory(int catId) { + PacketClient.sendClient(new CategoryItemsRequestPacket(EnumCategoryType.EFFECT, catId)); + } + + @Override + protected void requestItemData(int itemId) { + PacketClient.sendClient(new EffectGetPacket(itemId)); + } + + @Override + protected void onSaveCategory(Category cat) { + PacketClient.sendClient(new CategorySavePacket(EnumCategoryType.EFFECT, cat.writeNBT(new NBTTagCompound()))); + } + + @Override + protected void onRemoveCategory(int catId) { + PacketClient.sendClient(new CategoryRemovePacket(EnumCategoryType.EFFECT, catId)); + } + + @Override + protected void onAddItem(int catId) { + String name = "New"; + while (itemData.containsKey(name)) name += "_"; + CustomEffect newEffect = new CustomEffect(-1, name); + PacketClient.sendClient(new EffectSavePacket(newEffect.writeToNBT(false), "")); + } + + @Override + protected void onRemoveItem(int itemId) { + PacketClient.sendClient(new EffectRemovePacket(itemId)); + effect = new CustomEffect(); + } + + @Override + protected void onEditItem() { + if (effect != null && effect.id >= 0) { + setSubGui(new SubGuiEffectGeneral(this, effect)); + } + } + + @Override + protected void onCloneItem() { + if (effect != null && effect.id >= 0) { + PacketClient.sendClient(new EffectClonePacket(effect.id)); + } + } + + @Override + protected void onItemReceived(NBTTagCompound compound) { + effect = new CustomEffect(); + effect.readFromNBT(compound); + setPrevItemName(effect.name); + if (effect.id != -1) { + CustomEffectController.getInstance().getCustomEffects().replace(effect.id, effect); + } + } + + @Override + protected boolean hasSelectedItem() { + return effect != null && effect.id >= 0; + } + + @Override + protected int getSelectedItemId() { + return effect != null ? effect.id : -1; + } + + @Override + protected void sendMovePacket(int itemId, int destCatId) { + PacketClient.sendClient(new CategoryMoveItemPacket(EnumCategoryType.EFFECT, itemId, destCatId)); + } + + @Override + protected GuiScreen getWindowedVariant() { + return new GuiNPCManageEffects(npc); + } + + @Override + protected void saveCurrentItem() { + if (effect != null && effect.id >= 0 && prevItemName != null && !prevItemName.isEmpty()) { + PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), prevItemName)); + prevItemName = effect.name; + } + } + + @Override + protected void onSubGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiEffectGeneral) { + if (effect != null && effect.id >= 0) { + setPrevItemName(effect.name); + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + } + } + } + + @Override + protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) { + if (effect == null || effect.id == -1) return; + + int iconRenderSize = Math.min(previewW, previewH) / 3; + iconRenderSize = Math.max(32, Math.min(iconRenderSize, 128)); + int x = centerX - iconRenderSize / 2; + int y = centerY - iconRenderSize; + + TextureManager textureManager = mc.getTextureManager(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + ImageData data = ClientCacheHandler.getImageData(effect.icon); + if (data.imageLoaded()) { + data.bindTexture(); + int iconX = effect.iconX; + int iconY = effect.iconY; + int iconWidth = effect.getWidth(); + int iconHeight = effect.getHeight(); + int width = data.getTotalWidth(); + int height = data.getTotalHeight(); + func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); + } else { + textureManager.bindTexture(new ResourceLocation("customnpcs", "textures/marks/question.png")); + func_152125_a(x, y, 0, 0, 1, 1, iconRenderSize, iconRenderSize, 1, 1); + } + GL11.glDisable(GL11.GL_DEPTH_TEST); + textureManager.bindTexture(specialIcons); + func_152125_a(x, y, 0, 224, 16, 16, iconRenderSize, iconRenderSize, 256, 256); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } + + @Override + protected void drawItemDetails(int x, int y, int w) { + if (effect == null || effect.id == -1) return; + + String drawString = effect.getMenuName(); + fontRendererObj.drawString(drawString, x, y, 0xFFFFFF, true); + + y += 14; + fontRendererObj.drawString(StatCollector.translateToLocal("gui.name") + ": " + effect.name, x, y, 0xFFFFFF, false); + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("effect.runsEveryX") + ": " + effect.everyXTick + "t", x, y, 0xB5B5B5, false); + y += 12; + fontRendererObj.drawString(StatCollector.translateToLocal("effect.defaultLength") + ": " + effect.length + "s", x, y, 0xB5B5B5, false); + } + +} diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiLinkedItemDirectory.java b/src/main/java/noppes/npcs/client/gui/global/GuiLinkedItemDirectory.java new file mode 100644 index 000000000..20f92a51f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiLinkedItemDirectory.java @@ -0,0 +1,282 @@ +package noppes.npcs.client.gui.global; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.category.CategoryItemsRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket; +import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket; +import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket; +import kamkeel.npcs.network.packets.request.category.CategorySavePacket; +import kamkeel.npcs.network.packets.request.linked.LinkedGetPacket; +import kamkeel.npcs.network.packets.request.linked.LinkedItemBuildPacket; +import kamkeel.npcs.network.packets.request.linked.LinkedItemRemovePacket; +import kamkeel.npcs.network.packets.request.linked.LinkedItemClonePacket; +import kamkeel.npcs.network.packets.request.linked.LinkedItemSavePacket; +import kamkeel.npcs.util.ColorUtil; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientCacheHandler; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.item.SubGuiLinkedItem; +import noppes.npcs.client.gui.util.GuiDirectoryCategorized; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.client.renderer.ImageData; +import noppes.npcs.constants.EnumCategoryType; +import noppes.npcs.controllers.data.Category; +import noppes.npcs.controllers.data.LinkedItem; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; + +public class GuiLinkedItemDirectory extends GuiDirectoryCategorized { + public LinkedItem linkedItem = null; + public EntityNPCInterface npc; + + public GuiLinkedItemDirectory(EntityNPCInterface npc) { + super(); + this.npc = npc; + } + + @Override + protected String getTitle() { return "Linked Items"; } + + @Override + protected void requestCategoryList() { + PacketClient.sendClient(new CategoryListRequestPacket(EnumCategoryType.LINKED_ITEM)); + } + + @Override + protected void requestItemsInCategory(int catId) { + PacketClient.sendClient(new CategoryItemsRequestPacket(EnumCategoryType.LINKED_ITEM, catId)); + } + + @Override + protected void requestItemData(int itemId) { + LinkedGetPacket.GetItem(itemId); + } + + @Override + protected void onSaveCategory(Category cat) { + PacketClient.sendClient(new CategorySavePacket(EnumCategoryType.LINKED_ITEM, cat.writeNBT(new NBTTagCompound()))); + } + + @Override + protected void onRemoveCategory(int catId) { + PacketClient.sendClient(new CategoryRemovePacket(EnumCategoryType.LINKED_ITEM, catId)); + } + + @Override + protected void onAddItem(int catId) { + String name = "New"; + while (itemData.containsKey(name)) name += "_"; + LinkedItem newItem = new LinkedItem(name); + PacketClient.sendClient(new LinkedItemSavePacket(newItem.writeToNBT(false), "")); + } + + @Override + protected void onRemoveItem(int itemId) { + PacketClient.sendClient(new LinkedItemRemovePacket(itemId)); + linkedItem = null; + } + + @Override + protected void onEditItem() { + if (linkedItem != null && linkedItem.id >= 0) { + setSubGui(new SubGuiLinkedItem(this, linkedItem)); + } + } + + @Override + protected void onCloneItem() { + if (linkedItem != null && linkedItem.id >= 0) { + PacketClient.sendClient(new LinkedItemClonePacket(linkedItem.id)); + } + } + + @Override + protected void onItemReceived(NBTTagCompound compound) { + linkedItem = new LinkedItem(); + linkedItem.readFromNBT(compound); + setPrevItemName(linkedItem.name); + } + + @Override + protected boolean hasSelectedItem() { + return linkedItem != null && linkedItem.id >= 0; + } + + @Override + protected int getSelectedItemId() { + return linkedItem != null ? linkedItem.id : -1; + } + + @Override + protected void sendMovePacket(int itemId, int destCatId) { + PacketClient.sendClient(new CategoryMoveItemPacket(EnumCategoryType.LINKED_ITEM, itemId, destCatId)); + } + + @Override + protected GuiScreen getWindowedVariant() { + return new GuiNPCManageLinked(npc); + } + + @Override + protected void saveCurrentItem() { + if (linkedItem != null && linkedItem.id >= 0 && prevItemName != null && !prevItemName.isEmpty()) { + PacketClient.sendClient(new LinkedItemSavePacket(linkedItem.writeToNBT(false), prevItemName)); + prevItemName = linkedItem.name; + } + } + + @Override + protected void onSubGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiLinkedItem) { + if (linkedItem != null && linkedItem.id >= 0) { + setPrevItemName(linkedItem.name); + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + } + } + } + + @Override + protected void initRightPanel(int startY) { + // Reserve space for: edit+build row, copy+remove row, ID label + int bottomH = (btnH + gap) * 2 + 14; + previewX = rightX; + previewY = contentY; + previewW = rightPanelW; + previewH = contentH - bottomH - gap; + + int halfW = (rightPanelW - gap) / 2; + + // Edit + Build on first row + int row1Y = contentY + contentH - btnH * 2 - gap; + GuiNpcButton editBtn = new GuiNpcButton(51, rightX, row1Y, halfW, btnH, "gui.edit"); + editBtn.enabled = hasSelectedItem() && movePhase == 0; + addButton(editBtn); + + GuiNpcButton buildBtn = new GuiNpcButton(56, rightX + halfW + gap, row1Y, halfW, btnH, "gui.build"); + buildBtn.enabled = hasSelectedItem() && movePhase == 0; + addButton(buildBtn); + + // Copy + Remove on second row + int row2Y = row1Y + btnH + gap; + GuiNpcButton cloneBtn = new GuiNpcButton(52, rightX, row2Y, halfW, btnH, "gui.copy"); + cloneBtn.enabled = hasSelectedItem() && movePhase == 0; + addButton(cloneBtn); + + GuiNpcButton removeBtn = new GuiNpcButton(53, rightX + halfW + gap, row2Y, halfW, btnH, "gui.remove"); + removeBtn.enabled = hasSelectedItem() && movePhase == 0; + removeBtn.setTextColor(0xFF5555); + addButton(removeBtn); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 56 && linkedItem != null && linkedItem.id >= 0) { + PacketClient.sendClient(new LinkedItemBuildPacket(linkedItem.getId())); + return; + } + super.actionPerformed(guibutton); + } + + @Override + protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) { + if (linkedItem == null || linkedItem.id < 0) return; + + int iconRenderSize = Math.min(previewW, previewH) / 3; + iconRenderSize = Math.max(32, Math.min(iconRenderSize, 128)); + int x = centerX - iconRenderSize / 2; + int y = centerY - iconRenderSize; + + TextureManager textureManager = mc.getTextureManager(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + ImageData imageData = ClientCacheHandler.getImageData(linkedItem.display.texture); + if (imageData.imageLoaded()) { + float[] colors = ColorUtil.hexToRGB(linkedItem.display.itemColor); + GL11.glColor3f(colors[0], colors[1], colors[2]); + imageData.bindTexture(); + int iconWidth = imageData.getTotalWidth(); + int iconHeight = imageData.getTotalHeight(); + func_152125_a(x, y, 0, 0, iconWidth, iconHeight, iconRenderSize, iconRenderSize, iconWidth, iconHeight); + } else { + textureManager.bindTexture(new ResourceLocation("customnpcs", "textures/marks/question.png")); + func_152125_a(x, y, 0, 0, 1, 1, iconRenderSize, iconRenderSize, 1, 1); + } + GL11.glColor3f(1.0f, 1.0f, 1.0f); + } + + @Override + protected void drawItemDetails(int x, int y, int w) { + if (linkedItem == null || linkedItem.id < 0) return; + + fontRendererObj.drawString(linkedItem.name, x, y, 0xFFFFFF, true); + y += 14; + + int labelColor = 0xffae0d; + fontRendererObj.drawString(StatCollector.translateToLocal("display.version") + ": " + linkedItem.version, x, y, labelColor, false); + y += 12; + + labelColor = 0xff5714; + fontRendererObj.drawString(StatCollector.translateToLocal("display.maxStack") + ": " + linkedItem.stackSize, x, y, labelColor, false); + y += 12; + + labelColor = 0xf7ca28; + fontRendererObj.drawString(StatCollector.translateToLocal("display.digSpeed") + ": " + linkedItem.digSpeed, x, y, labelColor, false); + y += 12; + + labelColor = 0x29d6b9; + String[] useActions = { + StatCollector.translateToLocal("use_action.none"), + StatCollector.translateToLocal("use_action.block"), + StatCollector.translateToLocal("use_action.eat"), + StatCollector.translateToLocal("use_action.drink"), + StatCollector.translateToLocal("use_action.bow") + }; + int useActionIndex; + switch (linkedItem.itemUseAction) { + case 0: useActionIndex = 0; break; + case 1: useActionIndex = 1; break; + case 2: useActionIndex = 4; break; + case 3: useActionIndex = 2; break; + case 4: useActionIndex = 3; break; + default: useActionIndex = 0; break; + } + fontRendererObj.drawString(StatCollector.translateToLocal("display.useAction") + ": " + useActions[useActionIndex], x, y, labelColor, false); + y += 12; + + String[] armorOptions = { + StatCollector.translateToLocal("armor_type.none"), + StatCollector.translateToLocal("armor_type.all"), + StatCollector.translateToLocal("armor_type.head"), + StatCollector.translateToLocal("armor_type.chestplate"), + StatCollector.translateToLocal("armor_type.leggings"), + StatCollector.translateToLocal("armor_type.boots") + }; + int armorIndex; + if (linkedItem.armorType == -2) armorIndex = 0; + else if (linkedItem.armorType == -1) armorIndex = 1; + else armorIndex = linkedItem.armorType + 2; + fontRendererObj.drawString(StatCollector.translateToLocal("display.armor") + ": " + armorOptions[armorIndex], x, y, labelColor, false); + y += 12; + + labelColor = 0x7cff54; + fontRendererObj.drawString(StatCollector.translateToLocal("display.isTool") + ": " + ("" + linkedItem.isTool).toUpperCase(), x, y, labelColor, false); + y += 12; + + fontRendererObj.drawString(StatCollector.translateToLocal("display.isNormalItem") + ": " + ("" + linkedItem.isNormalItem).toUpperCase(), x, y, labelColor, false); + y += 12; + + labelColor = 0xce75fa; + fontRendererObj.drawString(StatCollector.translateToLocal("model.scale") + ": " + linkedItem.display.scaleX + ", " + linkedItem.display.scaleY + ", " + linkedItem.display.scaleZ, x, y, labelColor, false); + y += 12; + + fontRendererObj.drawString(StatCollector.translateToLocal("model.rotate") + ": " + linkedItem.display.rotationX + ", " + linkedItem.display.rotationY + ", " + linkedItem.display.rotationZ, x, y, labelColor, false); + y += 12; + + fontRendererObj.drawString(StatCollector.translateToLocal("model.translate") + ": " + linkedItem.display.translateX + ", " + linkedItem.display.translateY + ", " + linkedItem.display.translateZ, x, y, labelColor, 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 3ac3923b4..c7f1b7ce4 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java @@ -65,15 +65,22 @@ 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) + // Fullscreen button - FIRST + GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, guiTop + 8, 45, 20, "gui.fullscreen"); + fullBtn.setTextColor(0x55FF55); + fullBtn.setHoverText("gui.fullscreen.tooltip"); + this.addButton(fullBtn); + + // Toggle button String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; - this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel)); + GuiNpcButton toggleBtn = new GuiNpcButton(10, guiLeft + 368, guiTop + 36, 45, 20, toggleLabel); + toggleBtn.setTextColor(showingBuiltIn ? 0x55FFFF : 0xFFFFFF); + this.addButton(toggleBtn); // 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")); + this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 60, 45, 20, "gui.add")); + this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove")); } if (scrollAnimations == null) { @@ -198,6 +205,11 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol protected void actionPerformed(GuiButton guibutton) { GuiNpcButton button = (GuiNpcButton) guibutton; + if (button.id == 66) { + mc.displayGuiScreen(new GuiAnimationDirectory(npc)); + return; + } + // Toggle button if (button.id == 10) { showingBuiltIn = !showingBuiltIn; diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageDialogs.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageDialogs.java index eb0ede5bf..9267366d0 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageDialogs.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageDialogs.java @@ -411,6 +411,9 @@ public class GuiNPCManageDialogs extends GuiNPCInterface2 implements IScrollData } if (subgui instanceof SubGuiNpcDialog) { saveType(true); + if (dialog != null && dialog.id >= 0) { + setPrevDialogName(dialog.title); + } } } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java index 21ecb1b8d..80fe7b943 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java @@ -3,6 +3,7 @@ package noppes.npcs.client.gui.global; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.effects.EffectGetPacket; import kamkeel.npcs.network.packets.request.effects.EffectRemovePacket; +import kamkeel.npcs.network.packets.request.effects.EffectClonePacket; import kamkeel.npcs.network.packets.request.effects.EffectSavePacket; import kamkeel.npcs.network.packets.request.effects.EffectsGetPacket; import net.minecraft.client.gui.GuiButton; @@ -57,15 +58,21 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro public void initGui() { super.initGui(); - addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); + // Fullscreen button - FIRST + GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, guiTop + 8, 45, 20, "gui.fullscreen"); + fullBtn.setTextColor(0x55FF55); + fullBtn.setHoverText("gui.fullscreen.tooltip"); + addButton(fullBtn); - addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove")); + addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 36, 45, 20, "gui.add")); + + addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 60, 45, 20, "gui.remove")); getButton(1).enabled = effect != null && effect.id != -1; - addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 56, 45, 20, "gui.copy")); + addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 84, 45, 20, "gui.copy")); getButton(2).enabled = effect != null && effect.id != -1; - addButton(new GuiNpcButton(3, guiLeft + 368, guiTop + 80, 45, 20, "gui.edit")); + addButton(new GuiNpcButton(3, guiLeft + 368, guiTop + 108, 45, 20, "gui.edit")); getButton(3).enabled = effect != null && effect.id != -1; if (scrollEffects == null) { @@ -100,10 +107,14 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro displayGuiScreen(guiyesno); } } else if (button.id == 2) { - CustomEffect effect = this.effect.cloneEffect(); - while (data.containsKey(effect.name)) - effect.name += "_"; - PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), "")); + if (effect != null && effect.id >= 0) { + PacketClient.sendClient(new EffectClonePacket(effect.id)); + } + } + + if (button.id == 66) { + mc.displayGuiScreen(new GuiEffectDirectory(npc)); + return; } if (effect == null) @@ -173,7 +184,7 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro int iconWidth = effect.getWidth(); int iconHeight = effect.getHeight(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageLinked.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageLinked.java index 52e78f7d6..ea200e7e3 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageLinked.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageLinked.java @@ -5,6 +5,7 @@ import kamkeel.npcs.network.packets.request.linked.LinkedGetAllPacket; import kamkeel.npcs.network.packets.request.linked.LinkedGetPacket; import kamkeel.npcs.network.packets.request.linked.LinkedItemBuildPacket; import kamkeel.npcs.network.packets.request.linked.LinkedItemRemovePacket; +import kamkeel.npcs.network.packets.request.linked.LinkedItemClonePacket; import kamkeel.npcs.network.packets.request.linked.LinkedItemSavePacket; import kamkeel.npcs.network.packets.request.linked.LinkedNPCAddPacket; import kamkeel.npcs.network.packets.request.linked.LinkedNPCRemovePacket; @@ -86,6 +87,15 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, int y = guiTop + 8; + // Fullscreen button - FIRST (only for Items tab) + if (tab == 1) { + GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, y, 45, 20, "gui.fullscreen"); + fullBtn.setTextColor(0x55FF55); + fullBtn.setHoverText("gui.fullscreen.tooltip"); + this.addButton(fullBtn); + y += 22; + } + this.addButton(new GuiNpcButton(10, guiLeft + 368, y, 45, 20, "gui.npcs")); this.addButton(new GuiNpcButton(11, guiLeft + 368, y += 22, 45, 20, "gui.items")); getButton(10).enabled = tab == 1; @@ -216,6 +226,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, } private List getSearchList() { + if (data == null) return new ArrayList(); if (search.isEmpty()) { return new ArrayList(this.data.keySet()); } @@ -265,6 +276,11 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, scroll.setSelected(""); } + if (button.id == 66) { + mc.displayGuiScreen(new GuiLinkedItemDirectory(npc)); + return; + } + if (linkedItem == null) return; @@ -273,13 +289,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, } if (button.id == 4) { if (data.containsKey(scroll.getSelected()) && linkedItem != null && linkedItem.id >= 0) { - String name = linkedItem.name; - while (data.containsKey(name)) - name += "_"; - LinkedItem linkedItemClone = this.linkedItem.clone(); - linkedItemClone.name = name; - linkedItemClone.id = -1; - PacketClient.sendClient(new LinkedItemSavePacket(linkedItemClone.writeToNBT(false), "")); + PacketClient.sendClient(new LinkedItemClonePacket(this.linkedItem.id)); } } if (button.id == 5) { diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageQuest.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageQuest.java index f3d1679f2..e4e65d3c4 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageQuest.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageQuest.java @@ -401,6 +401,9 @@ public class GuiNPCManageQuest extends GuiNPCInterface2 implements IScrollData, } if (subgui instanceof SubGuiNpcQuest) { saveType(true); + if (quest != null && quest.id >= 0) { + setPrevQuestName(quest.title); + } } } 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 b06f9d097..b0398d48a 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -1,11 +1,18 @@ package noppes.npcs.client.gui.global; -import kamkeel.npcs.client.renderer.TelegraphRenderer; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityController; -import java.util.UUID; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.enums.UserType; import kamkeel.npcs.network.PacketClient; + +import java.util.UUID; +import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilitiesGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityGetPacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilityRemovePacket; +import kamkeel.npcs.network.packets.request.ability.ChainedAbilitySavePacket; 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,19 +23,19 @@ 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.SubGuiChainedAbilityConfig; import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm; -import noppes.npcs.client.gui.util.AbilityPreviewExecutor; -import noppes.npcs.client.gui.util.GuiAbilityInterface; +import kamkeel.npcs.controllers.data.ability.preview.AbilityPreviewExecutor; +import kamkeel.npcs.controllers.data.ability.gui.GuiAbilityInterface; 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.GuiTexturedButton; import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.IScrollData; @@ -42,33 +49,71 @@ import noppes.npcs.entity.EntityNPCInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Vector; /** * Global GUI for managing saved ability presets with 3D preview. - * + *

* Features: * - 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, - ITextfieldListener, GuiYesNoCallback, IScrollData, IGuiData { + implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback, + IChainedAbilityConfigCallback, ITextfieldListener, GuiYesNoCallback, + IScrollData, IGuiData { + + // ── Button IDs ──────────────────────────────────────────────────────────── + private static final int BTN_REMOVE = 1; + private static final int BTN_ADD = 2; + private static final int BTN_TOGGLE_VIEW = 10; + private static final int BTN_EDIT = 100; + private static final int BTN_PREVIEW_PLAY = 91; + private static final int BTN_PREVIEW_PAUSE = 92; + private static final int BTN_PREVIEW_STOP = 93; + private static final int BTN_USER_TYPE_FILTER = 11; + + // ── TextField / Label IDs ───────────────────────────────────────────────── + private static final int TF_SEARCH = 55; + private static final int LBL_PREVIEW_STATUS = 90; + + // ── Scroll IDs ──────────────────────────────────────────────────────────── + private static final int SCROLL_MAIN = 0; + + // ── Confirm dialog IDs ──────────────────────────────────────────────────── + private static final int CONFIRM_REMOVE_ABILITY = 1; + private static final int CONFIRM_REMOVE_CHAIN = 2; // ==================== DATA ==================== private GuiCustomScroll scroll; - private HashMap abilityData = new HashMap<>(); - /** Maps display name -> UUID for custom abilities */ - private final HashMap displayToUuid = new HashMap<>(); + private HashMap customData = new HashMap<>(); + private HashMap builtInData = new HashMap<>(); private String selected = null; - private String selectedUuid = null; private String search = ""; private Ability selectedAbility = null; + // ==================== VIEW MODE ==================== + // 0 = Custom, 1 = Built-in, 2 = Chained + private int viewMode = 0; + private boolean showingBuiltIn = false; + private boolean showingChained = false; + private boolean currentIsBuiltIn = false; + + // ==================== USER TYPE FILTER ==================== + // 0 = Both, 1 = NPC Only, 2 = Player Only + private int userTypeFilter = 0; + private static final String[] USER_TYPE_FILTER_LABELS = {"gui.both", "gui.npcs", "gui.players"}; + + // ==================== CHAINED DATA ==================== + private HashMap chainedData = new HashMap<>(); + private ChainedAbility selectedChain = null; + private ChainedAbility pendingSaveChain = null; + // ==================== PENDING SAVE ==================== private Ability pendingSaveAbility = null; - private boolean pendingNewCreation = false; // ==================== PENDING VARIANT ==================== private String pendingTypeId = null; @@ -88,7 +133,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 @@ -100,42 +145,68 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface public void initGui() { super.initGui(); - // Add button - addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); + // Fullscreen button - FIRST + GuiNpcButton fullBtn = new GuiNpcButton(66, guiLeft + 368, guiTop + 8, 45, 20, "gui.fullscreen"); + fullBtn.setTextColor(0x55FF55); + fullBtn.setHoverText("gui.fullscreen.tooltip"); + addButton(fullBtn); - // Remove button - addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove")); - getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected)); + // Toggle button — cycles: Custom → Built-in → Chained + String toggleLabel = showingChained ? "gui.chained" : (showingBuiltIn ? "gui.builtin" : "gui.custom"); + GuiNpcButton toggleBtn = new GuiNpcButton(BTN_TOGGLE_VIEW, guiLeft + 368, guiTop + 36, 45, 20, toggleLabel); + if (showingChained) toggleBtn.setTextColor(0xFFFF55); + else if (showingBuiltIn) toggleBtn.setTextColor(0x55FFFF); + else toggleBtn.setTextColor(0xFFFFFF); + addButton(toggleBtn); - // Edit button - addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 52, 45, 20, "gui.edit")); - getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + if (showingChained) { + // Chained view buttons + addButton(new GuiNpcButton(BTN_ADD, guiLeft + 368, guiTop + 60, 45, 20, "gui.add")); + addButton(new GuiNpcButton(BTN_REMOVE, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove")); + getButton(BTN_REMOVE).setEnabled(selected != null && !selected.isEmpty() && chainedData.containsKey(selected)); + addButton(new GuiNpcButton(BTN_EDIT, guiLeft + 368, guiTop + 108, 45, 20, "gui.edit")); + getButton(BTN_EDIT).setEnabled(selected != null && !selected.isEmpty() && selectedChain != null); + } else if (!showingBuiltIn) { + // Custom view buttons + addButton(new GuiNpcButton(BTN_ADD, guiLeft + 368, guiTop + 60, 45, 20, "gui.add")); + addButton(new GuiNpcButton(BTN_REMOVE, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove")); + getButton(BTN_REMOVE).setEnabled(selected != null && !selected.isEmpty() && customData.containsKey(selected)); + if (!currentIsBuiltIn) { + addButton(new GuiNpcButton(BTN_EDIT, guiLeft + 368, guiTop + 108, 45, 20, "gui.edit")); + getButton(BTN_EDIT).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + } + } - // Scroll list of saved abilities (right side) + // Scroll list (right side) if (scroll == null) { - scroll = new GuiCustomScroll(this, 0); + scroll = new GuiCustomScroll(this, SCROLL_MAIN); scroll.setSize(143, 185); } scroll.guiLeft = guiLeft + 220; scroll.guiTop = guiTop + 4; addScroll(scroll); - // Update scroll list scroll.setList(getSearchList()); - if (selected != null && displayToUuid.containsKey(selected)) { + if (selected != null) { scroll.setSelected(selected); } // Search bar - addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search)); + addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search)); - // Show ability info only if one is selected - if (selectedAbility == null || selected == null) { - return; + // User type filter button (only for Custom and Built-in views) + if (!showingChained) { + addButton(new GuiNpcButton(BTN_USER_TYPE_FILTER, guiLeft + 368, guiTop + 192, 45, 20, USER_TYPE_FILTER_LABELS[userTypeFilter])); } - // ID/Name label (below search bar) - addLabel(new GuiNpcLabel(10, "ID: " + selectedAbility.getId(), guiLeft + 220, guiTop + 215)); + // Check if we have something to preview + if (showingChained) { + if (selectedChain == null || selected == null || selectedChain.getEntries().isEmpty()) { + return; + } + } else if (selectedAbility == null || selected == null) { + return; + } // Play/Pause/Stop buttons (below model preview area) String animTexture = "customnpcs:textures/gui/animation.png"; @@ -146,30 +217,42 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface boolean isActive = previewExecutor.isActive(); if (!isPlaying || isPaused) { - // Show Play button String statusKey = isPaused ? "animation.paused" : "animation.stopped"; - addLabel(new GuiNpcLabel(90, statusKey, guiLeft + playButtonOffsetX, guiTop + 198)); - addButton(new GuiTexturedButton(91, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 11, 20, animTexture, 18, 71)); + addLabel(new GuiNpcLabel(LBL_PREVIEW_STATUS, statusKey, guiLeft + playButtonOffsetX, guiTop + 198)); + addButton(new GuiTexturedButton(BTN_PREVIEW_PLAY, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 11, 20, animTexture, 18, 71)); } else { - // Show Pause button - addLabel(new GuiNpcLabel(90, "animation.playing", guiLeft + playButtonOffsetX, guiTop + 198)); - addButton(new GuiTexturedButton(92, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 14, 20, animTexture, 0, 71)); + addLabel(new GuiNpcLabel(LBL_PREVIEW_STATUS, "animation.playing", guiLeft + playButtonOffsetX, guiTop + 198)); + addButton(new GuiTexturedButton(BTN_PREVIEW_PAUSE, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 14, 20, animTexture, 0, 71)); } if (isActive) { - // Show Stop button - addButton(new GuiTexturedButton(93, "", guiLeft + playButtonOffsetX + 90, guiTop + 192, 14, 20, animTexture, 33, 71)); + addButton(new GuiTexturedButton(BTN_PREVIEW_STOP, "", guiLeft + playButtonOffsetX + 90, guiTop + 192, 14, 20, animTexture, 33, 71)); } } + private HashMap getCurrentData() { + if (showingChained) return chainedData; + return showingBuiltIn ? builtInData : customData; + } + private List getSearchList() { - if (search.isEmpty()) { - return new ArrayList<>(displayToUuid.keySet()); - } + HashMap data = getCurrentData(); List list = new ArrayList<>(); - for (String name : displayToUuid.keySet()) { - if (name.toLowerCase().contains(search.toLowerCase())) { - list.add(name); + for (Map.Entry entry : data.entrySet()) { + String name = entry.getKey(); + + // Apply search filter + if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) { + continue; } + + // Apply UserType filter (only for Custom and Built-in views) + if (!showingChained && userTypeFilter != 0) { + UserType ut = UserType.fromOrdinal(entry.getValue()); + if (userTypeFilter == 1 && !ut.allowsNpc()) continue; + if (userTypeFilter == 2 && !ut.allowsPlayer()) continue; + } + + list.add(name); } return list; } @@ -227,43 +310,111 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface int id = guibutton.id; - if (id == 2) { + // Fullscreen + if (id == 66) { + previewExecutor.stop(); + mc.displayGuiScreen(new GuiAbilityDirectory(npc)); + return; + } + + // User type filter: Both → NPC → Player → Both + if (id == BTN_USER_TYPE_FILTER) { + userTypeFilter = (userTypeFilter + 1) % 3; + if (scroll != null) { + scroll.setList(getSearchList()); + } + initGui(); + return; + } + + // Toggle: Custom → Built-in → Chained → Custom + if (id == BTN_TOGGLE_VIEW) { + if (!showingBuiltIn && !showingChained) { + // Custom → Built-in + showingBuiltIn = true; + showingChained = false; + } else if (showingBuiltIn) { + // Built-in → Chained + showingBuiltIn = false; + showingChained = true; + } else { + // Chained → Custom + showingChained = false; + showingBuiltIn = false; + } + selected = null; + selectedAbility = null; + selectedChain = null; + currentIsBuiltIn = false; + search = ""; + previewExecutor.stop(); + if (scroll != null) { + scroll.clear(); + } + if (showingChained) { + PacketClient.sendClient(new ChainedAbilitiesGetPacket()); + } else { + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } + initGui(); + return; + } + + // Preview controls (shared across all views) + if (id == BTN_PREVIEW_PLAY) { + if (previewExecutor.isPaused()) { + previewExecutor.play(); + } else if (showingChained && selectedChain != null) { + previewExecutor.startChainPreview(selectedChain, npc); + } else if (selectedAbility != null) { + previewExecutor.startPreview(selectedAbility, npc); + } + initGui(); + return; + } else if (id == BTN_PREVIEW_PAUSE) { + previewExecutor.pause(); + initGui(); + return; + } else if (id == BTN_PREVIEW_STOP) { + previewExecutor.stop(); + initGui(); + return; + } + + if (showingChained) { + if (id == BTN_ADD) { + // New chained ability + ChainedAbility newChain = new ChainedAbility("New Chain"); + setSubGui(new SubGuiChainedAbilityConfig(newChain, this)); + } else if (id == BTN_REMOVE && selected != null) { + GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), CONFIRM_REMOVE_CHAIN); + displayGuiScreen(guiyesno); + } else if (id == BTN_EDIT && selectedChain != null) { + previewExecutor.stop(); + setSubGui(new SubGuiChainedAbilityConfig(selectedChain, this)); + } + return; + } + + if (id == BTN_ADD && !showingBuiltIn) { // Add — open type selection setSubGui(new SubGuiAbilityTypeSelect()); - } else if (id == 1 && selected != null && selectedUuid != null) { - GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), 1); + } else if (id == BTN_REMOVE && !showingBuiltIn && selected != null) { + GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), CONFIRM_REMOVE_ABILITY); displayGuiScreen(guiyesno); - } else if (id == 100 && selectedAbility != null) { + } else if (id == BTN_EDIT && !showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) { // Edit previewExecutor.stop(); setSubGui(selectedAbility.createConfigGui(this)); - } else if (id == 91) { - // Play button - if (selectedAbility != null) { - if (previewExecutor.isPaused()) { - previewExecutor.play(); - } else { - previewExecutor.startPreview(selectedAbility, npc); - } - initGui(); - } - } else if (id == 92) { - // Pause button - previewExecutor.pause(); - initGui(); - } else if (id == 93) { - // Stop button - previewExecutor.stop(); - initGui(); } } @Override public void keyTyped(char c, int i) { super.keyTyped(c, i); - if (getTextField(55) != null && getTextField(55).isFocused()) { - if (!search.equals(getTextField(55).getText())) { - search = getTextField(55).getText(); + if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) { + if (!search.equals(getTextField(TF_SEARCH).getText())) { + search = getTextField(TF_SEARCH).getText(); scroll.resetScroll(); scroll.setList(getSearchList()); } @@ -272,15 +423,20 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { - if (scroll.id == 0) { + if (scroll.id == SCROLL_MAIN) { 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 (showingChained) { + PacketClient.sendClient(new ChainedAbilityGetPacket(selected)); + } else if (showingBuiltIn) { + currentIsBuiltIn = true; + PacketClient.sendClient(new BuiltInAbilityGetPacket(selected)); + } else { + currentIsBuiltIn = false; + PacketClient.sendClient(new CustomAbilityGetPacket(selected)); } } } @@ -288,9 +444,10 @@ 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) { + if (scroll.id == SCROLL_MAIN && selection != null && !selection.isEmpty()) { + if (showingChained && selectedChain != null) { + setSubGui(new SubGuiChainedAbilityConfig(selectedChain, this)); + } else if (!showingBuiltIn && !showingChained && !currentIsBuiltIn && selectedAbility != null) { previewExecutor.stop(); setSubGui(selectedAbility.createConfigGui(this)); } @@ -301,22 +458,29 @@ 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; - displayToUuid.clear(); - for (String key : data.keySet()) { - // key format: "displayName\tUUID" - int tabIndex = key.indexOf('\t'); - if (tabIndex > 0) { - String displayName = key.substring(0, tabIndex); - String uuid = key.substring(tabIndex + 1); - displayToUuid.put(displayName, uuid); - } else { - displayToUuid.put(key, key); + this.customData = data; + if (!showingBuiltIn && !showingChained && scroll != null) { + scroll.setList(getSearchList()); + if (prevSelected != null && customData.containsKey(prevSelected)) { + scroll.setSelected(prevSelected); } } - if (scroll != null) { + initGui(); + } else if (type == EnumScrollData.BUILTIN_ABILITIES) { + this.builtInData = data; + if (showingBuiltIn && scroll != null) { scroll.setList(getSearchList()); - if (prevSelected != null && displayToUuid.containsKey(prevSelected)) { + if (selected != null && builtInData.containsKey(selected)) { + scroll.setSelected(selected); + } + } + initGui(); + } else if (type == EnumScrollData.CHAINED_ABILITIES) { + String prevSelected = scroll != null ? scroll.getSelected() : null; + this.chainedData = data; + if (showingChained && scroll != null) { + scroll.setList(getSearchList()); + if (prevSelected != null && chainedData.containsKey(prevSelected)) { scroll.setSelected(prevSelected); } } @@ -326,6 +490,21 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void setGuiData(NBTTagCompound compound) { + // Detect chained ability response (has "Entries" tag) + if (showingChained && compound.hasKey("Entries")) { + selectedChain = new ChainedAbility(); + selectedChain.readNBT(compound); + selected = selectedChain.getName(); + if (scroll != null) { + scroll.setSelected(selected); + } + initGui(); + return; + } + + // 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) { @@ -348,97 +527,115 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiChainedAbilityConfig) { + handleChainConfigClosed(); + initGui(); + return; + } 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()); - if (hasDuplicateName(newAbility)) { - pendingSaveAbility = newAbility; - pendingNewCreation = true; - pendingTypeId = null; - setSubGui(new SubGuiDuplicateNameConfirm()); - return; - } - pendingTypeId = null; - saveAndOpenConfig(newAbility); - return; - } - } - pendingTypeId = null; + if (handleVariantSelectClosed((SubGuiAbilityVariantSelect) subgui)) return; } 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; - } - saveAndOpenConfig(newAbility); - return; - } - } + if (handleTypeSelectClosed((SubGuiAbilityTypeSelect) subgui)) return; } else if (subgui instanceof SubGuiDuplicateNameConfirm) { - SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui; - if (confirm.isConfirmed() && pendingSaveAbility != null) { - if (pendingNewCreation) { - saveAndOpenConfig(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; - } - } + if (handleDuplicateNameClosed((SubGuiDuplicateNameConfirm) subgui)) 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; + if (handlePendingSave()) return; } initGui(); } - private void saveAndOpenConfig(Ability ability) { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + private void handleChainConfigClosed() { + if (pendingSaveChain != null) { + PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT(false))); + selected = pendingSaveChain.getName(); + pendingSaveChain = null; + } + } + + /** + * @return true if a SubGui was opened (caller should return early, skipping initGui) + */ + private boolean handleVariantSelectClosed(SubGuiAbilityVariantSelect gui) { + int idx = gui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + gui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + pendingTypeId = null; + openConfig(newAbility); + return true; + } + } + pendingTypeId = null; + return false; + } + + /** + * @return true if a SubGui was opened (caller should return early, skipping initGui) + */ + private boolean handleTypeSelectClosed(SubGuiAbilityTypeSelect gui) { + String typeId = gui.getSelectedTypeId(); + if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return true; + } + Ability newAbility = AbilityController.Instance.create(typeId); + if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } + newAbility.setId(UUID.randomUUID().toString()); + openConfig(newAbility); + return true; + } + } + return false; + } + + /** + * @return true if a SubGui was opened (caller should return early, skipping initGui) + */ + private boolean handleDuplicateNameClosed(SubGuiDuplicateNameConfirm gui) { + if (pendingSaveAbility == null) return false; + + if (gui.isConfirmed()) { + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false))); + pendingSaveAbility = null; + return false; + } + + if (gui.isBack()) { + Ability ability = pendingSaveAbility; + pendingSaveAbility = null; + setSubGui(ability.createConfigGui(this)); + return true; + } + + pendingSaveAbility = null; + return false; + } + + /** + * @return true if a SubGui was opened (caller should return early, skipping initGui) + */ + private boolean handlePendingSave() { + if (hasDuplicateName(pendingSaveAbility)) { + setSubGui(new SubGuiDuplicateNameConfirm()); + return true; + } + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false))); + pendingSaveAbility = null; + return false; + } + + private void openConfig(Ability ability) { + if (ability.isBuiltIn()) return; // Built-in abilities are immutable selectedAbility = ability; selected = ability.getName(); - selectedUuid = ability.getId(); previewExecutor.stop(); setSubGui(ability.createConfigGui(this)); } @@ -446,12 +643,12 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface 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; + if (!customData.containsKey(name)) return false; + // Name exists — check if it belongs to a different ability (by UUID) + String uuid = ability.getId(); + if (uuid == null || uuid.isEmpty()) return true; // New ability with conflicting name + Ability existing = AbilityController.Instance.getCustomAbilityByName(name); + return existing == null || !uuid.equals(existing.getId()); } @Override @@ -459,13 +656,18 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface NoppesUtil.openGUI(player, this); if (!result) return; - if (id == 1 && selected != null && selectedUuid != null) { - PacketClient.sendClient(new CustomAbilityRemovePacket(selectedUuid)); + if (id == CONFIRM_REMOVE_ABILITY && selected != null) { + PacketClient.sendClient(new CustomAbilityRemovePacket(selected)); scroll.clear(); selected = null; - selectedUuid = null; selectedAbility = null; initGui(); + } else if (id == CONFIRM_REMOVE_CHAIN && selected != null) { + PacketClient.sendClient(new ChainedAbilityRemovePacket(selected)); + scroll.clear(); + selected = null; + selectedChain = null; + initGui(); } } @@ -475,6 +677,11 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface pendingSaveAbility = ability; } + @Override + public void onChainedAbilitySaved(ChainedAbility chain) { + pendingSaveChain = chain; + } + @Override public void unFocused(GuiNpcTextField textfield) { // Search field handling is done in keyTyped diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAuction.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAuction.java new file mode 100644 index 000000000..84e16d24e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAuction.java @@ -0,0 +1,1096 @@ +package noppes.npcs.client.gui.global; + +import kamkeel.npcs.network.packets.request.auction.ManageAuctionPacket; +import net.minecraft.client.audio.PositionedSoundRecord; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.AuctionClientConfig; +import noppes.npcs.client.CustomNpcResourceListener; +import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.util.GuiContainerNPCInterface2; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.IGuiData; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.constants.EnumAuctionSort; +import noppes.npcs.constants.EnumClaimType; +import noppes.npcs.containers.ContainerManageAuction; +import noppes.npcs.controllers.data.AuctionClaim; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.util.AuctionFormatUtil; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +public class GuiNpcManageAuction extends GuiContainerNPCInterface2 implements IGuiData, ITextfieldListener { + private static final ResourceLocation SLOT_DEFAULT = new ResourceLocation("customnpcs", "textures/gui/slot.png"); + private static final ResourceLocation SLOT_AUCTION = new ResourceLocation("customnpcs", "textures/gui/auction/auction_slot.png"); + private static final ResourceLocation ICON_X = new ResourceLocation("customnpcs", "textures/gui/auction/x_icon.png"); + private static final ResourceLocation ICON_X_CANCEL = new ResourceLocation("customnpcs", "textures/gui/auction/x_icon_blue.png"); + private static final ResourceLocation ICON_CHECK = new ResourceLocation("customnpcs", "textures/gui/auction/check_icon.png"); + private static final ResourceLocation COIN_ICON = new ResourceLocation("customnpcs", "textures/items/npcCoinGold.png"); + + // Slot tints (ARGB) aligned with My Trades style. + private static final int TINT_BLUE = 0x605080FF; + private static final int TINT_GREEN = 0x6050FF50; + private static final int TINT_RED = 0x60FF5050; + + public enum Tab { + LISTINGS, + CREATE, + CLAIMS + } + + private enum PendingAction { + NONE, + STOP, + CANCEL, + CLAIM_ITEM, + CLAIM_CURRENCY + } + + private static final int BTN_TAB_LISTINGS = 100; + private static final int BTN_TAB_CREATE = 101; + private static final int BTN_TAB_CLAIMS = 102; + private static final int BTN_PAGE_PREV = 110; + private static final int BTN_PAGE_NEXT = 111; + private static final int BTN_SORT = 112; + private static final int BTN_CREATE = 120; + + private static final int TXT_SEARCH = 1; + private static final int TXT_FAKE_SELLER = 2; + private static final int TXT_FAKE_START = 3; + private static final int TXT_FAKE_BUYOUT = 4; + private static final int TXT_FAKE_DURATION = 5; + + private static final int RIGHT_X = 188; + private static final int RIGHT_WIDTH = 220; + private static final int TAB_Y = 10; + + private static final int LISTINGS_SORT_Y = 40; + private static final int LISTINGS_SEARCH_LABEL_Y = 66; + private static final int LISTINGS_SEARCH_FIELD_Y = 76; + private static final int LISTINGS_HINT_Y = 98; + private static final int LISTINGS_HINT2_Y = 110; + private static final int LISTINGS_HINT3_Y = 122; + private static final int LISTINGS_HINT4_Y = 134; + private static final int LISTINGS_DETAILS_TITLE_Y = 42; + private static final int DETAILS_PANEL_X = RIGHT_X; + private static final int DETAILS_PANEL_Y = 40; + private static final int DETAILS_PANEL_W = RIGHT_WIDTH - 8; + private static final int DETAILS_PANEL_H = 138; + + private static final int CREATE_FIELD_X = RIGHT_X + 82; + private static final int CREATE_FIELD_WIDTH = 126; + private static final int CREATE_SELLER_Y = 52; + private static final int CREATE_START_Y = 78; + private static final int CREATE_BUYOUT_Y = 104; + private static final int CREATE_DURATION_Y = 130; + private static final int CREATE_BUTTON_Y = 178; + + private final ContainerManageAuction manageContainer; + private final AuctionFilter filter = new AuctionFilter(); + + private Tab activeTab = Tab.LISTINGS; + private String searchText = ""; + + private String fakeSeller = "Server"; + private String fakeStartPrice = "1"; + private String fakeBuyoutPrice = ""; + private String fakeDurationHours = Integer.toString(Math.max(1, AuctionClientConfig.getAuctionDurationHours())); + + private int listingsPage = 0; + private int listingsTotalPages = 1; + private int listingsTotalCount = 0; + + private int claimsPage = 0; + private int claimsTotalPages = 1; + private int claimsTotalCount = 0; + private int claimsListingCount = 0; + private int claimsClaimCount = 0; + + private int pendingDisplaySlot = -1; + private PendingAction pendingAction = PendingAction.NONE; + + private String selectedListingId = null; + private AuctionListing selectedListing = null; + private int selectedDisplaySlot = -1; + private boolean listingsDetailsView = false; + + private String errorMessage = null; + private boolean createRequestPending = false; + + public GuiNpcManageAuction(EntityNPCInterface npc, ContainerManageAuction container) { + super(npc, container); + this.manageContainer = container; + this.drawDefaultBackground = false; + this.ySize = 200; + this.title = ""; + } + + @Override + public void initGui() { + super.initGui(); + + addButton(new GuiNpcButton(BTN_TAB_LISTINGS, guiLeft + RIGHT_X, guiTop + TAB_Y, 70, 20, "global.auction.manage.listings")); + addButton(new GuiNpcButton(BTN_TAB_CREATE, guiLeft + RIGHT_X + 74, guiTop + TAB_Y, 70, 20, "global.auction.manage.create")); + addButton(new GuiNpcButton(BTN_TAB_CLAIMS, guiLeft + RIGHT_X + 148, guiTop + TAB_Y, 70, 20, "global.auction.manage.claims")); + updateTabButtonState(); + + int pageButtonY = guiTop + ySize - 24; + addButton(new GuiNpcButton(BTN_PAGE_PREV, guiLeft + RIGHT_X, pageButtonY, 20, 20, "<")); + addButton(new GuiNpcButton(BTN_PAGE_NEXT, guiLeft + RIGHT_X + 24, pageButtonY, 20, 20, ">")); + + if (activeTab == Tab.LISTINGS && !listingsDetailsView) { + String sortName = filter.getSortBy().getDisplayName(); + addButton(new GuiNpcButton(BTN_SORT, guiLeft + RIGHT_X, guiTop + LISTINGS_SORT_Y, RIGHT_WIDTH - 8, 20, + StatCollector.translateToLocal("global.auction.manage.sort") + ": " + sortName)); + + addTextField(new GuiNpcTextField(TXT_SEARCH, this, fontRendererObj, + guiLeft + RIGHT_X, guiTop + LISTINGS_SEARCH_FIELD_Y, RIGHT_WIDTH - 8, 18, searchText)); + requestListings(); + } else if (activeTab == Tab.LISTINGS) { + manageContainer.setDisplayMode(ContainerManageAuction.DisplayMode.LISTINGS); + } else if (activeTab == Tab.CREATE) { + addTextField(new GuiNpcTextField(TXT_FAKE_SELLER, this, fontRendererObj, + guiLeft + CREATE_FIELD_X, guiTop + CREATE_SELLER_Y, CREATE_FIELD_WIDTH, 18, fakeSeller)); + + GuiNpcTextField startField = new GuiNpcTextField(TXT_FAKE_START, this, fontRendererObj, + guiLeft + CREATE_FIELD_X, guiTop + CREATE_START_Y, CREATE_FIELD_WIDTH, 18, fakeStartPrice); + startField.setIntegersOnly(); + addTextField(startField); + + GuiNpcTextField buyoutField = new GuiNpcTextField(TXT_FAKE_BUYOUT, this, fontRendererObj, + guiLeft + CREATE_FIELD_X, guiTop + CREATE_BUYOUT_Y, CREATE_FIELD_WIDTH, 18, fakeBuyoutPrice); + buyoutField.setIntegersOnly(); + addTextField(buyoutField); + + GuiNpcTextField durationField = new GuiNpcTextField(TXT_FAKE_DURATION, this, fontRendererObj, + guiLeft + CREATE_FIELD_X, guiTop + CREATE_DURATION_Y, CREATE_FIELD_WIDTH, 18, fakeDurationHours); + durationField.setIntegersOnly(); + addTextField(durationField); + + addButton(new GuiNpcButton(BTN_CREATE, guiLeft + RIGHT_X, guiTop + CREATE_BUTTON_Y, RIGHT_WIDTH - 8, 20, + "global.auction.manage.create.submit")); + } else if (activeTab == Tab.CLAIMS) { + requestClaims(); + } + + syncContainerSlots(); + updatePageButtons(); + } + + private void switchTab(Tab tab) { + if (activeTab == tab) return; + activeTab = tab; + listingsDetailsView = false; + if (tab != Tab.LISTINGS) { + selectedListing = null; + selectedListingId = null; + selectedDisplaySlot = -1; + } + clearPending(); + errorMessage = null; + initGui(); + } + + private void updateTabButtonState() { + GuiNpcButton listingsBtn = getButton(BTN_TAB_LISTINGS); + GuiNpcButton createBtn = getButton(BTN_TAB_CREATE); + GuiNpcButton claimsBtn = getButton(BTN_TAB_CLAIMS); + if (listingsBtn != null) { + listingsBtn.enabled = activeTab != Tab.LISTINGS || listingsDetailsView; + } + if (createBtn != null) { + createBtn.enabled = activeTab != Tab.CREATE; + } + if (claimsBtn != null) { + claimsBtn.enabled = activeTab != Tab.CLAIMS; + } + } + + private void syncContainerSlots() { + boolean showCreate = activeTab == Tab.CREATE; + manageContainer.setCreateSlotVisible(showCreate); + + boolean showDetail = activeTab == Tab.LISTINGS && listingsDetailsView && selectedListing != null; + manageContainer.setDetailSlotVisible(showDetail); + if (showDetail) { + manageContainer.setDetailItem(selectedListing.item); + } else { + manageContainer.clearDetailItem(); + } + } + + private void updatePageButtons() { + GuiNpcButton prev = getButton(BTN_PAGE_PREV); + GuiNpcButton next = getButton(BTN_PAGE_NEXT); + if (prev == null || next == null) return; + + if (activeTab == Tab.CREATE) { + prev.visible = false; + next.visible = false; + prev.enabled = false; + next.enabled = false; + return; + } + + if (activeTab == Tab.LISTINGS && listingsDetailsView) { + prev.visible = false; + next.visible = false; + prev.enabled = false; + next.enabled = false; + return; + } + + prev.visible = true; + next.visible = true; + if (activeTab == Tab.LISTINGS) { + prev.enabled = listingsPage > 0; + next.enabled = listingsPage < listingsTotalPages - 1; + } else { + prev.enabled = claimsPage > 0; + next.enabled = claimsPage < claimsTotalPages - 1; + } + } + + private void requestListings() { + filter.setSearchText(searchText); + manageContainer.setDisplayMode(ContainerManageAuction.DisplayMode.LISTINGS); + ManageAuctionPacket.requestListings(filter, listingsPage); + } + + private void requestClaims() { + manageContainer.setDisplayMode(ContainerManageAuction.DisplayMode.CLAIMS); + ManageAuctionPacket.requestGlobalClaims(claimsPage); + } + + private void cycleSort() { + EnumAuctionSort[] values = EnumAuctionSort.values(); + int next = (filter.getSortBy().ordinal() + 1) % values.length; + filter.setSortBy(values[next]); + listingsPage = 0; + clearPending(); + requestListings(); + initGui(); + } + + private void createFakeAuction() { + GuiNpcTextField sellerField = getTextField(TXT_FAKE_SELLER); + GuiNpcTextField startField = getTextField(TXT_FAKE_START); + GuiNpcTextField buyoutField = getTextField(TXT_FAKE_BUYOUT); + GuiNpcTextField durationField = getTextField(TXT_FAKE_DURATION); + + if (sellerField != null) fakeSeller = sellerField.getText(); + if (startField != null) fakeStartPrice = startField.getText(); + if (buyoutField != null) fakeBuyoutPrice = buyoutField.getText(); + if (durationField != null) fakeDurationHours = durationField.getText(); + + ItemStack staged = manageContainer.getCreateItem(); + if (staged == null) { + errorMessage = StatCollector.translateToLocal("global.auction.manage.error.noItem"); + return; + } + + long start = parseLong(fakeStartPrice, 0); + long buyout = parseLong(fakeBuyoutPrice, 0); + int duration = (int) parseLong(fakeDurationHours, AuctionClientConfig.getAuctionDurationHours()); + if (duration <= 0) { + duration = Math.max(1, AuctionClientConfig.getAuctionDurationHours()); + } + + if (start <= 0) { + errorMessage = StatCollector.translateToLocal("global.auction.manage.error.invalidStart"); + return; + } + if (buyout > 0 && buyout < start) { + errorMessage = StatCollector.translateToLocal("global.auction.manage.error.invalidBuyout"); + return; + } + + String seller = fakeSeller != null ? fakeSeller.trim() : ""; + if (seller.isEmpty()) { + seller = "Server"; + fakeSeller = seller; + } + + ManageAuctionPacket.createFakeListing(staged, seller, start, buyout, duration); + createRequestPending = true; + errorMessage = null; + } + + private long parseLong(String value, long fallback) { + if (value == null || value.trim().isEmpty()) return fallback; + try { + return Long.parseLong(value.trim()); + } catch (NumberFormatException ignored) { + return fallback; + } + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + super.actionPerformed(guibutton); + if (!(guibutton instanceof GuiNpcButton)) return; + + if (guibutton.id == BTN_TAB_LISTINGS) { + if (activeTab == Tab.LISTINGS && listingsDetailsView) { + listingsDetailsView = false; + selectedListing = null; + selectedListingId = null; + selectedDisplaySlot = -1; + clearPending(); + initGui(); + } else { + switchTab(Tab.LISTINGS); + } + return; + } + if (guibutton.id == BTN_TAB_CREATE) { + switchTab(Tab.CREATE); + return; + } + if (guibutton.id == BTN_TAB_CLAIMS) { + switchTab(Tab.CLAIMS); + return; + } + + if (guibutton.id == BTN_PAGE_PREV) { + if (activeTab == Tab.LISTINGS && listingsPage > 0) { + listingsPage--; + clearPending(); + requestListings(); + NoppesUtil.clickSound(); + } else if (activeTab == Tab.CLAIMS && claimsPage > 0) { + claimsPage--; + clearPending(); + requestClaims(); + NoppesUtil.clickSound(); + } + updatePageButtons(); + return; + } + + if (guibutton.id == BTN_PAGE_NEXT) { + if (activeTab == Tab.LISTINGS && listingsPage < listingsTotalPages - 1) { + listingsPage++; + clearPending(); + requestListings(); + NoppesUtil.clickSound(); + } else if (activeTab == Tab.CLAIMS && claimsPage < claimsTotalPages - 1) { + claimsPage++; + clearPending(); + requestClaims(); + NoppesUtil.clickSound(); + } + updatePageButtons(); + return; + } + + if (guibutton.id == BTN_SORT) { + cycleSort(); + NoppesUtil.clickSound(); + return; + } + + if (guibutton.id == BTN_CREATE) { + createFakeAuction(); + NoppesUtil.clickSound(); + } + } + + @Override + protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) { + if (slot == null) { + clearPending(); + return; + } + + if (manageContainer.isDisplaySlot(slotIndex)) { + int displayIndex = manageContainer.toDisplayIndex(slotIndex); + if (activeTab == Tab.LISTINGS) { + handleListingsSlotClick(displayIndex, mouseButton); + return; + } + if (activeTab == Tab.CLAIMS) { + handleClaimsSlotClick(displayIndex, mouseButton); + return; + } + } + + if (activeTab == Tab.CREATE) { + if (manageContainer.isCreateSlot(slotIndex)) { + if (manageContainer.getCreateItem() != null) { + boolean removeAll = mouseButton == 0; + manageContainer.removeFromCreateSlot(removeAll); + NoppesUtil.clickSound(); + } + return; + } + + if (manageContainer.isPlayerSlot(slotIndex)) { + ItemStack stack = slot.getStack(); + if (stack != null) { + boolean fullStack = mouseButton == 0; + manageContainer.addToCreateSlot(slotIndex, fullStack); + NoppesUtil.clickSound(); + } + return; + } + } + + clearPending(); + } + + private void handleListingsSlotClick(int displayIndex, int mouseButton) { + AuctionListing listing = manageContainer.getListingAtDisplay(displayIndex); + if (listing == null) { + clearPending(); + return; + } + + // Any non-matching input while pending cancels the operation. + if (pendingAction != PendingAction.NONE) { + if (displayIndex == pendingDisplaySlot && isConfirmInput(pendingAction, mouseButton)) { + ManageAuctionPacket.manageListing(listing.id, pendingAction == PendingAction.CANCEL); + clearPending(); + playConfirmSound(); + } else { + clearPending(); + } + return; + } + + if (mouseButton == 0) { + selectListing(displayIndex, listing); + clearPending(); + listingsDetailsView = true; + initGui(); + NoppesUtil.clickSound(); + return; + } + + if (isStopStartInput(mouseButton) || isCancelStartInput(mouseButton)) { + PendingAction action = isShiftKeyDown() ? PendingAction.CANCEL : PendingAction.STOP; + setPending(displayIndex, action); + NoppesUtil.clickSound(); + return; + } + + clearPending(); + } + + private void handleClaimsSlotClick(int displayIndex, int mouseButton) { + AuctionListing listing = manageContainer.getListingAtDisplay(displayIndex); + if (listing != null) { + if (pendingAction != PendingAction.NONE) { + if (displayIndex == pendingDisplaySlot && isConfirmInput(pendingAction, mouseButton)) { + ManageAuctionPacket.manageListing(listing.id, pendingAction == PendingAction.CANCEL); + clearPending(); + playConfirmSound(); + } else { + clearPending(); + } + return; + } + + if (isStopStartInput(mouseButton) || isCancelStartInput(mouseButton)) { + PendingAction action = isShiftKeyDown() ? PendingAction.CANCEL : PendingAction.STOP; + setPending(displayIndex, action); + NoppesUtil.clickSound(); + } else { + clearPending(); + } + return; + } + + AuctionClaim claim = manageContainer.getClaimAtDisplay(displayIndex); + if (claim == null) { + clearPending(); + return; + } + + PendingAction action = claim.type.isItem() ? PendingAction.CLAIM_ITEM : PendingAction.CLAIM_CURRENCY; + if (pendingAction != PendingAction.NONE) { + if (displayIndex == pendingDisplaySlot && pendingAction == action && isConfirmInput(action, mouseButton)) { + if (action == PendingAction.CLAIM_ITEM) { + ManageAuctionPacket.claimGlobalItem(claim.id); + } else { + ManageAuctionPacket.claimGlobalCurrency(claim.id); + } + clearPending(); + playConfirmSound(); + } else { + clearPending(); + } + return; + } + + if (mouseButton == 0) { + setPending(displayIndex, action); + NoppesUtil.clickSound(); + return; + } + + clearPending(); + } + + private boolean isStopStartInput(int mouseButton) { + return mouseButton == 1 && !isShiftKeyDown(); + } + + private boolean isCancelStartInput(int mouseButton) { + return mouseButton == 1 && isShiftKeyDown(); + } + + private boolean isConfirmInput(PendingAction action, int mouseButton) { + if (action == PendingAction.CLAIM_ITEM || action == PendingAction.CLAIM_CURRENCY) { + return mouseButton == 0; + } + if (action == PendingAction.STOP) { + return mouseButton == 1 && !isShiftKeyDown(); + } + if (action == PendingAction.CANCEL) { + return mouseButton == 1 && isShiftKeyDown(); + } + return false; + } + + private void selectListing(int displayIndex, AuctionListing listing) { + selectedDisplaySlot = displayIndex; + selectedListingId = listing != null ? listing.id : null; + selectedListing = listing; + syncContainerSlots(); + updateTabButtonState(); + } + + private void refreshSelectedListing(List pageListings) { + selectedListing = null; + selectedDisplaySlot = -1; + + if (selectedListingId == null || pageListings == null) { + syncContainerSlots(); + return; + } + + for (int i = 0; i < pageListings.size(); i++) { + AuctionListing listing = pageListings.get(i); + if (listing != null && selectedListingId.equals(listing.id)) { + selectedListing = listing; + selectedDisplaySlot = i; + break; + } + } + + if (selectedListing == null) { + selectedListingId = null; + } + + if (selectedListing == null) { + listingsDetailsView = false; + } + + syncContainerSlots(); + updateTabButtonState(); + } + + private void setPending(int displaySlot, PendingAction action) { + this.pendingDisplaySlot = displaySlot; + this.pendingAction = action; + manageContainer.setHiddenDisplaySlot(displaySlot); + } + + private void clearPending() { + manageContainer.clearHiddenDisplaySlot(); + pendingDisplaySlot = -1; + pendingAction = PendingAction.NONE; + } + + private void playConfirmSound() { + mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a( + new ResourceLocation("random.orb"), 1.0F)); + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + + if (activeTab == Tab.LISTINGS) { + GuiNpcTextField search = getTextField(TXT_SEARCH); + if (search != null && search.isFocused()) { + String text = search.getText(); + if (!text.equals(searchText)) { + searchText = text; + listingsPage = 0; + clearPending(); + requestListings(); + } + } + } + } + + @Override + public void unFocused(GuiNpcTextField textfield) { + if (textfield == null) return; + + if (textfield.id == TXT_SEARCH) { + searchText = textfield.getText(); + } else if (textfield.id == TXT_FAKE_SELLER) { + fakeSeller = textfield.getText(); + } else if (textfield.id == TXT_FAKE_START) { + fakeStartPrice = textfield.getText(); + } else if (textfield.id == TXT_FAKE_BUYOUT) { + fakeBuyoutPrice = textfield.getText(); + } else if (textfield.id == TXT_FAKE_DURATION) { + fakeDurationHours = textfield.getText(); + } + } + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("ManageAuctionListingsData")) { + listingsPage = compound.getInteger("Page"); + listingsTotalPages = Math.max(1, compound.getInteger("TotalPages")); + listingsTotalCount = compound.getInteger("TotalListings"); + + NBTTagList list = compound.getTagList("Listings", 10); + List listings = new ArrayList(); + for (int i = 0; i < list.tagCount(); i++) { + listings.add(AuctionListing.fromNBT(list.getCompoundTagAt(i))); + } + manageContainer.setListingsPage(listings); + refreshSelectedListing(listings); + updatePageButtons(); + } + + if (compound.hasKey("ManageAuctionClaimsData")) { + claimsPage = compound.getInteger("Page"); + claimsTotalPages = Math.max(1, compound.getInteger("TotalPages")); + claimsTotalCount = compound.hasKey("TotalEntries") ? compound.getInteger("TotalEntries") : compound.getInteger("TotalClaims"); + claimsClaimCount = compound.getInteger("TotalClaims"); + claimsListingCount = compound.hasKey("TotalListings") ? compound.getInteger("TotalListings") : 0; + + NBTTagList claimList = compound.getTagList("Claims", 10); + List claims = new ArrayList(); + for (int i = 0; i < claimList.tagCount(); i++) { + claims.add(AuctionClaim.fromNBT(claimList.getCompoundTagAt(i))); + } + + NBTTagList listingList = compound.getTagList("Listings", 10); + List listings = new ArrayList(); + for (int i = 0; i < listingList.tagCount(); i++) { + listings.add(AuctionListing.fromNBT(listingList.getCompoundTagAt(i))); + } + + manageContainer.setClaimsAndListingsPage(claims, listings); + updatePageButtons(); + } + + if (compound.getBoolean("ManageAuctionRefresh")) { + boolean createSuccess = compound.getBoolean("ManageAuctionCreateSuccess"); + createRequestPending = false; + if (createSuccess) { + manageContainer.clearCreateSlot(); + listingsDetailsView = false; + selectedListing = null; + selectedListingId = null; + selectedDisplaySlot = -1; + activeTab = Tab.LISTINGS; + clearPending(); + initGui(); + return; + } + + clearPending(); + if (activeTab == Tab.LISTINGS) { + requestListings(); + } else if (activeTab == Tab.CLAIMS) { + requestClaims(); + } + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + + drawDisplaySlotBackgrounds(); + drawPlayerInventorySlotBackgrounds(); + drawRightPanelSlotBackgrounds(); + drawClaimsTintOverlay(); + drawSelectedListingOverlay(); + drawClaimIndicators(); + drawPendingOverlay(); + } + + private void drawDisplaySlotBackgrounds() { + for (int row = 0; row < ContainerManageAuction.DISPLAY_ROWS; row++) { + for (int col = 0; col < ContainerManageAuction.DISPLAY_COLS; col++) { + int x = guiLeft + ContainerManageAuction.DISPLAY_X + col * 18; + int y = guiTop + ContainerManageAuction.DISPLAY_Y + row * 18; + drawAuctionSlot(x, y); + } + } + } + + private void drawPlayerInventorySlotBackgrounds() { + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 9; col++) { + int x = guiLeft + ContainerManageAuction.PLAYER_INV_X + col * 18; + int y = guiTop + ContainerManageAuction.PLAYER_INV_Y + row * 18; + drawDefaultSlot(x, y); + } + } + for (int col = 0; col < 9; col++) { + int x = guiLeft + ContainerManageAuction.PLAYER_INV_X + col * 18; + int y = guiTop + ContainerManageAuction.HOTBAR_Y; + drawDefaultSlot(x, y); + } + } + + private void drawRightPanelSlotBackgrounds() { + if (activeTab == Tab.LISTINGS && listingsDetailsView) { + drawDetailsPanelBackground(); + } + if (activeTab == Tab.LISTINGS && listingsDetailsView && selectedListing != null) { + drawAuctionSlot(guiLeft + ContainerManageAuction.DETAIL_SLOT_X, guiTop + ContainerManageAuction.DETAIL_SLOT_Y); + } else if (activeTab == Tab.CREATE) { + drawAuctionSlot(guiLeft + ContainerManageAuction.CREATE_SLOT_X, guiTop + ContainerManageAuction.CREATE_SLOT_Y); + } + } + + private void drawDetailsPanelBackground() { + int x = guiLeft + DETAILS_PANEL_X; + int y = guiTop + DETAILS_PANEL_Y; + int x2 = x + DETAILS_PANEL_W; + int y2 = y + DETAILS_PANEL_H; + + Gui.drawRect(x, y, x2, y2, 0xCC0F0F0F); + Gui.drawRect(x + 1, y + 1, x2 - 1, y2 - 1, 0x88202020); + Gui.drawRect(x, y, x2, y + 1, 0xFF3A3A3A); + Gui.drawRect(x, y2 - 1, x2, y2, 0xFF3A3A3A); + Gui.drawRect(x, y, x + 1, y2, 0xFF3A3A3A); + Gui.drawRect(x2 - 1, y, x2, y2, 0xFF3A3A3A); + } + + private void drawSelectedListingOverlay() { + if (activeTab != Tab.LISTINGS || selectedDisplaySlot < 0 || selectedDisplaySlot >= ContainerManageAuction.DISPLAY_SLOT_COUNT) { + return; + } + + int x = guiLeft + ContainerManageAuction.DISPLAY_X + (selectedDisplaySlot % ContainerManageAuction.DISPLAY_COLS) * 18; + int y = guiTop + ContainerManageAuction.DISPLAY_Y + (selectedDisplaySlot / ContainerManageAuction.DISPLAY_COLS) * 18; + drawColoredOverlay(x, y, 0x503080FF); + Gui.drawRect(x, y, x + 18, y + 1, 0xFF8AC4FF); + Gui.drawRect(x, y + 17, x + 18, y + 18, 0xFF8AC4FF); + Gui.drawRect(x, y, x + 1, y + 18, 0xFF8AC4FF); + Gui.drawRect(x + 17, y, x + 18, y + 18, 0xFF8AC4FF); + } + + private void drawClaimIndicators() { + if (activeTab != Tab.CLAIMS) return; + + for (int i = 0; i < ContainerManageAuction.DISPLAY_SLOT_COUNT; i++) { + AuctionClaim claim = manageContainer.getClaimAtDisplay(i); + if (claim == null) continue; + + boolean drawCoin = claim.type == EnumClaimType.CURRENCY + || (claim.type == EnumClaimType.REFUND && claim.item == null); + if (!drawCoin) continue; + + int x = guiLeft + ContainerManageAuction.DISPLAY_X + (i % ContainerManageAuction.DISPLAY_COLS) * 18; + int y = guiTop + ContainerManageAuction.DISPLAY_Y + (i / ContainerManageAuction.DISPLAY_COLS) * 18; + drawIconOverlay(x, y, COIN_ICON); + } + } + + private void drawClaimsTintOverlay() { + if (activeTab != Tab.CLAIMS) return; + for (int i = 0; i < ContainerManageAuction.DISPLAY_SLOT_COUNT; i++) { + int tint = getClaimsSlotTint(i); + if (tint == 0) continue; + + int x = guiLeft + ContainerManageAuction.DISPLAY_X + (i % ContainerManageAuction.DISPLAY_COLS) * 18; + int y = guiTop + ContainerManageAuction.DISPLAY_Y + (i / ContainerManageAuction.DISPLAY_COLS) * 18; + drawColoredOverlay(x, y, tint); + } + } + + private int getClaimsSlotTint(int displayIndex) { + AuctionListing listing = manageContainer.getListingAtDisplay(displayIndex); + if (listing != null) { + return TINT_BLUE; + } + + AuctionClaim claim = manageContainer.getClaimAtDisplay(displayIndex); + if (claim == null) return 0; + + if (claim.type == EnumClaimType.CURRENCY) { + return TINT_GREEN; + } + if (claim.type == EnumClaimType.REFUND) { + return TINT_RED; + } + if (claim.type == EnumClaimType.ITEM) { + return claim.isReturned ? TINT_RED : TINT_GREEN; + } + return TINT_GREEN; + } + + private void drawPendingOverlay() { + if (pendingDisplaySlot < 0 || pendingAction == PendingAction.NONE) return; + + int x = guiLeft + ContainerManageAuction.DISPLAY_X + (pendingDisplaySlot % ContainerManageAuction.DISPLAY_COLS) * 18; + int y = guiTop + ContainerManageAuction.DISPLAY_Y + (pendingDisplaySlot / ContainerManageAuction.DISPLAY_COLS) * 18; + + int color = 0x80FFFF00; + ResourceLocation icon = ICON_X; + float iconR = 1f; + float iconG = 1f; + float iconB = 1f; + if (pendingAction == PendingAction.STOP) { + color = 0x805080FF; + icon = ICON_X; + } else if (pendingAction == PendingAction.CANCEL) { + color = 0x80A040D0; + icon = ICON_X_CANCEL; + } else if (pendingAction == PendingAction.CLAIM_ITEM || pendingAction == PendingAction.CLAIM_CURRENCY) { + color = 0x8055FF55; + icon = ICON_CHECK; + } + + drawColoredOverlay(x, y, color); + drawIconOverlay(x, y, icon, iconR, iconG, iconB, 1f); + } + + private void drawAuctionSlot(int x, int y) { + GL11.glColor4f(1f, 1f, 1f, 1f); + mc.renderEngine.bindTexture(SLOT_AUCTION); + Gui.func_146110_a(x, y, 0, 0, 18, 18, 18, 18); + } + + private void drawDefaultSlot(int x, int y) { + GL11.glColor4f(1f, 1f, 1f, 1f); + mc.renderEngine.bindTexture(SLOT_DEFAULT); + drawTexturedModalRect(x, y, 0, 0, 18, 18); + } + + private void drawColoredOverlay(int x, int y, int color) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Gui.drawRect(x + 1, y + 1, x + 17, y + 17, color); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glColor4f(1f, 1f, 1f, 1f); + } + + private void drawIconOverlay(int x, int y, ResourceLocation icon) { + drawIconOverlay(x, y, icon, 1f, 1f, 1f, 1f); + } + + private void drawIconOverlay(int x, int y, ResourceLocation icon, float r, float g, float b, float a) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(r, g, b, a); + mc.renderEngine.bindTexture(icon); + Gui.func_146110_a(x + 1, y + 1, 0, 0, 16, 16, 16, 16); + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + int textColor = CustomNpcResourceListener.DefaultTextColor; + + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.title"), 8, 6, textColor); + + if (activeTab == Tab.LISTINGS) { + if (listingsDetailsView) { + drawListingsDetails(textColor); + } else { + drawPageText(listingsPage, listingsTotalPages, listingsTotalCount, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.search"), RIGHT_X, LISTINGS_SEARCH_LABEL_Y, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.hint.listings"), RIGHT_X, LISTINGS_HINT_Y, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.hint.stop"), RIGHT_X, LISTINGS_HINT2_Y, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.hint.cancel"), RIGHT_X, LISTINGS_HINT3_Y, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.selectListing"), RIGHT_X, LISTINGS_HINT4_Y, textColor); + } + } else if (activeTab == Tab.CLAIMS) { + drawPageText(claimsPage, claimsTotalPages, claimsTotalCount, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.hint.claims"), RIGHT_X, 58, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.hint.stop"), RIGHT_X, 70, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.hint.cancel"), RIGHT_X, 82, textColor); + String totals = claimsClaimCount + " claims | " + claimsListingCount + " listings"; + fontRendererObj.drawString(totals, RIGHT_X, 94, textColor); + } else { + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.seller"), RIGHT_X, CREATE_SELLER_Y + 5, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.startPrice"), RIGHT_X, CREATE_START_Y + 5, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.buyoutPrice"), RIGHT_X, CREATE_BUYOUT_Y + 5, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.durationHours"), RIGHT_X, CREATE_DURATION_Y + 5, textColor); + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.stagedItem"), RIGHT_X + 22, ContainerManageAuction.CREATE_SLOT_Y + 5, textColor); + + ItemStack staged = manageContainer.getCreateItem(); + if (staged != null) { + int available = manageContainer.countItemInPlayerInventory(staged); + String countText = staged.stackSize + "/" + available; + int countColor = staged.stackSize <= available ? 0x55FF55 : 0xFF5555; + fontRendererObj.drawStringWithShadow(countText, RIGHT_X + 22, ContainerManageAuction.CREATE_SLOT_Y + 16, countColor); + } + } + + if (errorMessage != null && !errorMessage.isEmpty()) { + fontRendererObj.drawString(EnumChatFormatting.RED + errorMessage, RIGHT_X, ySize - 12, 0xFFFFFF); + } + + drawDynamicTooltip(mouseX, mouseY); + } + + private void drawPageText(int page, int totalPages, int totalCount, int textColor) { + String pageText = (page + 1) + "/" + totalPages + " (" + totalCount + ")"; + fontRendererObj.drawString(StatCollector.translateToLocal("global.auction.manage.page") + ": " + pageText, + RIGHT_X + 48, ySize - 18, textColor); + } + + private void drawListingsDetails(int textColor) { + int panelLeft = DETAILS_PANEL_X + 6; + int panelRight = DETAILS_PANEL_X + DETAILS_PANEL_W - 6; + int y = LISTINGS_DETAILS_TITLE_Y; + + fontRendererObj.drawString(EnumChatFormatting.AQUA + StatCollector.translateToLocal("global.auction.manage.details"), panelLeft, y, 0xFFFFFF); + y += 12; + + if (selectedListing == null) { + fontRendererObj.drawString(EnumChatFormatting.GRAY + StatCollector.translateToLocal("global.auction.manage.selectListing"), panelLeft, y, 0xFFFFFF); + return; + } + + y = ContainerManageAuction.DETAIL_SLOT_Y + 1; + drawDetailsLine(panelLeft + 24, panelRight, y, EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller").replace("%s", ""), + EnumChatFormatting.WHITE + selectedListing.sellerName); + + y += 11; + long currentValue = selectedListing.hasBids() ? selectedListing.currentBid : selectedListing.startingPrice; + String currentLabel = selectedListing.hasBids() + ? StatCollector.translateToLocal("auction.info.currentBid") + : StatCollector.translateToLocal("auction.info.startingPrice"); + drawDetailsLine(panelLeft + 24, panelRight, y, EnumChatFormatting.YELLOW + currentLabel, + EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(currentValue)); + + y += 11; + if (selectedListing.hasBuyout()) { + drawDetailsLine(panelLeft + 24, panelRight, y, EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.info.buyoutPrice"), + EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(selectedListing.buyoutPrice)); + y += 11; + } + + drawDetailsLine(panelLeft + 24, panelRight, y, EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.info.bidCount"), + EnumChatFormatting.WHITE + Integer.toString(selectedListing.bidCount)); + y += 11; + + long remaining = selectedListing.getTimeRemaining(); + EnumChatFormatting timeColor = AuctionFormatUtil.isTimeUrgent(remaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE; + drawDetailsLine(panelLeft + 24, panelRight, y, EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.info.timeLeft"), + timeColor + AuctionFormatUtil.formatTimeRemaining(remaining)); + } + + private void drawDetailsLine(int leftX, int rightX, int y, String label, String value) { + fontRendererObj.drawString(label, leftX, y, 0xFFFFFF); + int width = fontRendererObj.getStringWidth(value); + fontRendererObj.drawString(value, rightX - width, y, 0xFFFFFF); + } + + private int getHoveredDisplaySlot(int mouseX, int mouseY) { + int relX = mouseX - ContainerManageAuction.DISPLAY_X; + int relY = mouseY - ContainerManageAuction.DISPLAY_Y; + if (relX < 0 || relY < 0) return -1; + + int col = relX / 18; + int row = relY / 18; + if (col < 0 || col >= ContainerManageAuction.DISPLAY_COLS || row < 0 || row >= ContainerManageAuction.DISPLAY_ROWS) return -1; + return col + row * ContainerManageAuction.DISPLAY_COLS; + } + + private void drawDynamicTooltip(int mouseX, int mouseY) { + if (hasSubGui()) return; + + // GuiContainer foreground receives absolute mouse coords; convert to GUI-local like auction GUIs. + int guiMouseX = mouseX - guiLeft; + int guiMouseY = mouseY - guiTop; + int hovered = getHoveredDisplaySlot(guiMouseX, guiMouseY); + + List tooltip = new ArrayList(); + + if (hovered >= 0) { + if (hovered == pendingDisplaySlot && pendingAction != PendingAction.NONE) { + if (pendingAction == PendingAction.STOP) { + tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("global.auction.manage.confirm.stop")); + } else if (pendingAction == PendingAction.CANCEL) { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("global.auction.manage.confirm.cancel")); + } else { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("global.auction.manage.confirm.claim")); + } + tooltip.add(EnumChatFormatting.DARK_GRAY + StatCollector.translateToLocal("auction.trades.otherClickCancel")); + } else if (activeTab == Tab.CLAIMS) { + AuctionClaim claim = manageContainer.getClaimAtDisplay(hovered); + if (claim != null && claim.item == null) { + if (claim.type == EnumClaimType.CURRENCY) { + tooltip.add(EnumChatFormatting.GREEN + "Sold Auction Claim"); + if (claim.itemName != null && !claim.itemName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.soldItem") + .replace("%s", EnumChatFormatting.WHITE + claim.itemName)); + } + if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.buyer") + .replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName)); + } + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency))); + } else if (claim.type == EnumClaimType.REFUND) { + tooltip.add(EnumChatFormatting.RED + "Outbid Refund Claim"); + if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy") + .replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName)); + } + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency))); + } else if (claim.type.isCurrency()) { + tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName()); + } + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim")); + } + } + } + + if (!tooltip.isEmpty()) { + drawHoveringText(tooltip, guiMouseX, guiMouseY, fontRendererObj); + } + } + + public ContainerManageAuction getManageContainer() { + return manageContainer; + } + + public Tab getActiveTab() { + return activeTab; + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcNaturalSpawns.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcNaturalSpawns.java index ecdec2990..9a0fa727d 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcNaturalSpawns.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcNaturalSpawns.java @@ -62,6 +62,12 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I this.addButton(new GuiNpcButton(1, guiLeft + 358, guiTop + 38, 58, 20, "gui.add")); this.addButton(new GuiNpcButton(2, guiLeft + 358, guiTop + 61, 58, 20, "gui.remove")); + getButton(1).setHoverText("tooltip.naturalspawns.main.addProfile"); + getButton(2).setHoverText("tooltip.naturalspawns.main.removeProfile"); + + if (getTextField(55) != null) { + getTextField(55).setHoverText("tooltip.naturalspawns.main.search"); + } if (this.spawn.id >= 0) showSpawn(); @@ -74,15 +80,18 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I int y = guiTop + 30; addLabel(new GuiNpcLabel(3, "spawning.biomes", guiLeft + 4, y)); addButton(new GuiNpcButton(3, guiLeft + 40, y - 5, 50, 20, "selectServer.edit")); + getButton(3).setHoverText("tooltip.naturalspawns.main.biomes"); addLabel(new GuiNpcLabel(11, StatCollector.translateToLocal("Dimensions"), guiLeft + 95, y)); addButton(new GuiNpcButton(11, guiLeft + 150, y - 5, 50, 20, "selectServer.edit")); + getButton(11).setHoverText("tooltip.naturalspawns.main.dimensions"); addLabel(new GuiNpcLabel(4, "spawning.options", guiLeft + 4, y += 22)); addButton(new GuiNpcButton(4, guiLeft + 90, y - 5, 50, 20, "selectServer.edit")); + getButton(4).setHoverText("tooltip.naturalspawns.main.options"); addSlider(new GuiNpcSlider(this, 5, guiLeft + 4, y += 17, 180, 20, (float) this.spawn.itemWeight / 100)); - addExtra(new GuiHoverText(1, "spawning.naturalInfo", guiLeft + 188, y + 5)); + addExtra(new GuiHoverText(1, "spawning.naturalInfoPerformance", guiLeft + 188, y + 5)); this.spawnEntryScroll.guiLeft = guiLeft + 4; this.spawnEntryScroll.guiTop = y + 40; @@ -96,13 +105,17 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I addScroll(this.spawnEntryScroll); addButton(new GuiNpcButton(21, guiLeft + 6, y += 20, 20, 20, "+")); + getButton(21).setHoverText("tooltip.naturalspawns.main.addEntry"); if (this.spawnEntryScroll.hasSelected()) { int selected = Integer.parseInt(this.spawnEntryScroll.getSelected()); addButton(new GuiNpcButton(22, guiLeft + 32, y, 20, 20, "-")); + getButton(22).setHoverText("tooltip.naturalspawns.main.removeEntry"); GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, "" + selected); num.integersOnly = true; addTextField(num); + getTextField(25).setHoverText("tooltip.naturalspawns.main.slot"); addButton(new GuiNpcButton(26, guiLeft + 92, y, 100, 20, this.getTitle(this.spawn.spawnCompounds.get(selected)))); + getButton(26).setHoverText("tooltip.naturalspawns.main.selectEntry"); } } diff --git a/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java index aa6d9c21a..cd5ddb2dd 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java @@ -81,10 +81,10 @@ public class CompassHudComponent extends HudComponent { ConfigClient.CompassEnabledProperty.set(ConfigClient.CompassEnabled); ConfigClient.CompassOverlayX = posX; - ConfigClient.CompassOverlayXProperty.set(ConfigClient.CompassOverlayX); + ConfigClient.CompassOverlayXProperty.set((double) ConfigClient.CompassOverlayX); ConfigClient.CompassOverlayY = posY; - ConfigClient.CompassOverlayYProperty.set(ConfigClient.CompassOverlayY); + ConfigClient.CompassOverlayYProperty.set((double) ConfigClient.CompassOverlayY); ConfigClient.CompassOverlayScale = scale; ConfigClient.CompassOverlayScaleProperty.set(ConfigClient.CompassOverlayScale); diff --git a/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java index fe6eb07b6..7eda9a335 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java @@ -2,5 +2,6 @@ package noppes.npcs.client.gui.hud; public enum EnumHudComponent { QuestTracker, - QuestCompass + QuestCompass, + AbilityHotbar } diff --git a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java index 5908cf9b8..5ffa2b50c 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java +++ b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java @@ -23,6 +23,7 @@ public class GuiHudEditor extends GuiScreen { private final int HANDLE_SIZE = 10; private final int RESET_POSITION_ID = 100; + private final int RESET_SIZE_ID = 104; // IDs for cycle buttons. private final int CYCLE_LEFT_ID = 101; @@ -90,9 +91,11 @@ public class GuiHudEditor extends GuiScreen { rowHeight += btn.height + spacingY; } } - // Always add the Reset Position button below the custom buttons. - GuiButton resetPos = new GuiButton(RESET_POSITION_ID, width / 2 - buttonWidth / 2, height - 70 - rowHeight, buttonWidth, 20, "Reset Position"); + // Always add the Reset Position and Reset Size buttons below the custom buttons. + GuiButton resetSize = new GuiButton(RESET_SIZE_ID, startXRight, height - 70 - rowHeight, buttonWidth, 20, "Reset Size"); + GuiButton resetPos = new GuiButton(RESET_POSITION_ID, startXLeft, height - 70 - rowHeight, buttonWidth, 20, "Reset Position"); buttonList.add(resetPos); + buttonList.add(resetSize); } // Now update (or add if missing) the cycle buttons at the very bottom. @@ -149,10 +152,11 @@ public class GuiHudEditor extends GuiScreen { int actualY = (int) (hud.posY / 100F * res.getScaledHeight()); int margin = 5; int barWidth = 6; // same as WIDTH_BAR_SIZE - int barX = actualX + (int) (hud.overlayWidth * effectiveScale) + margin; + int barX = actualX + (int) ((hud.overlayWidth + margin) * effectiveScale); int barY = actualY + (int) (((hud.overlayHeight - 20) / 2.0F) * effectiveScale); int barHeight = (int) (20 * effectiveScale); - if (mouseX >= barX && mouseX <= barX + barWidth && + int scaledBarWidth = Math.max(6, (int) (barWidth * effectiveScale)); + if (mouseX >= barX && mouseX <= barX + scaledBarWidth && mouseY >= barY && mouseY <= barY + barHeight) { resizingWidth = true; selectedComponent = hud; @@ -173,7 +177,8 @@ public class GuiHudEditor extends GuiScreen { int absHeight = (int) (hud.overlayHeight * effectiveScale); if (mouseX >= actualX && mouseX <= actualX + absWidth && mouseY >= actualY && mouseY <= actualY + absHeight) { - if (mouseX >= actualX + absWidth - HANDLE_SIZE && mouseY >= actualY + absHeight - HANDLE_SIZE) { + int scaledHandle = Math.max(8, (int) (HANDLE_SIZE * effectiveScale)); + if (mouseX >= actualX + absWidth - scaledHandle && mouseY >= actualY + absHeight - scaledHandle) { resizing = true; selectedComponent = hud; initialScale = hud.scale; @@ -214,24 +219,33 @@ public class GuiHudEditor extends GuiScreen { int newY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight) - dragOffsetY; if (newX < 0) newX = 0; if (newY < 0) newY = 0; - if (newX + (int) (selectedComponent.overlayWidth * effectiveScale) > scaledWidth) - newX = scaledWidth - (int) (selectedComponent.overlayWidth * effectiveScale); - if (newY + (int) (selectedComponent.overlayHeight * effectiveScale) > scaledHeight) - newY = scaledHeight - (int) (selectedComponent.overlayHeight * effectiveScale); - selectedComponent.posX = (int) (100F * newX / scaledWidth); - selectedComponent.posY = (int) (100F * newY / scaledHeight); + int compW = (int) Math.ceil(selectedComponent.overlayWidth * effectiveScale); + int compH = (int) Math.ceil(selectedComponent.overlayHeight * effectiveScale); + if (newX + compW > scaledWidth) + newX = scaledWidth - compW; + if (newY + compH > scaledHeight) + newY = scaledHeight - compH; + selectedComponent.posX = 100F * newX / scaledWidth; + selectedComponent.posY = 100F * newY / scaledHeight; } if (resizing) { int currentMouseX = Mouse.getX() * width / mc.displayWidth; - int deltaX = currentMouseX - initialMouseX; - selectedComponent.scale = initialScale + deltaX; + int currentMouseY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight); + int actualX = (int) (selectedComponent.posX / 100F * scaledWidth); + int actualY = (int) (selectedComponent.posY / 100F * scaledHeight); + // Use diagonal distance ratio so the resize handle tracks the mouse + float initDist = (float) Math.sqrt((double)(initialMouseX - actualX) * (initialMouseX - actualX) + (double)(initialMouseY - actualY) * (initialMouseY - actualY)); + float currDist = (float) Math.sqrt((double)(currentMouseX - actualX) * (currentMouseX - actualX) + (double)(currentMouseY - actualY) * (currentMouseY - actualY)); + if (initDist > 1) { + selectedComponent.scale = (int) (initialScale * currDist / initDist); + } if (selectedComponent.scale < 50) selectedComponent.scale = 50; - if (selectedComponent.scale > 300) selectedComponent.scale = 300; + if (selectedComponent.scale > 500) selectedComponent.scale = 500; } if (resizingWidth && (selectedComponent instanceof CompassHudComponent)) { int currentMouseX = Mouse.getX() * width / mc.displayWidth; int delta = currentMouseX - initialWidthMouseX; - selectedComponent.overlayWidth = initialOverlayWidth + delta; + selectedComponent.overlayWidth = initialOverlayWidth + (int) (delta / effectiveScale); if (selectedComponent.overlayWidth < 50) selectedComponent.overlayWidth = 50; if (selectedComponent.overlayWidth > 500) selectedComponent.overlayWidth = 500; } @@ -260,8 +274,13 @@ public class GuiHudEditor extends GuiScreen { } int centerX = (res.getScaledWidth() - compWidth) / 2; int centerY = (res.getScaledHeight() - compHeight) / 2; - selectedComponent.posX = (int) (100F * centerX / res.getScaledWidth()); - selectedComponent.posY = (int) (100F * centerY / res.getScaledHeight()); + selectedComponent.posX = 100F * centerX / res.getScaledWidth(); + selectedComponent.posY = 100F * centerY / res.getScaledHeight(); + updateCustomButtons(); + } + } else if (button.id == RESET_SIZE_ID) { + if (selectedComponent != null) { + selectedComponent.scale = 100; updateCustomButtons(); } } else if (button.id == CYCLE_LEFT_ID) { diff --git a/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java index 53a7a2170..bc153f890 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java @@ -8,7 +8,8 @@ import java.util.List; public abstract class HudComponent { // Stored as percentages (0-100) of the current screen resolution. - protected int posX = 50, posY = 50, scale = 100, textAlign = 0; + public float posX = 50, posY = 50; + protected int scale = 100, textAlign = 0; public boolean enabled = true; public boolean hasData = false; diff --git a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java index 8ed5ece3a..dc32caa16 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java @@ -39,6 +39,7 @@ public class QuestTrackingComponent extends HudComponent { if (turnIn != null && !turnIn.isEmpty()) { turnInLines.add(convertColorCodes(turnIn)); } + updateOverlayHeight(); } /** @@ -113,10 +114,10 @@ public class QuestTrackingComponent extends HudComponent { @Override public void save() { ConfigClient.QuestOverlayX = posX; - ConfigClient.QuestOverlayXProperty.set(ConfigClient.QuestOverlayX); + ConfigClient.QuestOverlayXProperty.set((double) ConfigClient.QuestOverlayX); ConfigClient.QuestOverlayY = posY; - ConfigClient.QuestOverlayYProperty.set(ConfigClient.QuestOverlayY); + ConfigClient.QuestOverlayYProperty.set((double) ConfigClient.QuestOverlayY); ConfigClient.QuestOverlayScale = scale; ConfigClient.QuestOverlayScaleProperty.set(ConfigClient.QuestOverlayScale); @@ -218,8 +219,8 @@ public class QuestTrackingComponent extends HudComponent { int compHeight = (int) (overlayHeight * effectiveScale); int centerX = (res.getScaledWidth() - compWidth) / 2; int centerY = (res.getScaledHeight() - compHeight) / 2; - posX = (int) (100F * centerX / res.getScaledWidth()); - posY = (int) (100F * centerY / res.getScaledHeight()); + posX = 100F * centerX / res.getScaledWidth(); + posY = 100F * centerY / res.getScaledHeight(); } else { super.onEditorButtonPressed(button); } @@ -239,6 +240,19 @@ public class QuestTrackingComponent extends HudComponent { } // ---------- Helper rendering methods ----------- (methods unchanged) ... + private void updateOverlayHeight() { + int lineHeight = mc.fontRenderer.FONT_HEIGHT + 4; + int contentHeight = 5; + contentHeight += questTitleLines.size() * lineHeight + 8; + contentHeight += questCategoryLines.size() * lineHeight + 8; + contentHeight += objectiveLines.size() * lineHeight; + if (!turnInLines.isEmpty()) { + contentHeight += 8; + } + contentHeight += turnInLines.size() * lineHeight; + overlayHeight = contentHeight; + } + private int renderTextBlock(List lines, int startY, int align, int color) { int y = startY; FontRenderer font = mc.fontRenderer; diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java new file mode 100644 index 000000000..974224960 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java @@ -0,0 +1,716 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.client.ClientAbilityState; +import noppes.npcs.client.KeyPressHandler; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.hud.HudComponent; +import noppes.npcs.config.ConfigClient; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerAbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +@SideOnly(Side.CLIENT) +public class AbilityHotbarComponent extends HudComponent { + public static final int TOTAL_SLOTS = AbilityHotbarData.TOTAL_SLOTS; + + private static final int BASE_SLOT_SIZE = 24; + private static final int BASE_SPACING = 28; + private static final int EDIT_HANDLE_SIZE = 10; + + private AbilityHotbarSlotRenderer[] slots = new AbilityHotbarSlotRenderer[TOTAL_SLOTS]; + + // Filtered carousel: only filled slots + one deselect entry + // Each entry is a raw slot index (0-11), or -1 for the deselect slot + private int[] activeIndices = new int[0]; + private int activeCenter = 0; + + private float scrollOffset = 0f; + private long scrollStartTime = 0; + private static final long SCROLL_DURATION = 150; + + private long lastUpdateTime = 0; + private static final long UPDATE_INTERVAL = 500; + + // Debounce: delay sending selection packet + private String pendingSelectKey = null; + private long pendingSelectTime = 0; + private static final long SELECT_DEBOUNCE = 300; + + // Grace period: don't let server state override local state after user interaction + private long lastUserCycleTime = 0; + private static final long USER_CYCLE_GRACE = 1000; + + // Fade: when ShowAlways=false, fade in/out when HUD key is held + private float fadeAlpha = 0f; + private long lastFadeTime = 0; + private static final float FADE_SPEED = 3f; // per second — ~333ms full transition + + private Minecraft mc; + + public AbilityHotbarComponent(Minecraft mc) { + this.mc = mc; + updateOverlayDimensions(); + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i] = new AbilityHotbarSlotRenderer(i); + } + load(); + } + + private int getEffectiveVisibleSlots() { + int configMax = ConfigClient.AbilityHotbarVisibleSlots; + if (configMax != 3 && configMax != 5 && configMax != 7) configMax = 5; + int filledCount = activeIndices.length - 1; // subtract deselect slot + if (filledCount < 0) filledCount = 0; + if (filledCount < 5) return Math.min(configMax, 3); + if (filledCount < 7) return Math.min(configMax, 5); + return configMax; + } + + private void updateOverlayDimensions() { + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + int visibleSlots = getEffectiveVisibleSlots(); + int span = BASE_SPACING * (visibleSlots - 1) + BASE_SLOT_SIZE; + int thick = BASE_SLOT_SIZE + 4; + if (isHorizontal) { + overlayWidth = span; + overlayHeight = thick; + } else { + overlayWidth = thick; + overlayHeight = span; + } + } + + @Override + public void loadData(NBTTagCompound compound) { + } + + @Override + public void load() { + posX = ConfigClient.AbilityHotbarX; + posY = ConfigClient.AbilityHotbarY; + scale = ConfigClient.AbilityHotbarScale; + enabled = ConfigClient.AbilityHotbarEnabled; + } + + @Override + public void save() { + ConfigClient.AbilityHotbarX = posX; + ConfigClient.AbilityHotbarXProperty.set((double) posX); + + ConfigClient.AbilityHotbarY = posY; + ConfigClient.AbilityHotbarYProperty.set((double) posY); + + ConfigClient.AbilityHotbarScale = scale; + ConfigClient.AbilityHotbarScaleProperty.set(scale); + + ConfigClient.AbilityHotbarEnabled = enabled; + ConfigClient.AbilityHotbarEnabledProperty.set(enabled); + + ConfigClient.AbilityHotbarHorizontalProperty.set(ConfigClient.AbilityHotbarHorizontal); + ConfigClient.AbilityHotbarAltTextureProperty.set(ConfigClient.AbilityHotbarAltTexture); + ConfigClient.AbilityHotbarTextPositionProperty.set(ConfigClient.AbilityHotbarTextPosition); + ConfigClient.AbilityHotbarVisibleSlotsProperty.set(ConfigClient.AbilityHotbarVisibleSlots); + ConfigClient.AbilityHotbarShowAlwaysProperty.set(ConfigClient.AbilityHotbarShowAlways); + ConfigClient.AbilityHotbarTextVisibilityProperty.set(ConfigClient.AbilityHotbarTextVisibility); + + if (ConfigClient.config.hasChanged()) { + ConfigClient.config.save(); + } + } + + @Override + public void renderOnScreen(float partialTicks) { + if (!enabled || isEditting) return; + if (mc.thePlayer == null || mc.currentScreen != null) return; + if (!hasAnyAbilities()) return; + + // Fade logic: when ShowAlways=false, only show while HUD key is held + boolean showAlways = ConfigClient.AbilityHotbarShowAlways; + long now = Minecraft.getSystemTime(); + if (!showAlways) { + boolean hudKeyHeld = isHudKeyHeld(); + float dt = lastFadeTime > 0 ? (now - lastFadeTime) / 1000f : 0f; + dt = Math.min(dt, 0.1f); // cap to avoid jumps after pauses + lastFadeTime = now; + if (hudKeyHeld || pendingSelectKey != null || scrollOffset != 0f) { + fadeAlpha = Math.min(1f, fadeAlpha + FADE_SPEED * dt); + } else { + fadeAlpha = Math.max(0f, fadeAlpha - FADE_SPEED * dt); + } + if (fadeAlpha <= 0f) return; + } else { + fadeAlpha = 1f; + lastFadeTime = now; + } + + long currentTime = Minecraft.getSystemTime(); + if (currentTime - lastUpdateTime > UPDATE_INTERVAL) { + updateAbilities(); + lastUpdateTime = currentTime; + } + + // Flush debounced selection packet + if (pendingSelectKey != null && currentTime - pendingSelectTime >= SELECT_DEBOUNCE) { + PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(pendingSelectKey)); + pendingSelectKey = null; + } + + updateScrollAnimation(); + updateOverlayDimensions(); + + if (activeIndices.length == 0) return; + + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + float effectiveScale = getEffectiveScale(sr); + int visibleSlots = getEffectiveVisibleSlots(); + int half = visibleSlots / 2; + + int actualX = (int) (posX / 100.0f * sr.getScaledWidth()); + int actualY = (int) (posY / 100.0f * sr.getScaledHeight()); + + GL11.glPushMatrix(); + GL11.glTranslatef(actualX, actualY, 0); + GL11.glScalef(effectiveScale, effectiveScale, 1); + + int centerX = overlayWidth / 2; + int centerY = overlayHeight / 2; + boolean activePhase = ClientAbilityState.activePhase; + + // Compute text visibility: 0=Shown, 1=Hidden, 2=Held + boolean showText; + int textVis = ConfigClient.AbilityHotbarTextVisibility; + if (textVis == 1) { + showText = false; + } else if (textVis == 2) { + showText = isHudKeyHeld(); + } else { + showText = true; + } + + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i].updateNameFade(); + } + + for (int offset = -half; offset <= half; offset++) { + int activeIdx = ((activeCenter + offset) % activeIndices.length + activeIndices.length) % activeIndices.length; + int rawSlotIndex = activeIndices[activeIdx]; + + float visualPos = offset + scrollOffset; + float absDist = Math.abs(visualPos); + + float slotScale; + if (absDist <= 1f) { + slotScale = 1.0f - 0.25f * absDist; + } else { + slotScale = 0.75f - 0.15f * (absDist - 1f); + } + slotScale = Math.max(0.1f, slotScale); + + int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale)); + + int cx, cy; + if (isHorizontal) { + cx = centerX + (int) (visualPos * BASE_SPACING); + cy = centerY; + } else { + cx = centerX; + cy = centerY + (int) (visualPos * BASE_SPACING); + } + + float maxDist = half + 0.5f; + if (absDist > maxDist) continue; + + float edgeAlpha = absDist > half - 0.5f ? 1f - (absDist - (half - 0.5f)) : 1f; + float slotAlpha = edgeAlpha * fadeAlpha; + boolean isCenter = (offset == 0 && scrollOffset == 0f); + + // Compute per-slot cooldown progress (all slots, not just center) + float slotCooldown = 0f; + if (rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null) { + slotCooldown = getCooldownProgressForSlot(rawSlotIndex); + } + + if (rawSlotIndex == -1) { + // Deselect slot — draw empty marker + drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha, activePhase); + } else { + slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText, activePhase); + } + } + + GL11.glPopMatrix(); + } + + private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha, boolean activePhase) { + float radius = size / 2f; + float baseAlpha = isCenter ? 0.9f : 0.6f; + float a = baseAlpha * alpha; + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + GL11.glPushMatrix(); + GL11.glTranslatef(cx, cy, 0); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + if (activePhase) { + if (isCenter) { + GL11.glColor4f(0.65f, 0.14f, 0.14f, a); + } else { + GL11.glColor4f(0.38f, 0.10f, 0.10f, a); + } + } else if (isCenter) { + GL11.glColor4f(0.5f, 0.2f, 0.2f, a); + } else { + GL11.glColor4f(0.3f, 0.3f, 0.3f, a); + } + + if (altTexture) { + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(-radius, -radius); + GL11.glVertex2f(radius, -radius); + GL11.glVertex2f(radius, radius); + GL11.glVertex2f(-radius, radius); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + for (int i = 0; i <= 32; i++) { + double angle = 2 * Math.PI * i / 32; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + + // Draw X mark + if (activePhase) { + if (isCenter) { + GL11.glColor4f(1.0f, 0.45f, 0.35f, alpha); + } else { + GL11.glColor4f(0.75f, 0.30f, 0.30f, alpha * 0.8f); + } + } else if (isCenter) { + GL11.glColor4f(0.8f, 0.4f, 0.4f, alpha); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, alpha * 0.8f); + } + float xSize = radius * 0.4f; + GL11.glLineWidth(2.0f); + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(-xSize, -xSize); + GL11.glVertex2f(xSize, xSize); + GL11.glVertex2f(-xSize, xSize); + GL11.glVertex2f(xSize, -xSize); + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + + @Override + public void renderEditing() { + isEditting = true; + updateOverlayDimensions(); + + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + float effectiveScale = getEffectiveScale(sr); + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + FontRenderer fr = mc.fontRenderer; + int visibleSlots = getEffectiveVisibleSlots(); + int half = visibleSlots / 2; + + int actualX = (int) (posX / 100.0f * sr.getScaledWidth()); + int actualY = (int) (posY / 100.0f * sr.getScaledHeight()); + + GL11.glPushMatrix(); + GL11.glTranslatef(actualX, actualY, 0); + GL11.glScalef(effectiveScale, effectiveScale, 1); + + int centerX = overlayWidth / 2; + int centerY = overlayHeight / 2; + + int[] slotCx = new int[visibleSlots]; + int[] slotCy = new int[visibleSlots]; + int[] slotSizes = new int[visibleSlots]; + + for (int offset = -half; offset <= half; offset++) { + float absDist = Math.abs(offset); + float slotScale; + if (absDist <= 1f) { + slotScale = 1.0f - 0.25f * absDist; + } else { + slotScale = 0.75f - 0.15f * (absDist - 1f); + } + slotScale = Math.max(0.1f, slotScale); + int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale)); + + int cx, cy; + if (isHorizontal) { + cx = centerX + offset * BASE_SPACING; + cy = centerY; + } else { + cx = centerX; + cy = centerY + offset * BASE_SPACING; + } + + int idx = offset + half; + slotCx[idx] = cx; + slotCy[idx] = cy; + slotSizes[idx] = scaledSize; + + float radius = scaledSize / 2f; + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + float alpha = offset == 0 ? 0.9f : 0.6f; + if (offset == 0) { + GL11.glColor4f(0.8f, 0.8f, 0.2f, alpha); + } else { + GL11.glColor4f(0.4f, 0.4f, 0.4f, alpha); + } + + if (altTexture) { + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(cx - radius, cy - radius); + GL11.glVertex2f(cx + radius, cy - radius); + GL11.glVertex2f(cx + radius, cy + radius); + GL11.glVertex2f(cx - radius, cy + radius); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(cx, cy); + for (int i = 0; i <= 32; i++) { + double angle = 2 * Math.PI * i / 32; + GL11.glVertex2f(cx + (float) (Math.cos(angle) * radius), cy + (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + } + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + for (int i = 0; i < visibleSlots; i++) { + String label = String.valueOf(i + 1); + float labelScale = slotSizes[i] / 24.0f; + if (labelScale < 0.4f) continue; + + int textColor = (i == half) ? 0xFFFFFFFF : 0xAABBBBBB; + int textW = fr.getStringWidth(label); + + GL11.glPushMatrix(); + GL11.glTranslatef(slotCx[i], slotCy[i], 0); + GL11.glScalef(labelScale, labelScale, 1); + fr.drawString(label, -textW / 2, -fr.FONT_HEIGHT / 2, textColor); + GL11.glPopMatrix(); + } + + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + String modeLabel = altTexture ? "Square" : "Circle"; + int modeLabelW = fr.getStringWidth(modeLabel); + fr.drawStringWithShadow(modeLabel, overlayWidth / 2 - modeLabelW / 2, overlayHeight + 2, 0xAA888888); + + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + net.minecraft.client.gui.Gui.drawRect(0, 0, overlayWidth, overlayHeight, 0x22000000); + drawRectOutline(0, 0, overlayWidth, overlayHeight, 0xCC66CC66); + + int handleLeft = overlayWidth - EDIT_HANDLE_SIZE; + int handleTop = overlayHeight - EDIT_HANDLE_SIZE; + net.minecraft.client.gui.Gui.drawRect(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFFE0E0E0); + drawRectOutline(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFF5A5A5A); + net.minecraft.client.gui.Gui.drawRect(handleLeft + 2, handleTop + 7, handleLeft + 8, handleTop + 8, 0xAA666666); + net.minecraft.client.gui.Gui.drawRect(handleLeft + 4, handleTop + 5, handleLeft + 8, handleTop + 6, 0xAA666666); + net.minecraft.client.gui.Gui.drawRect(handleLeft + 6, handleTop + 3, handleLeft + 8, handleTop + 4, 0xAA666666); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + GL11.glPopMatrix(); + } + + @Override + public void addEditorButtons(List buttonList) { + super.addEditorButtons(buttonList); + String orientLabel = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical"; + buttonList.add(new GuiButton(1, 0, 0, 120, 20, orientLabel)); + + String texLabel = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; + buttonList.add(new GuiButton(2, 0, 0, 120, 20, texLabel)); + + buttonList.add(new GuiButton(3, 0, 0, 120, 20, getTextPositionLabel())); + buttonList.add(new GuiButton(4, 0, 0, 120, 20, "Slots: " + ConfigClient.AbilityHotbarVisibleSlots)); + buttonList.add(new GuiButton(5, 0, 0, 120, 20, ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key")); + buttonList.add(new GuiButton(6, 0, 0, 120, 20, getTextVisibilityLabel())); + } + + @Override + public void onEditorButtonPressed(GuiButton button) { + if (button.id == 1) { + ConfigClient.AbilityHotbarHorizontal = !ConfigClient.AbilityHotbarHorizontal; + button.displayString = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical"; + updateOverlayDimensions(); + } else if (button.id == 2) { + ConfigClient.AbilityHotbarAltTexture = !ConfigClient.AbilityHotbarAltTexture; + button.displayString = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; + } else if (button.id == 3) { + // Toggle between 1 (Above/Left) and 2 (Below/Right) + ConfigClient.AbilityHotbarTextPosition = ConfigClient.AbilityHotbarTextPosition == 1 ? 2 : 1; + button.displayString = getTextPositionLabel(); + } else if (button.id == 4) { + int current = ConfigClient.AbilityHotbarVisibleSlots; + if (current <= 3) ConfigClient.AbilityHotbarVisibleSlots = 5; + else if (current <= 5) ConfigClient.AbilityHotbarVisibleSlots = 7; + else ConfigClient.AbilityHotbarVisibleSlots = 3; + button.displayString = "Slots: " + ConfigClient.AbilityHotbarVisibleSlots; + updateOverlayDimensions(); + } else if (button.id == 5) { + ConfigClient.AbilityHotbarShowAlways = !ConfigClient.AbilityHotbarShowAlways; + button.displayString = ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key"; + } else if (button.id == 6) { + ConfigClient.AbilityHotbarTextVisibility = (ConfigClient.AbilityHotbarTextVisibility + 1) % 3; + button.displayString = getTextVisibilityLabel(); + } else { + super.onEditorButtonPressed(button); + } + } + + private String getTextPositionLabel() { + boolean h = ConfigClient.AbilityHotbarHorizontal; + switch (ConfigClient.AbilityHotbarTextPosition) { + case 1: return h ? "Text: Above" : "Text: Left"; + case 2: return h ? "Text: Below" : "Text: Right"; + default: return h ? "Text: Below" : "Text: Right"; + } + } + + private String getTextVisibilityLabel() { + switch (ConfigClient.AbilityHotbarTextVisibility) { + case 0: return "Text: Shown"; + case 1: return "Text: Hidden"; + case 2: return "Text: Held"; + default: return "Text: Shown"; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Ability Update & Scroll + // ═══════════════════════════════════════════════════════════════════ + + private void updateAbilities() { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null) return; + + PlayerAbilityHotbarData hotbarData = playerData.hotbarData; + if (hotbarData == null) return; + + EntityPlayer clientPlayer = Minecraft.getMinecraft().thePlayer; + boolean globalBlock = clientPlayer != null && AbilityController.Instance != null + && !AbilityController.Instance.canPlayerActivate(clientPlayer); + + for (int i = 0; i < TOTAL_SLOTS; i++) { + AbilityHotbarData slotData = hotbarData.slots[i]; + String key = slotData.isEmpty() ? null : slotData.abilityKey; + Ability ability = null; + IAbilityAction action = null; + if (key != null && AbilityController.Instance != null) { + if (globalBlock) { + key = null; + } else { + if (slotData.isChainKey()) { + action = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + } else { + ability = AbilityController.Instance.resolveAbility(key); + action = ability; + } + if (ability == null && action == null) key = null; + + // Hide abilities whose player requirement is not met + if (action != null && clientPlayer != null && !action.isAvailableFor(clientPlayer)) { + key = null; + ability = null; + action = null; + } + } + } + slots[i].setAbility(key, ability, action); + } + + // Rebuild active indices: filled slots + one deselect slot (-1) + ArrayList active = new ArrayList<>(); + for (int i = 0; i < TOTAL_SLOTS; i++) { + if (slots[i].abilityKey != null) { + active.add(i); + } + } + active.add(-1); // Deselect slot at the end + activeIndices = new int[active.size()]; + for (int i = 0; i < active.size(); i++) { + activeIndices[i] = active.get(i); + } + + // Clamp activeCenter + if (activeCenter >= activeIndices.length) { + activeCenter = 0; + } + + // Don't override local selection state while user is scrolling, debounce is pending, + // or within the grace period after the last user interaction. + // This prevents the server state from fighting the local carousel position. + long now = Minecraft.getSystemTime(); + if (pendingSelectKey != null || scrollOffset != 0f || (now - lastUserCycleTime < USER_CYCLE_GRACE)) { + return; + } + + // Sync selected state and find which active index is selected + if (playerData.abilityData != null) { + String selectedKey = playerData.abilityData.getSelectedAbilityKey(); + boolean foundSelected = false; + for (int i = 0; i < TOTAL_SLOTS; i++) { + AbilityHotbarData slotData = hotbarData.slots[i]; + boolean sel = selectedKey != null && !slotData.isEmpty() + && selectedKey.equals(slotData.abilityKey); + slots[i].setSelectedState(sel); + if (sel) { + // Find this slot's position in activeIndices + for (int j = 0; j < activeIndices.length; j++) { + if (activeIndices[j] == i) { + activeCenter = j; + foundSelected = true; + break; + } + } + } + } + if (!foundSelected) { + // No ability selected on server — center on deselect slot + for (int j = 0; j < activeIndices.length; j++) { + if (activeIndices[j] == -1) { + activeCenter = j; + break; + } + } + } + } + } + + private boolean isHudKeyHeld() { + return KeyPressHandler.isHudKeyHeld(); + } + + public boolean hasAnyAbilities() { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.hotbarData == null) return false; + return playerData.hotbarData.hasAnyAbilities(); + } + + /** + * Get cooldown progress for a hotbar slot. + * Per-ability cooldown abilities use their own cooldown; others use global. + * @return 1.0 = fully on cooldown, 0.0 = ready + */ + private float getCooldownProgressForSlot(int slotIndex) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) return 0f; + + String key = slots[slotIndex].abilityKey; + Ability ability = slots[slotIndex].ability; + IAbilityAction action = slots[slotIndex].action; + + if (ability != null && ability.isPerAbilityCooldown()) { + return playerData.abilityData.getPerAbilityCooldownProgress(key); + } else if (action instanceof ChainedAbility && ((ChainedAbility) action).isPerAbilityCooldown()) { + return playerData.abilityData.getPerAbilityCooldownProgress(key); + } else { + return playerData.abilityData.getGlobalCooldownProgress(); + } + } + + public void onCycleNext() { + cycle(1); + } + + public void onCyclePrev() { + cycle(-1); + } + + private void cycle(int direction) { + if (!enabled) return; + if (mc.thePlayer == null || mc.currentScreen != null) return; + if (activeIndices.length == 0) return; + + activeCenter = ((activeCenter + direction) % activeIndices.length + activeIndices.length) % activeIndices.length; + scrollOffset = direction; + long now = Minecraft.getSystemTime(); + scrollStartTime = now; + lastUserCycleTime = now; + + int rawSlotIndex = activeIndices[activeCenter]; + + // Update selection states locally + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i].setSelectedState(i == rawSlotIndex); + } + + // Debounce: queue the selection, don't send immediately + String keyToSend = rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null + ? slots[rawSlotIndex].abilityKey : ""; + pendingSelectKey = keyToSend; + pendingSelectTime = Minecraft.getSystemTime(); + } + + private void updateScrollAnimation() { + if (scrollOffset == 0f) return; + + long now = Minecraft.getSystemTime(); + float t = (float) (now - scrollStartTime) / SCROLL_DURATION; + t = Math.min(t, 1f); + + float eased = easeOutCubic(t); + float initialOffset = scrollOffset < 0 ? -1f : 1f; + scrollOffset = initialOffset * (1f - eased); + + if (t >= 1f) scrollOffset = 0f; + } + + private float easeOutCubic(float x) { + float v = 1 - x; + return 1 - v * v * v; + } + + public void refresh() { + updateAbilities(); + lastUpdateTime = Minecraft.getSystemTime(); + } + + private void drawRectOutline(int left, int top, int right, int bottom, int color) { + net.minecraft.client.gui.Gui.drawRect(left, top, right, top + 1, color); + net.minecraft.client.gui.Gui.drawRect(left, bottom - 1, right, bottom, color); + net.minecraft.client.gui.Gui.drawRect(left, top, left + 1, bottom, color); + net.minecraft.client.gui.Gui.drawRect(right - 1, top, right, bottom, color); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java new file mode 100644 index 000000000..6f267d0e2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java @@ -0,0 +1,345 @@ +package noppes.npcs.client.gui.hud.ability; + +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.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import noppes.npcs.config.ConfigClient; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.opengl.GL11; + +@SideOnly(Side.CLIENT) +public class AbilityHotbarSlotRenderer extends Gui { + private static final int CIRCLE_SEGMENTS = 32; + private static final long NAME_FADE_DURATION = 180; + + public int index; + public String abilityKey = null; + public Ability ability = null; + public IAbilityAction action = null; + private AbilityIcon icon = null; + + public boolean isSelected = false; + public float nameAlpha = 0f; + private boolean nameFadingIn = false; + private long nameFadeStartTime = 0; + + public AbilityHotbarSlotRenderer(int index) { + this.index = index; + } + + public void setAbility(String key, Ability ability, IAbilityAction action) { + this.abilityKey = key; + this.ability = ability; + this.action = action; + if (ability != null) { + this.icon = AbilityIcon.fromAbility(ability); + } else if (action instanceof ChainedAbility) { + this.icon = AbilityIcon.fromChainedAbility((ChainedAbility) action); + } else { + this.icon = null; + } + } + + public void drawCarousel(Minecraft mc, ScaledResolution sr, float cooldownProgress, + int cx, int cy, int size, boolean isCenter, float slotAlpha, + boolean showText, boolean activePhase) { + float nameAlpha = this.nameAlpha; + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + if (size <= 0 || slotAlpha <= 0) return; + float radius = size / 2f; + float baseAlpha = isCenter ? 0.9f : 0.6f; + float alpha = baseAlpha * slotAlpha; + + GL11.glPushMatrix(); + GL11.glTranslatef(cx, cy, 0); + + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + float fillR; + float fillG; + float fillB; + float outlineR; + float outlineG; + float outlineB; + + if (activePhase) { + if (isCenter) { + fillR = 0.95f; + fillG = 0.26f; + fillB = 0.22f; + outlineR = 1.0f; + outlineG = 0.52f; + outlineB = 0.28f; + } else { + fillR = 0.36f; + fillG = 0.14f; + fillB = 0.14f; + outlineR = 0.65f; + outlineG = 0.22f; + outlineB = 0.20f; + } + } else if (isCenter) { + fillR = 0.8f; + fillG = 0.8f; + fillB = 0.2f; + outlineR = 0.8f; + outlineG = 0.8f; + outlineB = 0.2f; + } else { + fillR = 0.4f; + fillG = 0.4f; + fillB = 0.4f; + outlineR = 1f; + outlineG = 1f; + outlineB = 1f; + } + + if (altTexture) { + float baseR = activePhase ? 0.30f : 0.6f; + float baseG = activePhase ? 0.12f : 0.6f; + float baseB = activePhase ? 0.12f : 0.6f; + drawRoundedRect(-radius, -radius, radius, radius, baseR, baseG, baseB, 0.75f * alpha, false); + drawRoundedRect(-radius, -radius, radius, radius, fillR, fillG, fillB, alpha * 0.8f, true); + } else { + drawCircle(radius, outlineR, outlineG, outlineB, 0.66f * alpha, false); + drawCircle(radius, fillR, fillG, fillB, alpha * 0.8f, true); + } + + // Toggle active indicator: subtle green outline + int toggleState = getToggleState(); + if (toggleState > 0) { + float glowAlpha = 0.45f * slotAlpha; + if (altTexture) { + drawRoundedRect(-radius, -radius, radius, radius, 0.2f, 0.85f, 0.3f, glowAlpha, true); + } else { + drawCircle(radius, 0.2f, 0.85f, 0.3f, glowAlpha, true); + } + } + + // Ability icon + if (icon != null) { + GL11.glPushMatrix(); + float targetSize = size * 0.55f; + float iconNaturalSize = Math.max(icon.width, icon.height); + if (iconNaturalSize <= 0) iconNaturalSize = 16f; + float iconScale = targetSize / iconNaturalSize; + GL11.glScalef(iconScale, iconScale, 1); + icon.draw(toggleState, slotAlpha); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + + // Cooldown overlay (all slots) + if (cooldownProgress > 0 && abilityKey != null) { + drawCooldownOverlay(radius, cooldownProgress, altTexture, slotAlpha); + } + + GL11.glPopMatrix(); + + // Ability name on center slot (respects text position and visibility config) + int textPos = ConfigClient.AbilityHotbarTextPosition; + if (showText && isCenter && action != null && nameAlpha > 0) { + FontRenderer fr = mc.fontRenderer; + String name = getAbilityName(); + if (name != null && !name.isEmpty()) { + int a = (int) (nameAlpha * 255) & 0xFF; + int nameColor = (a << 24) | (getNameColor() & 0x00FFFFFF); + int nameX, nameY; + if (isHorizontal) { + nameX = cx - fr.getStringWidth(name) / 2; + if (textPos == 1) { + nameY = cy - (int) radius - fr.FONT_HEIGHT - 2; // Above + } else { + nameY = cy + (int) radius + 2; // Below + } + } else { + nameY = cy - fr.FONT_HEIGHT / 2; + if (textPos == 1) { + nameX = cx - (int) radius - fr.getStringWidth(name) - 4; // Left + } else { + nameX = cx + (int) radius + 4; // Right + } + } + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, nameAlpha); + fr.drawStringWithShadow(name, nameX, nameY, nameColor); + GL11.glDisable(GL11.GL_BLEND); + GL11.glColor4f(1, 1, 1, 1); + } + } + } + + private void drawRoundedRect(float x1, float y1, float x2, float y2, + float r, float g, float b, float a, boolean outline) { + 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.glColor4f(r, g, b, a); + + if (outline) { + GL11.glLineWidth(2.0f); + GL11.glBegin(GL11.GL_LINE_LOOP); + } else { + GL11.glBegin(GL11.GL_QUADS); + } + + GL11.glVertex2f(x1, y1); + GL11.glVertex2f(x2, y1); + GL11.glVertex2f(x2, y2); + GL11.glVertex2f(x1, y2); + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawCircle(float radius, float r, float g, float b, float a, boolean outline) { + 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.glColor4f(r, g, b, a); + + if (outline) { + GL11.glLineWidth(1.5f); + GL11.glBegin(GL11.GL_LINE_LOOP); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + } + + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + /** + * Draw a cooldown overlay on the slot. + * progress: 1.0 = fully on cooldown (just started), 0.0 = ready + * Renders a filled shape covering the entire slot that transitions from red to green. + */ + private void drawCooldownOverlay(float radius, float progress, boolean altTexture, float slotAlpha) { + progress = Math.min(1f, Math.max(0f, progress)); + if (progress <= 0f) return; + + // Color: red (progress=1.0) → orange → yellow-green → green (progress→0.0) + float cr, cg, cb; + if (progress > 0.5f) { + float t = (progress - 0.5f) * 2f; // 1.0 at progress=1.0, 0.0 at progress=0.5 + cr = 0.8f; + cg = 0.15f + 0.25f * (1f - t); // 0.15 → 0.4 + cb = 0.1f; + } else if (progress > 0.2f) { + float t = (progress - 0.2f) / 0.3f; // 1.0 at 0.5, 0.0 at 0.2 + cr = 0.8f * t + 0.3f * (1f - t); // 0.8 → 0.3 + cg = 0.4f * t + 0.7f * (1f - t); // 0.4 → 0.7 + cb = 0.1f; + } else { + float t = progress / 0.2f; // 1.0 at 0.2, 0.0 at 0.0 + cr = 0.3f * t + 0.1f * (1f - t); // 0.3 → 0.1 + cg = 0.7f * t + 0.7f * (1f - t); // 0.7 + cb = 0.1f + 0.1f * (1f - t); // 0.1 → 0.2 + } + + // Semi-transparent so icon is visible underneath; fade out near end + float overlayAlpha = 0.5f * slotAlpha * Math.min(1f, progress * 3f); + + 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.glColor4f(cr, cg, cb, overlayAlpha); + + if (altTexture) { + // Square slot: full filled rectangle + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(-radius, -radius); + GL11.glVertex2f(radius, -radius); + GL11.glVertex2f(radius, radius); + GL11.glVertex2f(-radius, radius); + GL11.glEnd(); + } else { + // Circle slot: full filled circle + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + private String getAbilityName() { + if (ability != null) { + int state = getToggleState(); + if (state > 0) { + String label = ability.getToggleStateLabel(state); + if (label != null) return label; + } + return ability.getDisplayName(); + } + if (action instanceof ChainedAbility) return ((ChainedAbility) action).getDisplayName(); + return action != null ? action.getName() : ""; + } + + private int getToggleState() { + if (ability == null || !ability.isToggleable()) return 0; + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer == null) return 0; + PlayerData playerData = PlayerData.get(mc.thePlayer); + if (playerData == null || playerData.abilityData == null) return 0; + return playerData.abilityData.getToggleState(abilityKey); + } + + private int getNameColor() { + if (ability != null && ability.isToggleable()) { + return getToggleState() > 0 ? 0xFF55FF55 : 0xFFFF5555; + } + return 0xFFFFFFFF; + } + + public void setSelectedState(boolean newSelectState) { + if (!isSelected && newSelectState) { + nameFadingIn = true; + nameFadeStartTime = Minecraft.getSystemTime(); + } + if (isSelected && !newSelectState) { + nameFadingIn = false; + nameFadeStartTime = Minecraft.getSystemTime(); + } + isSelected = newSelectState; + } + + public void updateNameFade() { + long now = Minecraft.getSystemTime(); + float t = (float) (now - nameFadeStartTime) / NAME_FADE_DURATION; + t = Math.min(1f, Math.max(0f, t)); + if (nameFadingIn) { + nameAlpha = t; + } else { + nameAlpha = 1f - t; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java new file mode 100644 index 000000000..2ed5f1512 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java @@ -0,0 +1,214 @@ +package noppes.npcs.client.gui.hud.ability; + +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.data.AbilityIconData; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.AnimationHelper; +import noppes.npcs.client.renderer.ImageData; +import org.lwjgl.opengl.GL11; + +@SideOnly(Side.CLIENT) +public class AbilityIcon extends Gui { + private static final ResourceLocation FALLBACK_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/ability_fallback.png"); + + // Backed by AbilityIconData + private final AbilityIconData data; + public int width; + public int height; + + // Default icon layers (extracted from ability) + private Ability.DefaultIconLayer[] defaultLayers = null; + private int defaultIconWidth = 48; + private int defaultIconHeight = 48; + + private AbilityIcon(AbilityIconData data) { + this.data = data; + this.width = data.width; + this.height = data.height; + } + + public static AbilityIcon fromAbility(Ability ability) { + if (ability != null) { + AbilityIcon icon = new AbilityIcon(AbilityIconData.fromAbility(ability)); + icon.defaultLayers = ability.getDefaultIconLayers(); + icon.defaultIconWidth = ability.getDefaultIconWidth(); + icon.defaultIconHeight = ability.getDefaultIconHeight(); + return icon; + } + return fromDefaults(); + } + + public static AbilityIcon fromChainedAbility(ChainedAbility chain) { + if (chain != null) { + return new AbilityIcon(AbilityIconData.fromChainedAbility(chain)); + } + return fromDefaults(); + } + + public static AbilityIcon fromAction(IAbilityAction action) { + if (action instanceof Ability) return fromAbility((Ability) action); + if (action instanceof ChainedAbility) return fromChainedAbility((ChainedAbility) action); + return fromDefaults(); + } + + private static AbilityIcon fromDefaults() { + return new AbilityIcon(AbilityIconData.fromCustomData(new NBTTagCompound())); + } + + public void draw() { + draw(0); + } + + public void draw(int state) { + draw(state, 1.0f); + } + + public void draw(int state, float alpha) { + TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; + + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + if (data.isEnabled()) { + // Path 1: Custom icon — draw each active layer bottom-to-top + GL11.glScalef(data.scale, data.scale, 1); + boolean drewAny = false; + for (int i = 0; i < data.getLayerCount(); i++) { + AbilityIconData.Layer layer = data.getLayer(i); + if (!layer.hasTexture()) continue; + ImageData imageData = ClientCacheHandler.getImageData(layer.texture); + if (imageData != null && imageData.imageLoaded()) { + int tint = layer.tintColor; + float r = ((tint >> 16) & 0xFF) / 255f; + float g = ((tint >> 8) & 0xFF) / 255f; + float b = (tint & 0xFF) / 255f; + GL11.glColor4f(r, g, b, alpha); + renderEngine.bindTexture(imageData.getLocation()); + Tessellator t = getLayerTessellator(imageData, layer, i == 0 ? state : 0); + t.draw(); + drewAny = true; + } + } + if (!drewAny) { + GL11.glColor4f(1, 1, 1, alpha); + renderEngine.bindTexture(FALLBACK_TEXTURE); + getFallbackTessellator().draw(); + } + } else if (hasDefaultLayers()) { + // Path 2: Default layers — draw each layer with its dynamic color + for (Ability.DefaultIconLayer defLayer : defaultLayers) { + String texPath = defLayer.getTextureForState(state); + if (texPath == null || texPath.isEmpty()) continue; + ImageData imageData = ClientCacheHandler.getImageData(texPath); + if (imageData != null && imageData.imageLoaded()) { + int color = defLayer.getColor(); + float r = ((color >> 16) & 0xFF) / 255f; + float g = ((color >> 8) & 0xFF) / 255f; + float b = (color & 0xFF) / 255f; + GL11.glColor4f(r, g, b, alpha); + renderEngine.bindTexture(imageData.getLocation()); + getDefaultIconTessellator().draw(); + } + } + } else { + // Path 3: No custom icon, no default layers — generic fallback + GL11.glColor4f(1, 1, 1, alpha); + renderEngine.bindTexture(FALLBACK_TEXTURE); + getFallbackTessellator().draw(); + } + + GL11.glPopMatrix(); + } + + private boolean hasDefaultLayers() { + return defaultLayers != null && defaultLayers.length > 0; + } + + private Tessellator getLayerTessellator(ImageData imageData, AbilityIconData.Layer layer, int state) { + float hw = data.width / 2f; + float hh = data.height / 2f; + + float texW = imageData.getTotalWidth(); + float texH = imageData.getTotalHeight(); + + // State UV overrides only apply to layer 0 + int ix = (state > 0) ? data.getIconXForState(state) : layer.iconX; + int iy = (state > 0) ? data.getIconYForState(state) : layer.iconY; + + // Animation V offset + float vOff = 0f; + if (imageData.isAnimated()) { + vOff = imageData.getCurrentFrameVOffset(); + } else if (data.isAnimated()) { + vOff = AnimationHelper.getFrameVOffset((int) texH, data.getFrameCount(), data.getFrameTime()); + } + + float u1 = ix / texW; + float v1 = vOff + iy / texH; + float u2 = (ix + data.width) / texW; + float v2 = vOff + (iy + data.height) / texH; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, u1, v2); + t.addVertexWithUV(hw, hh, zLevel, u2, v2); + t.addVertexWithUV(hw, -hh, zLevel, u2, v1); + t.addVertexWithUV(-hw, -hh, zLevel, u1, v1); + return t; + } + + private Tessellator getDefaultIconTessellator() { + float hw = defaultIconWidth / 2f; + float hh = defaultIconHeight / 2f; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, 0, 1); + t.addVertexWithUV(hw, hh, zLevel, 1, 1); + t.addVertexWithUV(hw, -hh, zLevel, 1, 0); + t.addVertexWithUV(-hw, -hh, zLevel, 0, 0); + return t; + } + + private Tessellator getFallbackTessellator() { + float hw = 16f; + float hh = 16f; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, 0, 1); + t.addVertexWithUV(hw, hh, zLevel, 1, 1); + t.addVertexWithUV(hw, -hh, zLevel, 1, 0); + t.addVertexWithUV(-hw, -hh, zLevel, 0, 0); + return t; + } + + public boolean hasTexture() { + return data.isEnabled() || hasDefaultLayers(); + } + + /** + * Returns the approximate visual size (max dimension) that draw() produces. + * Custom icon: max(width,height) * scale. Default icon: max(defaultW,defaultH). Fallback: 32. + */ + public float getDrawSize() { + if (data.isEnabled()) { + return Math.max(width, height) * data.scale; + } + if (hasDefaultLayers()) { + return Math.max(defaultIconWidth, defaultIconHeight); + } + return 32f; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java b/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java index b71f6642a..defa42faa 100644 --- a/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java +++ b/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java @@ -10,8 +10,10 @@ import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.client.CustomNpcResourceListener; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.gui.SubGuiColorSelector; -import noppes.npcs.client.gui.global.GuiNPCManageLinked; +import noppes.npcs.client.gui.SubGuiTagSelect; +import net.minecraft.client.gui.GuiScreen; import noppes.npcs.client.gui.script.GuiScriptInterface; import noppes.npcs.client.gui.util.GuiButtonBiDirectional; import noppes.npcs.client.gui.util.GuiMenuTopButton; @@ -36,7 +38,7 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe private int tab = -1; private int colorPicked = 0; - public SubGuiLinkedItem(GuiNPCManageLinked parent, LinkedItem linkedItem) { + public SubGuiLinkedItem(GuiScreen parent, LinkedItem linkedItem) { this.linkedItem = linkedItem; this.parent = parent; this.originalName = linkedItem.name; @@ -158,6 +160,8 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe } GuiButtonBiDirectional useActionButton = new GuiButtonBiDirectional(6, x + 120, y, 100, 20, useActions, useActionIndex); addButton(useActionButton); + + addButton(new GuiNpcButton(40, x + 230, y, 100, 20, "gui.tags")); y += spacing; // Armor Type: BiDirectional button (None, All, Head, Chestplate, Leggings, Boots) @@ -286,6 +290,31 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe scrollWindow.addLabel(new GuiNpcLabel(70, "display.durabilityShow", x, localY + 5, 0xFFFFFF)); GuiNpcButtonYesNo durabilityButton = new GuiNpcButtonYesNo(26, x + 120, localY, linkedItem.display.durabilityShow); scrollWindow.addButton(durabilityButton); + localY += 30; + + // Animation controls + scrollWindow.addLabel(new GuiNpcLabel(80, "gui.animated", x, localY + 5, 0xFFFFFF)); + boolean isAnim = linkedItem.display.animated != null && linkedItem.display.animated; + GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(29, x + 120, localY, isAnim); + animBtn.setHoverText("gui.animated.hover"); + scrollWindow.addButton(animBtn); + localY += 25; + + if (isAnim) { + scrollWindow.addLabel(new GuiNpcLabel(81, "gui.frameCount", x, localY + 5, 0xFFFFFF)); + GuiNpcTextField fcField = new GuiNpcTextField(71, this, x + 120, localY, 60, 20, + "" + (linkedItem.display.frameCount != null ? linkedItem.display.frameCount : 1)); + fcField.setIntegersOnly().setMinMaxDefault(1, 256, 1); + scrollWindow.addTextField(fcField); + localY += 25; + + scrollWindow.addLabel(new GuiNpcLabel(82, "gui.frameTime", x, localY + 5, 0xFFFFFF)); + GuiNpcTextField ftField = new GuiNpcTextField(72, this, x + 120, localY, 60, 20, + "" + (linkedItem.display.frametime != null ? linkedItem.display.frametime : 2)); + ftField.setIntegersOnly().setMinMaxDefault(1, 100, 2); + scrollWindow.addTextField(ftField); + localY += 25; + } scrollWindow.scrollY = 0; scrollWindow.maxScrollY = Math.max(localY - scrollWindow.clipHeight, 0); @@ -310,6 +339,9 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe PacketClient.sendClient(new LinkedItemSavePacket(linkedItem.writeToNBT(false), originalName)); GuiScriptInterface.open(this.parent, new LinkedItemScript(linkedItem.id)); return; + } else if (id == 40) { + setSubGui(new SubGuiTagSelect(linkedItem.tagUUIDs)); + return; } else if (id == 20) { // Open confirmation for version bump. GuiYesNo guiyesno = new GuiYesNo(this, "Confirm", "Bump version and update all linked items?", 20); @@ -381,6 +413,9 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe linkedItem.isNormalItem = ((GuiNpcButtonYesNo) guibutton).getBoolean(); } else if (id == 26 && guibutton instanceof GuiNpcButtonYesNo) { linkedItem.display.durabilityShow = ((GuiNpcButtonYesNo) guibutton).getBoolean(); + } else if (id == 29 && guibutton instanceof GuiNpcButtonYesNo) { + linkedItem.display.animated = ((GuiNpcButtonYesNo) guibutton).getBoolean(); + initGui(); } } @@ -429,6 +464,10 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe linkedItem.display.translateY = textField.getFloat(); } else if (id == 63) { linkedItem.display.translateZ = textField.getFloat(); + } else if (id == 71) { + linkedItem.display.frameCount = Math.max(1, textField.getInteger()); + } else if (id == 72) { + linkedItem.display.frametime = Math.max(1, textField.getInteger()); } } @@ -472,7 +511,20 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe int iconWidth = data.getTotalWidth(); int iconHeight = data.getTotalWidth(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); + + // Animation V offset for preview + if (data.isAnimated()) { + iconY += (int) (data.getCurrentFrameVOffset() * height); + iconHeight = data.getFrameHeight(); + } else if (linkedItem.display.animated != null && linkedItem.display.animated + && linkedItem.display.frameCount != null && linkedItem.display.frameCount > 1) { + iconY += (int) (AnimationHelper.getFrameVOffset(height, linkedItem.display.frameCount, linkedItem.display.frametime) * height); + iconHeight = height / linkedItem.display.frameCount; + } else { + iconHeight = data.getTotalWidth(); + height = data.getTotalWidth(); + } float[] colors = ColorUtil.hexToRGB(linkedItem.display.itemColor); GL11.glColor3f(colors[0], colors[1], colors[2]); diff --git a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNPCGlobalMainMenu.java b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNPCGlobalMainMenu.java index b055cbf43..36370eb92 100644 --- a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNPCGlobalMainMenu.java +++ b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNPCGlobalMainMenu.java @@ -247,7 +247,7 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 { NoppesUtil.requestOpenGUI(EnumGuiType.ManageAbilities); } if (id == 22) { - // NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction); + NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction); } } diff --git a/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java b/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java index 11ffa198d..b61c1e1b7 100644 --- a/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java +++ b/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java @@ -11,20 +11,23 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import noppes.npcs.client.AuctionClientConfig; +import noppes.npcs.client.gui.global.GuiNpcManageAuction; import noppes.npcs.constants.EnumClaimType; import noppes.npcs.containers.ContainerAuctionListing; import noppes.npcs.containers.ContainerAuctionSell; import noppes.npcs.containers.ContainerAuctionTrades; +import noppes.npcs.containers.ContainerManageAuction; import noppes.npcs.containers.SlotAuctionDisplay; import noppes.npcs.controllers.data.AuctionClaim; import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.util.AuctionFormatUtil; import java.util.List; /** * Handles adding auction information to item tooltips when viewing auction GUIs. * Called from ItemTooltipEvent in ClientEventHandler. - * + *

* Uses slot-based lookup (slot index) instead of ItemStack comparison to correctly * handle duplicate items with different auction data (e.g., two porkchops at different prices). */ @@ -48,6 +51,8 @@ public class AuctionTooltipHandler { addTradesTooltip((GuiAuctionTrades) screen, event.itemStack, event.toolTip); } else if (screen instanceof GuiAuctionSell) { addSellTooltip((GuiAuctionSell) screen, event.itemStack, event.toolTip); + } else if (screen instanceof GuiNpcManageAuction) { + addManageAuctionTooltip((GuiNpcManageAuction) screen, event.itemStack, event.toolTip); } } @@ -88,25 +93,25 @@ public class AuctionTooltipHandler { // Current bid or starting price if (listing.hasBids()) { tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid") - .replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid))); + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid))); tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount)); } else { tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice") - .replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.startingPrice))); + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice))); tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids")); } // Buyout price if (listing.hasBuyout()) { tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout") - .replace("%s", EnumChatFormatting.GREEN + formatCurrency(listing.buyoutPrice))); + .replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice))); } // Time remaining long timeRemaining = listing.getTimeRemaining(); String timeText = StatCollector.translateToLocal("auction.timeLeft") - .replace("%s", formatTimeRemaining(timeRemaining)); - tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); + .replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining)); + tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); } // ========== Trades Page ========== @@ -144,7 +149,7 @@ public class AuctionTooltipHandler { if (listing.hasBids()) { tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid") - .replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid))); + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid))); tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount)); } else { tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids")); @@ -152,8 +157,8 @@ public class AuctionTooltipHandler { long timeRemaining = listing.getTimeRemaining(); String timeText = StatCollector.translateToLocal("auction.timeLeft") - .replace("%s", formatTimeRemaining(timeRemaining)); - tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); + .replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining)); + tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); tooltip.add(""); tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel")); @@ -164,13 +169,13 @@ public class AuctionTooltipHandler { tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding")); tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid") - .replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid))); + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid))); tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount)); long timeRemaining = listing.getTimeRemaining(); String timeText = StatCollector.translateToLocal("auction.timeLeft") - .replace("%s", formatTimeRemaining(timeRemaining)); - tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); + .replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining)); + tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); tooltip.add(""); tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.clickToRebid")); @@ -210,7 +215,7 @@ public class AuctionTooltipHandler { // Amount for currency claims if (claim.type.isCurrency()) { tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount") - .replace("%s", EnumChatFormatting.GOLD + formatCurrency(claim.currency))); + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency))); } // Expiration @@ -254,48 +259,125 @@ public class AuctionTooltipHandler { } } - // ========== Formatting Utilities ========== + // ========== Global Manage Auction ========== - private static String formatCurrency(long amount) { - if (amount < 1000) { - return amount + " " + AuctionClientConfig.getCurrencyName(); - } - StringBuilder sb = new StringBuilder(); - String str = "" + amount; - int count = 0; - for (int i = str.length() - 1; i >= 0; i--) { - if (count > 0 && count % 3 == 0) { - sb.insert(0, ','); + private static void addManageAuctionTooltip(GuiNpcManageAuction gui, ItemStack stack, List tooltip) { + Slot slot = findHoveredSlot(gui, stack); + if (slot == null) return; + + ContainerManageAuction container = gui.getManageContainer(); + if (container == null) return; + + GuiNpcManageAuction.Tab tab = gui.getActiveTab(); + + if (tab == GuiNpcManageAuction.Tab.LISTINGS && container.isDisplaySlot(slot.slotNumber)) { + int displayIndex = container.toDisplayIndex(slot.slotNumber); + AuctionListing listing = container.getListingAtDisplay(displayIndex); + if (listing == null) return; + + tooltip.add(""); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller") + .replace("%s", EnumChatFormatting.WHITE + listing.sellerName)); + + if (listing.hasBids()) { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid))); + tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount)); + } else { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice))); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids")); + } + + if (listing.hasBuyout()) { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout") + .replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice))); + } + + long timeRemaining = listing.getTimeRemaining(); + String timeText = StatCollector.translateToLocal("auction.timeLeft") + .replace("%s", AuctionFormatUtil.formatTimeRemaining(timeRemaining)); + tooltip.add((AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); + + tooltip.add(""); + tooltip.add(EnumChatFormatting.AQUA + "Left-click: View details"); + tooltip.add(EnumChatFormatting.GOLD + "Right-click: Stop player"); + tooltip.add(EnumChatFormatting.LIGHT_PURPLE + "Shift+Right-click: Cancel to global"); + return; + } + + if (tab == GuiNpcManageAuction.Tab.CLAIMS && container.isDisplaySlot(slot.slotNumber)) { + int displayIndex = container.toDisplayIndex(slot.slotNumber); + AuctionClaim claim = container.getClaimAtDisplay(displayIndex); + if (claim != null) { + addGlobalClaimTooltip(claim, tooltip); + return; + } + + AuctionListing listing = container.getListingAtDisplay(displayIndex); + if (listing != null) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller") + .replace("%s", EnumChatFormatting.WHITE + listing.sellerName)); + if (listing.hasBids()) { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.currentBid))); + } else { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(listing.startingPrice))); + } + if (listing.hasBuyout()) { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout") + .replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice))); + } + tooltip.add(""); + tooltip.add(EnumChatFormatting.GOLD + "Right-click: Stop player"); + tooltip.add(EnumChatFormatting.LIGHT_PURPLE + "Shift+Right-click: Cancel to global"); + } + return; + } + + if (tab == GuiNpcManageAuction.Tab.CREATE) { + if (container.isCreateSlot(slot.slotNumber)) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.leftClear")); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.rightRemove")); + } else if (container.isPlayerSlot(slot.slotNumber)) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne")); } - sb.insert(0, str.charAt(i)); - count++; } - return sb.toString() + " " + AuctionClientConfig.getCurrencyName(); } - private static String formatTimeRemaining(long milliseconds) { - if (milliseconds <= 0) { - return StatCollector.translateToLocal("auction.ended"); + private static void addGlobalClaimTooltip(AuctionClaim claim, List tooltip) { + tooltip.add(""); + if (claim.type == EnumClaimType.ITEM) { + tooltip.add(EnumChatFormatting.AQUA + "Global Item Claim"); + } else if (claim.type == EnumClaimType.CURRENCY) { + tooltip.add(EnumChatFormatting.GOLD + "Global Currency Claim"); + if (claim.itemName != null && !claim.itemName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.soldItem") + .replace("%s", EnumChatFormatting.WHITE + claim.itemName)); + } + if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.buyer") + .replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName)); + } + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency))); + tooltip.add(EnumChatFormatting.GRAY + "Claiming this does not change your balance."); + } else if (claim.type == EnumClaimType.REFUND) { + tooltip.add(EnumChatFormatting.RED + "Global Refund Claim"); + if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy") + .replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName)); + } + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency))); } - - long seconds = (milliseconds / 1000) % 60; - long minutes = (milliseconds / 60000) % 60; - long hours = (milliseconds / 3600000) % 24; - long days = milliseconds / 86400000; - - StringBuilder sb = new StringBuilder(); - if (days > 0) { - sb.append(days).append("d "); - } - if (hours > 0 || days > 0) { - sb.append(hours).append("h "); - } - if (minutes > 0 || hours > 0 || days > 0) { - sb.append(minutes).append("m"); - } else { - sb.append(seconds).append("s"); - } - - return sb.toString(); + tooltip.add(""); + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim")); } + } diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java index afe47fb44..5b74ad3c3 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java @@ -15,6 +15,7 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.containers.ContainerAuctionBidding; import noppes.npcs.controllers.data.AuctionListing; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.util.AuctionFormatUtil; import org.lwjgl.opengl.GL11; import java.util.ArrayList; @@ -36,7 +37,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis private int btnBidY = 110; private int btnBuyoutX = 82; private int btnBuyoutY = 110; - private int infoX = 110; + private int infoX = 105; private int infoY = 50; // Button IDs @@ -81,7 +82,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis return -1; } - /** Update button visibility based on listing state */ + /** + * Update button visibility based on listing state + */ private void updateButtonState() { if (listing == null) { if (btnBid != null) btnBid.setVisible(false); @@ -123,7 +126,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis private void openBidSubGui() { if (listing == null) return; long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement()); - setSubGui(new SubGuiAuctionBid(listing.id, minBid, playerBalance)); + setSubGui(new SubGuiAuctionBid(listing.id, minBid, listing.buyoutPrice, playerBalance)); } private void openBuyNowSubGui() { @@ -184,9 +187,11 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis drawAuctionInfo(); } - /** Draw auction listing information on the right side */ + /** + * Draw auction listing information on the right side + */ private void drawAuctionInfo() { - int x = guiLeft + 105; + int x = guiLeft + infoX; int y = guiTop + infoY; int xRight = guiLeft + 215; @@ -206,7 +211,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis String bidLabel = StatCollector.translateToLocal("auction.info.currentBid") + ":"; fontRendererObj.drawString(EnumChatFormatting.YELLOW + bidLabel, x, y, 0xFFFFFF); - label = formatCurrency(listing.currentBid); + label = AuctionFormatUtil.formatCurrency(listing.currentBid); length = fontRendererObj.getStringWidth(label); fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF); y += lineHeight + 4; @@ -223,9 +228,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis String startLabel = StatCollector.translateToLocal("auction.info.startingPrice"); fontRendererObj.drawString(EnumChatFormatting.YELLOW + startLabel, x, y, 0xFFFFFF); - label = formatCurrency(listing.startingPrice); + label = AuctionFormatUtil.formatCurrency(listing.startingPrice); length = fontRendererObj.getStringWidth(label); - fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF); + fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF); y += lineHeight + 4; } @@ -234,9 +239,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis String buyoutLabel = StatCollector.translateToLocal("auction.info.buyoutPrice"); fontRendererObj.drawString(EnumChatFormatting.GREEN + buyoutLabel, x, y, 0xFFFFFF); - label = formatCurrency(listing.buyoutPrice); + label = AuctionFormatUtil.formatCurrency(listing.buyoutPrice); length = fontRendererObj.getStringWidth(label); - fontRendererObj.drawString(EnumChatFormatting.GREEN + label, xRight - length, y, 0xFFFFFF); + fontRendererObj.drawString(EnumChatFormatting.GREEN + label, xRight - length, y, 0xFFFFFF); y += lineHeight + 4; } @@ -244,9 +249,9 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis String timeLabel = StatCollector.translateToLocal("auction.info.timeLeft"); fontRendererObj.drawString(EnumChatFormatting.GRAY + timeLabel, x, y, 0xFFFFFF); long timeRemaining = listing.getTimeRemaining(); - EnumChatFormatting timeColor = timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE; + EnumChatFormatting timeColor = AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE; - label = timeColor + formatTimeRemaining(timeRemaining); + label = timeColor + AuctionFormatUtil.formatTimeRemaining(timeRemaining); length = fontRendererObj.getStringWidth(label); fontRendererObj.drawString(label, xRight - length, y, 0xFFFFFF); y += lineHeight + 4; @@ -278,14 +283,14 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis if (listing != null) { long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement()); tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.bid.minimum") - .replace("%s", EnumChatFormatting.WHITE + formatCurrency(minBid) + " " + AuctionClientConfig.getCurrencyName())); + .replace("%s", EnumChatFormatting.WHITE + AuctionFormatUtil.formatCurrency(minBid) + " " + AuctionClientConfig.getCurrencyName())); } } else if (btnBuyout != null && btnBuyout.visible && btnBuyout.isHovered()) { tooltip = new ArrayList<>(); tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.bid.buyout")); if (listing != null && listing.hasBuyout()) { tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.info.buyoutPrice") + ":"); - tooltip.add(EnumChatFormatting.GREEN + formatCurrency(listing.buyoutPrice) + " " + AuctionClientConfig.getCurrencyName()); + tooltip.add(EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrency(listing.buyoutPrice) + " " + AuctionClientConfig.getCurrencyName()); } } @@ -305,5 +310,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis // Block all slot interactions - view only } - public AuctionListing getListing() { return listing; } + public AuctionListing getListing() { + return listing; + } } diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java index c34223550..048260d4c 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java @@ -34,6 +34,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { public static final int PAGE_SELL = 1; public static final int PAGE_CLAIMS = 2; + // Overlay color + protected static final int OVERLAY_DARK = 0xC0000000; + // Navigation button IDs protected static final int BTN_NAV_LISTINGS = 100; protected static final int BTN_NAV_SELL = 101; @@ -66,7 +69,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { initNavigationButtons(); } - /** Initialize navigation buttons */ + /** + * Initialize navigation buttons + */ protected void initNavigationButtons() { int page = getCurrentPage(); @@ -86,7 +91,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { addButton(btnClaims); } - /** Returns current page constant - implement in subclass */ + /** + * Returns current page constant - implement in subclass + */ protected abstract int getCurrentPage(); @Override @@ -133,7 +140,9 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { } } - /** Draw navigation button tooltips */ + /** + * Draw navigation button tooltips + */ protected void drawNavButtonTooltips(int mouseX, int mouseY) { List tooltip = null; if (btnListings != null && btnListings.isHovered()) tooltip = btnListings.getTooltipLines(); @@ -151,14 +160,18 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { // ========== Slot Drawing Utilities ========== - /** Draw auction slot background (18x18) */ + /** + * Draw auction slot background (18x18) + */ protected void drawAuctionSlot(int x, int y) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); mc.renderEngine.bindTexture(AUCTION_SLOT); Gui.func_146110_a(x, y, 0, 0, 18, 18, 18, 18); } - /** Draw colored overlay on slot (ARGB format) */ + /** + * Draw colored overlay on slot (ARGB format) + */ protected void drawColoredOverlay(int x, int y, int color) { GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); @@ -170,12 +183,16 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } - /** Draw dark overlay for unavailable slots */ + /** + * Draw dark overlay for unavailable slots + */ protected void drawDarkenedOverlay(int x, int y) { - drawColoredOverlay(x, y, 0xC0000000); + drawColoredOverlay(x, y, OVERLAY_DARK); } - /** Draw icon texture on slot (16x16) */ + /** + * Draw icon texture on slot (16x16) + */ protected void drawIconOverlay(int x, int y, ResourceLocation icon) { GL11.glPushMatrix(); GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); @@ -189,42 +206,11 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { GL11.glPopMatrix(); } - /** Subclasses implement this to draw specific content */ + /** + * Subclasses implement this to draw specific content + */ protected abstract void drawAuctionContent(float partialTicks, int mouseX, int mouseY); - // ========== Formatting Utilities ========== - - /** Format currency with commas (e.g., 1000 -> "1,000") */ - protected String formatCurrency(long amount) { - if (amount < 1000) return "" + amount; - StringBuilder sb = new StringBuilder(); - String str = "" + amount; - int count = 0; - for (int i = str.length() - 1; i >= 0; i--) { - if (count > 0 && count % 3 == 0) sb.insert(0, ','); - sb.insert(0, str.charAt(i)); - count++; - } - return sb.toString(); - } - - /** Format time remaining (e.g., "2d 5h 30m") */ - protected String formatTimeRemaining(long ms) { - if (ms <= 0) return "Ended"; - - long seconds = (ms / 1000) % 60; - long minutes = (ms / 60000) % 60; - long hours = (ms / 3600000) % 24; - long days = ms / 86400000; - - StringBuilder sb = new StringBuilder(); - if (days > 0) sb.append(days).append("d "); - if (hours > 0 || days > 0) sb.append(hours).append("h "); - if (minutes > 0 || hours > 0 || days > 0) sb.append(minutes).append("m"); - else sb.append(seconds).append("s"); - return sb.toString(); - } - @Override public void save() { // Override in subclasses if needed diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionListing.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionListing.java index 381747c6a..85312f5ad 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionListing.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionListing.java @@ -58,8 +58,6 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis private AuctionFilter filter; private int currentPage = 0; private int totalPages = 1; - private int totalListings = 0; - private boolean dataLoaded = false; // Buttons defined on this page private GuiAuctionNavButton btnFilter; @@ -100,12 +98,16 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis return PAGE_LISTINGS; } - /** Request listings from server */ + /** + * Request listings from server + */ private void requestListings() { AuctionActionPacket.requestListings(filter, currentPage); } - /** Update pagination button visibility based on current page state */ + /** + * Update pagination button visibility based on current page state + */ private void updatePaginationVisibility() { if (btnPageUp != null) { btnPageUp.setVisible(currentPage > 0); @@ -195,7 +197,8 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis } @Override - public void subGuiClosed(SubGuiInterface subgui) {} + public void subGuiClosed(SubGuiInterface subgui) { + } // ========== Data Handling ========== @@ -204,7 +207,6 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis if (compound.hasKey("ListingsData")) { currentPage = compound.getInteger("Page"); totalPages = compound.getInteger("TotalPages"); - totalListings = compound.getInteger("TotalListings"); // Load listings listingContainer.displayInventory.clear(); @@ -213,7 +215,7 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis AuctionListing listing = AuctionListing.fromNBT(list.getCompoundTagAt(i)); listingContainer.displayInventory.setListing(i, listing); } - dataLoaded = true; + updatePaginationVisibility(); } else if (compound.hasKey("ListingsRefresh")) { requestListings(); } @@ -297,6 +299,11 @@ public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiLis // Block other slot interactions } - public AuctionFilter getFilter() { return filter; } - public ContainerAuctionListing getListingContainer() { return listingContainer; } + public AuctionFilter getFilter() { + return filter; + } + + public ContainerAuctionListing getListingContainer() { + return listingContainer; + } } diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java index a8784b3b0..af87ab39b 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java @@ -7,15 +7,17 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; +import noppes.npcs.client.AuctionClientConfig; import noppes.npcs.client.NoppesUtil; import noppes.npcs.client.gui.util.GuiAuctionNavButton; 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.ITextfieldListener; -import noppes.npcs.client.AuctionClientConfig; import noppes.npcs.containers.ContainerAuctionSell; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.util.AuctionFormatUtil; +import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; @@ -103,7 +105,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis return PAGE_SELL; } - /** Update visibility of buyout price field based on toggle state */ + /** + * Update visibility of buyout price field based on toggle state + */ private void updateBuyoutVisibility() { if (lblBuyout != null) { lblBuyout.enabled = allowBuyout; @@ -117,7 +121,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis } } - /** Update the buyout toggle button tooltip */ + /** + * Update the buyout toggle button tooltip + */ private void updateBuyoutTooltip() { if (btnAllowBuyout == null) return; @@ -239,7 +245,7 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis // Draw listing fee info (uses cached config from server) String feeText = StatCollector.translateToLocal("auction.sell.fee") - .replace("%s", formatCurrency(AuctionClientConfig.getListingFee()) + " " + AuctionClientConfig.getCurrencyName()); + .replace("%s", AuctionFormatUtil.formatCurrency(AuctionClientConfig.getListingFee()) + " " + AuctionClientConfig.getCurrencyName()); fontRendererObj.drawString(EnumChatFormatting.GRAY + feeText, guiLeft + contentX, guiTop + contentY + 77, 0xFFFFFF); // Draw error message if any @@ -250,7 +256,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis drawSellSlotIndicator(slotX, slotY); } - /** Draw indicator showing staged vs available items */ + /** + * Draw indicator showing staged vs available items + */ private void drawSellSlotIndicator(int slotX, int slotY) { ItemStack sellItem = sellContainer.getItemToSell(); if (sellItem != null) { @@ -308,7 +316,9 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis drawSellPageTooltips(mouseX, mouseY); } - /** Draw tooltips for sell page buttons */ + /** + * Draw tooltips for sell page buttons + */ private void drawSellPageTooltips(int mouseX, int mouseY) { List tooltip = null; @@ -326,7 +336,11 @@ public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldLis } if (tooltip != null && !tooltip.isEmpty()) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj); + GL11.glPopAttrib(); + GL11.glPopMatrix(); } } } diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java index f52d5fa63..05e83c5bc 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java @@ -50,7 +50,7 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { private int pendingSlot = -1; private PendingOp pendingOp = PendingOp.NONE; - private enum PendingOp { NONE, CANCEL, CLAIM } + private enum PendingOp {NONE, CANCEL, CLAIM} public GuiAuctionTrades(EntityNPCInterface npc, ContainerAuctionTrades container) { super(npc, container); @@ -88,10 +88,16 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); - if (listing != null && tradesContainer.isSellingAt(slot) && mouseButton == 1) { - // Right-click on own listing = show cancel - setPending(slot, PendingOp.CANCEL); - NoppesUtil.clickSound(); + if (listing != null && tradesContainer.isSellingAt(slot)) { + if (mouseButton == 0) { + // Left-click on own listing = view details + AuctionActionPacket.openBidding(listing.id); + NoppesUtil.clickSound(); + } else if (mouseButton == 1) { + // Right-click on own listing = show cancel + setPending(slot, PendingOp.CANCEL); + NoppesUtil.clickSound(); + } } else if (listing != null && tradesContainer.isBiddingAt(slot) && mouseButton == 0) { // Left-click on active bid = open bidding GUI to increase bid AuctionActionPacket.openBidding(listing.id); @@ -117,7 +123,9 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { } } - /** Handle click on pending operation slot */ + /** + * Handle click on pending operation slot + */ private void handlePendingClick(int mouseButton) { if (pendingOp == PendingOp.CANCEL && mouseButton == 1) { // Right-click confirms cancel @@ -159,14 +167,18 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { } } - /** Set pending operation and hide slot item */ + /** + * Set pending operation and hide slot item + */ private void setPending(int slot, PendingOp op) { pendingSlot = slot; pendingOp = op; tradesContainer.setHiddenSlot(slot); } - /** Clear pending operation and restore slot */ + /** + * Clear pending operation and restore slot + */ private void clearPending() { if (pendingSlot >= 0) { tradesContainer.clearHiddenSlot(); @@ -175,13 +187,17 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { pendingOp = PendingOp.NONE; } - /** Play confirmation sound */ + /** + * Play confirmation sound + */ private void playConfirmSound() { mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a( new ResourceLocation("random.orb"), 1.0F)); } - /** Get slot index at mouse position */ + /** + * Get slot index at mouse position + */ private int getSlotAt(int mouseX, int mouseY) { int relX = mouseX - guiLeft - GRID_X; int relY = mouseY - guiTop - GRID_Y; @@ -239,7 +255,9 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { } } - /** Get tint color for slot based on contents */ + /** + * Get tint color for slot based on contents + */ private int getSlotTint(int slot) { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); @@ -281,7 +299,9 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { } } - /** Draw tooltip for a trade slot */ + /** + * Draw tooltip for a trade slot + */ private void drawTradeTooltip(int slot, int x, int y) { List tooltip = new ArrayList<>(); @@ -301,16 +321,13 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); - if (listing != null) { - if (tradesContainer.isSellingAt(slot)) { - tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.trades.activeListing")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel")); - } else if (tradesContainer.isBiddingAt(slot)) { - tooltip.add(EnumChatFormatting.AQUA + StatCollector.translateToLocal("auction.trades.activeBid")); - tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.winningBid")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToIncrease")); - } - } else if (claim != null) { + // Slots with items have tooltips handled by AuctionTooltipHandler via ItemTooltipEvent + if (listing != null) return; + if (claim != null && (claim.type == EnumClaimType.ITEM || + (claim.type == EnumClaimType.REFUND && claim.item != null))) return; + + // Non-item slots (currency claims, refund without item, unavailable) + if (claim != null) { switch (claim.type) { case CURRENCY: tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.soldClaim")); @@ -328,20 +345,6 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.outbidBy") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName); } tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName()); - // Show rebid option if item is present (active listing) - if (claim.item != null) { - tooltip.add(""); - tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund")); - return; // Skip the generic claim message - } - break; - case ITEM: - if (claim.isReturned) { - tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expiredClaim")); - } else { - tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.wonClaim")); - } break; } tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToClaim")); 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/player/GuiQuestCompletion.java b/src/main/java/noppes/npcs/client/gui/player/GuiQuestCompletion.java index 66767e7cf..6f488c492 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiQuestCompletion.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiQuestCompletion.java @@ -15,7 +15,7 @@ import org.lwjgl.opengl.GL11; public class GuiQuestCompletion extends GuiNPCInterface implements ITopButtonListener { private Quest quest; - private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/smallbg.png"); + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/menubg.png"); public GuiQuestCompletion(Quest quest) { super(); diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiTransportSelection.java b/src/main/java/noppes/npcs/client/gui/player/GuiTransportSelection.java index f266059a6..e86769131 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiTransportSelection.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiTransportSelection.java @@ -20,7 +20,7 @@ import java.util.Vector; public class GuiTransportSelection extends GuiNPCInterface implements ITopButtonListener, IScrollData { - private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/smallbg.png"); + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/menubg.png"); protected int xSize; protected int guiLeft; protected int guiTop; diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java index a1793c545..2bb766415 100644 --- a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java @@ -10,6 +10,7 @@ import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.util.AuctionFormatUtil; /** * Sub GUI for placing a bid on an auction. @@ -22,14 +23,16 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe private final String listingId; private final long minimumBid; + private final long buyoutPrice; private final long playerBalance; private long bidAmount; private boolean successful = false; private String errorMessage = null; - public SubGuiAuctionBid(String listingId, long minimumBid, long playerBalance) { + public SubGuiAuctionBid(String listingId, long minimumBid, long buyoutPrice, long playerBalance) { this.listingId = listingId; this.minimumBid = minimumBid; + this.buyoutPrice = buyoutPrice; this.playerBalance = playerBalance; this.bidAmount = minimumBid; @@ -49,13 +52,13 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe // Minimum bid info String minText = StatCollector.translateToLocal("auction.bid.minimum") - .replace("%s", EnumChatFormatting.DARK_RED + formatCurrency(minimumBid) + " " + currencyName); + .replace("%s", EnumChatFormatting.DARK_RED + AuctionFormatUtil.formatCurrency(minimumBid) + " " + currencyName); addLabel(new GuiNpcLabel(1, minText, guiLeft + 15, y)); y += 14; // Your balance String balanceText = StatCollector.translateToLocal("auction.bid.yourBalance") - .replace("%s", EnumChatFormatting.DARK_GREEN + formatCurrency(playerBalance) + " " + currencyName); + .replace("%s", EnumChatFormatting.DARK_GREEN + AuctionFormatUtil.formatCurrency(playerBalance) + " " + currencyName); addLabel(new GuiNpcLabel(2, balanceText, guiLeft + 15, y)); y += 18; @@ -77,7 +80,7 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe int totalBtnWidth = btnWidth * 2 + btnSpacing; int btnX = centerX - totalBtnWidth / 2; - addButton(new GuiNpcButton(btnBidId, btnX, y, btnWidth, 20, "auction.bid.placeBid")); + addButton(new GuiNpcButton(btnBidId, btnX, y, btnWidth, 20, "auction.bid.place")); addButton(new GuiNpcButton(btnCancelId, btnX + btnWidth + btnSpacing, y, btnWidth, 20, "gui.cancel")); } @@ -117,7 +120,7 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe // Validate if (bidAmount < minimumBid) { errorMessage = StatCollector.translateToLocal("auction.error.bidTooLow") - .replace("%s", formatCurrency(minimumBid)); + .replace("%s", AuctionFormatUtil.formatCurrency(minimumBid)); updateErrorLabel(); return; } @@ -128,6 +131,12 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe return; } + if (buyoutPrice > 0 && bidAmount >= buyoutPrice) { + errorMessage = StatCollector.translateToLocal("auction.error.bidExceedsBuyout"); + updateErrorLabel(); + return; + } + // Send bid packet AuctionActionPacket.placeBid(listingId, bidAmount); successful = true; @@ -144,17 +153,4 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe public boolean wasSuccessful() { return successful; } - - private String formatCurrency(long amount) { - if (amount < 1000) return "" + amount; - StringBuilder sb = new StringBuilder(); - String str = "" + amount; - int count = 0; - for (int i = str.length() - 1; i >= 0; i--) { - if (count > 0 && count % 3 == 0) sb.insert(0, ','); - sb.insert(0, str.charAt(i)); - count++; - } - return sb.toString(); - } } diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java index b63471047..4884c7ae4 100644 --- a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java @@ -8,6 +8,7 @@ import noppes.npcs.client.AuctionClientConfig; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.util.AuctionFormatUtil; /** * Sub GUI for confirming a buyout purchase. @@ -54,14 +55,14 @@ public class SubGuiAuctionBuyNow extends SubGuiInterface { y += 16; // Buyout price - String priceText = EnumChatFormatting.DARK_RED + formatCurrency(buyoutPrice) + " " + currencyName; + String priceText = EnumChatFormatting.DARK_RED + AuctionFormatUtil.formatCurrency(buyoutPrice) + " " + currencyName; int priceWidth = fontRendererObj.getStringWidth(priceText); addLabel(new GuiNpcLabel(2, priceText, centerX - priceWidth / 2, y)); y += 20; // Your balance String balanceLabel = StatCollector.translateToLocal("auction.bid.yourBalance"); - String balanceText = balanceLabel.replace("%s", EnumChatFormatting.DARK_GREEN + formatCurrency(playerBalance) + " " + currencyName); + String balanceText = balanceLabel.replace("%s", EnumChatFormatting.DARK_GREEN + AuctionFormatUtil.formatCurrency(playerBalance) + " " + currencyName); addLabel(new GuiNpcLabel(3, balanceText, guiLeft + 20, y)); y += 14; @@ -105,17 +106,4 @@ public class SubGuiAuctionBuyNow extends SubGuiInterface { public boolean wasSuccessful() { return successful; } - - private String formatCurrency(long amount) { - if (amount < 1000) return "" + amount; - StringBuilder sb = new StringBuilder(); - String str = "" + amount; - int count = 0; - for (int i = str.length() - 1; i >= 0; i--) { - if (count > 0 && count % 3 == 0) sb.insert(0, ','); - sb.insert(0, str.charAt(i)); - count++; - } - return sb.toString(); - } } diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java new file mode 100644 index 000000000..b613a3911 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java @@ -0,0 +1,1169 @@ +package noppes.npcs.client.gui.player.inventory; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityTogglePacket; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.hud.ability.AbilityIcon; +import noppes.npcs.client.gui.util.GuiMenuTopButton; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import tconstruct.client.tabs.AbstractTab; + +import noppes.npcs.controllers.MagicController; +import noppes.npcs.controllers.data.Magic; +import noppes.npcs.controllers.data.MagicData; +import noppes.npcs.controllers.data.MagicEntry; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener { + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/standardbg.png"); + + // Sub-tab: 0 = Abilities, 1 = Toggles + private int subTab = 0; + private static final int BTN_TAB_ABILITIES = -200; + private static final int BTN_TAB_TOGGLES = -201; + private static final int BTN_SCROLL_LEFT = -202; + private static final int BTN_SCROLL_RIGHT = -203; + + // ═══ Panel Bounds (relative to guiLeft/guiTop) ═══ + // Selection panel (RIGHT side - icon grid) + private int selLeft = 140; + private int selTop = 4; + private int selRight = 316; + private int selBottom = 150; + + // Information panel (LEFT side - ability details) + private int infoLeft = 5; + private int infoTop = 4; + private int infoRight = 137; + private int infoBottom = 150; + + // Hotbar panel (BOTTOM) + private int hbLeft = 5; + private int hbTop = 153; + private int hbRight = 316; + private int hbBottom = 190; + + // ═══ Grid Settings ═══ + private int gridPad = 3; + private int gridCellSize = 22; + private int gridCols = 7; + + // ═══ Hotbar Settings ═══ + private int hbSlotSize = 18; + private int hbSlotGap = 2; + private int hbSlots = AbilityHotbarData.TOTAL_SLOTS; + + // ═══ Info Panel Settings ═══ + private int infoPad = 5; + private int infoIconSize = 40; + + // ═══ Drag Settings ═══ + private int dragThreshold = 3; + + // ═══ Filtered ability data ═══ + private List filteredKeys = new ArrayList<>(); + private List filteredDisplayNames = new ArrayList<>(); + private List filteredIcons = new ArrayList<>(); + private List filteredAbilities = new ArrayList<>(); + private List filteredActions = new ArrayList<>(); + + // ═══ Grid state ═══ + private int scrollRow = 0; + private int hoveredGridIndex = -1; + private float[] gridHoverScale; + private int selectedIndex = -1; + + // ═══ Detail panel cache ═══ + private AbilityIcon cachedDetailIcon = null; + private int cachedDetailIndex = -1; + + // ═══ Info panel scroll ═══ + private int infoScrollOffset = 0; + private int infoContentHeight = 0; + private int lastInfoIndex = -1; + + // ═══ Hotbar state ═══ + private int hoveredSlotIndex = -1; + private AbilityIcon[] hotbarIcons = new AbilityIcon[AbilityHotbarData.TOTAL_SLOTS]; + + // ═══ Drag state ═══ + private boolean isDragging = false; + private boolean dragPending = false; + private String draggedKey = null; + private AbilityIcon draggedIcon = null; + private int dragSourceSlot = -1; + private int dragStartX, dragStartY; + private int dragMouseX, dragMouseY; + + // ═══ Close sync ═══ + private String initialSelectedKey = null; + + // ═══ Toggle double-tap ═══ + private long lastToggleClickTime = 0; + private int lastToggleClickIndex = -1; + + public GuiAbilities() { + super(); + xSize = 280; + ySize = 180; + + hbSlotSize = 23; + gridCellSize = 24; + gridCols = 7; + } + + @Override + public void initGui() { + super.initGui(); + + GuiMenuTopButton tabAbilities = new GuiMenuTopButton(BTN_TAB_ABILITIES, guiLeft + xSize - 10, guiTop - 17, "gui.abilities"); + tabAbilities.active = (subTab == 0); + addTopButton(tabAbilities); + + GuiMenuTopButton tabToggles = new GuiMenuTopButton(BTN_TAB_TOGGLES, "gui.toggles", tabAbilities); + tabToggles.active = (subTab == 1); + addTopButton(tabToggles); + + buildFilteredList(); + updateHotbarIcons(); + + // Scroll buttons for ability grid + int totalRows = (filteredKeys.size() + gridCols - 1) / gridCols; + int visibleRows = getGridVisibleRows(); + if (totalRows > visibleRows) { + int scrollBtnY = guiTop + selBottom + 1; + int btnW = 14; + int btnH = 12; + addButton(new GuiNpcButton(BTN_SCROLL_LEFT, guiLeft + selRight - btnW * 2 - 2, scrollBtnY, btnW, btnH, "<")); + addButton(new GuiNpcButton(BTN_SCROLL_RIGHT, guiLeft + selRight - btnW, scrollBtnY, btnW, btnH, ">")); + getButton(BTN_SCROLL_LEFT).setEnabled(scrollRow > 0); + getButton(BTN_SCROLL_RIGHT).setEnabled(scrollRow < getMaxScrollRow()); + } + + // Capture initial selected key for close sync + if (initialSelectedKey == null) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + initialSelectedKey = playerData.abilityData.getSelectedAbilityKey(); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Data Building + // ═══════════════════════════════════════════════════════════════════ + + private void buildFilteredList() { + filteredKeys.clear(); + filteredDisplayNames.clear(); + filteredIcons.clear(); + filteredAbilities.clear(); + filteredActions.clear(); + cachedDetailIcon = null; + cachedDetailIndex = -1; + + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) return; + + List abilities = playerData.abilityData.getUnlockedAbilityList(); + + // Build temporary lists before sorting + List tempKeys = new ArrayList<>(); + List tempNames = new ArrayList<>(); + List tempIcons = new ArrayList<>(); + List tempAbilities = new ArrayList<>(); + List tempActions = new ArrayList<>(); + + for (String key : abilities) { + Ability ability = null; + IAbilityAction action = null; + + if (key.startsWith(AbilityHotbarData.CHAIN_PREFIX)) { + String chainKey = key.substring(AbilityHotbarData.CHAIN_PREFIX.length()); + if (AbilityController.Instance != null) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey); + action = chain; + } + } else if (AbilityController.Instance != null) { + ability = AbilityController.Instance.resolveAbility(key); + action = ability; + } + + boolean isToggle = ability != null && ability.isToggleable(); + if (subTab == 0 && isToggle) continue; + if (subTab == 1 && !isToggle) continue; + + String displayName; + if (action instanceof ChainedAbility) { + displayName = "\u00A76\u2726 " + ((ChainedAbility) action).getDisplayName(); + } else if (ability != null) { + displayName = ability.getDisplayName(); + } else { + displayName = key; + } + + tempKeys.add(key); + tempNames.add(displayName); + tempIcons.add(AbilityIcon.fromAction(action)); + tempAbilities.add(ability); + tempActions.add(action); + } + + // Sort: toggles tab sorts enabled first, then by type, then by display name + List indices = new ArrayList<>(); + for (int i = 0; i < tempNames.size(); i++) indices.add(i); + final boolean sortTogglesFirst = (subTab == 1); + Collections.sort(indices, new Comparator() { + @Override + public int compare(Integer a, Integer b) { + if (sortTogglesFirst && playerData != null && playerData.abilityData != null) { + boolean aToggled = playerData.abilityData.isAbilityToggled(tempKeys.get(a)); + boolean bToggled = playerData.abilityData.isAbilityToggled(tempKeys.get(b)); + if (aToggled != bToggled) return aToggled ? -1 : 1; + } + // Sort by type first + Ability abilityA = tempAbilities.get(a); + Ability abilityB = tempAbilities.get(b); + String typeA = abilityA != null ? abilityA.getTypeId() : ""; + String typeB = abilityB != null ? abilityB.getTypeId() : ""; + if (typeA == null) typeA = ""; + if (typeB == null) typeB = ""; + int typeCompare = typeA.compareToIgnoreCase(typeB); + if (typeCompare != 0) return typeCompare; + // Then by display name (strip color codes for comparison) + return stripFormatting(tempNames.get(a)).compareToIgnoreCase(stripFormatting(tempNames.get(b))); + } + }); + + for (int idx : indices) { + filteredKeys.add(tempKeys.get(idx)); + filteredDisplayNames.add(tempNames.get(idx)); + filteredIcons.add(tempIcons.get(idx)); + filteredAbilities.add(tempAbilities.get(idx)); + filteredActions.add(tempActions.get(idx)); + } + + gridHoverScale = new float[filteredKeys.size()]; + Arrays.fill(gridHoverScale, 1.0f); + scrollRow = 0; + selectedIndex = -1; + } + + private String stripFormatting(String s) { + return s.replaceAll("\u00A7.", "").trim(); + } + + private void updateHotbarIcons() { + PlayerData playerData = ClientCacheHandler.playerData; + for (int i = 0; i < hbSlots; i++) { + hotbarIcons[i] = null; + if (playerData == null || playerData.hotbarData == null) continue; + AbilityHotbarData slotData = playerData.hotbarData.getSlot(i); + if (slotData == null || slotData.isEmpty()) continue; + + if (AbilityController.Instance != null) { + if (slotData.isChainKey()) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + if (chain != null) hotbarIcons[i] = AbilityIcon.fromChainedAbility(chain); + } else { + Ability ability = AbilityController.Instance.resolveAbility(slotData.abilityKey); + if (ability != null) hotbarIcons[i] = AbilityIcon.fromAbility(ability); + } + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Grid Positioning Helpers + // ═══════════════════════════════════════════════════════════════════ + + private int getGridVisibleRows() { + int usableHeight = (selBottom - selTop) - gridPad * 2; + return usableHeight / gridCellSize; + } + + private int getGridStartX() { + int panelWidth = selRight - selLeft; + int usableWidth = panelWidth - gridPad * 2; + int gridWidth = gridCols * gridCellSize; + int offsetX = (usableWidth - gridWidth) / 2; + return guiLeft + selLeft + gridPad + offsetX; + } + + private int getGridStartY() { + int panelHeight = selBottom - selTop; + int usableHeight = panelHeight - gridPad * 2; + int visibleRows = getGridVisibleRows(); + int gridHeight = visibleRows * gridCellSize; + int offsetY = (usableHeight - gridHeight) / 2; + return guiTop + selTop + gridPad + offsetY; + } + + private int getMaxScrollRow() { + int totalRows = (filteredKeys.size() + gridCols - 1) / gridCols; + return Math.max(0, totalRows - getGridVisibleRows()); + } + + // ═══════════════════════════════════════════════════════════════════ + // Drawing + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.renderEngine.bindTexture(resource); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, 252, 195); + drawTexturedModalRect(guiLeft + 252, guiTop, 188, 0, 67, 195); + super.drawScreen(mouseX, mouseY, partialTicks); + + updateHoverState(mouseX, mouseY); + updateHoverScales(); + + // Panel backgrounds + drawGradientRect(guiLeft + selLeft, guiTop + selTop, guiLeft + selRight, guiTop + selBottom, 0xC0101010, 0xC0101010); + drawGradientRect(guiLeft + infoLeft, guiTop + infoTop, guiLeft + infoRight, guiTop + infoBottom, 0xC0101010, 0xC0101010); + drawGradientRect(guiLeft + hbLeft, guiTop + hbTop, guiLeft + hbRight, guiTop + hbBottom, 0xC0101010, 0xC0101010); + + // RIGHT panel: Selection grid (with scissor clipping) + drawIconGrid(mouseX, mouseY); + + // LEFT panel: Ability information + drawInfoPanel(); + + // BOTTOM panel: Hotbar + drawHotbarSection(mouseX, mouseY); + + // Drag ghost + if (isDragging && draggedIcon != null) { + drawDragGhost(mouseX, mouseY); + } + + // Tooltip (last - renders on top) + drawTooltip(mouseX, mouseY); + } + + private void drawIconGrid(int mouseX, int mouseY) { + int visibleRows = getGridVisibleRows(); + int gridStartX = getGridStartX(); + int gridStartY = getGridStartY(); + int startIndex = scrollRow * gridCols; + + // GL Scissor to clip grid content within the selection panel + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + int scissorX = (guiLeft + selLeft) * scaleFactor; + int scissorY = mc.displayHeight - (guiTop + selBottom) * scaleFactor; + int scissorW = (selRight - selLeft) * scaleFactor; + int scissorH = (selBottom - selTop) * scaleFactor; + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(scissorX, scissorY, scissorW, scissorH); + + int maxVisibleCount = gridCols * visibleRows; + for (int vi = 0; vi < maxVisibleCount; vi++) { + int absIndex = startIndex + vi; + if (absIndex >= filteredKeys.size()) break; + + int col = vi % gridCols; + int row = vi / gridCols; + int cellX = gridStartX + col * gridCellSize; + int cellY = gridStartY + row * gridCellSize; + + boolean isHovered = (hoveredGridIndex == absIndex) && !isDragging; + boolean isSelected = (selectedIndex == absIndex); + boolean isDragSource = isDragging && dragSourceSlot == -1 && draggedKey != null + && draggedKey.equals(filteredKeys.get(absIndex)); + + // Compute toggle state early so border can reflect it + int cellToggleState = 0; + Ability cellAbility = filteredAbilities.get(absIndex); + PlayerData cellPlayerData = ClientCacheHandler.playerData; + if (cellAbility != null && cellAbility.isToggleable() && cellPlayerData != null && cellPlayerData.abilityData != null) { + cellToggleState = cellPlayerData.abilityData.getToggleState(filteredKeys.get(absIndex)); + } + + // Cell background + int bgColor; + if (isDragSource) bgColor = 0x40333333; + else if (isSelected) bgColor = 0x60505070; + else if (isHovered) bgColor = 0x60404060; + else bgColor = 0x40202030; + drawRect(cellX, cellY, cellX + gridCellSize - 1, cellY + gridCellSize - 1, bgColor); + + // Cell border + int borderColor; + if (cellToggleState > 0) borderColor = 0x7733DD55; + else if (isSelected) borderColor = 0xAA9999DD; + else if (isHovered) borderColor = 0xAA8888CC; + else borderColor = 0x40404060; + drawHorizontalLine(cellX, cellX + gridCellSize - 2, cellY, borderColor); + drawHorizontalLine(cellX, cellX + gridCellSize - 2, cellY + gridCellSize - 2, borderColor); + drawVerticalLine(cellX, cellY, cellY + gridCellSize - 2, borderColor); + drawVerticalLine(cellX + gridCellSize - 2, cellY, cellY + gridCellSize - 2, borderColor); + + GL11.glColor4f(1, 1, 1, 1); + + // Icon (state-aware for multi-state toggles) + AbilityIcon icon = filteredIcons.get(absIndex); + if (icon != null) { + float hoverScale = gridHoverScale[absIndex]; + float targetPixels = (gridCellSize - 4) * hoverScale; + float drawSize = icon.getDrawSize(); + float iconScale = targetPixels / drawSize; + + int iconCenterX = cellX + (gridCellSize - 1) / 2; + int iconCenterY = cellY + (gridCellSize - 1) / 2; + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCenterX, iconCenterY, 0); + GL11.glScalef(iconScale, iconScale, 1); + + float alpha = isDragSource ? 0.3f : 1.0f; + GL11.glColor4f(1, 1, 1, alpha); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + icon.draw(cellToggleState); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + } + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Restore GL state + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + // Scroll buttons are added in initGui() + } + + private void drawInfoPanel() { + int infoIndex = hoveredGridIndex >= 0 ? hoveredGridIndex : selectedIndex; + if (infoIndex < 0 || infoIndex >= filteredKeys.size()) return; + + // Reset scroll when ability changes + if (infoIndex != lastInfoIndex) { + infoScrollOffset = 0; + lastInfoIndex = infoIndex; + } + + FontRenderer fr = mc.fontRenderer; + int panelInnerLeft = guiLeft + infoLeft + infoPad; + int panelInnerTop = guiTop + infoTop + infoPad; + int panelInnerWidth = (infoRight - infoLeft) - infoPad * 2; + int panelHeight = infoBottom - infoTop; + + // Cached icon for detail preview + if (cachedDetailIndex != infoIndex) { + cachedDetailIcon = filteredIcons.get(infoIndex); + cachedDetailIndex = infoIndex; + } + + Ability ability = filteredAbilities.get(infoIndex); + + // Get toggle state for icon rendering and state display + int toggleState = 0; + PlayerData togglePlayerData = ClientCacheHandler.playerData; + if (ability != null && ability.isToggleable() && togglePlayerData != null && togglePlayerData.abilityData != null) { + toggleState = togglePlayerData.abilityData.getToggleState(filteredKeys.get(infoIndex)); + } + + // GL Scissor to clip info panel content + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + int scissorX = (guiLeft + infoLeft) * scaleFactor; + int scissorY = mc.displayHeight - (guiTop + infoBottom) * scaleFactor; + int scissorW = (infoRight - infoLeft) * scaleFactor; + int scissorH = panelHeight * scaleFactor; + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(scissorX, scissorY, scissorW, scissorH); + + int y = panelInnerTop - infoScrollOffset; + + // Preview icon (centered, state-aware for multi-state toggles) + if (cachedDetailIcon != null) { + float drawSize = cachedDetailIcon.getDrawSize(); + float iconScale = (float) infoIconSize / drawSize; + + int iconCX = panelInnerLeft + panelInnerWidth / 2; + int iconCY = y + infoIconSize / 2 + 4; + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCX, iconCY, 0); + GL11.glScalef(iconScale, iconScale, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, 1); + cachedDetailIcon.draw(toggleState); + GL11.glPopMatrix(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + y += infoIconSize + 12; + } + + // Ability name (centered, wrapped) + String name = filteredDisplayNames.get(infoIndex); + List nameLines = fr.listFormattedStringToWidth(name, panelInnerWidth); + for (String line : nameLines) { + int lineX = panelInnerLeft + (panelInnerWidth - fr.getStringWidth(line)) / 2; + fr.drawStringWithShadow(line, lineX, y, 0xFFFFFF); + y += fr.FONT_HEIGHT + 1; + } + y += 4; + + if (ability != null) { + // Type info + String typeId = ability.getTypeId(); + if (typeId != null && !typeId.isEmpty()) { + String translated = StatCollector.translateToLocal(typeId); + if (!translated.equals(typeId)) { + int textW = fr.getStringWidth(translated); + fr.drawStringWithShadow("\u00A77" + translated, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xAAAAAA); + y += fr.FONT_HEIGHT + 3; + } + } + + // Toggle info + if (ability.isToggleable()) { + String toggleText = "[" + StatCollector.translateToLocal("gui.toggle") + "]"; + int textW = fr.getStringWidth(toggleText); + fr.drawStringWithShadow("\u00A7a" + toggleText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FF55); + y += fr.FONT_HEIGHT + 3; + } + + // Toggle state + if (ability.isToggleable()) { + String stateText; + String prefix; + if (toggleState > 0) { + String stateLabel = ability.getToggleStateLabel(toggleState); + stateText = stateLabel != null ? stateLabel : StatCollector.translateToLocal("gui.toggle.active"); + prefix = "\u00A72"; + } else { + stateText = StatCollector.translateToLocal("gui.toggle.inactive"); + prefix = "\u00A78"; + } + int textW = fr.getStringWidth(stateText); + fr.drawStringWithShadow(prefix + stateText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, toggleState > 0 ? 0x55FF55 : 0x888888); + y += fr.FONT_HEIGHT + 3; + } + + // Cooldown info — yellow if per-ability cooldown + if (ability.getCooldownTicks() > 0) { + float seconds = ability.getCooldownTicks() / 20.0f; + String cdText = StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s"; + int textW2 = fr.getStringWidth(cdText); + boolean perAbility = ability.isPerAbilityCooldown(); + String cdColor = perAbility ? "\u00A7e" : "\u00A77"; + int cdColorInt = perAbility ? 0xFFFF55 : 0xAAAAAA; + fr.drawStringWithShadow(cdColor + cdText, panelInnerLeft + (panelInnerWidth - textW2) / 2, y, cdColorInt); + y += fr.FONT_HEIGHT + 3; + + if (perAbility) { + String perText = "[" + StatCollector.translateToLocal("ability.perAbilityCooldown") + "]"; + int ptW = fr.getStringWidth(perText); + fr.drawStringWithShadow("\u00A7e" + perText, panelInnerLeft + (panelInnerWidth - ptW) / 2, y, 0xFFFF55); + y += fr.FONT_HEIGHT + 3; + } + } + + // Damage info + float baseDamage = ability.getDisplayDamage(); + if (baseDamage > 0) { + float displayDamage = baseDamage; + if (AbilityController.Instance != null && mc.thePlayer != null) { + displayDamage = AbilityController.Instance.fireModifyProjectileDamage(ability, mc.thePlayer, baseDamage); + } + String label = ability.isDisplayDamageDPS() + ? StatCollector.translateToLocal("gui.dps") + : StatCollector.translateToLocal("ability.preview.damage"); + String dmgText = label + ": " + String.format("%.1f", displayDamage); + int textW = fr.getStringWidth(dmgText); + fr.drawStringWithShadow("\u00A7c" + dmgText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xFF5555); + y += fr.FONT_HEIGHT + 3; + } + + // Barrier health + float baseHealth = ability.getDisplayBarrierHealth(); + if (baseHealth > 0) { + float displayHealth = baseHealth; + if (AbilityController.Instance != null && mc.thePlayer != null) { + displayHealth = AbilityController.Instance.fireModifyBarrierHealth(ability, mc.thePlayer, baseHealth); + } + String healthText = StatCollector.translateToLocal("ability.preview.health") + ": " + String.format("%.0f", displayHealth); + int textW = fr.getStringWidth(healthText); + fr.drawStringWithShadow("\u00A7a" + healthText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FF55); + y += fr.FONT_HEIGHT + 3; + } + + // Barrier reflection + if (ability.isDisplayReflect()) { + String reflectText = StatCollector.translateToLocal("ability.reflect") + ": " + String.format("%.0f%%", ability.getDisplayReflectStrength()); + int textW = fr.getStringWidth(reflectText); + fr.drawStringWithShadow("\u00A7d" + reflectText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xFF55FF); + y += fr.FONT_HEIGHT + 3; + } + + // Barrier absorbing + if (ability.isDisplayAbsorbing()) { + String absorbText = "[" + StatCollector.translateToLocal("ability.absorbing") + "]"; + int textW = fr.getStringWidth(absorbText); + fr.drawStringWithShadow("\u00A7b" + absorbText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FFFF); + y += fr.FONT_HEIGHT + 3; + } + + // Magic info + if (ability.hasMagic()) { + y += 2; + MagicData magicData = ability.getMagicData(); + if (magicData.isEmpty()) { + String magicText = StatCollector.translateToLocal("ability.preview.magic.casters"); + int textW = fr.getStringWidth(magicText); + fr.drawStringWithShadow("\u00A79" + magicText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x5555FF); + y += fr.FONT_HEIGHT + 3; + } else { + for (Map.Entry entry : magicData.getMagics().entrySet()) { + Magic magic = MagicController.getInstance() != null + ? MagicController.getInstance().getMagic(entry.getKey()) : null; + String magicName = magic != null ? magic.getDisplayName() : "Magic #" + entry.getKey(); + String splitText = magicName + ": " + Math.round(entry.getValue().split * 100) + "%"; + int textW = fr.getStringWidth(splitText); + fr.drawStringWithShadow("\u00A79" + splitText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x5555FF); + y += fr.FONT_HEIGHT + 1; + } + y += 2; + } + } + } + + // Track content height for scroll limits + infoContentHeight = (y + infoScrollOffset) - panelInnerTop + infoPad * 2; + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Scroll indicator + if (infoContentHeight > panelHeight) { + int maxScroll = Math.max(1, infoContentHeight - panelHeight); + if (infoScrollOffset > maxScroll) infoScrollOffset = maxScroll; + float scrollPercent = (float) infoScrollOffset / maxScroll; + int barHeight = panelHeight - 4; + int thumbHeight = Math.max(8, barHeight * panelHeight / infoContentHeight); + int thumbY = guiTop + infoTop + 2 + (int) ((barHeight - thumbHeight) * scrollPercent); + int barX = guiLeft + infoRight - 3; + drawRect(barX, guiTop + infoTop + 2, barX + 2, guiTop + infoTop + 2 + barHeight, 0x40FFFFFF); + drawRect(barX, thumbY, barX + 2, thumbY + thumbHeight, 0xA0FFFFFF); + } + } + + private void drawHotbarSection(int mouseX, int mouseY) { + FontRenderer fr = mc.fontRenderer; + + // Get selected ability key for yellow border + PlayerData selPlayerData = ClientCacheHandler.playerData; + String selectedKey = null; + if (selPlayerData != null && selPlayerData.abilityData != null) { + selectedKey = selPlayerData.abilityData.getSelectedAbilityKey(); + } + + // Hotbar slots centered within the panel + int panelWidth = hbRight - hbLeft; + int panelHeight = hbBottom - hbTop; + int totalSlotsWidth = hbSlots * (hbSlotSize + hbSlotGap) - hbSlotGap; + int hotbarStartX = guiLeft + hbLeft + (panelWidth - totalSlotsWidth) / 2; + int hotbarStartY = guiTop + hbTop + (panelHeight - hbSlotSize) / 2; + + for (int i = 0; i < hbSlots; i++) { + int sx = hotbarStartX + i * (hbSlotSize + hbSlotGap); + int sy = hotbarStartY; + + boolean isHovered = (hoveredSlotIndex == i); + boolean isDragHover = isDragging && isHovered; + + // Check if this slot's ability is the currently selected one + boolean isSelectedSlot = false; + if (selectedKey != null && !selectedKey.isEmpty() && selPlayerData.hotbarData != null) { + AbilityHotbarData slotData = selPlayerData.hotbarData.getSlot(i); + if (slotData != null && !slotData.isEmpty() && selectedKey.equals(slotData.abilityKey)) { + isSelectedSlot = true; + } + } + + // Slot background + int bgColor = isDragHover ? 0x80606030 : (isSelectedSlot ? 0x60505020 : (isHovered ? 0x60505050 : 0x50303030)); + drawRect(sx, sy, sx + hbSlotSize, sy + hbSlotSize, bgColor); + + // Slot border - yellow for selected, drag color, hover color, or default + int borderColor; + if (isDragHover) borderColor = 0xFFCCCC44; + else if (isSelectedSlot) borderColor = 0xFFCCCC00; + else if (isHovered) borderColor = 0xAA888888; + else borderColor = 0x60505050; + drawHorizontalLine(sx, sx + hbSlotSize - 1, sy, borderColor); + drawHorizontalLine(sx, sx + hbSlotSize - 1, sy + hbSlotSize - 1, borderColor); + drawVerticalLine(sx, sy, sy + hbSlotSize - 1, borderColor); + drawVerticalLine(sx + hbSlotSize - 1, sy, sy + hbSlotSize - 1, borderColor); + + GL11.glColor4f(1, 1, 1, 1); + + // Icon or slot number + AbilityIcon icon = hotbarIcons[i]; + boolean isSourceSlot = isDragging && dragSourceSlot == i; + + if (icon != null && !isSourceSlot) { + int iconCX = sx + hbSlotSize / 2; + int iconCY = sy + hbSlotSize / 2; + float targetPixels = hbSlotSize - 4; + float drawSize = icon.getDrawSize(); + float s = targetPixels / drawSize; + + // Compute toggle state for this hotbar slot's ability + int hbToggleState = 0; + if (selPlayerData != null && selPlayerData.abilityData != null && selPlayerData.hotbarData != null) { + AbilityHotbarData slotData = selPlayerData.hotbarData.getSlot(i); + if (slotData != null && !slotData.isEmpty()) { + hbToggleState = selPlayerData.abilityData.getToggleState(slotData.abilityKey); + } + } + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCX, iconCY, 0); + GL11.glScalef(s, s, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + icon.draw(hbToggleState); + GL11.glPopMatrix(); + GL11.glColor4f(1, 1, 1, 1); + } else { + String slotLabel = String.valueOf(i + 1); + int labelColor = isSourceSlot ? 0x333333 : 0x666666; + int lx = sx + (hbSlotSize - fr.getStringWidth(slotLabel)) / 2; + int ly = sy + (hbSlotSize - fr.FONT_HEIGHT) / 2 + 1; + fr.drawString(slotLabel, lx, ly, labelColor); + } + } + + // Restore GL + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawDragGhost(int mouseX, int mouseY) { + if (draggedIcon == null) return; + + float targetPixels = gridCellSize; + float drawSize = draggedIcon.getDrawSize(); + float ghostScale = targetPixels / drawSize; + + GL11.glPushMatrix(); + GL11.glTranslatef(mouseX, mouseY, 100); + GL11.glScalef(ghostScale, ghostScale, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, 0.8f); + draggedIcon.draw(0); + GL11.glColor4f(1, 1, 1, 1); + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawTooltip(int mouseX, int mouseY) { + if (isDragging) return; + + if (hoveredGridIndex >= 0 && hoveredGridIndex < filteredDisplayNames.size()) { + List lines = new ArrayList<>(); + lines.add(filteredDisplayNames.get(hoveredGridIndex)); + + Ability ability = filteredAbilities.get(hoveredGridIndex); + if (ability != null) { + String typeId = ability.getTypeId(); + if (typeId != null && !typeId.isEmpty()) { + String translated = StatCollector.translateToLocal(typeId); + if (!translated.equals(typeId)) { + lines.add("\u00A77" + translated); + } + } + if (ability.isToggleable()) { + lines.add("\u00A7a[" + StatCollector.translateToLocal("gui.toggle") + "]"); + } + if (ability.getCooldownTicks() > 0) { + float seconds = ability.getCooldownTicks() / 20.0f; + lines.add("\u00A77" + StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s"); + } + } + + drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); + GL11.glDisable(GL11.GL_LIGHTING); + } + + if (hoveredSlotIndex >= 0 && hoveredSlotIndex < hbSlots) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slotData = playerData.hotbarData.getSlot(hoveredSlotIndex); + if (slotData != null && !slotData.isEmpty()) { + String name = getHotbarSlotDisplayName(slotData); + if (name != null) { + List lines = new ArrayList<>(); + lines.add(name); + lines.add("\u00A78Right-click to remove"); + drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); + GL11.glDisable(GL11.GL_LIGHTING); + } + } + } + } + } + + private String getHotbarSlotDisplayName(AbilityHotbarData slotData) { + if (AbilityController.Instance == null) return null; + if (slotData.isChainKey()) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + return chain != null ? chain.getDisplayName() : null; + } + Ability ability = AbilityController.Instance.resolveAbility(slotData.abilityKey); + return ability != null ? ability.getDisplayName() : null; + } + + // ═══════════════════════════════════════════════════════════════════ + // Hover & Animation + // ═══════════════════════════════════════════════════════════════════ + + private void updateHoverState(int mouseX, int mouseY) { + hoveredGridIndex = -1; + hoveredSlotIndex = -1; + + // Grid hit test (RIGHT panel - selection) + int visibleRows = getGridVisibleRows(); + int gridStartX = getGridStartX(); + int gridStartY = getGridStartY(); + int startIndex = scrollRow * gridCols; + + if (mouseX >= guiLeft + selLeft && mouseX < guiLeft + selRight + && mouseY >= guiTop + selTop && mouseY < guiTop + selBottom) { + for (int vi = 0; vi < gridCols * visibleRows; vi++) { + int absIndex = startIndex + vi; + if (absIndex >= filteredKeys.size()) break; + + int col = vi % gridCols; + int row = vi / gridCols; + int cellX = gridStartX + col * gridCellSize; + int cellY = gridStartY + row * gridCellSize; + + if (mouseX >= cellX && mouseX < cellX + gridCellSize - 1 + && mouseY >= cellY && mouseY < cellY + gridCellSize - 1) { + hoveredGridIndex = absIndex; + break; + } + } + } + + // Hotbar hit test + int panelWidth = hbRight - hbLeft; + int panelHeight = hbBottom - hbTop; + int totalSlotsWidth = hbSlots * (hbSlotSize + hbSlotGap) - hbSlotGap; + int hotbarStartX = guiLeft + hbLeft + (panelWidth - totalSlotsWidth) / 2; + int hotbarStartY = guiTop + hbTop + (panelHeight - hbSlotSize) / 2; + + for (int i = 0; i < hbSlots; i++) { + int sx = hotbarStartX + i * (hbSlotSize + hbSlotGap); + if (mouseX >= sx && mouseX < sx + hbSlotSize + && mouseY >= hotbarStartY && mouseY < hotbarStartY + hbSlotSize) { + hoveredSlotIndex = i; + break; + } + } + } + + private void updateHoverScales() { + if (gridHoverScale == null) return; + for (int i = 0; i < gridHoverScale.length; i++) { + float target = (i == hoveredGridIndex && !isDragging) ? 1.12f : 1.0f; + gridHoverScale[i] += (target - gridHoverScale[i]) * 0.3f; + if (Math.abs(gridHoverScale[i] - target) < 0.005f) { + gridHoverScale[i] = target; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Mouse Handlers + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void mouseClicked(int mouseX, int mouseY, int button) { + if (hasSubGui()) { + super.mouseClicked(mouseX, mouseY, button); + return; + } + + // Right-click on hotbar slot -> clear + if (button == 1 && hoveredSlotIndex >= 0) { + saveHotbarSlot(hoveredSlotIndex, ""); + updateHotbarIcons(); + return; + } + + // Left-click: start potential drag or select + if (button == 0) { + if (hoveredGridIndex >= 0 && hoveredGridIndex < filteredKeys.size()) { + // Toggle double-tap detection on toggle tab + if (subTab == 1) { + long now = System.currentTimeMillis(); + if (lastToggleClickIndex == hoveredGridIndex && (now - lastToggleClickTime) < 400) { + String key = filteredKeys.get(hoveredGridIndex); + Ability ability = filteredAbilities.get(hoveredGridIndex); + if (ability != null && ability.isToggleable()) { + PacketHandler.Instance.sendToServer(new AbilityTogglePacket(key)); + lastToggleClickIndex = -1; + lastToggleClickTime = 0; + // Rebuild list after a short delay to reflect new state + // For now just select and return - the list rebuilds on next initGui + selectedIndex = hoveredGridIndex; + cachedDetailIcon = null; + cachedDetailIndex = -1; + return; + } + } + lastToggleClickIndex = hoveredGridIndex; + lastToggleClickTime = now; + } + + selectedIndex = hoveredGridIndex; + cachedDetailIcon = null; + cachedDetailIndex = -1; + dragPending = true; + draggedKey = filteredKeys.get(hoveredGridIndex); + draggedIcon = filteredIcons.get(hoveredGridIndex); + dragSourceSlot = -1; + dragStartX = mouseX; + dragStartY = mouseY; + return; + } + + if (hoveredSlotIndex >= 0 && hotbarIcons[hoveredSlotIndex] != null) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slotData = playerData.hotbarData.getSlot(hoveredSlotIndex); + if (slotData != null && !slotData.isEmpty()) { + dragPending = true; + draggedKey = slotData.abilityKey; + draggedIcon = hotbarIcons[hoveredSlotIndex]; + dragSourceSlot = hoveredSlotIndex; + dragStartX = mouseX; + dragStartY = mouseY; + return; + } + } + } + } + + super.mouseClicked(mouseX, mouseY, button); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int button, long timeSinceLastClick) { + if (dragPending && !isDragging) { + int dx = mouseX - dragStartX; + int dy = mouseY - dragStartY; + if (dx * dx + dy * dy > dragThreshold * dragThreshold) { + isDragging = true; + } + } + if (isDragging) { + dragMouseX = mouseX; + dragMouseY = mouseY; + } + + super.mouseClickMove(mouseX, mouseY, button, timeSinceLastClick); + } + + @Override + protected void mouseMovedOrUp(int mouseX, int mouseY, int state) { + if (isDragging && draggedKey != null) { + updateHoverState(mouseX, mouseY); + + if (hoveredSlotIndex >= 0) { + if (dragSourceSlot >= 0) { + swapHotbarSlots(dragSourceSlot, hoveredSlotIndex); + } else { + saveHotbarSlot(hoveredSlotIndex, draggedKey); + } + updateHotbarIcons(); + } else if (dragSourceSlot >= 0 && hoveredGridIndex >= 0) { + saveHotbarSlot(dragSourceSlot, ""); + updateHotbarIcons(); + } + } + + isDragging = false; + dragPending = false; + draggedKey = null; + draggedIcon = null; + dragSourceSlot = -1; + + super.mouseMovedOrUp(mouseX, mouseY, state); + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + + int wheel = Mouse.getEventDWheel(); + if (wheel != 0) { + int mouseX = Mouse.getEventX() * width / mc.displayWidth; + int mouseY = height - Mouse.getEventY() * height / mc.displayHeight - 1; + + if (mouseX >= guiLeft + infoLeft && mouseX < guiLeft + infoRight + && mouseY >= guiTop + infoTop && mouseY < guiTop + infoBottom) { + // Info panel scroll + int panelHeight = infoBottom - infoTop; + int maxInfoScroll = Math.max(0, infoContentHeight - panelHeight); + if (wheel > 0) { + infoScrollOffset = Math.max(0, infoScrollOffset - 10); + } else { + infoScrollOffset = Math.min(maxInfoScroll, infoScrollOffset + 10); + } + } else { + int maxScroll = getMaxScrollRow(); + if (wheel > 0) { + scrollRow = Math.max(0, scrollRow - 1); + } else { + scrollRow = Math.min(maxScroll, scrollRow + 1); + } + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Actions & Network + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void actionPerformed(GuiButton btn) { + if (btn instanceof AbstractTab) return; + + if (btn.id <= -100 && btn.id > -200) { + super.actionPerformed(btn); + return; + } + + if (btn.id == BTN_TAB_ABILITIES) { + subTab = 0; + initGui(); + return; + } + if (btn.id == BTN_TAB_TOGGLES) { + subTab = 1; + initGui(); + return; + } + if (btn.id == BTN_SCROLL_LEFT) { + scrollRow = Math.max(0, scrollRow - 1); + initGui(); + return; + } + if (btn.id == BTN_SCROLL_RIGHT) { + scrollRow = Math.min(getMaxScrollRow(), scrollRow + 1); + initGui(); + return; + } + } + + private void saveHotbarSlot(int slotIndex, String abilityKey) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slot = playerData.hotbarData.getSlot(slotIndex); + if (slot != null) { + slot.abilityKey = abilityKey; + } + } + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagCompound slotTag = new NBTTagCompound(); + slotTag.setInteger("slot", slotIndex); + slotTag.setString("abilityKey", abilityKey != null ? abilityKey : ""); + compound.setTag("AbilityHotbar" + slotIndex, slotTag); + PacketHandler.Instance.sendToServer(new AbilityHotbarSavePacket(slotIndex, compound)); + } + + private void swapHotbarSlots(int fromSlot, int toSlot) { + if (fromSlot == toSlot) return; + + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.hotbarData == null) return; + + AbilityHotbarData fromData = playerData.hotbarData.getSlot(fromSlot); + AbilityHotbarData toData = playerData.hotbarData.getSlot(toSlot); + if (fromData == null || toData == null) return; + + String fromKey = fromData.abilityKey; + String toKey = toData.abilityKey; + + saveHotbarSlot(fromSlot, toKey != null ? toKey : ""); + saveHotbarSlot(toSlot, fromKey != null ? fromKey : ""); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + // Send selection sync if changed + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + String currentKey = playerData.abilityData.getSelectedAbilityKey(); + boolean changed = (initialSelectedKey == null && currentKey != null && !currentKey.isEmpty()) + || (initialSelectedKey != null && !initialSelectedKey.equals(currentKey)); + if (changed) { + PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(currentKey != null ? currentKey : "")); + } + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (i == 1 || isInventoryKey(i)) { + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java index f27913d89..3e4b9706a 100644 --- a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java @@ -73,6 +73,14 @@ public class GuiCNPCInventory extends GuiNPCInterface { addSideButton(profileButton); } + y += 21; + GuiMenuSideButton abilitiesButton = new GuiMenuSideButton(-105, guiLeft + xSize + 37, this.guiTop + y, 22, 22, ""); + abilitiesButton.rightSided = true; + abilitiesButton.active = activeTab == -105; + abilitiesButton.renderIconPosX = 80; + abilitiesButton.renderResource = specialIcons; + addSideButton(abilitiesButton); + y += 21; GuiMenuSideButton clientButton = new GuiMenuSideButton(-103, guiLeft + xSize + 37, this.guiTop + y, 22, 22, ""); clientButton.rightSided = true; @@ -154,6 +162,10 @@ public class GuiCNPCInventory extends GuiNPCInterface { activeTab = -104; mc.displayGuiScreen(new GuiProfiles()); } + if (guibutton.id == -105 && activeTab != -105) { + activeTab = -105; + mc.displayGuiScreen(new GuiAbilities()); + } } } diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiProfiles.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiProfiles.java index f9e627fe7..56777ca6f 100644 --- a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiProfiles.java +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiProfiles.java @@ -429,6 +429,9 @@ public class GuiProfiles extends GuiCNPCInventory implements ISubGuiListener, IC } private boolean isMouseOverScrollbar(int mouseX, int mouseY) { + if (maxScrollY <= 0) + return false; + int scrollbarX = guiLeft + xSize + 30; int scrollbarY = guiTop + 27; int scrollbarHeight = ySize - 35; diff --git a/src/main/java/noppes/npcs/client/gui/roles/GuiNpcSpawner.java b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcSpawner.java index d57dd417c..5c6140d8b 100644 --- a/src/main/java/noppes/npcs/client/gui/roles/GuiNpcSpawner.java +++ b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcSpawner.java @@ -184,8 +184,13 @@ public class GuiNpcSpawner extends GuiNPCInterface2 implements ITextfieldListene GuiNpcMobSpawnerSelector selector = (GuiNpcMobSpawnerSelector) gui; if (selector.isServer) { String selected = selector.getSelected(); - if (selected != null) - PacketClient.sendClient(new JobSpawnerAddPacket(selector.isServer, selected, selector.activeTab, slot)); + if (selected != null) { + if (selector.activeFolder != null) { + PacketClient.sendClient(new JobSpawnerAddPacket(selector.isServer, selected, selector.activeFolder, slot)); + } else { + PacketClient.sendClient(new JobSpawnerAddPacket(selector.isServer, selected, selector.activeTab, slot)); + } + } } else { NBTTagCompound compound = selector.getCompound(); if (compound != null) { diff --git a/src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java index 7b54518e3..1e5aab8d1 100644 --- a/src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java +++ b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java @@ -21,6 +21,7 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex private final ResourceLocation slot = new ResourceLocation("customnpcs", "textures/gui/slot.png"); private RoleTrader role; + private boolean marketRelinked = false; // Currency cost textfield IDs start at 100 (100-117 for slots 0-17) private static final int CURRENCY_FIELD_ID_START = 100; @@ -116,8 +117,14 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex @Override public void save() { - PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, false)); + // Linking to a different market already replaced the server's role with that market's + // data. Pushing this GUI's pre-link state back would overwrite the market being linked to. + if (marketRelinked) + return; + + // Save the role first so the market is written from the edited data, not the stale data. PacketClient.sendClient(new RoleSavePacket(role.writeToNBT(new NBTTagCompound()))); + PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, false)); } @Override @@ -129,6 +136,7 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex String name = guiNpcTextField.getText(); if (!name.equalsIgnoreCase(role.marketName)) { role.marketName = name; + marketRelinked = true; PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, true)); } return; diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiJaninoScript.java b/src/main/java/noppes/npcs/client/gui/script/GuiJaninoScript.java deleted file mode 100644 index 9fb601162..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiJaninoScript.java +++ /dev/null @@ -1,429 +0,0 @@ -package noppes.npcs.client.gui.script; - - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiYesNo; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.util.StatCollector; -import noppes.npcs.NoppesStringUtils; -import noppes.npcs.client.gui.util.GuiCustomScroll; -import noppes.npcs.client.gui.util.GuiMenuTopButton; -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.GuiNpcTextArea; -import noppes.npcs.client.gui.util.GuiScriptTextArea; -import noppes.npcs.client.gui.util.ICustomScrollListener; -import noppes.npcs.client.gui.util.ISubGuiListener; -import noppes.npcs.client.gui.util.ITextChangeListener; -import noppes.npcs.client.gui.util.SubGuiInterface; -import noppes.npcs.controllers.ScriptController; -import noppes.npcs.janino.JaninoScript; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback, ITextChangeListener, ICustomScrollListener, ISubGuiListener { - - private GuiScriptTextArea textArea; - private int activeTab = 0; - public List allExternalScripts = new ArrayList<>(); - private final int scriptLimit = 1; - public String previousHookClicked = ""; - - // GUI display list - List hooklist = new ArrayList<>(); - - // Map from display name (with parameters if overloaded) to Method - Map hookMap = new HashMap<>(); - - public final GuiScreen parent; - private final JaninoScript container; - - public Runnable saveFunction; - - public GuiJaninoScript(GuiScreen parent, JaninoScript handler) { - this.drawDefaultBackground = true; - this.closeOnEsc = true; - this.xSize = 420; - this.setBackground("menubg.png"); - - this.parent = parent; - this.container = handler; - - createHookList(); - - String lang = handler.getLanguage(); - allExternalScripts.addAll(ScriptController.Instance.getScripts(lang)); - } - - public GuiJaninoScript setSave(Runnable run) { - saveFunction = run; - return this; - } - - public void createHookList() { - // Group all declared methods of the handler's type by their method name - Map> grouped = Arrays.stream(container.type.getDeclaredMethods()) - .collect(Collectors.groupingBy(Method::getName)); - - for (Map.Entry> entry : grouped.entrySet()) { - List methods = entry.getValue(); - - // Sort overloads by number of parameters (ascending) - // This ensures the simplest overload comes first - methods.sort(Comparator.comparingInt(Method::getParameterCount)); - boolean first = true; - - - for (Method m : methods) { - if (Modifier.isFinal(m.getModifiers())) - continue; //skip finals - - String displayName = first ? m.getName() : - m.getName() + "(" + Arrays.stream(m.getParameterTypes()) - .map(Class::getSimpleName) - .collect(Collectors.joining(", ")) + ")"; - - - hooklist.add(displayName); - hookMap.put(displayName, m); - first = false; - } - } - } - - public void initGui() { - this.ySize = (int) ((double) this.xSize * 0.56); - if ((double) this.ySize > (double) this.height * 0.95) { - this.ySize = (int) ((double) this.height * 0.95); - this.xSize = (int) ((double) this.ySize / 0.56); - } - - this.bgScale = (float) this.xSize / 400.0F; - super.initGui(); - this.guiTop += 10; - int yoffset = (int) ((double) this.ySize * 0.02); - GuiMenuTopButton top; - addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 2, guiTop - 17, "X")); - this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings")); - int topXoffset = 0; - int topYoffset = 0; - - - if (this.container != null) { - this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script")); - } else { - this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+")); - } - - top = this.getTopButton(this.activeTab); - if (top == null) { - this.activeTab = 0; - top = this.getTopButton(0); - } - - top.active = true; - if (this.activeTab == 1) { - GuiCustomScroll hooks = new GuiCustomScroll(this, 1); - hooks.allowUserInput = false; - hooks.setSize(108, 198); - hooks.guiLeft = this.guiLeft - 110; - hooks.guiTop = this.guiTop + 14; - - hooks.setUnsortedList(this.hooklist); - this.addScroll(hooks); - GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5); - hookLabel.color = 11184810; - this.addLabel(hookLabel); - JaninoScript container = this.container; - if (textArea == null) - textArea = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script); - else - textArea.init(this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script); - textArea.enableCodeHighlighting(); - textArea.setListener(this); - this.closeOnEsc(textArea::closeOnEsc); - this.addTextField(textArea); - - int left1 = this.guiLeft + this.xSize - 104; - this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear")); - this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste")); - this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy")); - this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove")); - - this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript")); - // this.getButton(107).enabled = false; - - GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable(); - scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2); - scroll.guiLeft = left1; - scroll.guiTop = this.guiTop + 88 + yoffset; - if (container != null) - scroll.setList(container.externalScripts); - - this.addScroll(scroll); - } else { - GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText()); - var8.enabled = false; - this.addTextField(var8); - int var9 = this.guiLeft + this.xSize - 150; - this.addButton(new GuiNpcButton(100, var9, this.guiTop + 125, 60, 20, "gui.copy")); - this.addButton(new GuiNpcButton(102, var9, this.guiTop + 146, 60, 20, "gui.clear")); - this.addLabel(new GuiNpcLabel(1, "script.language", var9, this.guiTop + 15)); - String containerLang = container.getLanguage(); - this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, new String[]{containerLang.equals("Java") ? "Janino (JVM 8)" : containerLang}, - this.getLanguageIndex())); - // this.getButton(103).enabled = !this.languages.isEmpty(); - this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36)); - // Note: GuiJaninoScript is deprecated; enabled button disabled - this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20, new String[]{"gui.no", "gui.yes"}, 0)); - - this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website")); - this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum")); - this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc")); - this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc")); - } - - this.xSize = 420; - this.ySize = 256; - } - - public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { - String hook = scroll.getSelected(); - if (this.previousHookClicked.equals(hook)) { - String addString = ""; - if (!this.getTextField(2) - .getText() - .isEmpty()) { - addString = addString + "\n"; - } - - addString = addString + generateMethodStub(hookMap.get(hook)); - this.getTextField(2) - .setText(this.getTextField(2) - .getText() + addString); - this.previousHookClicked = ""; - } else { - this.previousHookClicked = hook; - } - } - - public void confirmClicked(boolean flag, int i) { - if (flag) { - if (i == 0) - this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus"); - else if (i == 1) - this.openLink("https://kamkeel.github.io/CustomNPC-Plus/"); - else if (i == 2) - this.openLink("https://kamkeel.github.io/CustomNPC-Plus/"); - else if (i == 3) - this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html"); - - if (i == 10) { //Remove - this.container.setScript(""); - this.activeTab = 0; - } else if (i == 101) { //Paste - this.getTextField(2) - .setText(NoppesStringUtils.getClipboardContents()); - this.setScript(); - } else if (i == 102) { //Clear - if (this.activeTab == 1) - container.script = ""; - else - this.container.clearConsole(); - - this.initGui(); - } - } - - this.displayGuiScreen(this); - } - - protected void actionPerformed(GuiButton guibutton) { - if (guibutton.id == -1) { - close(); - return; - } - - if (guibutton.id == 0) { - this.setScript(); - this.activeTab = 0; - this.initGui(); - container.ensureCompiled(); - } - - if (guibutton.id == this.scriptLimit) { - // if (container.container == null) - //this.container.container = new ScriptContainer(this.container); - // else - // this.setScript(); - this.activeTab = 1; - this.initGui(); - } - - if (guibutton.id == 109) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true)); - } else if (guibutton.id == 110) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true)); - } else if (guibutton.id == 111) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true)); - } else if (guibutton.id == 112) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true)); - } - - GuiYesNo confirmScreen; - - //Copy - if (guibutton.id == 100) { - NoppesStringUtils.setClipboardContents(this.getTextField(2) - .getText()); - } - //Paste - else if (guibutton.id == 101) { - GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101); - this.displayGuiScreen(guiyesno); - } - //Clear - else if (guibutton.id == 102) { - confirmScreen = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102); - this.displayGuiScreen(confirmScreen); - } - //Enable - else if (guibutton.id == 104) { - // Deprecated GUI - enabled is now per-handler, not per-unit - } - //Remove - else if (guibutton.id == 105) { - confirmScreen = new GuiYesNo(this, "", guibutton.displayString, 10); - this.displayGuiScreen(confirmScreen); - } - //Load Script - else if (guibutton.id == 107) { - setSubGui(new SubGuiSelectList(allExternalScripts, container.externalScripts, "All Scripts", "Selected Scripts")); - } - } - - public void subGuiClosed(SubGuiInterface sub) { - if (sub instanceof SubGuiSelectList) - container.setExternalScripts(((SubGuiSelectList) sub).selected); - - } - - /** - * Generates a stub string for a given Method. - */ - public static String generateMethodStub(Method method) { - String mods = java.lang.reflect.Modifier.toString(method.getModifiers()); - if (!mods.isEmpty()) - mods += " "; - - String returnTypeStr = method.getReturnType() - .getSimpleName(); - String name = method.getName(); - - Map typeCount = new HashMap<>(); - String params = Arrays.stream(method.getParameters()) - .map(p -> { - String typeName = p.getType() - .getSimpleName(); - String baseName = Character.toLowerCase(typeName.charAt(0)) + typeName.substring(1); - - int count = typeCount.getOrDefault(baseName, 0) + 1; - typeCount.put(baseName, count); - - // append number if same type of arg exists - String paramName = count == 1 ? baseName : baseName + (count - 1); - - return typeName + " " + paramName; - }) - .collect(Collectors.joining(", ")); - - String body; - Class returnType = method.getReturnType(); - if (returnType == void.class) - body = ""; - else if (returnType.isPrimitive()) { - if (returnType == boolean.class) - body = " return false;"; - else if (returnType == char.class) - body = " return '\\0';"; - else - body = " return 0;"; - } else { - body = " return null;"; - } - - return String.format("%s%s %s(%s) {\n%s\n}\n", mods, returnTypeStr, name, params, body); - } - - private String getConsoleText() { - Map map = this.container.getConsole(); - StringBuilder builder = new StringBuilder(); - Iterator var3 = map.entrySet() - .iterator(); - - while (var3.hasNext()) { - Map.Entry entry = (Map.Entry) var3.next(); - builder.insert(0, new Date(entry.getKey()) + entry.getValue() + "\n"); - } - - return builder.toString(); - } - - private int getLanguageIndex() { - return 0; - } - - private void setScript() { - if (this.activeTab == 1) { - String text = this.getTextField(2) - .getText(); - text = text.replace("\r\n", "\n"); - text = text.replace("\r", "\n"); - container.setScript(text); - } - } - - public void save() { - if (saveFunction != null) - saveFunction.run(); - else if (parent instanceof GuiNPCInterface) - ((GuiNPCInterface) parent).save(); - } - - public void textUpdate(String text) { -// container.setScript(text); - } - - public static GuiJaninoScript create(GuiScreen parent, JaninoScript script, int width, int height) { - GuiJaninoScript gui = new GuiJaninoScript(parent, script); - gui.setWorldAndResolution(Minecraft.getMinecraft(), width, height); - Minecraft.getMinecraft().currentScreen = gui; - gui.initGui(); - return gui; - } - - - @Override - public void close() { - this.save(); - this.setScript(); - container.ensureCompiled(); - parent.setWorldAndResolution(mc, width, height); - parent.initGui(); - mc.currentScreen = parent; - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptGlobal.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptGlobal.java index 52ab86b24..88770f1e0 100644 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptGlobal.java +++ b/src/main/java/noppes/npcs/client/gui/script/GuiScriptGlobal.java @@ -16,7 +16,7 @@ import org.lwjgl.opengl.GL11; import java.util.HashMap; public class GuiScriptGlobal extends GuiNPCInterface implements IGuiData { - private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/smallbg.png"); + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/menubg.png"); private HashMap> scriptGuiClasses = new HashMap<>(); public GuiScriptGlobal() { diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptInterface.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptInterface.java index 82012429f..0b7829ebd 100644 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptInterface.java +++ b/src/main/java/noppes/npcs/client/gui/script/GuiScriptInterface.java @@ -11,7 +11,10 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.util.StatCollector; import noppes.npcs.NoppesStringUtils; import noppes.npcs.client.NoppesUtil; +import noppes.npcs.controllers.APIRegistry; import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.SubGuiAPISelect; +import noppes.npcs.client.gui.util.SubGuiConfirmLink; import noppes.npcs.client.gui.util.GuiMenuTopButton; import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.GuiNpcButton; @@ -25,6 +28,7 @@ import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.IJTextAreaListener; import noppes.npcs.client.gui.util.ITextChangeListener; import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; @@ -32,15 +36,11 @@ import noppes.npcs.controllers.data.ForgeDataScript; import noppes.npcs.controllers.data.IScriptHandler; import noppes.npcs.controllers.data.IScriptHandlerPacket; import noppes.npcs.controllers.data.IScriptUnit; +import noppes.npcs.janino.JaninoScript; import noppes.npcs.scripted.item.ScriptCustomItem; import org.lwjgl.opengl.Display; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener { @@ -50,6 +50,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb protected int scriptLimit = 1; public List hookList = new ArrayList(); protected boolean loaded = false; + protected boolean serverDataReceived = false; protected Map textAreas = new HashMap<>(); protected GuiScreen parent; @@ -104,6 +105,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.drawDefaultBackground = true; this.closeOnEsc = true; this.xSize = 420; + this.isPannableGUI = true; this.setBackground("menubg.png"); } @@ -119,9 +121,17 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb // Initialize hooks from handler gui.hookList = new ArrayList<>(handler.getHooks()); + JSTypeRegistry registry = JSTypeRegistry.getInstance(); + if (!registry.isInitialized()) { + registry.initializeFromResources(); + } + registry.syncHooksFromScriptHookControllerIfNeeded(); + // Request data from server if (handler instanceof IScriptHandlerPacket) ((IScriptHandlerPacket) handler).requestData(); + else + gui.serverDataReceived = true; // No server data to wait for return gui; } @@ -138,6 +148,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb public void initGui() { // ==================== BASE LAYOUT CALCULATION ==================== + isPanning = false; this.ySize = (int) ((double) this.xSize * 0.56D); if ((double) this.ySize > (double) this.height * 0.95D) { this.ySize = (int) ((double) this.height * 0.95D); @@ -277,6 +288,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb // Set the script context for context-aware hook autocomplete activeArea.setScriptContext(getScriptContext()); + activeArea.enableCodeHighlighting(); + + updateScriptDocumentImports(activeArea, container); // Setup fullscreen key binding GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> { @@ -300,13 +314,24 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy")); this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove")); - // Language toggle button (only if handler supports Janino and there is more than one option) - if (handler.supportsJanino() && getLanguageOptions().size() > 1 && container != null) { - this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20, container.getLanguage())); + // Per-tab language button — cycles through all available languages + List langOptions = getLanguageOptions(); + if (langOptions.size() > 1 && container != null) { + int langIdx = getContainerLanguageIndex(langOptions, container); + this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20, + langOptions.toArray(new String[0]), langIdx)); } this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript")); + // Disable all buttons until server data arrives + if (!serverDataReceived) { + for (int btnId : new int[]{100, 101, 102, 105, 107, 113}) { + GuiNpcButton btn = getButton(btnId); + if (btn != null) btn.enabled = false; + } + } + GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable(); scroll.setSize(100, (int) ((double) this.ySize * 0.54D) - yoffset * 2); scroll.guiLeft = left1; @@ -316,8 +341,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb } this.addScroll(scroll); } - } + computePanBounds(editorX, editorY, editorWidth, editorHeight); + } /** * Initialize the settings tab layout (console view). */ @@ -331,12 +357,11 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb int var9 = this.guiLeft + this.xSize - 150; this.addButton(new GuiNpcButton(100, var9, this.guiTop + 125, 60, 20, "gui.copy")); this.addButton(new GuiNpcButton(102, var9, this.guiTop + 146, 60, 20, "gui.clear")); - this.addLabel(new GuiNpcLabel(1, "script.language", var9, this.guiTop + 15)); + this.addLabel(new GuiNpcLabel(1, "script.default", var9, this.guiTop + 15)); List languageOptions = getLanguageOptions(); this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, languageOptions.toArray(new String[0]), this.getLanguageIndex(languageOptions))); - this.getButton(103).enabled = languageOptions.size() > 0; this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36)); this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20, new String[]{"gui.no", "gui.yes"}, this.handler.getEnabled() ? 1 : 0)); @@ -346,9 +371,24 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb } this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website")); - this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum")); - this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc")); - this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc")); + this.addButton(new GuiNpcButton(110, var9 + 81, this.guiTop + 78, 80, 20, "gui.api")); + + // Disable all buttons until server data arrives + if (!serverDataReceived) { + for (int btnId : new int[]{100, 102, 103, 104, 106, 109, 110}) { + GuiNpcButton btn = getButton(btnId); + if (btn != null) btn.enabled = false; + } + } else { + // Language button requires options to be available + this.getButton(103).enabled = languageOptions.size() > 0; + } + + int consoleX = this.guiLeft + 4 + yoffset; + int consoleY = this.guiTop + 6 + yoffset; + int consoleW = this.xSize - 160 - yoffset; + int consoleH = (int) ((float) this.ySize * 0.92F) - yoffset * 2; + computePanBounds(consoleX, consoleY, consoleW, consoleH); } public GuiScriptInterface setDimensions(int x, int y) { @@ -367,30 +407,34 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb return handler.getContext(); } - // ==================== RENDERING ==================== - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - super.drawScreen(mouseX, mouseY, partialTicks); - - // Draw fullscreen button on top of everything when on script editor tab - // Skip for useSettingsToggle GUIs (like GuiScript) - they handle this themselves - if (this.activeTab > 0 && !useSettingsToggle && !handler.isSingleContainer()) { - fullscreenButton.draw(mouseX, mouseY); + protected boolean isPannableArea(int mx, int my) { + if (activeTab > 0 && fullscreenButton.isMouseOver(mx, my)) { + return false; } + + GuiScriptTextArea activeArea = getActiveScriptArea(); + if (activeArea != null && activeArea.isPointOnAutocompleteMenu(mx, my)) { + return false; + } + + return super.isPannableArea(mx, my); } - // ==================== MOUSE HANDLING ==================== - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) { - // Check fullscreen button first when on script editor tab - // Skip for useSettingsToggle GUIs (like GuiScript) - they handle this themselves - if (this.activeTab > 0 && !useSettingsToggle && !handler.isSingleContainer() && fullscreenButton.mouseClicked(mouseX, mouseY, mouseButton)) { + public void mouseClicked(int i, int j, int k) { + int adjX = panAdjustedX(i); + int adjY = panAdjustedY(j); + + GuiScriptTextArea activeArea = getActiveScriptArea(); + boolean isOverAutocomplete = activeArea != null + && activeArea.isPointOnAutocompleteMenu(adjX, adjY); + if (isOverAutocomplete) { + activeArea.mouseClicked(adjX, adjY, k); return; } - super.mouseClicked(mouseX, mouseY, mouseButton); + super.mouseClicked(i, j, k); } public String previousHookClicked = ""; @@ -413,11 +457,40 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.getTextField(2).setText(this.getTextField(2).getText() + addString); previousHookClicked = ""; + + updateScriptDocumentImports(getActiveScriptArea(), container); } else { previousHookClicked = hook; } } + public void updateScriptDocumentImports(GuiScriptTextArea activeArea, IScriptUnit container) { + // For JaninoScripts, add implicit imports (default imports + hook signature types) + // These allow the syntax highlighter to resolve types without explicit import statements + if (container instanceof JaninoScript) { + JaninoScript janinoScript = (JaninoScript) container; + ScriptContext ctx = getScriptContext(); + // Add default imports (e.g., noppes.npcs.api.*, noppes.npcs.api.entity.*, etc.) + activeArea.addImplicitImports(janinoScript.getDefaultImports()); + + // Add hook types from signatures (parameters + return types) + // e.g., INpcEvent.InitEvent, Color, String, IOverlayContext, etc. + Set hookTypes = janinoScript.getHookTypes(); + activeArea.addImplicitImports(hookTypes.toArray(new String[0])); + + // Add wildcard imports for each event class in the script context: INpcEvent.*, IProjectileEvent.* + // so nested types like INpcEvent.CollideEvent resolve without explicit import + Set wildcardImports = new HashSet<>(); + for (String fqn : ctx.getNamespaceFQNs()) + wildcardImports.add(fqn + ".*"); + activeArea.addImplicitImports(wildcardImports.toArray(new String[0])); + + + // Format to update which implicit imports are actually used + activeArea.formatCodeText(); + } + } + @Override public void unFocused(GuiNpcTextField textfield) { @@ -467,6 +540,26 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb return 0; } + /** + * Finds the index of a container's language within the available options. + * Used for the per-tab language button (113). + * + * @param languageOptions The list of available languages. + * @param container The script unit whose language to find. + * @return The 0-based index, or 0 if not found. + */ + protected int getContainerLanguageIndex(List languageOptions, IScriptUnit container) { + if (languageOptions == null || languageOptions.isEmpty() || container == null) + return 0; + + String current = container.getLanguage(); + for (int i = 0; i < languageOptions.size(); i++) { + if (current != null && languageOptions.get(i).equalsIgnoreCase(current)) + return i; + } + return 0; + } + /** * Retrieves the list of available scripting languages for this handler. *

@@ -478,19 +571,35 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb */ protected List getLanguageOptions() { List options = new ArrayList<>(); + + // Start with languages known from the server if (this.languages != null && !this.languages.isEmpty()) options.addAll(this.languages.keySet()); - if ((options.isEmpty() || !options.contains("Java")) && this.handler != null && this.handler.supportsJanino()) { - List scripts = new ArrayList<>(); - if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) { - scripts.addAll(ScriptController.Instance.scripts.keySet()); + if (this.handler != null) { + if (this.handler.supportsJanino()) { + // Handler supports Java — ensure it's in the list + if (!options.contains("Java")) { + List scripts = new ArrayList<>(); + if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) { + scripts.addAll(ScriptController.Instance.scripts.keySet()); + } + if (this.languages == null) + this.languages = new HashMap(); + if (!this.languages.containsKey("Java")) + this.languages.put("Java", scripts); + options.add("Java"); + } + } else { + // Handler does not support Java — remove it + options.remove("Java"); + } + + // Ensure at least the handler's default language is present + String defaultLang = this.handler.getLanguage(); + if (defaultLang != null && !defaultLang.isEmpty() && !options.contains(defaultLang)) { + options.add(0, defaultLang); } - if (this.languages == null) - this.languages = new HashMap(); - if (!this.languages.containsKey("Java")) - this.languages.put("Java", scripts); - options.add("Java"); } return options; @@ -502,17 +611,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus"); } - if (i == 1) { - this.openLink("https://kamkeel.github.io/CustomNPC-Plus/"); - } - - if (i == 2) { - this.openLink("https://kamkeel.github.io/CustomNPC-Plus/"); - } - - if (i == 3) { - this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html"); - } if (i == 10) { handler.removeScriptUnit(this.activeTab - 1); this.activeTab = 0; @@ -591,13 +689,13 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb if (guibutton.id == scriptLimit) { if (handler.isSingleContainer()) { if (handler.getSingleScript() == null) { - handler.addScriptUnit(new ScriptContainer(handler)); + handler.addScriptUnit(createDefaultScriptUnit()); } else { this.setScript(); } this.activeTab = 1; } else { - handler.addScriptUnit(new ScriptContainer(this.handler)); + handler.addScriptUnit(createDefaultScriptUnit()); this.activeTab = this.handler.getScripts().size(); } this.initGui(); @@ -608,15 +706,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb } if (guibutton.id == 110) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true)); - } - - if (guibutton.id == 111) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true)); - } - - if (guibutton.id == 112) { - this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true)); + if (APIRegistry.Instance.size() == 1) { + String url = APIRegistry.Instance.getEntries().values().iterator().next(); + this.setSubGui(new SubGuiConfirmLink(url)); + } else { + this.setSubGui(new SubGuiAPISelect()); + } } if (guibutton.id == 100) { @@ -655,43 +750,47 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb if (guibutton.id == 107) { IScriptUnit container = getCurrentContainer(); if (container == null) { - container = new ScriptContainer(this.handler); + container = createDefaultScriptUnit(); handler.addScriptUnit(container); } - String language = container != null ? container.getLanguage() : this.handler.getLanguage(); + String language = container.getLanguage(); this.setSubGui(new EventGuiScriptList((List) this.languages.get(language), container)); } - // Language toggle button - switch between ECMAScript and Java + // Per-tab language cycling button if (guibutton.id == 113) { + String selectedLanguage = ((GuiNpcButton) guibutton).displayString; int idx = getActiveScriptIndex(); if (idx >= 0 && idx < handler.getScripts().size()) { IScriptUnit currentUnit = handler.getScripts().get(idx); - IScriptUnit newUnit; + boolean currentIsJanino = currentUnit.isJanino(); + boolean targetIsJanino = "Java".equals(selectedLanguage); - if (currentUnit.isJanino()) { - // Switch from Java to ECMAScript - newUnit = new ScriptContainer(handler); + if (currentIsJanino && !targetIsJanino) { + // Switch from Java to a non-Java language + IScriptUnit newUnit = new ScriptContainer(handler); newUnit.setScript(currentUnit.getScript()); newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts())); - } else { - // Switch from ECMAScript to Java - newUnit = handler.createJaninoScriptUnit(); + handler.replaceScriptUnit(idx, newUnit); + textAreas.remove(idx); + initGui(); + } else if (!currentIsJanino && targetIsJanino) { + // Switch from non-Java to Java + IScriptUnit newUnit = handler.createJaninoScriptUnit(); if (newUnit != null) { newUnit.setScript(currentUnit.getScript()); newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts())); - } else { - return; // Handler doesn't support Janino + handler.replaceScriptUnit(idx, newUnit); + textAreas.remove(idx); + initGui(); } + } else if (!currentIsJanino) { + // Switch between non-Java languages (e.g., ECMAScript to Lua) + currentUnit.setLanguage(selectedLanguage); + GuiScriptTextArea area = getActiveScriptArea(); + if (area != null) area.setLanguage(selectedLanguage); } - - handler.replaceScriptUnit(idx, newUnit); - // Clear the cached text area so it recreates with new language - textAreas.remove(idx); - - // Reinitialize the GUI - initGui(); } } } @@ -701,7 +800,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb IScriptUnit container = getCurrentContainer(); if (container == null) { - container = new ScriptContainer(this.handler); + container = createDefaultScriptUnit(); handler.addScriptUnit(container); } @@ -718,6 +817,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb public void setGuiData(NBTTagCompound compound) { if (handler instanceof IScriptHandlerPacket) { IScriptHandlerPacket.GuiDataResult result = ((IScriptHandlerPacket) handler).setGuiData(compound); + if (result == null) { + return; // Unrelated packet, ignore + } if (result.kind == IScriptHandlerPacket.GuiDataKind.LOAD_COMPLETE) { loaded = true; return; @@ -733,6 +835,10 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb return; } + // For non-IScriptHandlerPacket handlers, ignore unrelated packets + if (!compound.hasKey("ScriptLanguage") && !compound.hasKey("Languages")) { + return; + } loadLanguagesData(compound); } @@ -771,11 +877,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb } this.languages = languages; + this.serverDataReceived = true; this.initGui(); } public void save() { - if (!loaded) + if (!loaded || !serverDataReceived) return; this.setScript(); @@ -820,6 +927,22 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb super.close(); } + /** + * Create a new script unit using the handler's default language. + * If default is Java, creates a JaninoScript; otherwise a ScriptContainer + * with its language set to the handler's default. + */ + protected IScriptUnit createDefaultScriptUnit() { + String defaultLang = handler.getLanguage(); + if ("Java".equals(defaultLang)) { + IScriptUnit unit = handler.createJaninoScriptUnit(); + if (unit != null) return unit; + } + ScriptContainer sc = new ScriptContainer(handler); + sc.setLanguage(defaultLang); + return sc; + } + // ==================== FULLSCREEN METHODS ==================== /** diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java index 7161722d5..e6f2ce61c 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java @@ -5,7 +5,6 @@ import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket; 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.GuiNpcTextField; import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IScrollData; diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiQuestSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiQuestSelection.java index 288964545..cf805fe44 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiQuestSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiQuestSelection.java @@ -2,6 +2,8 @@ package noppes.npcs.client.gui.select; import com.google.common.collect.Lists; import net.minecraft.client.gui.GuiButton; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted; +import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.util.GuiCustomScroll; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; @@ -27,6 +29,31 @@ public class GuiQuestSelection extends SubGuiInterface implements ICustomScrollL private QuestCategory selectedCategory; public Quest selectedQuest; + /** + * Builds the condition editor's quest-select field. + *

+ * This lives here rather than in ConditionQuestCompleted because the lambdas below carry + * this class in their method descriptors. The condition is a both-side class, and @SideOnly + * does not strip the synthetic lambda methods it generates - so anything reflecting over its + * declared methods on a server would resolve those descriptors and fail to find this type. + */ + public static FieldDef createConditionField(ConditionQuestCompleted condition) { + return FieldDef.subGuiField("condition.select_quest", + () -> new GuiQuestSelection(condition.getQuestId()), + gui -> { + GuiQuestSelection sel = (GuiQuestSelection) gui; + if (sel.selectedQuest != null) { + condition.setQuestId(sel.selectedQuest.id); + } + }) + .buttonLabel(() -> { + if (condition.getQuestId() < 0) return "None"; + Quest q = QuestController.Instance.quests.get(condition.getQuestId()); + return q != null ? q.title : "ID:" + condition.getQuestId(); + }) + .clearable(() -> condition.setQuestId(-1)); + } + private GuiSelectionListener listener; private String catSearch = ""; private String questSearch = ""; diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java index aae3043ce..220833f2b 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java @@ -145,11 +145,13 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL scrollSounds.resetScroll(); getTextField(66).setText(""); soundSearch = ""; + scrollSounds.setList(domains.get(selectedDomain)); + getButton(1).enabled = false; } if (guiCustomScroll.id == 1) { selectedResource = new ResourceLocation(selectedDomain, guiCustomScroll.getSelected()); + getButton(1).enabled = true; } - initGui(); } @Override diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiTexturePathSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiTexturePathSelection.java new file mode 100644 index 000000000..7e67a32d1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/select/GuiTexturePathSelection.java @@ -0,0 +1,319 @@ +package noppes.npcs.client.gui.select; + +import com.google.common.collect.Lists; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.client.renderer.ImageData; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Texture path selector SubGui with a texture preview panel instead of NPC rendering. + * Reuses the cached texture data from {@link GuiTextureSelection}. + */ +public class GuiTexturePathSelection extends SubGuiInterface implements ICustomScrollListener { + + private final String up = "..<" + StatCollector.translateToLocal("gui.up") + ">.."; + private GuiCustomScroll scrollCategories; + private GuiCustomScroll scrollTextures; + + private String location = ""; + private String selectedDomain; + public ResourceLocation selectedResource; + + private final HashMap> domains = new HashMap<>(); + private final HashMap textures = new HashMap<>(); + + private String catSearch = ""; + private String texSearch = ""; + + // Preview + private static final int PREVIEW_SIZE = 90; + + public GuiTexturePathSelection(String texture) { + drawDefaultBackground = false; + title = ""; + setBackground("menubg.png"); + xSize = 366; + ySize = 226; + + // Populate from GuiTextureSelection's cache (trigger a scan if needed) + long now = System.currentTimeMillis(); + if (GuiTextureSelection.cachedTextures != null && !GuiTextureSelection.cachedTextures.isEmpty() + && now - GuiTextureSelection.lastCacheTime() < GuiTextureSelection.CACHE_DURATION_MS) { + domains.putAll(GuiTextureSelection.cachedDomains()); + } else { + // Force a scan by creating a temporary GuiTextureSelection + GuiTextureSelection temp = new GuiTextureSelection(null, null); + domains.putAll(GuiTextureSelection.cachedDomains()); + } + + if (texture != null && !texture.isEmpty()) { + selectedResource = new ResourceLocation(texture); + selectedDomain = selectedResource.getResourceDomain(); + if (!domains.containsKey(selectedDomain)) { + selectedDomain = null; + } + int i = selectedResource.getResourcePath().lastIndexOf('/'); + location = selectedResource.getResourcePath().substring(0, i + 1); + } + } + + @Override + public void initGui() { + super.initGui(); + + if (selectedDomain != null) { + title = selectedDomain + ":" + location; + } else { + title = ""; + } + + // Buttons + this.addButton(new GuiNpcButton(2, guiLeft + xSize - 46, guiTop + ySize - 28, 42, 20, "gui.done")); + this.addButton(new GuiNpcButton(1, guiLeft + xSize - 92, guiTop + ySize - 28, 42, 20, "gui.cancel")); + + // Category scroll + if (scrollCategories == null) { + scrollCategories = new GuiCustomScroll(this, 0); + scrollCategories.setSize(90, 163); + } + if (selectedDomain == null) { + scrollCategories.setList(getCatSearch()); + } else { + List list = new ArrayList<>(); + list.add(up); + List data = domains.get(selectedDomain); + if (data != null) { + for (GuiTextureSelection.TextureData td : data) { + if (location.isEmpty() || td.path.startsWith(location) && !td.path.equals(location)) { + String path = td.path.substring(location.length()); + int i = path.indexOf('/'); + if (i < 0) continue; + path = path.substring(0, i); + if (!path.isEmpty() && !list.contains(path)) { + list.add(path); + } + } + } + } + scrollCategories.setList(list); + } + scrollCategories.guiLeft = guiLeft + 4; + scrollCategories.guiTop = guiTop + 14; + this.addScroll(scrollCategories); + addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 179, 90, 20, catSearch)); + + // Texture scroll + if (scrollTextures == null) { + scrollTextures = new GuiCustomScroll(this, 1); + scrollTextures.setSize(160, 163); + } + if (selectedDomain != null) { + textures.clear(); + List data = domains.get(selectedDomain); + List allList = new ArrayList<>(); + String loc = location; + if (scrollCategories.hasSelected() && !scrollCategories.getSelected().equals(up)) { + loc += scrollCategories.getSelected() + '/'; + } + if (data != null) { + for (GuiTextureSelection.TextureData td : data) { + if (td.path.equals(loc) && !allList.contains(td.name)) { + allList.add(td.name); + textures.put(td.name, td); + } + } + } + scrollTextures.setList(filterTexSearch(allList)); + } + if (selectedResource != null) { + scrollTextures.setSelected(selectedResource.getResourcePath()); + } + scrollTextures.guiLeft = guiLeft + 95; + scrollTextures.guiTop = guiTop + 14; + this.addScroll(scrollTextures); + addTextField(new GuiNpcTextField(66, this, fontRendererObj, guiLeft + 95, guiTop + 179, 160, 20, texSearch)); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + super.drawScreen(mouseX, mouseY, partialTicks); + drawTexturePreview(); + } + + private void drawTexturePreview() { + int previewX = guiLeft + 260; + int previewY = guiTop + 14; + + // Draw border/background for preview area + drawRect(previewX - 1, previewY - 1, previewX + PREVIEW_SIZE + 1, previewY + PREVIEW_SIZE + 1, 0xFFA0A0A0); + drawRect(previewX, previewY, previewX + PREVIEW_SIZE, previewY + PREVIEW_SIZE, 0xFF000000); + + if (selectedResource == null) { + String none = StatCollector.translateToLocal("gui.none"); + int w = fontRendererObj.getStringWidth(none); + fontRendererObj.drawString(none, previewX + (PREVIEW_SIZE - w) / 2, previewY + PREVIEW_SIZE / 2 - 4, 0xFF808080); + return; + } + + ImageData imageData = ClientCacheHandler.getImageData(selectedResource.toString()); + if (imageData == null || !imageData.imageLoaded()) { + String loading = "..."; + int w = fontRendererObj.getStringWidth(loading); + fontRendererObj.drawString(loading, previewX + (PREVIEW_SIZE - w) / 2, previewY + PREVIEW_SIZE / 2 - 4, 0xFF808080); + return; + } + + int texW = imageData.getTotalWidth(); + int texH = imageData.getTotalHeight(); + if (texW <= 0 || texH <= 0) return; + + // Scale to fit within PREVIEW_SIZE while maintaining aspect ratio + float scale = Math.min((float) PREVIEW_SIZE / texW, (float) PREVIEW_SIZE / texH); + int drawW = (int) (texW * scale); + int drawH = (int) (texH * scale); + int drawX = previewX + (PREVIEW_SIZE - drawW) / 2; + int drawY = previewY + (PREVIEW_SIZE - drawH) / 2; + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + imageData.bindTexture(); + drawScaledTexture(drawX, drawY, drawW, drawH); + + // Draw dimensions label below preview + String dims = texW + " x " + texH; + int dw = fontRendererObj.getStringWidth(dims); + fontRendererObj.drawString(dims, previewX + (PREVIEW_SIZE - dw) / 2, previewY + PREVIEW_SIZE + 4, 0xFFCCCCCC); + + // Draw resource path below dimensions + String path = selectedResource.toString(); + if (fontRendererObj.getStringWidth(path) > PREVIEW_SIZE + 4) { + // Truncate from the left + while (fontRendererObj.getStringWidth("..." + path) > PREVIEW_SIZE + 4 && path.length() > 1) { + path = path.substring(1); + } + path = "..." + path; + } + int pw = fontRendererObj.getStringWidth(path); + fontRendererObj.drawString(path, previewX + (PREVIEW_SIZE - pw) / 2, previewY + PREVIEW_SIZE + 15, 0xFF999999); + } + + private void drawScaledTexture(int x, int y, int width, int height) { + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + tess.addVertexWithUV(x, y + height, zLevel, 0.0, 1.0); + tess.addVertexWithUV(x + width, y + height, zLevel, 1.0, 1.0); + tess.addVertexWithUV(x + width, y, zLevel, 1.0, 0.0); + tess.addVertexWithUV(x, y, zLevel, 0.0, 0.0); + tess.draw(); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + super.actionPerformed(guibutton); + if (guibutton.id == 1) { + // Cancel - clear selection + selectedResource = null; + } + close(); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll == scrollTextures) { + if (scroll.id == 1) { + GuiTextureSelection.TextureData data = textures.get(scroll.getSelected()); + if (data != null) { + selectedResource = new ResourceLocation(selectedDomain, data.absoluteName); + } + } + } else { + initGui(); + scrollTextures.resetScroll(); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (scroll == scrollCategories) { + if (selectedDomain == null) { + selectedDomain = selection; + } else if (selection.equals(up)) { + int i = location.lastIndexOf('/', location.length() - 2); + if (i < 0) { + if (location.isEmpty()) { + selectedDomain = null; + } + location = ""; + } else { + location = location.substring(0, i + 1); + } + } else { + location = location + selection + '/'; + } + scrollCategories.selected = -1; + scrollTextures.selected = -1; + initGui(); + } else { + // Double-click on texture = confirm + close(); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(55) != null && getTextField(55).isFocused()) { + if (!catSearch.equals(getTextField(55).getText())) { + catSearch = getTextField(55).getText().toLowerCase(); + scrollCategories.resetScroll(); + if (selectedDomain == null) { + scrollCategories.setList(getCatSearch()); + } + } + } + if (getTextField(66) != null && getTextField(66).isFocused()) { + if (!texSearch.equals(getTextField(66).getText())) { + texSearch = getTextField(66).getText().toLowerCase(); + scrollTextures.resetScroll(); + initGui(); + } + } + } + + private List getCatSearch() { + if (catSearch.isEmpty()) { + return new ArrayList<>(domains.keySet()); + } + List list = new ArrayList<>(); + for (String name : domains.keySet()) { + if (name.toLowerCase().contains(catSearch)) + list.add(name); + } + return list; + } + + private List filterTexSearch(List source) { + if (texSearch.isEmpty()) { + return source; + } + List list = new ArrayList<>(); + for (String name : source) { + if (name.toLowerCase().contains(texSearch)) + list.add(name); + } + return list; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiTextureSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiTextureSelection.java index 3b8fda84d..b1cab23f4 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiTextureSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiTextureSelection.java @@ -54,11 +54,21 @@ public class GuiTextureSelection extends SubGuiInterface implements ICustomScrol private final HashMap textures = new HashMap<>(); // --- Cache static fields --- - private static final long CACHE_DURATION = 180000L; // 3 minutes in milliseconds + static final long CACHE_DURATION = 180000L; // 3 minutes in milliseconds private static long lastCacheTime = 0; private static HashMap> cachedDomains = new HashMap<>(); public static HashMap cachedTextures = new HashMap<>(); + public static final long CACHE_DURATION_MS = CACHE_DURATION; + + public static long lastCacheTime() { + return lastCacheTime; + } + + public static HashMap> cachedDomains() { + return cachedDomains; + } + public GuiTextureSelection(EntityNPCInterface npc, String texture) { this.npc = npc; drawDefaultBackground = false; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java index 665dd2259..a71c9762f 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java @@ -64,14 +64,14 @@ public class GuiAuctionNavButton extends GuiNpcButton { /** * Create a fully customizable button. * - * @param id Button ID - * @param x X position - * @param y Y position - * @param buttonSize Size of the button background texture (e.g., 18 for 18x18, 10 for 10x10) - * @param iconSize Size of the icon texture (e.g., 16 for 16x16, 8 for 8x8) - * @param tooltipKey Lang key for tooltip - * @param iconTexture Icon texture to draw inside the button - * @param textureNormal Background texture for normal state + * @param id Button ID + * @param x X position + * @param y Y position + * @param buttonSize Size of the button background texture (e.g., 18 for 18x18, 10 for 10x10) + * @param iconSize Size of the icon texture (e.g., 16 for 16x16, 8 for 8x8) + * @param tooltipKey Lang key for tooltip + * @param iconTexture Icon texture to draw inside the button + * @param textureNormal Background texture for normal state * @param texturePressed Background texture for pressed/hover state */ public GuiAuctionNavButton(int id, int x, int y, int buttonSize, int iconSize, String tooltipKey, 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 f9b3df568..fc8bf30eb 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java @@ -19,6 +19,7 @@ public class GuiCustomScroll extends GuiScreen { public static final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/misc.png"); public List list; public final HashMap colors = new HashMap<>(); + public final HashSet nonInteractive = new HashSet<>(); public int id; public int guiLeft = 0; @@ -217,21 +218,25 @@ public class GuiCustomScroll extends GuiScreen { } else text = displayString; - // Entries with a custom color are non-interactive (headers/separators) + // Non-interactive entries (headers/separators) — colored, no hover/selection Integer customColor = colors.get(rawEntry); - if (customColor != null) { + if (nonInteractive.contains(rawEntry)) { if (!text.isEmpty()) - fontRendererObj.drawString(text, j, k, customColor); + fontRendererObj.drawString(text, j, k, customColor != null ? customColor : 0xffffff); } 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); drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k + 10, 0xffffffff); - fontRendererObj.drawString(text, j, k, 0xffffff); + int selColor = customColor != null ? customColor : 0xffffff; + fontRendererObj.drawString(text, j, k, selColor); } else if (i == hover) { - fontRendererObj.drawString(text, j, k, 0x00ff00); - } else - fontRendererObj.drawString(text, j, k, 0xffffff); + int hoverColor = customColor != null ? customColor : 0x00ff00; + fontRendererObj.drawString(text, j, k, hoverColor); + } else { + int defaultColor = customColor != null ? customColor : 0xffffff; + fontRendererObj.drawString(text, j, k, defaultColor); + } } } @@ -252,8 +257,8 @@ public class GuiCustomScroll extends GuiScreen { continue; } - // Skip non-interactive entries (colored headers/separators) - if (colors.containsKey(list.get(j1))) { + // Skip non-interactive entries (headers/separators) + if (nonInteractive.contains(list.get(j1))) { continue; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollTagged.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollTagged.java new file mode 100644 index 000000000..efeb3e6f5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollTagged.java @@ -0,0 +1,102 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.util.StatCollector; +import noppes.npcs.controllers.TagController; +import noppes.npcs.controllers.data.Tag; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.UUID; + +/** + * Scroll list that renders CNPC tags next to item names. + * Used in directory/fullscreen GUIs for Forms, Auras, Outlines, etc. + */ +public class GuiCustomScrollTagged extends GuiCustomScroll { + private HashMap> itemTagMap = new HashMap<>(); + private boolean showTags = true; + + public GuiCustomScrollTagged(GuiScreen parent, int id) { + super(parent, id); + } + + public void setItemTagMap(HashMap> tagMap) { + this.itemTagMap = tagMap != null ? tagMap : new HashMap<>(); + } + + public HashMap> getItemTagMap() { + return itemTagMap; + } + + public void setShowTags(boolean show) { + this.showTags = show; + } + + @Override + protected void drawItems() { + for (int i = 0; i < list.size(); i++) { + int j = 4; + int k = (14 * i + 4) - scrollY; + if (k >= 4 && k + 12 < ySize) { + int xOffset = scrollHeight < ySize - 8 ? 0 : 10; + String rawEntry = list.get(i); + String displayString = StatCollector.translateToLocal(rawEntry); + + String text = ""; + float maxWidth = showTags && itemTagMap.containsKey(rawEntry) + ? (xSize + xOffset - 8) * 0.5f + : (xSize + xOffset - 8) * 0.8f; + + if (fontRendererObj.getStringWidth(displayString) > maxWidth) { + for (int h = 0; h < displayString.length(); h++) { + char c = displayString.charAt(h); + text += c; + if (fontRendererObj.getStringWidth(text) > maxWidth) + break; + } + if (displayString.length() > text.length()) + text += "..."; + } else { + text = displayString; + } + + 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); + drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k + 10, 0xffffffff); + fontRendererObj.drawString(text, j, k, 0xffffff); + } else if (i == hover) { + fontRendererObj.drawString(text, j, k, 0x00ff00); + } else { + fontRendererObj.drawString(text, j, k, 0xffffff); + } + + // Draw tags after item name + if (showTags && itemTagMap.containsKey(rawEntry)) { + int tagStartX = j + fontRendererObj.getStringWidth(text) + 3; + int maxX = j + xSize - 18 + xOffset; + HashSet tagUUIDs = itemTagMap.get(rawEntry); + TagController tc = TagController.getInstance(); + if (tc != null && tagUUIDs != null) { + for (UUID uuid : tagUUIDs) { + Tag tag = tc.getTagFromUUID(uuid); + if (tag != null && !tag.hideTag) { + String tagText = "[" + tag.name + "]"; + int tagWidth = fontRendererObj.getStringWidth(tagText); + if (tagStartX + tagWidth > maxX) break; + fontRendererObj.drawString(tagText, tagStartX, k, tag.color); + tagStartX += tagWidth + 3; + } + } + } + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java b/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java index 750c60668..957237610 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java @@ -4,29 +4,29 @@ package noppes.npcs.client.gui.util; * Abstract base class for fullscreen directory-browsing GUIs. * Provides a configurable three-panel layout (left nav, center content, right actions) * with percentage-based sizing, panel backgrounds/borders, and an optional resizable divider. - * + *

* Subclasses override abstract hooks to populate each panel region. * Designed for reuse across Cloner, Quest Manager, Dialog Manager, etc. */ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScrollListener, ISubGuiListener { // ===== LAYOUT CONFIG (subclasses may override in constructor) ===== - protected float leftPanelPercent = 0.20f; + protected float leftPanelPercent = 0.20f; protected float rightPanelPercent = 0.10f; - protected int minLeftPanelW = 80; + protected int minLeftPanelW = 80; protected int minRightPanelW = 40; - protected int minCenterW = 100; + protected int minCenterW = 100; // ===== LAYOUT CONSTANTS ===== - protected int pad = 10; + protected int pad = 10; protected int topBarH = 24; - protected int gap = 4; - protected int btnH = 20; + protected int gap = 4; + protected int btnH = 20; // ===== PANEL COLORS ===== - protected int panelBg = 0xC0101010; + protected int panelBg = 0xC0101010; protected int panelBorder = 0xFF333333; - protected int topBarBg = 0xC0181818; + protected int topBarBg = 0xC0181818; // ===== COMPUTED LAYOUT (populated by computeLayout) ===== protected int originX, originY, usableW, usableH; @@ -35,10 +35,10 @@ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScr protected int rightX; // ===== OPTIONAL RESIZABLE DIVIDER (between left and center) ===== - protected boolean enableDivider = false; - protected int dividerWidth = 5; - protected int dividerLineHeight = 20; - protected int minDividerPanelW = 50; + protected boolean enableDivider = false; + protected int dividerWidth = 5; + protected int dividerLineHeight = 20; + protected int minDividerPanelW = 50; private int dividerOffset; private boolean isDragging = false; private int dragStartX; @@ -57,8 +57,8 @@ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScr usableW = width - 2 * pad; usableH = height - 2 * pad; - leftPanelW = Math.max(minLeftPanelW, (int)(usableW * leftPanelPercent)); - rightPanelW = Math.max(minRightPanelW, (int)(usableW * rightPanelPercent)); + leftPanelW = Math.max(minLeftPanelW, (int) (usableW * leftPanelPercent)); + rightPanelW = Math.max(minRightPanelW, (int) (usableW * rightPanelPercent)); if (rightPanelPercent <= 0) { rightPanelW = 0; @@ -73,7 +73,7 @@ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScr contentX = originX + leftPanelW + gap; contentY = originY + topBarH + gap; contentH = usableH - topBarH - gap; - rightX = contentX + contentW + gap; + rightX = contentX + contentW + gap; if (enableDivider && dividerOffset == 0) { dividerOffset = leftPanelW; @@ -128,7 +128,9 @@ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScr drawRect(divX + 1, handleTop, divX + dividerWidth - 1, handleTop + dividerLineHeight, 0xFF707070); } - /** Override for extra drawing after super.drawScreen (e.g. status text) */ + /** + * Override for extra drawing after super.drawScreen (e.g. status text) + */ protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { } @@ -177,7 +179,9 @@ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScr super.mouseMovedOrUp(mouseX, mouseY, state); } - /** Called when divider is dragged. Override to update scroll sizes. */ + /** + * Called when divider is dragged. Override to update scroll sizes. + */ protected void onDividerMoved(int newOffset) { } @@ -192,15 +196,23 @@ public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScr // ===== ABSTRACT HOOKS (subclass must implement) ===== - /** Populate top bar buttons. topBtnY is the y-coordinate for the button row. */ + /** + * Populate top bar buttons. topBtnY is the y-coordinate for the button row. + */ protected abstract void initTopBar(int topBtnY); - /** Populate the left navigation panel (scrolls, search fields, buttons). */ + /** + * Populate the left navigation panel (scrolls, search fields, buttons). + */ protected abstract void initLeftPanel(); - /** Populate the center content panel (main scroll list). */ + /** + * Populate the center content panel (main scroll list). + */ protected abstract void initCenterPanel(); - /** Populate the right action panel. startY is the first button y-coordinate. */ + /** + * Populate the right action panel. startY is the first button y-coordinate. + */ protected abstract void initRightPanel(int startY); } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiDirectoryCategorized.java b/src/main/java/noppes/npcs/client/gui/util/GuiDirectoryCategorized.java new file mode 100644 index 000000000..b27429ec1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiDirectoryCategorized.java @@ -0,0 +1,830 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.controllers.TagController; +import noppes.npcs.controllers.data.Category; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiYesNo; +import net.minecraft.client.gui.GuiYesNoCallback; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.CustomNpcResourceListener; +import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.SubGuiEditText; +import noppes.npcs.constants.EnumScrollData; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; +import java.util.Vector; + +/** + * Fullscreen categorized manager base class (Cloner-inspired layout). + * Left=categories with icons, Center=items, Right=preview+details. + * Top bar has item operations (Add/Remove/Clone/Move) + search. + */ +public abstract class GuiDirectoryCategorized extends GuiDirectory + implements IScrollData, IGuiData, GuiYesNoCallback, ISubGuiListener { + + // ========== Scrolls ========== + protected GuiCustomScrollIcons catScroll = new GuiCustomScrollIcons(this, 2); + protected GuiCustomScrollTagged itemScroll = new GuiCustomScrollTagged(this, 0); + + // ========== Data ========== + protected HashMap catData = new HashMap<>(); + protected HashMap itemData = new HashMap<>(); + + // ========== Selection ========== + protected String prevCatName = ""; + protected String prevItemName = ""; + protected int selectedCatId = -1; + + // ========== Search ========== + protected String catSearch = ""; + protected String itemSearch = ""; + + // ========== Preview ========== + protected float zoomed = 60; + protected float rotation; + protected int previewX, previewY, previewW, previewH; + + // ========== Move Workflow ========== + protected int movePhase = 0; // 0=off, 1=selecting items, 2=selecting destination + protected HashSet moveSelection = new HashSet<>(); + protected static final int MAX_MOVE_ITEMS = 5; + + // ========== New Item Category ========== + protected int pendingNewItemCatId = -1; + + // ========== Pending Move Destination ========== + private int pendingMoveDestCatId = -1; + private String pendingMoveDestName = ""; + + // ========== Category Data Loaded ========== + private boolean itemDataLoaded = false; + + // ========== Collapse ========== + protected boolean leftCollapsed = false; + private static final ResourceLocation DIRECTORY_ICON = new ResourceLocation("customnpcs", "textures/gui/directory.png"); + + // ========== Scroll Reset Flag ========== + private boolean resetItemScroll = false; + + // ========== Nav list data ========== + private List navNames = new ArrayList<>(); + private List navIcons = new ArrayList<>(); + + // ========== Constructor ========== + public GuiDirectoryCategorized() { + super(); + leftPanelPercent = 0.15f; + rightPanelPercent = 0.35f; + minLeftPanelW = 120; + minRightPanelW = 150; + requestCategoryList(); + } + + /** + * Whether this GUI currently has a category panel. + * Subclasses override to return false for built-in modes. + */ + protected boolean hasCategories() { return true; } + + @Override + protected void computeLayout() { + if (leftCollapsed || !hasCategories()) { + leftPanelPercent = 0.0f; + minLeftPanelW = 0; + } else if (leftPanelPercent <= 0) { + leftPanelPercent = 0.15f; + minLeftPanelW = 120; + } + super.computeLayout(); + + // Force 50/50 split between center and right when left panel is hidden + if (leftPanelW <= 0) { + int available = usableW - 3 * gap; + rightPanelW = available / 2; + contentW = available - rightPanelW; + contentX = originX + gap; + rightX = contentX + contentW + gap; + } + } + + @Override + protected void drawPanels() { + if (leftPanelW <= 0) { + if (rightPanelW > 0) { + GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder); + } + } else { + super.drawPanels(); + } + } + + // ========== Abstract hooks ========== + protected abstract String getTitle(); + protected abstract void requestCategoryList(); + protected abstract void requestItemsInCategory(int catId); + protected abstract void requestItemData(int itemId); + protected abstract void onSaveCategory(Category cat); + protected abstract void onRemoveCategory(int catId); + protected abstract void onAddItem(int catId); + protected abstract void onRemoveItem(int itemId); + protected abstract void onEditItem(); + protected abstract void onCloneItem(); + protected abstract void onItemReceived(NBTTagCompound compound); + protected abstract boolean hasSelectedItem(); + protected abstract int getSelectedItemId(); + + protected GuiScreen getWindowedVariant() { return null; } + protected void drawItemPreview(int centerX, int centerY, int mouseX, int mouseY, float partialTicks) {} + protected void drawItemDetails(int x, int y, int w) {} + protected void saveCurrentItem() {} + + /** + * Hook for name-based items (e.g. abilities) that don't use numeric IDs. + * Called when a new item needs to be moved to a category but getSelectedItemId() returns -1. + */ + protected void onMoveNewItem(int catId) {} + + protected void setPrevItemName(String name) { + this.prevItemName = name; + } + + /** + * Hook for subclasses to add buttons at the START of the top bar (before Add/Remove/Clone/Move). + * Return the new x position after adding buttons. + */ + protected int initExtraTopBarButtons(int x, int topBtnY) { + return x; + } + + // ========== Top Bar ========== + @Override + protected void initTopBar(int topBtnY) { + int x = originX + 2; + + // Collapse/Expand button + GuiNpcButton collapseBtn = new GuiNpcButton(19, x, topBtnY, btnH, btnH, ""); + collapseBtn.enabled = hasCategories() && movePhase == 0; + addButton(collapseBtn); + x += btnH + 2; + + x = initExtraTopBarButtons(x, topBtnY); + int topBtnW = 55; + + // ADD + GuiNpcButton addBtn = new GuiNpcButton(50, x, topBtnY, topBtnW, btnH, "gui.add"); + addBtn.enabled = selectedCatId >= 0 && movePhase == 0; + addButton(addBtn); + x += topBtnW + 2; + + // MOVE + String moveLabel = movePhase > 0 ? "gui.moving" : "gui.move"; + GuiNpcButton moveBtn = new GuiNpcButton(54, x, topBtnY, topBtnW, btnH, moveLabel); + moveBtn.enabled = selectedCatId >= 0 && !leftCollapsed && hasCategories(); + addButton(moveBtn); + x += topBtnW + 2; + + // Confirm (only during move phase 1) + if (movePhase == 1) { + GuiNpcButton confirmBtn = new GuiNpcButton(55, x, topBtnY, topBtnW, btnH, "gui.confirm"); + confirmBtn.enabled = !moveSelection.isEmpty(); + confirmBtn.setTextColor(0x55FFFF); + addButton(confirmBtn); + x += topBtnW + 2; + } + + // Right side: close, minimize + int closeX = originX + usableW - btnH - 2; + addButton(new GuiNpcButton(17, closeX, topBtnY, btnH, btnH, "X")); + int minimizeX = closeX - btnH - 2; + if (getWindowedVariant() != null) { + addButton(new GuiNpcButton(18, minimizeX, topBtnY, btnH, btnH, "-")); + } + + // Search field is now under the center panel — see initCenterPanel() + } + + // ========== Left Panel: Category Navigation ========== + @Override + protected void initLeftPanel() { + if (leftCollapsed || !hasCategories()) return; + boolean catSelected = selectedCatId > 0; // non-Uncategorized selected + int bottomRows = catSelected ? 3 : 2; + int bottomH = bottomRows * (btnH + gap); + int navH = contentH - bottomH; + + buildNavList(); + + int savedCatScrollY = catScroll.scrollY; + catScroll.clear(); + catScroll.colors.clear(); + catScroll.setSize(leftPanelW, navH); + catScroll.guiLeft = originX; + catScroll.guiTop = contentY; + catScroll.setListWithIcons(navNames, navIcons); + catScroll.setSelected(prevCatName); + catScroll.scrollY = Math.max(0, Math.min(savedCatScrollY, catScroll.maxScrollY)); + + // Phase 1: categories locked (not clickable) + if (movePhase == 1) { + catScroll.setSelectable(false); + } + // Phase 2: color nav items orange (selectable) or red (current/source category) + if (movePhase == 2) { + catScroll.setSelectable(true); + for (String name : navNames) { + catScroll.colors.put(name, name.equals(prevCatName) ? 0xFF5555 : 0xFFAA00); + } + } else if (movePhase == 0) { + catScroll.setSelectable(true); + } + + addScroll(catScroll); + + // Category search + int searchY = contentY + navH + gap; + addTextField(new GuiNpcTextField(3, this, fontRendererObj, originX, searchY, leftPanelW, btnH, catSearch)); + + // Add category button + int addY = searchY + btnH + gap; + GuiNpcButton addCatBtn = new GuiNpcButton(40, originX, addY, leftPanelW, btnH, "gui.addCategory"); + if (movePhase > 0) addCatBtn.enabled = false; + addButton(addCatBtn); + + // Rename / Remove (non-Uncategorized only) + if (catSelected) { + int crudY = addY + btnH + gap; + int halfW = (leftPanelW - gap) / 2; + GuiNpcButton renameBtn = new GuiNpcButton(41, originX, crudY, halfW, btnH, "gui.edit"); + if (movePhase > 0) renameBtn.enabled = false; + addButton(renameBtn); + + GuiNpcButton removeBtn = new GuiNpcButton(42, originX + halfW + gap, crudY, halfW, btnH, "gui.remove"); + removeBtn.enabled = movePhase == 0 && isCategoryEmpty(selectedCatId); + addButton(removeBtn); + } + } + + // ========== Center Panel: Items ========== + @Override + protected void initCenterPanel() { + int searchH = btnH + gap; + int scrollH = contentH - (movePhase == 0 ? searchH : 0); + + int savedItemScrollY = resetItemScroll ? 0 : itemScroll.scrollY; + resetItemScroll = false; + + itemScroll.clear(); + itemScroll.colors.clear(); + itemScroll.setSize(contentW, scrollH); + itemScroll.guiLeft = contentX; + itemScroll.guiTop = contentY; + + if (movePhase == 1) { + itemScroll.multipleSelection = true; + itemScroll.setSelectable(true); + itemScroll.setSelectedList(moveSelection); + } else if (movePhase == 2) { + itemScroll.multipleSelection = true; + itemScroll.setSelectedList(moveSelection); + itemScroll.setSelectable(false); + for (String name : moveSelection) { + itemScroll.colors.put(name, 0xFFFF55); + } + } else { + itemScroll.multipleSelection = false; + itemScroll.setSelectable(true); + } + + itemScroll.setList(getItemSearchList()); + if (movePhase == 0) { + itemScroll.setSelected(prevItemName); + } + itemScroll.scrollY = Math.max(0, Math.min(savedItemScrollY, itemScroll.maxScrollY)); + addScroll(itemScroll); + + // Search field under center panel + if (movePhase == 0) { + int searchY = contentY + scrollH + gap; + addTextField(new GuiNpcTextField(1, this, fontRendererObj, contentX, searchY, contentW, btnH, itemSearch)); + } + } + + // ========== Right Panel: Preview + Edit/Copy/Remove ========== + @Override + protected void initRightPanel(int startY) { + // Preview area — reserve space for 3 buttons + ID label at bottom + int bottomH = (btnH + gap) * 2 + 14; // edit+copy row, remove row, ID label + previewX = rightX; + previewY = contentY; + previewW = rightPanelW; + previewH = contentH - bottomH - gap; + + // Bottom buttons: Edit + Copy on one row, Remove below + int btnY = contentY + contentH - btnH * 2 - gap; + int halfW = (rightPanelW - gap) / 2; + + GuiNpcButton editBtn = new GuiNpcButton(51, rightX, btnY, halfW, btnH, "gui.edit"); + editBtn.enabled = hasSelectedItem() && movePhase == 0; + addButton(editBtn); + + GuiNpcButton cloneBtn = new GuiNpcButton(52, rightX + halfW + gap, btnY, halfW, btnH, "gui.copy"); + cloneBtn.enabled = hasSelectedItem() && movePhase == 0; + addButton(cloneBtn); + + int removeY = btnY + btnH + gap; + GuiNpcButton removeBtn = new GuiNpcButton(53, rightX, removeY, rightPanelW, btnH, "gui.remove"); + removeBtn.enabled = hasSelectedItem() && movePhase == 0; + removeBtn.setTextColor(0xFF5555); + addButton(removeBtn); + } + + // ========== Drawing ========== + @Override + protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { + // Draw collapse button icon + GuiNpcButton collapseBtn = getButton(19); + if (collapseBtn != null && collapseBtn.visible) { + mc.getTextureManager().bindTexture(DIRECTORY_ICON); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + int iconSize = 16; + int iconX = collapseBtn.xPosition + (collapseBtn.width - iconSize) / 2; + int iconY = collapseBtn.yPosition + (collapseBtn.height - iconSize) / 2; + int texY; + if (!collapseBtn.enabled) { + texY = 32; + } else { + boolean hovered = mouseX >= collapseBtn.xPosition && mouseY >= collapseBtn.yPosition + && mouseX < collapseBtn.xPosition + collapseBtn.width + && mouseY < collapseBtn.yPosition + collapseBtn.height; + texY = hovered ? 16 : 0; + } + func_152125_a(iconX, iconY, 0, texY, 16, 16, iconSize, iconSize, 256, 256); + GL11.glDisable(GL11.GL_BLEND); + } + + if (!hasSubGui()) { + // Draw preview background + GuiUtil.drawRectD(previewX, previewY, previewX + previewW, previewY + previewH, 0xA0101010); + + // Zoom/rotation in preview area + if (isMouseOverPreview(mouseX, mouseY)) { + float wheel = Mouse.getDWheel() * 0.035f; + if (wheel != 0) { + zoomed += wheel; + zoomed = Math.max(5, Math.min(200, zoomed)); + } + if (Mouse.isButtonDown(0) || Mouse.isButtonDown(1)) { + rotation -= Mouse.getDX() * 0.75f; + } + } + + // Draw preview content + if (hasSelectedItem()) { + int centerX = previewX + previewW / 2; + int centerY = previewY + (int)(previewH * 0.75f); + drawItemPreview(centerX, centerY, mouseX, mouseY, partialTicks); + } + + // Draw details text + if (hasSelectedItem()) { + drawItemDetails(previewX + 4, previewY + 4, previewW - 8); + } + + // Draw ID (skip if -1, e.g. abilities use names not IDs) + if (hasSelectedItem() && getSelectedItemId() >= 0) { + String idStr = StatCollector.translateToLocal("gui.id") + ": " + getSelectedItemId(); + int idY = contentY + contentH - btnH * 2 - gap - 12; + fontRendererObj.drawString(idStr, previewX + 4, idY, 0xFFFFFF, true); + } + } + + // Move phase overlay text + if (movePhase == 1) { + String text = String.format(StatCollector.translateToLocal("gui.move.selectItems"), MAX_MOVE_ITEMS); + int textW = fontRendererObj.getStringWidth(text); + fontRendererObj.drawStringWithShadow(text, width / 2 - textW / 2, height - pad - 10, 0x55FF55); + } else if (movePhase == 2) { + String text = StatCollector.translateToLocal("gui.move.selectCategory"); + int textW = fontRendererObj.getStringWidth(text); + fontRendererObj.drawStringWithShadow(text, width / 2 - textW / 2, height - pad - 10, 0xFF5555); + } + } + + protected boolean isMouseOverPreview(int mouseX, int mouseY) { + return mouseX >= previewX && mouseX <= previewX + previewW + && mouseY >= previewY && mouseY <= previewY + previewH; + } + + // ========== Nav List Builder ========== + private void buildNavList() { + navNames.clear(); + navIcons.clear(); + String searchLower = catSearch.toLowerCase(); + + // Uncategorized always first + String uncatName = "Uncategorized"; + if (searchLower.isEmpty() || uncatName.toLowerCase().contains(searchLower)) { + navNames.add(uncatName); + navIcons.add(GuiCustomScrollIcons.ICON_TAB); + } + + // Other categories + for (String name : catData.keySet()) { + if (name.equals(uncatName)) continue; + if (searchLower.isEmpty() || name.toLowerCase().contains(searchLower)) { + navNames.add(name); + navIcons.add(GuiCustomScrollIcons.ICON_FOLDER); + } + } + } + + protected boolean isCategoryEmpty(int catId) { + if (!itemDataLoaded) return false; + return itemData == null || itemData.isEmpty(); + } + + // ========== Search ========== + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + + GuiNpcTextField itemSearchField = getTextField(1); + if (itemSearchField != null) { + String newText = itemSearchField.getText().toLowerCase(); + if (!itemSearch.equals(newText)) { + itemSearch = newText; + itemScroll.setList(getItemSearchList()); + } + } + + GuiNpcTextField catSearchField = getTextField(3); + if (catSearchField != null) { + String newText = catSearchField.getText().toLowerCase(); + if (!catSearch.equals(newText)) { + catSearch = newText; + buildNavList(); + catScroll.setListWithIcons(navNames, navIcons); + catScroll.setSelected(prevCatName); + } + } + } + + protected List getItemSearchList() { + if (selectedCatId < 0) return new ArrayList<>(); + if (itemSearch.isEmpty()) return new ArrayList<>(itemData.keySet()); + List list = new ArrayList<>(); + HashMap> tagMap = itemScroll.getItemTagMap(); + for (String name : itemData.keySet()) { + if (name.toLowerCase().contains(itemSearch)) { + list.add(name); + } else if (tagMap != null && tagMap.containsKey(name)) { + // Search by tag name — match [tagname] or just tagname + HashSet uuids = tagMap.get(name); + TagController tc = TagController.getInstance(); + if (tc != null) { + for (UUID uuid : uuids) { + noppes.npcs.controllers.data.Tag tag = tc.getTagFromUUID(uuid); + if (tag != null && tag.name.toLowerCase().contains(itemSearch.replace("[", "").replace("]", ""))) { + list.add(name); + break; + } + } + } + } + } + return list; + } + + // ========== Actions ========== + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + + // Close + if (id == 17) close(); + + // Collapse/Expand + if (id == 19 && hasCategories() && movePhase == 0) { + leftCollapsed = !leftCollapsed; + initGui(); + return; + } + + // Minimize + if (id == 18) { + GuiScreen windowed = getWindowedVariant(); + if (windowed != null) { + Minecraft.getMinecraft().displayGuiScreen(windowed); + return; + } + } + + // ===== Item operations ===== + + // Add item + if (id == 50 && selectedCatId >= 0 && movePhase == 0) { + pendingNewItemCatId = selectedCatId > 0 ? selectedCatId : -1; + onAddItem(selectedCatId); + requestItemsInCategory(selectedCatId); + } + + // Edit item + if (id == 51 && hasSelectedItem() && movePhase == 0) { + onEditItem(); + } + + // Clone item + if (id == 52 && hasSelectedItem() && movePhase == 0) { + onCloneItem(); + requestItemsInCategory(selectedCatId); + } + + // Remove item + if (id == 53 && hasSelectedItem() && movePhase == 0) { + GuiYesNo guiyesno = new GuiYesNo(this, itemScroll.getSelected(), StatCollector.translateToLocal("gui.delete"), 2); + displayGuiScreen(guiyesno); + } + + // Move button + if (id == 54) { + if (movePhase == 0) { + // Start move phase 1 + movePhase = 1; + moveSelection.clear(); + initGui(); + } else { + // Cancel move + movePhase = 0; + moveSelection.clear(); + initGui(); + } + } + + // Confirm move (transition phase 1 → 2) + if (id == 55 && movePhase == 1 && !moveSelection.isEmpty()) { + movePhase = 2; + initGui(); + } + + // ===== Left panel category operations ===== + + // Add category + if (id == 40 && movePhase == 0) { + String name = "New"; + while (catData.containsKey(name)) name += "_"; + Category cat = new Category(-1, name); + onSaveCategory(cat); + } + + // Rename category + if (id == 41 && selectedCatId > 0 && movePhase == 0) { + setSubGui(new SubGuiEditText(prevCatName)); + } + + // Remove category + if (id == 42 && selectedCatId > 0 && movePhase == 0) { + GuiYesNo guiyesno = new GuiYesNo(this, prevCatName, StatCollector.translateToLocal("gui.delete"), 5); + displayGuiScreen(guiyesno); + } + } + + // ========== Scroll Events ========== + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + // Category scroll + if (guiCustomScroll.id == 2) { + // Block category clicks during move phase 1 (selecting items) + if (movePhase == 1) return; + + String selected = catScroll.getSelected(); + if (selected == null) return; + + // Move phase 2: destination selected — show confirmation + if (movePhase == 2) { + if (!selected.equals(prevCatName)) { + Integer destCatId = catData.get(selected); + if (destCatId != null) { + pendingMoveDestCatId = destCatId; + pendingMoveDestName = selected; + setSubGui(new SubGuiCategoryMoveConfirm(moveSelection.size(), selected)); + } + } + return; + } + + // Normal category selection + if (!selected.equals(prevCatName)) { + pendingNewItemCatId = -1; + itemDataLoaded = false; + Integer catId = catData.get(selected); + if (catId != null) { + selectedCatId = catId; + itemScroll.selected = -1; + prevItemName = ""; + requestItemsInCategory(selectedCatId); + prevCatName = selected; + resetItemScroll = true; + initGui(); + } + } + } + + // Item scroll + if (guiCustomScroll.id == 0) { + pendingNewItemCatId = -1; + if (movePhase == 1) { + // Enforce max selection during move + if (moveSelection.size() > MAX_MOVE_ITEMS) { + // Remove excess — keep only first MAX_MOVE_ITEMS + HashSet trimmed = new HashSet<>(); + int count = 0; + for (String s : moveSelection) { + if (count++ >= MAX_MOVE_ITEMS) break; + trimmed.add(s); + } + moveSelection.clear(); + moveSelection.addAll(trimmed); + itemScroll.setSelectedList(moveSelection); + } + // Update confirm button state + if (getButton(55) != null) { + getButton(55).enabled = !moveSelection.isEmpty(); + } + return; + } + + String selected = itemScroll.getSelected(); + if (selected != null && !selected.equals(prevItemName)) { + Integer itemId = itemData.get(selected); + if (itemId != null) { + requestItemData(itemId); + prevItemName = selected; + } + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && hasSelectedItem() && movePhase == 0) { + onEditItem(); + } + } + + // ========== Move Execution ========== + protected abstract void sendMovePacket(int itemId, int destCatId); + + protected void executeMoveItems(int destCatId) { + for (String name : moveSelection) { + Integer itemId = itemData.get(name); + if (itemId != null) { + sendMovePacket(itemId, destCatId); + } + } + movePhase = 0; + moveSelection.clear(); + // Refresh current category items + if (selectedCatId >= 0) { + requestItemsInCategory(selectedCatId); + } + initGui(); + } + + // ========== Data from Server ========== + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.CATEGORY_LIST) { + // Category list arrived + String name = catScroll.getSelected(); + this.catData = data; + buildNavList(); + catScroll.setListWithIcons(navNames, navIcons); + if (name != null) catScroll.setSelected(name); + else catScroll.setSelected(prevCatName); + + // Auto-select Uncategorized on first load + if (selectedCatId < 0 && catData.containsKey("Uncategorized")) { + selectedCatId = catData.get("Uncategorized"); + prevCatName = "Uncategorized"; + catScroll.setSelected(prevCatName); + requestItemsInCategory(selectedCatId); + } + initGui(); + } else if (type == EnumScrollData.CATEGORY_GROUP) { + // Items within selected category + String name = itemScroll.getSelected(); + this.itemData = data; + this.itemDataLoaded = true; + itemScroll.setList(getItemSearchList()); + if (name != null) itemScroll.setSelected(name); + initGui(); + } + // Ignore OPTIONAL and other types silently + } + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("CategoryTagMap")) { + // Tag map for category items + HashMap> tagMap = new HashMap<>(); + NBTTagList entries = compound.getTagList("CategoryTagMap", 10); + for (int i = 0; i < entries.tagCount(); i++) { + NBTTagCompound entry = entries.getCompoundTagAt(i); + String itemName = entry.getString("Name"); + HashSet uuids = TagController.readTagUUIDs(entry, "Tags"); + if (!uuids.isEmpty()) { + tagMap.put(itemName, uuids); + } + } + itemScroll.setItemTagMap(tagMap); + return; + } + onItemReceived(compound); + if (pendingNewItemCatId > 0 && hasSelectedItem()) { + if (getSelectedItemId() >= 0) { + sendMovePacket(getSelectedItemId(), pendingNewItemCatId); + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + } else { + onMoveNewItem(pendingNewItemCatId); + } + } + pendingNewItemCatId = -1; + initGui(); + } + + // ========== SubGui ========== + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiEditText) { + if (!((SubGuiEditText) subgui).cancelled && selectedCatId > 0) { + String name = ((SubGuiEditText) subgui).text; + if (name != null && !name.isEmpty() && !name.equals(prevCatName) && !catData.containsKey(name)) { + Category cat = new Category(selectedCatId, name); + onSaveCategory(cat); + catData.remove(prevCatName); + catData.put(name, selectedCatId); + prevCatName = name; + } + } + // Restore category selection to current name (handles validation failure) + catScroll.setSelected(prevCatName); + } + if (subgui instanceof SubGuiCategoryMoveConfirm) { + SubGuiCategoryMoveConfirm confirm = (SubGuiCategoryMoveConfirm) subgui; + if (confirm.confirmed && !moveSelection.isEmpty() && pendingMoveDestCatId >= 0) { + executeMoveItems(pendingMoveDestCatId); + } else { + // Cancelled — stay in phase 2 + } + pendingMoveDestCatId = -1; + pendingMoveDestName = ""; + } + onSubGuiClosed(subgui); + } + + protected void onSubGuiClosed(SubGuiInterface subgui) {} + + // ========== Confirm Dialog ========== + @Override + public void confirmClicked(boolean result, int id) { + NoppesUtil.openGUI(player, this); + if (!result) return; + + // Remove category + if (id == 5 && selectedCatId > 0) { + onRemoveCategory(selectedCatId); + selectedCatId = -1; + prevCatName = ""; + itemData.clear(); + catScroll.selected = -1; + } + + // Remove item + if (id == 2 && itemScroll.getSelected() != null && itemData.containsKey(itemScroll.getSelected())) { + onRemoveItem(itemData.get(itemScroll.getSelected())); + itemData.clear(); + prevItemName = ""; + if (selectedCatId >= 0) requestItemsInCategory(selectedCatId); + } + initGui(); + } + + @Override + public void setSelected(String selected) {} + + @Override + public void save() {} +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java index a390ddfc1..b27f36519 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java @@ -6,6 +6,7 @@ import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.texture.TextureManager; import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.controllers.data.CustomEffect; import noppes.npcs.controllers.data.PlayerEffect; @@ -80,9 +81,17 @@ public class GuiEffectBar extends GuiScreen { int iconWidth = entry.effect.getWidth(); int iconHeight = entry.effect.getHeight(); int texWidth = imageData.getTotalWidth(); + int texHeight = imageData.getTotalHeight(); + + // Animation V offset + if (imageData.isAnimated()) { + iconV += (int) (imageData.getCurrentFrameVOffset() * texHeight); + } else if (entry.effect.animated && entry.effect.frameCount > 1) { + iconV += (int) (AnimationHelper.getFrameVOffset(texHeight, entry.effect.frameCount, entry.effect.frametime) * texHeight); + } // Use iconYOffset to vertically center the icon - func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texWidth); + func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight); GL11.glDisable(GL11.GL_DEPTH_TEST); Minecraft.getMinecraft().getTextureManager().bindTexture(specialIcons); @@ -190,7 +199,14 @@ public class GuiEffectBar extends GuiScreen { if (imageData != null && imageData.imageLoaded()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); imageData.bindTexture(); - func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalWidth()); + int tooltipIconV = hoveredEffect.iconY; + int tooltipTexH = imageData.getTotalHeight(); + if (imageData.isAnimated()) { + tooltipIconV += (int) (imageData.getCurrentFrameVOffset() * tooltipTexH); + } else if (hoveredEffect.animated && hoveredEffect.frameCount > 1) { + tooltipIconV += (int) (AnimationHelper.getFrameVOffset(tooltipTexH, hoveredEffect.frameCount, hoveredEffect.frametime) * tooltipTexH); + } + func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, tooltipIconV, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), tooltipTexH); } textureManager.bindTexture(specialIcons); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java index 413ca7b39..9d972be3d 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java @@ -24,10 +24,21 @@ public class GuiMenuTopButton extends GuiNpcButton { height = 20; } + /** + * Place to the RIGHT of the given button. + */ public GuiMenuTopButton(int i, GuiButton parent, String s) { this(i, parent.xPosition + parent.width, parent.yPosition, s); } + /** + * Place to the LEFT of the given button. + */ + public GuiMenuTopButton(int i, String s, GuiButton rightNeighbor) { + this(i, rightNeighbor.xPosition - (Minecraft.getMinecraft().fontRenderer.getStringWidth(StatCollector.translateToLocal(s)) + 12), + rightNeighbor.yPosition, s); + } + public GuiMenuTopButton(int i, GuiButton parent, String s, IButtonListener listener) { this(i, parent, s); @@ -85,7 +96,10 @@ public class GuiMenuTopButton extends GuiNpcButton { @Override public boolean mousePressed(Minecraft minecraft, int i, int j) { - boolean bo = !active && getVisible() && hover; + int h = this.height - (active ? 0 : 2); + boolean bo = !active && getVisible() + && i >= xPosition && j >= yPosition + && i < xPosition + getWidth() && j < yPosition + h; if (bo && listener != null) { listener.actionPerformed(this); return false; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java b/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java index 5ca2edfb0..37ce2b789 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java @@ -34,7 +34,7 @@ public class GuiModelInterface2 extends GuiNPCInterface2 { } /** - * @param npc The NPC for preview rendering + * @param npc The NPC for preview rendering * @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden. * Use false when opened from the global menu without a real NPC. */ @@ -151,8 +151,9 @@ public class GuiModelInterface2 extends GuiNPCInterface2 { @Override public void keyTyped(char par1, int par2) { + boolean hadSubGui = hasSubGui(); super.keyTyped(par1, par2); - if (par2 == 1) { + if (par2 == 1 && !hadSubGui) { close(); } } 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 cf9143c66..24d08cff2 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -61,6 +61,30 @@ public abstract class GuiNPCInterface extends GuiScreen { public float bgScaleZ = 1; public int bgTextureHeight = 256; // Actual content height in texture (for bottom border stitching) + // ==================== VIEWPORT PANNING ==================== + /** + * If true, this GUI supports viewport panning via click-drag on empty areas. + * Subclasses set this to true and call computePanBounds() to enable. + */ + protected boolean isPannableGUI = false; + protected boolean isPanning = false; + protected double panStartX, panStartY; + + /** + * Cumulative pan offset in scaled GUI pixels. + * Positive values = viewport shifted right/down (content appears to move left/up). + */ + public double currentPanX, currentPanY; + + public double getPanX() { return currentPanX; } + public double getPanY() { return currentPanY; } + + protected double minPanX, maxPanX, minPanY, maxPanY; + protected int panViewportX, panViewportY, panViewportWidth, panViewportHeight; + + /** Pan-adjusted mouse coordinates, updated every frame in drawScreen for hit-testing panned components. */ + protected int panAdjMouseX, panAdjMouseY; + public GuiNPCInterface(EntityNPCInterface npc) { this.player = Minecraft.getMinecraft().thePlayer; this.npc = npc; @@ -161,28 +185,39 @@ public abstract class GuiNPCInterface extends GuiScreen { if (subgui != null) subgui.mouseClicked(i, j, k); else { - for (GuiNpcTextField tf : new ArrayList(textfields.values())) - if (tf.enabled) - tf.mouseClicked(i, j, k); + int adjX = isPannableGUI ? panAdjustedX(i) : i; + int adjY = isPannableGUI ? panAdjustedY(j) : j; + + if (isPannableGUI && k == 0 && isPannableArea(adjX, adjY)) { + isPanning = true; + panStartX = i; + panStartY = j; + return; + } + + mouseEvent(adjX, adjY, k); + vanillaMouseClicked(adjX, adjY, k); for (GuiScrollWindow guiScrollableComponent : scrollWindows.values()) { - guiScrollableComponent.mouseClicked(i, j, k); + guiScrollableComponent.mouseClicked(adjX, adjY, k); } if (k == 0) { for (GuiCustomScroll scroll : new ArrayList(scrolls.values())) { - scroll.mouseClicked(i, j, k); + scroll.mouseClicked(adjX, adjY, k); } } - // Process diagram mouse clicks for (GuiDiagram diagram : diagrams.values()) { - if (diagram.isWithin(i, j)) { - if (diagram.mouseClicked(i, j, k)) + if (diagram.isWithin(adjX, adjY)) { + if (diagram.mouseClicked(adjX, adjY, k)) return; } } - mouseEvent(i, j, k); - vanillaMouseClicked(i, j, k); + + for (GuiNpcTextField tf : new ArrayList(textfields.values())) + if (tf.enabled) + tf.mouseClicked(adjX, adjY, k); + } } @@ -223,7 +258,12 @@ public abstract class GuiNPCInterface extends GuiScreen { subgui.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); return; } - super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + if (isPannableGUI && isPanning) { + return; + } + int adjX = isPannableGUI ? panAdjustedX(mouseX) : mouseX; + int adjY = isPannableGUI ? panAdjustedY(mouseY) : mouseY; + super.mouseClickMove(adjX, adjY, clickedMouseButton, timeSinceLastClick); } @Override @@ -232,12 +272,72 @@ public abstract class GuiNPCInterface extends GuiScreen { subgui.mouseMovedOrUp(mouseX, mouseY, state); return; } - super.mouseMovedOrUp(mouseX, mouseY, state); + if (isPannableGUI && state == 0 && isPanning) { + isPanning = false; + panStartX = 0; + panStartY = 0; + return; + } + int adjX = isPannableGUI ? panAdjustedX(mouseX) : mouseX; + int adjY = isPannableGUI ? panAdjustedY(mouseY) : mouseY; + super.mouseMovedOrUp(adjX, adjY, state); } public void mouseEvent(int i, int j, int k) { } + // ==================== VIEWPORT PANNING METHODS ==================== + + protected boolean isPannableArea(int mx, int my) { + for (Object obj : this.buttonList) { + GuiButton btn = (GuiButton) obj; + if (btn.visible && mx >= btn.xPosition && mx < btn.xPosition + btn.width + && my >= btn.yPosition && my < btn.yPosition + btn.height) { + return false; + } + } + + for (GuiCustomScroll scroll : scrolls.values()) { + if (scroll.visible && scroll.isMouseOver(mx, my)) { + return false; + } + } + + for (GuiNpcTextField tf : textfields.values()) { + if (tf.enabled && mx >= tf.xPosition && mx < tf.xPosition + tf.width + && my >= tf.yPosition && my < tf.yPosition + tf.height) { + return false; + } + } + + return true; + } + + protected void computePanBounds(int vpX, int vpY, int vpW, int vpH) { + this.panViewportX = vpX; + this.panViewportY = vpY; + this.panViewportWidth = vpW; + this.panViewportHeight = vpH; + + int panRange = Math.max(this.width, this.height) / 2; + this.minPanX = -panRange; + this.maxPanX = panRange; + this.minPanY = -panRange; + this.maxPanY = panRange; + } + + protected int panAdjustedX(int rawMouseX) { + return rawMouseX + (int) currentPanX; + } + + protected int panAdjustedY(int rawMouseY) { + return rawMouseY + (int) currentPanY; + } + + public boolean hasPanOffset() { + return isPannableGUI && (currentPanX != 0 || currentPanY != 0); + } + @Override protected void actionPerformed(GuiButton guibutton) { if (subgui != null) @@ -375,50 +475,101 @@ public abstract class GuiNPCInterface extends GuiScreen { public void drawScreen(int i, int j, float f) { mouseX = i; mouseY = j; + + boolean panning = hasPanOffset(); + int drawX = panning ? panAdjustedX(i) : i; + int drawY = panning ? panAdjustedY(j) : j; + panAdjMouseX = drawX; + panAdjMouseY = drawY; + + // Smooth pan: update pan offset every frame using raw mouse delta + if (isPannableGUI && isPanning && Mouse.isButtonDown(0)) { + double deltaX = i - panStartX; + double deltaY = j - panStartY; + + currentPanX = Math.max(minPanX, Math.min(maxPanX, currentPanX - deltaX)); + currentPanY = Math.max(minPanY, Math.min(maxPanY, currentPanY - deltaY)); + + panStartX = i; + panStartY = j; + + panning = hasPanOffset(); + drawX = panning ? panAdjustedX(i) : i; + drawY = panning ? panAdjustedY(j) : j; + panAdjMouseX = drawX; + panAdjMouseY = drawY; + } else if (isPanning && !Mouse.isButtonDown(0)) { + isPanning = false; + } + if (drawDefaultBackground && subgui == null) drawDefaultBackground(); + if (panning) { + GL11.glPushMatrix(); + GL11.glTranslated(-currentPanX, -currentPanY, 0); + } + if (background != null && mc.renderEngine != null) { drawBackground(); } boolean subGui = hasSubGui(); + + // Mouse.getDWheel() clears the accumulated delta, so only the first caller in a frame + // ever sees it. Read it once here and let each widget take it in turn; anything that + // consumes it zeroes it so later widgets - the script editor, for one - are not left + // reading an already-drained wheel. + mouseScroll = Mouse.getDWheel(); + drawCenteredString(fontRendererObj, title, width / 2, guiTop + 4, 0xffffff); for (GuiNpcLabel label : labels.values()) label.drawLabel(this, fontRendererObj); - for (GuiNpcTextField tf : textfields.values()) { - tf.drawTextBox(i, j); - } for (GuiCustomScroll scroll : scrolls.values()) { scroll.updateSubGUI(subGui); - scroll.drawScreen(i, j, f, !subGui && scroll.isMouseOver(i, j) ? Mouse.getDWheel() : 0); + int delta = !subGui && scroll.isMouseOver(drawX, drawY) ? mouseScroll : 0; + if (delta != 0) + mouseScroll = 0; + scroll.drawScreen(drawX, drawY, f, delta); } - // Draw scrollable windows. for (GuiScrollWindow guiScrollableComponent : scrollWindows.values()) { - guiScrollableComponent.drawScreen(i, j, f, !subGui && guiScrollableComponent.isMouseOver(i, j) ? Mouse.getDWheel() : 0); + int delta = !subGui && guiScrollableComponent.isMouseOver(drawX, drawY) ? mouseScroll : 0; + if (delta != 0) + mouseScroll = 0; + guiScrollableComponent.drawScreen(drawX, drawY, f, delta); } for (GuiDiagram diagram : diagrams.values()) { - diagram.drawDiagram(i, j, subGui); + diagram.drawDiagram(drawX, drawY, subGui); } - super.drawScreen(i, j, f); + super.drawScreen(drawX, drawY, f); for (GuiCustomScroll scroll : scrolls.values()) if (scroll.hoverableText) { - scroll.drawHover(i, j); + scroll.drawHover(drawX, drawY); } for (GuiNpcButton button : buttons.values()) { button.updateSubGUI(subGui); if (!button.hoverableText.isEmpty()) { - button.drawHover(i, j, subGui); + button.drawHover(drawX, drawY, subGui); } } - for (GuiNpcTextField textField : textfields.values()) { - if (textField.hasHoverText()) { - textField.drawHover(i, j, subGui); + for (GuiNpcTextField tf : textfields.values()) { + tf.drawTextBox(drawX, drawY); + if (tf.hasHoverText()) + tf.drawHover(drawX, drawY, subGui); + } + + for(GuiScrollWindow guiScrollableComponent : scrollWindows.values()) { + if (guiScrollableComponent.isMouseOver(drawX, drawY)) { + guiScrollableComponent.drawHoverTexts(drawX, drawY); } } for (GuiScreen gui : extra.values()) - gui.drawScreen(i, j, f); + gui.drawScreen(drawX, drawY, f); + + if (panning) { + GL11.glPopMatrix(); + } if (subgui != null) { subgui.drawScreen(i, j, f); @@ -440,8 +591,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/GuiNpcButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java index 4ebafd54f..489069610 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java @@ -5,6 +5,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; @@ -82,7 +83,8 @@ public class GuiNpcButton extends GuiButton { } public void setHoverText(String text) { - this.hoverableText = StatCollector.translateToLocal(text); + String translated = StatCollector.translateToLocal(text); + this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n"); } public int getValue() { @@ -165,8 +167,13 @@ public class GuiNpcButton extends GuiButton { } } } - // First, draw the button normally using the superclass method. - super.drawButton(mc, mouseX, mouseY); + // Wide buttons (>396px) break the vanilla 200px button texture. + // Draw them with a three-patch approach instead. + if (this.width > 396) { + drawWideButton(mc, mouseX, mouseY); + } else { + super.drawButton(mc, mouseX, mouseY); + } // Restore original display string this.displayString = original; // Then, if an icon texture is set, draw it. @@ -174,17 +181,58 @@ public class GuiNpcButton extends GuiButton { mc.getTextureManager().bindTexture(iconTexture); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); - // Calculate the icon position so that it's centered in the button. - // (Assumes the button's (xPosition,yPosition) is its top left.) int iconX = this.xPosition + (this.width - iconWidth) / 2; int iconY = this.yPosition + (this.height - iconHeight) / 2; - // Draw the texture; we assume texture coordinates start at (0,0) with the desired size. this.drawTexturedModalRect(iconX, iconY, iconPosX, iconPosY, iconWidth, iconHeight); RenderHelper.disableStandardItemLighting(); GL11.glPopMatrix(); } } + /** + * Draws a button wider than the vanilla 200px texture allows. + * Uses three-patch rendering: left cap, tiled center, right cap. + */ + private void drawWideButton(Minecraft mc, int mouseX, int mouseY) { + FontRenderer fontrenderer = mc.fontRenderer; + mc.getTextureManager().bindTexture(buttonTextures); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.field_146123_n = mouseX >= this.xPosition && mouseY >= this.yPosition + && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; + int k = this.getHoverState(this.field_146123_n); + GL11.glEnable(GL11.GL_BLEND); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + int texY = 46 + k * 20; + int cap = 100; + + // Left cap (first 100px of texture) + this.drawTexturedModalRect(this.xPosition, this.yPosition, 0, texY, cap, this.height); + // Right cap (last 100px of texture) + this.drawTexturedModalRect(this.xPosition + this.width - cap, this.yPosition, 200 - cap, texY, cap, this.height); + // Tile the center column to fill the gap + int gapStart = this.xPosition + cap; + int gapEnd = this.xPosition + this.width - cap; + for (int x = gapStart; x < gapEnd; x += 2) { + int drawW = Math.min(2, gapEnd - x); + this.drawTexturedModalRect(x, this.yPosition, 99, texY, drawW, this.height); + } + + this.mouseDragged(mc, mouseX, mouseY); + + int l = 14737632; + if (packedFGColour != 0) { + l = packedFGColour; + } else if (!this.enabled) { + l = 10526880; + } else if (this.field_146123_n) { + l = 16777120; + } + this.drawCenteredString(fontrenderer, this.displayString, + this.xPosition + this.width / 2, this.yPosition + (this.height - 8) / 2, l); + } + public void drawHover(int i, int j, boolean hasSubGui) { if (hasSubGui || !visible || hoverableText.isEmpty()) return; @@ -201,13 +249,30 @@ public class GuiNpcButton extends GuiButton { Minecraft mc = Minecraft.getMinecraft(); String displayString = StatCollector.translateToLocal(hoverableText); GL11.glColor4f(1, 1, 1, 1); - List lines = TextSplitter.splitText(displayString, 30); + List lines = splitHoverText(displayString, 30); drawHoveringText(lines, i, j, mc); GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); } } + private List splitHoverText(String text, int maxLineLength) { + List lines = new ArrayList(); + if (text == null || text.isEmpty()) + return lines; + + String normalized = text.replace("\\n", "\n"); + String[] explicitLines = normalized.split("\\r?\\n", -1); + for (String line : explicitLines) { + if (line.isEmpty()) { + lines.add(""); + continue; + } + lines.addAll(TextSplitter.splitText(line, maxLineLength)); + } + return lines; + } + protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) { if (mc.fontRenderer == null || textLines.isEmpty()) return; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java index 60b4afdb6..4a1ac4b24 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java @@ -60,12 +60,13 @@ public class GuiNpcLabel extends Gui { /** * Draws hover tooltip if the mouse is over this label. - * @param localMouseX Mouse X in scroll-local coordinates (for hit testing) - * @param localMouseY Mouse Y in scroll-local coordinates (for hit testing) + * + * @param localMouseX Mouse X in scroll-local coordinates (for hit testing) + * @param localMouseY Mouse Y in scroll-local coordinates (for hit testing) * @param screenMouseX Mouse X in screen coordinates (for tooltip positioning) * @param screenMouseY Mouse Y in screen coordinates (for tooltip positioning) - * @param hasSubGui Whether a sub-gui is open - * @param fr FontRenderer for measuring label width + * @param hasSubGui Whether a sub-gui is open + * @param fr FontRenderer for measuring label width */ public void drawHover(int localMouseX, int localMouseY, int screenMouseX, int screenMouseY, boolean hasSubGui, FontRenderer fr) { if (hasSubGui || hoverableText.isEmpty()) return; 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..b527663d6 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java @@ -1,17 +1,19 @@ package noppes.npcs.client.gui.util; +import kamkeel.npcs.util.TextSplitter; +import kamkeel.npcs.util.FileNameHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; -import net.minecraft.util.StatCollector; import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.util.StatCollector; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import net.minecraft.client.renderer.RenderHelper; -import kamkeel.npcs.util.TextSplitter; + +import java.util.ArrayList; import java.util.List; -import java.util.Iterator; public class GuiNpcTextField extends GuiTextField { public boolean enabled = true; @@ -26,11 +28,12 @@ public class GuiNpcTextField extends GuiTextField { public float minFloat = 0, maxFloat = Float.MAX_VALUE, defFloat = 0; protected static GuiNpcTextField activeTextfield = null; public boolean canEdit = true; + private boolean fileNameSafe = false; public String hoverableText = ""; private boolean wasHovered = false; private int hoverCount = 0; - private final int[] allowedSpecialChars = {14, 211, 203, 205}; + private final int[] allowedSpecialChars = {14, 211, 203, 205, 199, 207}; public GuiNpcTextField(int id, GuiScreen parent, FontRenderer fontRenderer, int i, int j, int k, int l, String s) { super(fontRenderer, i, j, k, l); @@ -60,6 +63,9 @@ public class GuiNpcTextField extends GuiTextField { if (integersOnly && getText().isEmpty() && c == '-') return true; + if ((floatsOnly || doublesOnly) && getText().isEmpty() && c == '-') + return true; + for (int j : allowedSpecialChars) if (j == i) return true; @@ -69,11 +75,50 @@ public class GuiNpcTextField extends GuiTextField { @Override public boolean textboxKeyTyped(char c, int i) { - if (!charAllowed(c, i) || !canEdit) + if (!canEdit || !isFocused()) + return false; + + if (fileNameSafe && !GuiScreen.isCtrlKeyDown() && !isFileNameCharAllowed(c, i)) { + return false; + } + + // Allow Ctrl shortcuts (select all, copy, paste, cut) to bypass char filter + if (GuiScreen.isCtrlKeyDown()) { + // For Ctrl+V (paste) on numeric fields, filter clipboard to valid chars + if (i == 47 && isNumericField()) { + String clipboard = GuiScreen.getClipboardString(); + if (clipboard != null) { + StringBuilder filtered = new StringBuilder(); + for (char ch : clipboard.toCharArray()) { + if (Character.isDigit(ch) || ch == '-' || ((doublesOnly || floatsOnly) && ch == '.')) + filtered.append(ch); + } + if (filtered.length() > 0) + writeText(filtered.toString()); + } + return true; + } + if (i == 47 && fileNameSafe) { + String clipboard = GuiScreen.getClipboardString(); + if (clipboard != null) { + String filtered = filterFileNameClipboard(clipboard); + if (!filtered.isEmpty()) + writeText(filtered); + } + return true; + } + boolean handled = super.textboxKeyTyped(c, i); + return handled; + } + if (!charAllowed(c, i)) return false; return super.textboxKeyTyped(c, i); } + private boolean isNumericField() { + return integersOnly || doublesOnly || floatsOnly; + } + public boolean isEmpty() { return getText().trim().length() == 0; } @@ -155,6 +200,9 @@ public class GuiNpcTextField extends GuiTextField { else if (getFloat() > maxFloat) setText(maxFloat + ""); } + if (fileNameSafe) { + normalizeFileNameText(); + } setCursorPositionZero(); if (listener != null) listener.unFocused(this); @@ -214,8 +262,54 @@ public class GuiNpcTextField extends GuiTextField { return this; } + public GuiNpcTextField setFileNameSafe() { + fileNameSafe = true; + normalizeFileNameText(); + return this; + } + + private boolean isSpecialNavigationKey(int keyCode) { + for (int allowed : allowedSpecialChars) { + if (allowed == keyCode) { + return true; + } + } + return false; + } + + private boolean isFileNameCharAllowed(char c, int keyCode) { + if (isSpecialNavigationKey(keyCode) || c < 32) { + return true; + } + return Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == ' '; + } + + private String filterFileNameClipboard(String clipboard) { + StringBuilder filtered = new StringBuilder(clipboard.length()); + for (int idx = 0; idx < clipboard.length(); idx++) { + char c = clipboard.charAt(idx); + if (Character.isLetterOrDigit(c) || c == '_' || c == '-') { + filtered.append(c); + } else if (Character.isWhitespace(c)) { + filtered.append(' '); + } + } + return filtered.toString(); + } + + private void normalizeFileNameText() { + String current = getText(); + String sanitized = FileNameHelper.sanitizeTextInput(current); + if (sanitized.equals(current)) return; + + int cursor = getCursorPosition(); + setText(sanitized); + setCursorPosition(Math.min(cursor, sanitized.length())); + } + public void setHoverText(String text) { - this.hoverableText = StatCollector.translateToLocal(text); + String translated = StatCollector.translateToLocal(text); + this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n"); } public boolean hasHoverText() { @@ -224,14 +318,18 @@ public class GuiNpcTextField extends GuiTextField { public boolean isMouseOver(int mouseX, int mouseY) { return mouseX >= xPosition && mouseX < xPosition + width && - mouseY >= yPosition && mouseY < yPosition + height; + mouseY >= yPosition && mouseY < yPosition + height; } public void drawHover(int mouseX, int mouseY, boolean hasSubGui) { + drawHover(mouseX, mouseY, mouseX, mouseY, hasSubGui); + } + + public void drawHover(int hitMouseX, int hitMouseY, int tooltipMouseX, int tooltipMouseY, boolean hasSubGui) { if (hasSubGui || !enabled || hoverableText.isEmpty()) return; - boolean isHovered = isMouseOver(mouseX, mouseY); + boolean isHovered = isMouseOver(hitMouseX, hitMouseY); if (!isHovered) { wasHovered = false; hoverCount = 0; @@ -249,13 +347,30 @@ public class GuiNpcTextField extends GuiTextField { GL11.glPushMatrix(); Minecraft mc = Minecraft.getMinecraft(); GL11.glColor4f(1, 1, 1, 1); - List lines = TextSplitter.splitText(hoverableText, 30); - drawHoveringText(lines, mouseX, mouseY, mc); + List lines = splitHoverText(hoverableText, 30); + drawHoveringText(lines, tooltipMouseX, tooltipMouseY, mc); GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); } } + private List splitHoverText(String text, int maxLineLength) { + List lines = new ArrayList(); + if (text == null || text.isEmpty()) + return lines; + + String normalized = text.replace("\\n", "\n"); + String[] explicitLines = normalized.split("\\r?\\n", -1); + for (String line : explicitLines) { + if (line.isEmpty()) { + lines.add(""); + continue; + } + lines.addAll(TextSplitter.splitText(line, maxLineLength)); + } + return lines; + } + protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) { if (mc.fontRenderer == null || textLines.isEmpty()) return; @@ -334,14 +449,14 @@ public class GuiNpcTextField extends GuiTextField { } protected void drawGradientRect(int left, int top, int right, int bottom, int startColor, int endColor, int zLevel) { - float f = (float)(startColor >> 24 & 255) / 255.0F; - float f1 = (float)(startColor >> 16 & 255) / 255.0F; - float f2 = (float)(startColor >> 8 & 255) / 255.0F; - float f3 = (float)(startColor & 255) / 255.0F; - float f4 = (float)(endColor >> 24 & 255) / 255.0F; - float f5 = (float)(endColor >> 16 & 255) / 255.0F; - float f6 = (float)(endColor >> 8 & 255) / 255.0F; - float f7 = (float)(endColor & 255) / 255.0F; + float f = (float) (startColor >> 24 & 255) / 255.0F; + float f1 = (float) (startColor >> 16 & 255) / 255.0F; + float f2 = (float) (startColor >> 8 & 255) / 255.0F; + float f3 = (float) (startColor & 255) / 255.0F; + float f4 = (float) (endColor >> 24 & 255) / 255.0F; + float f5 = (float) (endColor >> 16 & 255) / 255.0F; + float f6 = (float) (endColor >> 8 & 255) / 255.0F; + float f7 = (float) (endColor & 255) / 255.0F; GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_ALPHA_TEST); @@ -350,11 +465,11 @@ public class GuiNpcTextField extends GuiTextField { net.minecraft.client.renderer.Tessellator tessellator = net.minecraft.client.renderer.Tessellator.instance; tessellator.startDrawingQuads(); tessellator.setColorRGBA_F(f1, f2, f3, f); - tessellator.addVertex((double)right, (double)top, (double)zLevel); - tessellator.addVertex((double)left, (double)top, (double)zLevel); + tessellator.addVertex((double) right, (double) top, (double) zLevel); + tessellator.addVertex((double) left, (double) top, (double) zLevel); tessellator.setColorRGBA_F(f5, f6, f7, f4); - tessellator.addVertex((double)left, (double)bottom, (double)zLevel); - tessellator.addVertex((double)right, (double)bottom, (double)zLevel); + tessellator.addVertex((double) left, (double) bottom, (double) zLevel); + tessellator.addVertex((double) right, (double) bottom, (double) zLevel); tessellator.draw(); GL11.glShadeModel(GL11.GL_FLAT); GL11.glDisable(GL11.GL_BLEND); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java index be148c11d..70283b7e0 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java @@ -8,17 +8,24 @@ import noppes.npcs.NoppesStringUtils; import noppes.npcs.client.ClientProxy; import noppes.npcs.client.gui.script.GuiScriptInterface; import noppes.npcs.client.gui.util.key.OverlayKeyPresetViewer; -import noppes.npcs.client.gui.util.script.BracketMatcher; -import noppes.npcs.client.gui.util.script.CommentHandler; -import noppes.npcs.client.gui.util.script.CursorNavigation; -import noppes.npcs.client.gui.util.script.GoToLineDialog; -import noppes.npcs.client.gui.util.script.IndentHelper; -import noppes.npcs.client.gui.util.script.JavaTextContainer; +import noppes.npcs.client.gui.util.script.*; import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; -import noppes.npcs.client.gui.util.script.RenameRefactorHandler; -import noppes.npcs.client.gui.util.script.ScrollState; -import noppes.npcs.client.gui.util.script.SearchReplaceBar; -import noppes.npcs.client.gui.util.script.SelectionState; +// New interpreter system imports +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteMenu; +import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; +import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.Token; +import noppes.npcs.client.gui.util.script.interpreter.token.ScriptColorScheme; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.hover.GutterIconRenderer; +import noppes.npcs.client.gui.util.script.interpreter.hover.HoverState; +import noppes.npcs.client.gui.util.script.interpreter.hover.TokenHoverRenderer; +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteManager; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; import noppes.npcs.client.key.impl.ScriptEditorKeys; import noppes.npcs.constants.ScriptContext; import noppes.npcs.util.ValueUtil; @@ -36,7 +43,7 @@ import static net.minecraft.client.gui.GuiScreen.isCtrlKeyDown; /** * Script text editor component with syntax highlighting, bracket matching, * smooth scrolling, and IDE-like features. - *

+ * * Helper classes used: * - ScrollState: smooth scroll animation and state management * - SelectionState: cursor position and text selection management @@ -47,10 +54,12 @@ import static net.minecraft.client.gui.GuiScreen.isCtrlKeyDown; */ public class GuiScriptTextArea extends GuiNpcTextField { + private GuiScriptInterface parent; + // ==================== DIMENSIONS & POSITION ==================== public int x; public int y; - + // ==================== STATE FLAGS ==================== public boolean active = false; public boolean enabled = true; @@ -60,11 +69,11 @@ public class GuiScriptTextArea extends GuiNpcTextField { public boolean tripleClicked = false; private int clickCount = 0; private long lastClicked = 0L; - + // ==================== TEXT & CONTAINER ==================== public String text = null; public String highlightedWord; - private JavaTextContainer container = null; + private ScriptTextContainer container = null; private boolean enableCodeHighlighting = false; // Extra empty lines to allow padding at the bottom of the editor viewport private int bottomPaddingLines = 6; @@ -89,16 +98,31 @@ public class GuiScriptTextArea extends GuiNpcTextField { // ==================== HELPER CLASS INSTANCES ==================== private final ScrollState scroll = new ScrollState(); private final SelectionState selection = new SelectionState(); - + private final HoverState hoverState = new HoverState(); + /** When true, clicking a token will pin its hover tooltip until dismissed. */ + public boolean clickToPinEnabled = false; + // ==================== UI COMPONENTS ==================== private int cursorCounter; private ITextChangeListener listener; private static int LINE_NUMBER_GUTTER_WIDTH = 25; - + + // ==================== GUTTER ICONS ==================== + /** Hover state for gutter icons - tracks which icon the mouse is over */ + private MethodInfo hoveredGutterMethod = null; + // ==================== UNDO/REDO ==================== public List undoList = new ArrayList<>(); public List redoList = new ArrayList<>(); public boolean undoing = false; + + // Atomic undo: group typing into word-based undo steps + private long lastTypingTime = 0; + private int lastTypingPos = -1; + + // Clipboard tracking for line-copy paste behavior + private boolean lastCopyWasLine = false; + private String lastCopiedLineText = null; // ==================== KEYS ==================== public static final ScriptEditorKeys KEYS = new ScriptEditorKeys(); @@ -107,17 +131,26 @@ public class GuiScriptTextArea extends GuiNpcTextField { // ==================== SEARCH/REPLACE ==================== public static final SearchReplaceBar searchBar = new SearchReplaceBar(); + // ==================== PASTE SETTINGS ==================== + private static final int PASTE_TRAILING_WS_TRIM_THRESHOLD = 16; + // ==================== GO TO LINE ==================== private final GoToLineDialog goToLineDialog = new GoToLineDialog(); // ==================== RENAME REFACTOR ==================== private final RenameRefactorHandler renameHandler = new RenameRefactorHandler(); + // ==================== AUTOCOMPLETE ==================== + private final AutocompleteManager autocompleteManager = new AutocompleteManager(); + // ==================== CONSTRUCTOR ==================== public GuiScriptTextArea(GuiScreen guiScreen, int id, int x, int y, int width, int height, String text) { super(id, guiScreen, x, y, width, height, null); init(x, y, width, height, text); + + if (guiScreen instanceof GuiScriptInterface) + this.parent = (GuiScriptInterface) guiScreen; } public void init(int x, int y, int width, int height, String text) { @@ -134,12 +167,13 @@ public class GuiScriptTextArea extends GuiNpcTextField { this.searchBaseHeight = 0; this.searchAppliedOffset = 0; this.searchBaseInitialized = false; - + KEYS_OVERLAY.openOnClick = true; initGui(); initializeKeyBindings(); + // Propagate click-to-pin option into hover state + hoverState.setClickToPinEnabled(clickToPinEnabled); } - public void initGui() { int endX = x + width, endY = y + height; int xOffset = hasVerticalScrollbar() ? -8 : -2; @@ -147,11 +181,16 @@ public class GuiScriptTextArea extends GuiNpcTextField { KEYS_OVERLAY.borderCol1 = KEYS_OVERLAY.borderCol2 = 0xFF3c3c3c; int overlayWidth = 160; KEYS_OVERLAY.initGui(x + (width - overlayWidth) / 2 + 5, y + height / 10, overlayWidth, - height - height / 5 - 10); + height - height / 5 - 10); KEYS_OVERLAY.viewButton.scale = 0.45f; KEYS_OVERLAY.viewButton.initGui(endX + xOffset, endY - 26); - + + // Dismiss autocomplete on resize to avoid positioning issues + if (autocompleteManager != null) { + autocompleteManager.dismiss(); + } + // Initialize search bar (preserves state across initGui calls) searchBar.initGui(x, y, width); if (searchBar.isVisible()) { // If open @@ -160,7 +199,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (!active) // Focus search if opening another script tab & bar is open searchBar.focus(false); } - + // Initialize Go To Line dialog goToLineDialog.initGui(x, y, width); } @@ -203,7 +242,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { int visibleLines = effectiveHeight / container.lineHeight; // Calculate how many lines the search bar covers int linesHiddenBySRB = searchBarOffset > 0 ? (int) Math.ceil( - (double) searchBarOffset / container.lineHeight) : 0; + (double) searchBarOffset / container.lineHeight) : 0; for (int i = 0; i < container.lines.size(); i++) { LineData ld = container.lines.get(i); @@ -426,7 +465,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { } @Override - public JavaTextContainer getContainer() { + public ScriptTextContainer getContainer() { return container; } @@ -453,48 +492,128 @@ public class GuiScriptTextArea extends GuiNpcTextField { return width - LINE_NUMBER_GUTTER_WIDTH - 8; // Account for gutter and scrollbar } }); + + // Initialize Autocomplete Manager with callback + autocompleteManager.setInsertCallback(new AutocompleteManager.InsertCallback() { + @Override + public void insertText(String text, int startPosition) { + // Replace text from startPosition to current cursor + String fullText = GuiScriptTextArea.this.text; + int cursorPos = selection.getCursorPosition(); + + // Bounds check to prevent StringIndexOutOfBoundsException + int start = Math.max(0, Math.min(startPosition, fullText.length())); + int cursor = Math.max(start, Math.min(cursorPos, fullText.length())); + + String before = fullText.substring(0, start); + String after = fullText.substring(cursor); + setText(before + text + after); + selection.reset(start + text.length()); + scrollToCursor(); + } + + @Override + public void replaceTextRange(String text, int startPosition, int endPosition) { + // Replace text from startPosition to endPosition + String fullText = GuiScriptTextArea.this.text; + + // Bounds check to prevent StringIndexOutOfBoundsException + int start = Math.max(0, Math.min(startPosition, fullText.length())); + int end = Math.max(start, Math.min(endPosition, fullText.length())); + + String before = fullText.substring(0, start); + String after = fullText.substring(end); + setText(before + text + after); + selection.reset(start + text.length()); + scrollToCursor(); + } + + @Override + public void addImport(String importPath) { + // Add import statement and sort all imports + addAndSortImport(importPath); + } + + @Override + public int getCursorPosition() { + return selection.getCursorPosition(); + } + + @Override + public void setCursorPosition(int position) { + selection.reset(Math.max(0, Math.min(position, GuiScriptTextArea.this.text.length()))); + scrollToCursor(); + } + + @Override + public String getText() { + return GuiScriptTextArea.this.text; + } + + @Override + public int[] getCursorScreenPosition() { + // Calculate screen position of cursor for menu placement + int cursorLine = getCursorLineIndex(); + int cursorCol = 0; + if (container != null && container.lines != null && cursorLine < container.lines.size()) { + LineData ld = container.lines.get(cursorLine); + int cursorOffset = selection.getCursorPosition() - ld.start; + ScriptLine sl = container.getDocument() != null ? container.getDocument().getLine(cursorLine) : null; + if (sl != null) { + cursorCol = sl.getRenderedWidth(0, Math.min(cursorOffset, ld.text.length())); + } else { + cursorCol = ClientProxy.Font.width(ld.text.substring(0, Math.min(cursorOffset, ld.text.length()))); + } + } + + int screenX = GuiScriptTextArea.this.x + LINE_NUMBER_GUTTER_WIDTH + 1 + cursorCol; + int lineY = cursorLine - scroll.getScrolledLine(); + int screenY = GuiScriptTextArea.this.y + lineY * (container != null ? container.lineHeight : 12); + + return new int[] { screenX, screenY }; + } + + @Override + public int[] getViewportDimensions() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + return new int[] { sr.getScaledWidth(), sr.getScaledHeight() }; + } + }); } public boolean fullscreen() { return GuiScriptInterface.isFullscreen; } - - public void setLanguage(String language) { - if (this.container != null) { - // this.container.setLanguage(language); - if (this.enableCodeHighlighting) { - this.container.formatCodeText(); - } - } - } - + // ==================== RENDERING ==================== public void drawTextBox(int xMouse, int yMouse) { if (!visible) return; clampSelectionBounds(); - - // Dynamically calculate gutter width based on line count digits + + // Dynamically calculate gutter width based on line count digits + icon space if (container != null && container.linesCount > 0) { int maxLineNum = container.linesCount; String maxLineStr = "" + maxLineNum; int digitWidth = ClientProxy.Font.width(maxLineStr); - LINE_NUMBER_GUTTER_WIDTH = digitWidth + 10; // 10px total padding (5px left + 5px right) + LINE_NUMBER_GUTTER_WIDTH = digitWidth + 10 + GutterIconRenderer.ICON_GUTTER_WIDTH; // 10px padding + icon space } // Draw outer border around entire area int offset = fullscreen() ? 2 : 1; drawRect(x - offset, y - offset - searchBar.getTotalHeight(), x + width + offset, y + height + offset, - 0xffa0a0a0); + ScriptColorScheme.getBackgroundStyle().getBorderColor()); int searchHeight = searchBar.getTotalHeight(); // Draw line number gutter background - drawRect(x, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, 0xff000000); + int viewportX = x + LINE_NUMBER_GUTTER_WIDTH; + drawRect(x, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, ScriptColorScheme.getBackgroundStyle().getGutterColor()); // Draw text viewport background (starts after gutter) - drawRect(x + LINE_NUMBER_GUTTER_WIDTH, y, x + width, y + height, 0xff000000); + drawRect(x + LINE_NUMBER_GUTTER_WIDTH, y, x + width, y + height, ScriptColorScheme.getBackgroundStyle().getBackgroundColor()); // Draw separator line between gutter and text area - drawRect(x + LINE_NUMBER_GUTTER_WIDTH - 1, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, 0xff3c3f41); + drawRect(x + LINE_NUMBER_GUTTER_WIDTH-1, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, ScriptColorScheme.getBackgroundStyle().getGutterSeparatorColor()); // Enable scissor test to clip drawing to the TEXT viewport rectangle (excludes gutter) GL11.glEnable(GL11.GL_SCISSOR_TEST); @@ -504,27 +623,104 @@ public class GuiScriptTextArea extends GuiNpcTextField { int maxScroll = Math.max(0, getPaddedLineCount() - container.visibleLines); - // Handle mouse wheel scroll - only consume when mouse is over this text area - boolean isMouseOverTextArea = xMouse >= x && xMouse < x + width && yMouse >= y && yMouse < y + height; - int wheelDelta = 0; - if (isMouseOverTextArea) { - wheelDelta = Mouse.getDWheel(); - if (listener instanceof GuiNPCInterface) { - ((GuiNPCInterface) listener).mouseScroll = wheelDelta; + // Handle mouse wheel scroll + // Take whatever the parent screen has left for this frame rather than polling the wheel + // again - the poll is destructive and the parent has already drained it. + int wheelDelta = listener instanceof GuiNPCInterface ? ((GuiNPCInterface) listener).mouseScroll : Mouse.getDWheel(); + if (listener instanceof GuiNPCInterface) { + ((GuiNPCInterface) listener).mouseScroll = 0; + + // Intercept wheel scroll for tooltip (highest priority) + // Only consume the wheel event when the tooltip actually has content to scroll; + // otherwise let it fall through to the editor so non-scrollable tooltips don't eat input. + if (wheelDelta != 0 && hoverState.isTooltipVisible()) { + if (hoverState.isMouseOverTooltip(xMouse, yMouse)) { + hoverState.scrollTooltip(wheelDelta); + wheelDelta = 0; + } else { + hoverState.clearHover(); + } } - boolean canScroll = !KEYS_OVERLAY.isVisible() || KEYS_OVERLAY.isVisible() && !KEYS_OVERLAY.aboveOverlay; - if (wheelDelta != 0 && canScroll) - scroll.applyWheelScroll(wheelDelta, maxScroll); + + // Let autocomplete menu consume scroll first if visible + if (wheelDelta != 0 && autocompleteManager.isVisible() && autocompleteManager.mouseScrolled(xMouse, yMouse, wheelDelta)) { + // Autocomplete consumed the scroll + } else { + boolean canScroll = !KEYS_OVERLAY.isVisible() || KEYS_OVERLAY.isVisible() && !KEYS_OVERLAY.aboveOverlay; + if (wheelDelta != 0 && canScroll) { + int previousScrollLine = scroll.getScrolledLine(); + scroll.applyWheelScroll(wheelDelta, maxScroll); + if (scroll.getScrolledLine() != previousScrollLine) { + hoverState.clearHover(); + } + } + } } // Handle scrollbar dragging (delegated to ScrollState) - if (scroll.isClickScrolling()) + if (scroll.isClickScrolling()) { + int prevLine = scroll.getScrolledLine(); scroll.handleClickScrolling(yMouse, x, y, height, container.visibleLines, getPaddedLineCount(), maxScroll); - + if (scroll.getScrolledLine() != prevLine) { + hoverState.clearHover(); + } + } + // Handle tooltip scrollbar drag (update each frame; release when button lifted) + if (hoverState.isDraggingScrollbar()) { + if (Mouse.isButtonDown(0)) { + hoverState.updateScrollbarDrag(yMouse); + } else { + hoverState.releaseScrollbarDrag(); + } + } + // Handle tooltip panel drag (update each frame; release when button lifted) + if (hoverState.isDraggingTooltip()) { + if (Mouse.isButtonDown(0)) { + hoverState.updateTooltipDrag(xMouse, yMouse); + } else { + hoverState.releaseTooltipDrag(); + } + } + // Handle tooltip panel resize (update each frame; release when button lifted) + if (hoverState.isResizingTooltip()) { + if (Mouse.isButtonDown(0)) { + hoverState.updateTooltipResize(xMouse, yMouse); + } else { + hoverState.releaseTooltipResize(); + } + } + // Handle autocomplete scrollbar drag + if (autocompleteManager.isDraggingScrollbarMenu()) { + if (Mouse.isButtonDown(0)) { + autocompleteManager.updateScrollbarDrag(yMouse); + } else { + autocompleteManager.releaseScrollbarDrag(); + } + } + // Handle autocomplete panel drag + if (autocompleteManager.isDraggingPanel()) { + if (Mouse.isButtonDown(0)) { + autocompleteManager.updatePanelDrag(xMouse, yMouse); + } else { + autocompleteManager.releasePanelDrag(); + } + } + // Handle autocomplete panel resize + if (autocompleteManager.isResizingPanel()) { + if (Mouse.isButtonDown(0)) { + autocompleteManager.updatePanelResize(xMouse, yMouse); + } else { + autocompleteManager.releasePanelResize(); + } + } + // Update scroll animation scroll.initializeIfNeeded(scroll.getScrolledLine()); scroll.update(maxScroll); + // Update hover state for token tooltips + updateHoverState(xMouse, yMouse); + // Handle click-dragging for selection if (clicked) { clicked = Mouse.isButtonDown(0); @@ -535,7 +731,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { doubleClicked = false; tripleClicked = false; } - setCursor(i, true); + setCursor(i, true); } } else if (doubleClicked || tripleClicked) { doubleClicked = false; @@ -546,8 +742,8 @@ public class GuiScriptTextArea extends GuiNpcTextField { // Calculate braces next to cursor to highlight int startBracket = 0, endBracket = 0; if (selection.getStartSelection() >= 0 && text != null && text.length() > 0 && - (selection.getEndSelection() - selection.getStartSelection() == 1 || !selection.hasSelection())) { - int[] span = BracketMatcher.findBracketSpanAt(text, selection.getStartSelection()); + (selection.getEndSelection() - selection.getStartSelection() == 1 || !selection.hasSelection())) { + int[] span = BracketMatcher.findBracketSpanAt(text,selection.getStartSelection()); if (span != null) { startBracket = span[0]; endBracket = span[1]; @@ -555,12 +751,12 @@ public class GuiScriptTextArea extends GuiNpcTextField { } List list = new ArrayList<>(container.lines); - + // Build brace spans: {origDepth, open line, close line, adjustedDepth} List braceSpans = BracketMatcher.computeBraceSpans(text, list); // Always highlight unmatched braces (positions in text) List unmatchedBraces = BracketMatcher.findUnmatchedBracePositions(text); - + // Determine which exact brace span (openLine/closeLine) to highlight indent guides for int highlightedOpenLine = -1; int highlightedCloseLine = -1; @@ -629,34 +825,34 @@ public class GuiScriptTextArea extends GuiNpcTextField { float fracPixels = (float) (fracOffset * container.lineHeight); GL11.glPushMatrix(); GL11.glTranslatef(0.0f, -fracPixels, 0.0f); - - + + // Expand render range by one line above/below so partially-visible lines are drawn int renderStart = Math.max(0, scroll.getScrolledLine() - 1); // Compute the last line index to render, including the last partially-visible line if any. // Adds the fractional scroll offset (fracOffset * lineHeight) to ensure the bottom line is drawn // when only part of it is visible in the viewport. int renderEnd = (int) Math.min(list.size() - 1, - scroll.getScrolledLine() + container.visibleLines + fracPixels + 1); + scroll.getScrolledLine() + container.visibleLines + fracPixels + 1); // Strings start drawing vertically this much into the line. int stringYOffset = 2; - + // Render LINE GUTTER numbers for (int i = renderStart; i <= renderEnd; i++) { int posY = y + (i - scroll.getScrolledLine()) * container.lineHeight + stringYOffset; String lineNum = "" + (i + 1); int lineNumWidth = ClientProxy.Font.width(lineNum); - int lineNumX = x + LINE_NUMBER_GUTTER_WIDTH - lineNumWidth - 5; // right-align with 5px padding + int lineNumX = x + LINE_NUMBER_GUTTER_WIDTH - lineNumWidth - 5 - GutterIconRenderer.ICON_GUTTER_WIDTH; // right-align before icon space int lineNumY = posY + 1; // Highlight current line number - int lineNumColor = 0xFF606366; + int lineNumColor = ScriptColorScheme.getBackgroundStyle().getLineNumberColor(); if (active && isEnabled()) { for (int li = 0; li < list.size(); li++) { LineData ld = list.get(li); if (selection.getCursorPosition() >= ld.start && selection.getCursorPosition() < ld.end || (li == list.size() - 1 && selection.getCursorPosition() == text.length())) { if (li == i) { - lineNumColor = 0xFFb9c7d6; + lineNumColor = ScriptColorScheme.getBackgroundStyle().getLineNumberActiveColor(); break; } } @@ -664,10 +860,11 @@ public class GuiScriptTextArea extends GuiNpcTextField { } ClientProxy.Font.drawString(lineNum, lineNumX, lineNumY, lineNumColor); } - + // Render Viewport for (int i = renderStart; i <= renderEnd; i++) { LineData data = list.get(i); + ScriptLine scriptLine = container.getDocument().getLine(i); String line = data.text; int w = line.length(); // Use integer Y relative to scrolledLine; fractional offset applied via GL translate @@ -676,13 +873,13 @@ public class GuiScriptTextArea extends GuiNpcTextField { //Highlight braces the cursor position is on if (startBracket != endBracket) { if (startBracket >= data.start && startBracket < data.end) { - int s = ClientProxy.Font.width(line.substring(0, startBracket - data.start)); - int e = ClientProxy.Font.width(line.substring(0, startBracket - data.start + 1)) + 1; + int s = scriptLine.getRenderedWidth(0, startBracket - data.start); + int e = scriptLine.getRenderedWidth(0, startBracket - data.start + 1) + 1; drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight + 0, 0x9900cc00); } if (endBracket >= data.start && endBracket < data.end) { - int s = ClientProxy.Font.width(line.substring(0, endBracket - data.start)); - int e = ClientProxy.Font.width(line.substring(0, endBracket - data.start + 1)) + 1; + int s = scriptLine.getRenderedWidth(0, endBracket - data.start); + int e = scriptLine.getRenderedWidth(0, endBracket - data.start + 1) + 1; drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight + 0, 0x9900cc00); } } @@ -692,8 +889,8 @@ public class GuiScriptTextArea extends GuiNpcTextField { for (int ubPos : unmatchedBraces) { if (ubPos >= data.start && ubPos < data.end) { int rel = ubPos - data.start; - int s = ClientProxy.Font.width(line.substring(0, rel)); - int e = ClientProxy.Font.width(line.substring(0, rel + 1)) + 1; + int s = scriptLine.getRenderedWidth(0, rel); + int e = scriptLine.getRenderedWidth(0, rel + 1) + 1; drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0xffcc0000); } } @@ -703,13 +900,13 @@ public class GuiScriptTextArea extends GuiNpcTextField { Matcher m = container.regexWord.matcher(line); while (m.find()) { if (line.substring(m.start(), m.end()).equals(highlightedWord)) { - int s = ClientProxy.Font.width(line.substring(0, m.start())); - int e = ClientProxy.Font.width(line.substring(0, m.end())) + 1; + int s = scriptLine.getRenderedWidth(0, m.start()); + int e = scriptLine.getRenderedWidth(0, m.end()) + 1; drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0x99004c00); } } } - + // Highlight search matches if (searchBar.isVisible()) { List searchMatches = searchBar.getMatches(); @@ -721,8 +918,8 @@ public class GuiScriptTextArea extends GuiNpcTextField { int matchStart = Math.max(match[0] - data.start, 0); int matchEnd = Math.min(match[1] - data.start, line.length()); if (matchStart < matchEnd) { - int s = ClientProxy.Font.width(line.substring(0, matchStart)); - int e = ClientProxy.Font.width(line.substring(0, matchEnd)) + 1; + int s = scriptLine.getRenderedWidth(0, matchStart); + int e = scriptLine.getRenderedWidth(0, matchEnd) + 1; boolean isExcluded = searchBar.isMatchExcluded(mi); // Current match gets brighter highlight, others get dimmer int highlightColor = (mi == currentMatchIdx) ? 0xBB4488ff : 0x662266aa; @@ -756,10 +953,10 @@ public class GuiScriptTextArea extends GuiNpcTextField { boolean isEmpty = (occ[0] == occ[1]); if (occStart <= occEnd) { // Changed from < to <= to handle empty case - int s = ClientProxy.Font.width(line.substring(0, occStart)); - int e = isEmpty ? s + 2 : ClientProxy.Font.width( - line.substring(0, occEnd)) + 1; // 2px wide for empty - int occX = x + LINE_NUMBER_GUTTER_WIDTH + s; + int s = scriptLine.getRenderedWidth(0, occStart); + int e = isEmpty ? s + 2 : scriptLine.getRenderedWidth( + 0, occEnd) + 1; // 2px wide for empty + int occX = x + LINE_NUMBER_GUTTER_WIDTH + s; int occEndX = x + LINE_NUMBER_GUTTER_WIDTH + 2 + e; boolean isPrimary = renameHandler.isPrimaryOccurrence(occ[0]); @@ -772,12 +969,12 @@ public class GuiScriptTextArea extends GuiNpcTextField { int borderColor = 0xDDFFFFFF; //RED BG drawRect(occX, posY, occEndX, posY + container.lineHeight, 0x33ff0000); - + // Top border drawRect(occX, posY, occEndX, posY + 1, borderColor); - // Bottom border + // Bottom border drawRect(occX, posY + container.lineHeight - 1, occEndX, - posY + container.lineHeight, borderColor); + posY + container.lineHeight, borderColor); // Left border drawRect(occX, posY, occX + 1, posY + container.lineHeight, borderColor); // Right border @@ -789,8 +986,8 @@ public class GuiScriptTextArea extends GuiNpcTextField { String currentWord = renameHandler.getCurrentWord(); if (currentWord != null && cursorInWord >= 0 && cursorInWord <= currentWord.length()) { String beforeCursor = currentWord.substring(0, - Math.min(cursorInWord, currentWord.length())); - int cursorX = occX + ClientProxy.Font.width(beforeCursor); + Math.min(cursorInWord, currentWord.length())); + int cursorX = occX + scriptLine.getRenderedWidth(occStart, occStart + beforeCursor.length()); // drawRect(cursorX, posY + 1, cursorX + 1, posY + container.lineHeight - 1, // 0xFFFFFFFF); } @@ -800,18 +997,18 @@ public class GuiScriptTextArea extends GuiNpcTextField { } } } - + // Highlight the current line (light gray) under any selection if (active && isEnabled() && (selection.getCursorPosition() >= data.start && selection.getCursorPosition() < data.end || (i == list.size() - 1 && selection.getCursorPosition() == text.length()))) { - drawRect(x, posY, x + width - 1, posY + container.lineHeight, 0x22e0e0e0); + drawRect(x , posY, x + width - 1, posY + container.lineHeight, 0x22e0e0e0); } // Highlight selection if (selection.hasSelection() && selection.getEndSelection() > data.start && selection.getStartSelection() <= data.end) { if (selection.getStartSelection() < data.end) { - int s = ClientProxy.Font.width( - line.substring(0, Math.max(selection.getStartSelection() - data.start, 0))); - int e = ClientProxy.Font.width( - line.substring(0, Math.min(selection.getEndSelection() - data.start, w))) + 1; + int s = scriptLine.getRenderedWidth( + 0, Math.max(selection.getStartSelection() - data.start, 0)); + int e = scriptLine.getRenderedWidth( + 0, Math.min(selection.getEndSelection() - data.start, w)) + 1; drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0x992172ff); } } @@ -848,30 +1045,43 @@ public class GuiScriptTextArea extends GuiNpcTextField { boolean highlighted = (openLine == highlightedOpenLine && closeLine == highlightedCloseLine); int guideColor = highlighted ? 0x9933cc00 : 0x33FFFFFF; - + int topY = y + (drawStart - scroll.getScrolledLine()) * container.lineHeight; int bottomY = y + (endLine - scroll.getScrolledLine() + 1) * container.lineHeight; - if (highlighted) - bottomY -= 2; + if(highlighted) + bottomY-=2; drawRect(gx, topY, gx + 1, bottomY, guideColor); } } int yPos = posY + stringYOffset; - data.drawString(x + LINE_NUMBER_GUTTER_WIDTH + 1, yPos, 0xFFe0e0e0); + + //data.drawString(x + LINE_NUMBER_GUTTER_WIDTH + 1, yPos, 0xFFe0e0e0); + + //scriptLine.drawString(x+LINE_NUMBER_GUTTER_WIDTH + 1, yPos, 0xFFe0e0e0); + scriptLine.drawStringHex(x + LINE_NUMBER_GUTTER_WIDTH + 1, yPos); // Draw cursor: pause blinking while user is active recently boolean recentInput = selection.hadRecentInput(); if (active && isEnabled() && (recentInput || (cursorCounter / 10) % 2 == 0) && (selection.getCursorPosition() >= data.start && selection.getCursorPosition() < data.end || (i == list.size() - 1 && selection.getCursorPosition() == text.length()))) { - int posX = x + LINE_NUMBER_GUTTER_WIDTH + ClientProxy.Font.width( - line.substring(0, Math.min(selection.getCursorPosition() - data.start, line.length()))); - drawRect(posX + 1, posY, posX + 2, posY + container.lineHeight, 0xffffffff); + int posX = x + LINE_NUMBER_GUTTER_WIDTH + scriptLine.getRenderedWidth( + 0, Math.min(selection.getCursorPosition() - data.start, line.length())); + drawRect(posX + 1, posY, posX + 2, posY + container.lineHeight, ScriptColorScheme.getBackgroundStyle().getCaretColor()); } } } + + // Render gutter icons for method override/implements + if (container != null && container.getDocument() != null) { + hoveredGutterMethod = GutterIconRenderer.renderIcons(container.lineHeight, + x + LINE_NUMBER_GUTTER_WIDTH - GutterIconRenderer.ICON_GUTTER_WIDTH + 1, y, renderStart, renderEnd, + scroll.getScrolledLine(), stringYOffset, container.getDocument().getAllMethods(), container.lines, + xMouse, yMouse, fracPixels); + } + GL11.glPopMatrix(); GL11.glDisable(GL11.GL_SCISSOR_TEST); - + if (hasVerticalScrollbar()) { Minecraft.getMinecraft().renderEngine.bindTexture(GuiCustomScroll.resource); int effLines = Math.max(1, getPaddedLineCount()); @@ -881,27 +1091,51 @@ public class GuiScriptTextArea extends GuiNpcTextField { double linesCount = (double) effLines; int posY = (int) (y + 1f * scroll.getScrollPos() / linesCount * (height - 4)) + 1; - drawRect(posX, posY, posX + 5, posY + sbSize + 2, 0xFFe0e0e0); + drawRect(posX, posY, posX + 5, posY + sbSize + 2, ScriptColorScheme.getBackgroundStyle().getScrollbarColor()); } - // Draw search/replace bar (overlays viewport) + if (parent != null) + parent.fullscreenButton.draw(xMouse, yMouse); + + searchBar.ownerGui = parent; searchBar.draw(xMouse, yMouse); - + // Draw go to line dialog (overlays everything) goToLineDialog.draw(xMouse, yMouse); + KEYS_OVERLAY.draw(xMouse, yMouse, wheelDelta); + + autocompleteManager.getMenu().ownerGui = parent; + autocompleteManager.draw(xMouse, yMouse); + + // Draw hover tooltips (on top of everything) + if (hoverState.isTooltipVisible()) { + int xOffset = hasVerticalScrollbar() ? -8 : -2; + int viewportWidth = width - LINE_NUMBER_GUTTER_WIDTH; + int viewportY = y; + int viewportHeight = height; + TokenHoverRenderer.render(hoverState, viewportX, viewportWidth+xOffset, viewportY, viewportHeight,parent); + } + + // Draw gutter icon tooltip + if (hoveredGutterMethod != null) { + GutterIconRenderer.renderTooltip(hoveredGutterMethod, xMouse, yMouse, x, width, y, height); + } } private void scissorViewport() { Minecraft mc = Minecraft.getMinecraft(); ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); int scaleFactor = sr.getScaleFactor(); - int scissorX = (this.x) * scaleFactor; - int scissorY = (sr.getScaledHeight() - (this.y + this.height)) * scaleFactor; - int scissorW = (this.width) * scaleFactor; + double panX = parent != null ? parent.getPanX() : 0; + double panY = parent != null ? parent.getPanY() : 0; + int scissorX = (int)((this.x - panX) * scaleFactor); + int scissorY = (int)((sr.getScaledHeight() - (this.y - panY + this.height)) * scaleFactor); + int scissorW = this.width * scaleFactor; int scissorH = this.height * scaleFactor; GL11.glScissor(scissorX, scissorY, scissorW, scissorH); } + // ==================== SELECTION & CURSOR POSITION ==================== // Get cursor position from mouse coordinates @@ -913,20 +1147,23 @@ public class GuiScriptTextArea extends GuiNpcTextField { // visible lines (fractional positions) correctly hit that line. double fracPixels = scroll.getFractionalOffset() * container.lineHeight; double yMouseD = yMouse + fracPixels; - + ArrayList list = new ArrayList(this.container.lines); for (int i = 0; i < list.size(); ++i) { LineData data = (LineData) list.get(i); //+1 to account for the fractional line - if (i >= scroll.getScrolledLine() && i <= scroll.getScrolledLine() + this.container.visibleLines + 1) { + if (i >= scroll.getScrolledLine() && i <= scroll.getScrolledLine() + this.container.visibleLines +1) { double yPos = (i - scroll.getScrolledLine()) * this.container.lineHeight; if (yMouseD >= yPos && yMouseD < yPos + this.container.lineHeight) { + ScriptLine scriptLine = container.getDocument() != null ? container.getDocument().getLine(i) : null; int lineWidth = 0; char[] chars = data.text.toCharArray(); for (int j = 1; j <= chars.length; ++j) { - int w = ClientProxy.Font.width(data.text.substring(0, j)); + int w = scriptLine != null + ? scriptLine.getRenderedWidth(0, j) + : ClientProxy.Font.width(data.text.substring(0, j)); if (xMouse < lineWidth + (w - lineWidth) / 2) { return data.start + j - 1; } @@ -952,13 +1189,123 @@ public class GuiScriptTextArea extends GuiNpcTextField { private int getCursorLineIndex() { return selection.getCursorLineIndex(container.lines, text != null ? text.length() : 0); } + + /** + * Get the token at a specific screen position (mouse coordinates). + * Also returns the token's screen position and dimensions for tooltip placement. + * + * @param xMouse Screen X coordinate + * @param yMouse Screen Y coordinate + * @return Array of [Token, tokenScreenX, tokenScreenY, tokenWidth] or null if no token + */ + private Object[] getTokenAtScreenPosition(int xMouse, int yMouse) { + if (container == null || !(container instanceof ScriptTextContainer)) { + return null; + } + + ScriptTextContainer scriptContainer = (ScriptTextContainer) container; + + // Check if mouse is within the text viewport + int viewportX = x + LINE_NUMBER_GUTTER_WIDTH + 1; + if (xMouse < viewportX || xMouse > x + width || yMouse < y || yMouse > y + height) { + return null; + } + + // Adjust mouse position relative to text area + int relativeY = yMouse - y; - + // Account for fractional scrolling + double fracOffset = scroll.getFractionalOffset(); + double fracPixels = fracOffset * container.lineHeight; + double adjustedY = relativeY + fracPixels; + + // Find which line the mouse is over + int lineIdx = scroll.getScrolledLine() + (int)(adjustedY / container.lineHeight); + if (lineIdx < 0 || lineIdx >= container.lines.size()) { + return null; + } + + ScriptLine lineData = container.getDocument().getLine(lineIdx); + String lineText = lineData.getText(); + int lineStart = lineData.getGlobalStart(); + + // Get the token at this position + int globalMouseX = getSelectionPos(xMouse,yMouse); + Token token = lineData.getTokenAt(globalMouseX, (t) -> t.getType() != TokenType.DEFAULT); // Ignore default tokens i.e. whitespaces + if (token == null) + return null; + + // Calculate token's screen position + int tokenLocalStart = token.getGlobalStart() - lineStart; + int tokenLocalEnd = token.getGlobalEnd() - lineStart; + tokenLocalStart = Math.max(0, Math.min(tokenLocalStart, lineText.length())); + tokenLocalEnd = Math.max(0, Math.min(tokenLocalEnd, lineText.length())); + + int tokenScreenX = viewportX + lineData.getRenderedWidth(0, tokenLocalStart); + int tokenScreenY = y + (lineIdx - scroll.getScrolledLine()) * container.lineHeight - (int)fracPixels; + int tokenWidth = lineData.getRenderedWidth(tokenLocalStart, tokenLocalEnd); + + return new Object[] { token, tokenScreenX, tokenScreenY, tokenWidth }; + } + + /** + * Update hover state based on current mouse position. + * Called every frame from drawTextBox. + */ + private void updateHoverState(int xMouse, int yMouse) { + // Keep tooltip alive and skip token re-evaluation while it is being dragged + if (hoverState.isDraggingTooltip()) { + hoverState.setLastMousePosition(xMouse, yMouse); + return; + } + // Keep tooltip alive while resizing (mouse may be outside the panel bounds) + if (hoverState.isResizingTooltip()) { + hoverState.setLastMousePosition(xMouse, yMouse); + return; + } + // Tooltip has been dragged or resized — keep it pinned until an explicit outside click + if (hoverState.hasOverriddenPosition() || hoverState.hasOverriddenSize()) { + hoverState.setLastMousePosition(xMouse, yMouse); + return; + } + // If mouse is currently over the tooltip panel, keep it visible — do not clear or re-evaluate tokens + if (hoverState.isTooltipVisible() && hoverState.isMouseOverTooltip(xMouse, yMouse)) { + hoverState.setLastMousePosition(xMouse, yMouse); + return; + } + // Don't show tooltips when not active, clicking, or when overlays are visible + if (!isEnabled() || clicked || searchBar.isVisible() || + goToLineDialog.isVisible() || KEYS_OVERLAY.isVisible() || renameHandler.isActive() || autocompleteManager.isVisible()) { + hoverState.clearHover(); + return; + } + + // Get token at current mouse position + Object[] tokenInfo = getTokenAtScreenPosition(xMouse, yMouse); + + if (tokenInfo != null) { + Token token = (Token) tokenInfo[0]; + int tokenScreenX = (Integer) tokenInfo[1]; + int tokenScreenY = (Integer) tokenInfo[2]; + int tokenWidth = (Integer) tokenInfo[3]; + + hoverState.update(xMouse, yMouse, token, tokenScreenX, tokenScreenY, tokenWidth); + } else { + // If mouse is over the tooltip box, keep tooltip visible — do not clear + if (hoverState.isMouseOverTooltip(xMouse, yMouse)) { + hoverState.setLastMousePosition(xMouse, yMouse); + return; + } + hoverState.update(xMouse, yMouse, null, 0, 0, 0); + } + } + + // Scroll viewport to keep cursor visible (minimal adjustment, like IntelliJ) // Only scrolls if cursor is outside the visible area private void scrollToCursor() { if (container == null || container.lines == null || container.lines.isEmpty()) return; - + int lineIdx = getCursorLineIndex(); int visible = Math.max(1, container.visibleLines); int effectiveVisible = Math.max(1, visible - bottomPaddingLines); @@ -1038,13 +1385,35 @@ public class GuiScriptTextArea extends GuiNpcTextField { } }); - // COPY: Copy selection to clipboard + // COPY: Copy selection to clipboard (or entire line if no selection) KEYS.COPY.setTask(e -> { if (!e.isPress() || !isActive.get()) return; - if (selection.hasSelection()) + if (selection.hasSelection()) { NoppesStringUtils.setClipboardContents(selection.getSelectedText(text)); + lastCopyWasLine = false; + lastCopiedLineText = null; + } else { + // Copy entire current line (including newline) + int cursor = selection.getCursorPosition(); + LineData targetLine = null; + for (LineData line : container.lines) { + if (cursor >= line.start && cursor <= line.end) { + targetLine = line; + break; + } + } + + if (targetLine != null) { + int safeStart = Math.max(0, Math.min(targetLine.start, text.length())); + int safeEnd = Math.max(safeStart, Math.min(targetLine.end, text.length())); + String lineText = text.substring(safeStart, safeEnd); + NoppesStringUtils.setClipboardContents(lineText); + lastCopyWasLine = true; + lastCopiedLineText = lineText; + } + } }); // PASTE: Insert clipboard contents at caret @@ -1052,7 +1421,48 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (!e.isPress() || !isActive.get()) return; - addText(NoppesStringUtils.getClipboardContents()); + String clipboardRaw = NoppesStringUtils.getClipboardContents(); + if (clipboardRaw == null) + clipboardRaw = ""; + + boolean isLinePaste = lastCopyWasLine && lastCopiedLineText != null && clipboardRaw.equals(lastCopiedLineText); + String clipboard = FormatHelper.sanitizeClipboard(clipboardRaw, PASTE_TRAILING_WS_TRIM_THRESHOLD); + + if (selection.hasSelection()) { + addText(clipboard); + lastCopyWasLine = false; + lastCopiedLineText = null; + scrollToCursor(); + return; + } + + if (isLinePaste && container != null && container.lines != null) { + LineData currentLine = selection.findCurrentLine(container.lines); + if (currentLine != null) { + int insertPos = Math.max(0, Math.min(currentLine.end, text.length())); + String insertText = clipboard; + + // Ensure insertion happens on the line below + if (insertPos > 0 && text.charAt(insertPos - 1) != '\n') { + insertText = "\n" + insertText; + } + + // Ensure the inserted line doesn't merge with the following line + if (insertPos < text.length() && !insertText.endsWith("\n")) { + insertText = insertText + "\n"; + } + + String newText = text.substring(0, insertPos) + insertText + text.substring(insertPos); + setText(newText); + + int newCursor = insertPos + (insertText.startsWith("\n") ? 1 : 0); + selection.reset(Math.min(newCursor, newText.length())); + scrollToCursor(); + return; + } + } + + addText(clipboard); scrollToCursor(); }); @@ -1165,6 +1575,142 @@ public class GuiScriptTextArea extends GuiNpcTextField { } }); + // DELETE_LINE: Delete the current line + KEYS.DELETE_LINE.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + if (text == null || text.isEmpty()) + return; + + int cursor = selection.getCursorPosition(); + + LineData targetLine = null; + int targetIndex = -1; + for (LineData line : container.lines) { + if (cursor >= line.start && cursor <= line.end) { + targetLine = line; + targetIndex = container.lines.indexOf(line); + break; + } + } + + if (targetLine == null) + return; + + int start = Math.max(0, Math.min(targetLine.start, text.length())); + int end = Math.max(start, Math.min(targetLine.end, text.length())); + + String newText = text.substring(0, start) + text.substring(end); + setText(newText); + + int newCursor = 0; + if (targetIndex > 0 && targetIndex <= container.lines.size() - 1) { + LineData previousLine = container.lines.get(targetIndex - 1); + int prevStart = Math.max(0, Math.min(previousLine.start, newText.length())); + int prevEnd = Math.max(prevStart, Math.min(previousLine.end, newText.length())); + int prevLen = Math.max(0, prevEnd - prevStart); + int offsetInLine = Math.max(0, Math.min(cursor - targetLine.start, prevLen)); + newCursor = Math.min(prevStart + offsetInLine, newText.length()); + } + + selection.reset(Math.min(newCursor, newText.length())); + scrollToCursor(); + }); + + // MOVE_LINE_UP: Move current line up + KEYS.MOVE_LINE_UP.setThrottleInterval(50).setTask(e -> { + if ((!e.isPress() && !e.isHold()) || !isActive.get()) + return; + + if (text == null || text.isEmpty()) + return; + + int tLen = text.length(); + int cursor = Math.max(0, Math.min(selection.getCursorPosition(), tLen)); + + // Work on real newline-delimited lines, not wrapped LineData. + int currStart = text.lastIndexOf('\n', Math.max(0, cursor - 1)); + currStart = currStart == -1 ? 0 : (currStart + 1); + if (currStart == 0) + return; // Can't move first line up + + int currEnd = text.indexOf('\n', cursor); + currEnd = currEnd == -1 ? tLen : (currEnd + 1); + + int prevEnd = currStart; + int prevStart = text.lastIndexOf('\n', Math.max(0, prevEnd - 2)); + prevStart = prevStart == -1 ? 0 : (prevStart + 1); + + String previousText = text.substring(prevStart, prevEnd); + String currentText = text.substring(currStart, currEnd); + + // If current line is the last line without a trailing newline, but it is being moved + // into the middle, ensure it ends with '\n' by transferring the '\n' from the previous line. + if (!currentText.endsWith("\n") && previousText.endsWith("\n") && !previousText.isEmpty()) { + currentText = currentText + "\n"; + previousText = previousText.substring(0, previousText.length() - 1); + } + + String before = text.substring(0, prevStart); + String after = text.substring(currEnd); + String newText = before + currentText + previousText + after; + setText(newText); + + int currentContentLen = currentText.endsWith("\n") ? Math.max(0, currentText.length() - 1) : currentText.length(); + int offsetInLine = Math.max(0, Math.min(cursor - currStart, currentContentLen)); + int newCursor = Math.min(prevStart + offsetInLine, newText.length()); + selection.reset(newCursor); + scrollToCursor(); + }); + + // MOVE_LINE_DOWN: Move current line down + KEYS.MOVE_LINE_DOWN.setThrottleInterval(50).setTask(e -> { + if ((!e.isPress() && !e.isHold()) || !isActive.get()) + return; + + if (text == null || text.isEmpty()) + return; + + int tLen = text.length(); + int cursor = Math.max(0, Math.min(selection.getCursorPosition(), tLen)); + + // Work on real newline-delimited lines, not wrapped LineData. + int currStart = text.lastIndexOf('\n', Math.max(0, cursor - 1)); + currStart = currStart == -1 ? 0 : (currStart + 1); + + int currEnd = text.indexOf('\n', cursor); + currEnd = currEnd == -1 ? tLen : (currEnd + 1); + if (currEnd >= tLen) + return; // Can't move last line down + + int nextStart = currEnd; + int nextEnd = text.indexOf('\n', nextStart); + nextEnd = nextEnd == -1 ? tLen : (nextEnd + 1); + + String currentText = text.substring(currStart, currEnd); + String nextText = text.substring(nextStart, nextEnd); + + // If the next line is the last line and doesn't end with '\n' (common when it contains + // only indentation spaces), swapping can merge whitespace onto the moved line. + // Fix by transferring the '\n' from currentText to nextText. + if (!nextText.endsWith("\n") && currentText.endsWith("\n") && !currentText.isEmpty()) { + currentText = currentText.substring(0, currentText.length() - 1); + nextText = nextText + "\n"; + } + + String before = text.substring(0, currStart); + String after = text.substring(nextEnd); + String newText = before + nextText + currentText + after; + setText(newText); + + int currentContentLen = currentText.endsWith("\n") ? Math.max(0, currentText.length() - 1) : currentText.length(); + int offsetInLine = Math.max(0, Math.min(cursor - currStart, currentContentLen)); + int newCursor = Math.min(currStart + nextText.length() + offsetInLine, newText.length()); + selection.reset(newCursor); + scrollToCursor(); + }); + // Check if can open just for SearchReplaceBar and GoToLine @@ -1173,27 +1719,27 @@ public class GuiScriptTextArea extends GuiNpcTextField { KEYS.SEARCH.setTask(e -> { if (!e.isPress() || !openBoxes.get()) return; - + unfocusAll(); searchBar.openSearch(); }); - + // SEARCH_REPLACE: Open search+replace bar (Ctrl+Shift+R) // Works in search bar. KEYS.SEARCH_REPLACE.setTask(e -> { if (!e.isPress() || !openBoxes.get()) return; - + unfocusAll(); searchBar.openSearchReplace(); }); - + // GO_TO_LINE: Open go to line dialog (Ctrl+G) // Works in search bar. KEYS.GO_TO_LINE.setTask(e -> { if (!e.isPress() || !openBoxes.get()) return; - + unfocusAll(); goToLineDialog.toggle(); }); @@ -1210,6 +1756,14 @@ public class GuiScriptTextArea extends GuiNpcTextField { renameHandler.startRename(); } }); + + // AUTOCOMPLETE: Trigger autocomplete (Ctrl+Space) + KEYS.AUTOCOMPLETE.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + autocompleteManager.triggerExplicit(); + }); } public void unfocusAll() { @@ -1217,6 +1771,8 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (goToLineDialog.hasFocus()) goToLineDialog.unfocus(); if (renameHandler.isActive()) renameHandler.cancel(); + if (autocompleteManager.isVisible()) + autocompleteManager.dismiss(); } // ==================== KEYBOARD INPUT HANDLING ==================== @@ -1232,14 +1788,32 @@ public class GuiScriptTextArea extends GuiNpcTextField { // Handle rename refactor input first if active if (renameHandler.isActive() && renameHandler.keyTyped(c, i)) return true; - + // Handle Go To Line dialog input first if it has focus - if (goToLineDialog.isVisible() && goToLineDialog.keyTyped(c, i)) - return true; - + if (goToLineDialog.isVisible() &&goToLineDialog.keyTyped(c, i)) + return true; + // Handle search bar input first if it has focus - if (searchBar.isVisible() && searchBar.keyTyped(c, i)) + if (searchBar.isVisible() && searchBar.keyTyped(c, i)) return true; + + // Handle autocomplete navigation keys first when visible + if (autocompleteManager.isVisible()) { + if (autocompleteManager.keyPressed(i)) { + return true; + } + } + + // Dismiss pinned/resized tooltip on Escape + if (i == Keyboard.KEY_ESCAPE && hoverState.isTooltipVisible() + && (hoverState.hasOverriddenPosition() || hoverState.hasOverriddenSize())) { + hoverState.clearHover(); + return true; + } + // Ignore if any global keys bound to this code are currently pressed + if (KEYS.hasMatchingKeyPressed(i)) + return false; + if (!active) return false; @@ -1268,20 +1842,31 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (i == Keyboard.KEY_LEFT) { int j = 1; // default: move one character if (isCtrlKeyDown()) { - // When Ctrl is down, compute distance to previous word boundary. - // We match words in the text slice before the cursor and pick - // the last match start as the new boundary. - Matcher m = container.regexWord.matcher(text.substring(0, selection.getCursorPosition())); - while (m.find()) { - if (m.start() == m.end()) - continue; // skip empty matches - // j becomes the number of chars to move left to reach word start - j = selection.getCursorPosition() - m.start(); + int pos = selection.getCursorPosition(); + int g = pos; + java.util.function.IntPredicate isWordChar = ch -> Character.isLetterOrDigit(ch) || ch == '_'; + + if (pos > 0) { + char left = text.charAt(pos - 1); + if (Character.isWhitespace(left)) { + while (g - 1 >= 0 && Character.isWhitespace(text.charAt(g - 1))) g--; + } else if (isWordChar.test(left)) { + while (g - 1 >= 0 && isWordChar.test(text.charAt(g - 1))) g--; + } else { + while (g - 1 >= 0 && !Character.isWhitespace(text.charAt(g - 1)) && !isWordChar.test(text.charAt(g - 1))) g--; + } } + j = Math.max(1, pos - g); } int newPos = Math.max(selection.getCursorPosition() - j, 0); // If Shift is held, extend selection; otherwise place caret. setCursor(newPos, GuiScreen.isShiftKeyDown()); + + // Notify autocomplete of cursor movement + if (autocompleteManager.isVisible()) { + autocompleteManager.onCursorMove(text, newPos); + } + return true; } @@ -1289,26 +1874,30 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (i == Keyboard.KEY_RIGHT) { int j = 1; // default: move one character if (isCtrlKeyDown()) { - String after = text.substring(selection.getCursorPosition()); - Matcher m = container.regexWord.matcher(after); - if (m.find()) { - if (m.start() == 0) { - // If the first match starts at 0 (cursor at word start), - // try to find the next match so we advance past the current word. - if (m.find()) - j = m.start(); - else - j = Math.max(1, after.length()); + int pos = selection.getCursorPosition(); + int end = pos; + java.util.function.IntPredicate isWordChar = ch -> Character.isLetterOrDigit(ch) || ch == '_'; + + if (pos < text.length()) { + char first = text.charAt(pos); + if (Character.isWhitespace(first)) { + while (end < text.length() && Character.isWhitespace(text.charAt(end))) end++; + } else if (isWordChar.test(first)) { + while (end < text.length() && isWordChar.test(text.charAt(end))) end++; } else { - j = m.start(); + while (end < text.length() && !Character.isWhitespace(text.charAt(end)) && !isWordChar.test(text.charAt(end))) end++; } - } else { - // No word match found after cursor -> jump to end - j = Math.max(1, after.length()); } + j = Math.max(1, end - pos); } int newPos = Math.min(selection.getCursorPosition() + j, text.length()); setCursor(newPos, GuiScreen.isShiftKeyDown()); + + // Notify autocomplete of cursor movement + if (autocompleteManager.isVisible()) { + autocompleteManager.onCursorMove(text, newPos); + } + return true; } @@ -1345,29 +1934,141 @@ public class GuiScriptTextArea extends GuiNpcTextField { return true; } - // RETURN/ENTER: special handling when preceding char is an opening brace '{' + // RETURN/ENTER: special handling for /** javadoc stub and opening brace '{' if (i == Keyboard.KEY_RETURN) { int cursorPos = selection.getCursorPosition(); + + // JSDoc / comment Enter behavior summary: + // - If the caret is at (or after spaces/tabs following) "/**", Enter generates a JSDoc stub. + // - If an inline closer exists ("/** */"), expand to a multi-line block without duplicating "*/". + // - If already inside an existing JSDoc with "*" lines, insert a new " * " line (IDE-style). + // - If the caret is on a "*" line inside an unclosed JSDoc block, Enter inserts a new " * " line. + // - Multi-line selections are not special-cased (avoid surprising mass edits). + + if (selection.hasSelection() && text != null && selection.getSelectedText(text).indexOf('\n') != -1) { + addText(Character.toString('\n') + getAutoIndentForEnter()); + scrollToCursor(); + return true; + } + + // Check for /** javadoc stub auto-generation + String before = getSelectionBeforeText(); + int beforeTrimEnd = before.length(); + while (beforeTrimEnd > 0) { + char ch = before.charAt(beforeTrimEnd - 1); + if (ch == ' ' || ch == '\t') { + beforeTrimEnd--; + } else { + break; + } + } + + if (before.substring(0, beforeTrimEnd).endsWith("/**")) { + // Derive indentation from the logical source line (not soft-wrapped LineData). + String indent = getLogicalLineIndentAt(Math.max(0, Math.min(cursorPos, text != null ? text.length() : 0))); + + // Look ahead for a function declaration to generate smart JSDoc + String after = getSelectionAfterText(); + + String afterTrimmed = after; + int wsLen = 0; + while (wsLen < afterTrimmed.length() && (afterTrimmed.charAt(wsLen) == ' ' || afterTrimmed.charAt(wsLen) == '\t')) { + wsLen++; + } + if (wsLen < afterTrimmed.length() && afterTrimmed.charAt(wsLen) == '\n') { + int idx = wsLen + 1; + while (idx < afterTrimmed.length() && (afterTrimmed.charAt(idx) == ' ' || afterTrimmed.charAt(idx) == '\t')) { + idx++; + } + if (afterTrimmed.startsWith("*/", idx)) { + // Inline "/** */" -> expand to multi-line and keep the existing closer. + String restAfterCloser = afterTrimmed.substring(Math.min(idx + 2, afterTrimmed.length())); + String expanded = "\n" + indent + " * " + "\n" + indent + " */" + restAfterCloser; + setText(before + expanded, true); + int newCursorPos = before.length() + 1 + indent.length() + 3; // +1 for \n, +3 for " * " + selection.reset(newCursorPos); + scrollToCursor(); + return true; + } + if (idx < afterTrimmed.length() && afterTrimmed.charAt(idx) == '*') { + int closerPos = afterTrimmed.indexOf("*/", idx); + if (closerPos != -1) { + // Already inside a multi-line JSDoc -> insert a new " * " line. + addText("\n" + indent + " * "); + int newCursorPos = before.length() + 1 + indent.length() + 3; // +1 for \n, +3 for " * " + selection.reset(newCursorPos); + scrollToCursor(); + return true; + } + } + } + if (afterTrimmed.substring(wsLen).startsWith("*/")) { + // Inline "/** */" (same line) -> expand to multi-line and keep the existing closer. + String restAfterCloser = afterTrimmed.substring(wsLen + 2); + String expanded = "\n" + indent + " * " + "\n" + indent + " */" + restAfterCloser; + setText(before + expanded, true); + int newCursorPos = before.length() + 1 + indent.length() + 3; // +1 for \n, +3 for " * " + selection.reset(newCursorPos); + scrollToCursor(); + return true; + } + + // Look ahead for a function declaration to generate smart JSDoc + String javadocStub = generateJSDocStub(after, indent); + addText(javadocStub); + + // Position cursor after " * " on the description line + int newCursorPos = before.length() + 1 + indent.length() + 3; // +1 for \n, +3 for " * " + selection.reset(newCursorPos); + scrollToCursor(); + return true; + } + + if (text != null && !text.isEmpty()) { + int openPos = text.lastIndexOf("/**", Math.max(0, cursorPos - 1)); + if (openPos != -1) { + int closeBetween = text.indexOf("*/", openPos + 3); + if (closeBetween == -1 || closeBetween >= cursorPos) { + int lineStart = text.lastIndexOf('\n', Math.max(0, cursorPos - 1)) + 1; + int lineEnd = text.indexOf('\n', lineStart); + if (lineEnd == -1) { + lineEnd = text.length(); + } + String line = text.substring(lineStart, lineEnd); + String trimmed = line.trim(); + if (trimmed.startsWith("*") && !trimmed.startsWith("*/")) { + // Continuation line inside an unclosed JSDoc block. + int openLineStart = text.lastIndexOf('\n', Math.max(0, openPos - 1)) + 1; + int openLineEnd = text.indexOf('\n', openLineStart); + if (openLineEnd == -1) { + openLineEnd = text.length(); + } + String openLine = text.substring(openLineStart, openLineEnd); + String baseIndent = openLine.substring(0, IndentHelper.getLineIndent(openLine)); + addText("\n" + baseIndent + " * "); + int newCursorPos = cursorPos + 1 + baseIndent.length() + 3; + selection.reset(Math.min(newCursorPos, this.text.length())); + scrollToCursor(); + return true; + } + } + } + } + int prevNonWs = cursorPos - 1; while (prevNonWs >= 0 && prevNonWs < (text != null ? text.length() : 0) && Character.isWhitespace( - text.charAt(prevNonWs))) { + text.charAt(prevNonWs))) { prevNonWs--; } if (prevNonWs >= 0 && cursorPos <= (text != null ? text.length() : 0) && text.charAt(prevNonWs) == '{') { - String indent = ""; - for (LineData ld : this.container.lines) { - if (prevNonWs >= ld.start && prevNonWs < ld.end) { - indent = ld.text.substring(0, IndentHelper.getLineIndent(ld.text)); - break; - } - } - if (indent == null) - indent = ""; + String indent = getLogicalLineIndentAt(prevNonWs); String childIndent = indent + " "; - String before = getSelectionBeforeText(); String after = getSelectionAfterText(); + // Check if there's non-whitespace content on the current line after the cursor. + // If so, just add a newline + child indent without inserting a closing brace + // (the user is typing inside an existing expression). int firstNewline = after.indexOf('\n'); String leadingSegment = firstNewline == -1 ? after : after.substring(0, firstNewline); if (leadingSegment.trim().length() > 0) { @@ -1376,7 +2077,14 @@ public class GuiScriptTextArea extends GuiNpcTextField { return true; } - boolean hasMatchingCloseSameIndent = false; + // Use BracketMatcher to determine if the opening '{' already has a + // properly matched closing '}' at the correct indent. Pure indent-based + // heuristics (scanning the 'after' substring) are unreliable for lambdas + // and nested callbacks; BracketMatcher uses stack-based pairing on the + // full text, then we verify the close brace sits at the same indent as + // the open brace's line — ensuring parent-scoped braces aren't mistaken + // for our own. + boolean hasMatchingClose = false; try { int openLineIdx = -1; int bracePos = prevNonWs; @@ -1391,24 +2099,42 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (openLineIdx >= 0) { List spans = BracketMatcher.computeBraceSpans(text, this.container.lines); for (int[] span : spans) { - int spanOpen = span[1]; - int spanClose = span[2]; - if (spanOpen == openLineIdx) { - int closeIndent = IndentHelper.getLineIndent(this.container.lines.get(spanClose).text); - if (closeIndent == indent.length()) { - hasMatchingCloseSameIndent = true; + if (span[1] == openLineIdx) { + int closeLineIdx = span[2]; + if (closeLineIdx < this.container.lines.size()) { + int closeIndent = IndentHelper.getLineIndent( + this.container.lines.get(closeLineIdx).text); + // <= handles multi-line declarations where '{' sits on a + // continuation line with higher indent than the closing '}' + if (closeIndent <= indent.length()) { + hasMatchingClose = true; + } } break; } } } } catch (Exception ex) { - hasMatchingCloseSameIndent = false; + hasMatchingClose = false; } - if (hasMatchingCloseSameIndent) { + if (hasMatchingClose) { addText("\n" + childIndent); scrollToCursor(); + } else if (isLambdaOpening(prevNonWs, text)) { + int parenPos = findLambdaParentParen(prevNonWs, text); + if (parenPos >= 0) { + String parentIndent = getParentIndentForLambda(parenPos, container.lines); + String insert = "\n" + childIndent + "\n" + parentIndent + "});"; + setText(before + insert + after); + selection.reset(before.length() + 1 + childIndent.length()); + scrollToCursor(); + } else { + String insert = "\n" + childIndent + "\n" + indent + "}"; + setText(before + insert + after); + selection.reset(before.length() + 1 + childIndent.length()); + scrollToCursor(); + } } else { String insert = "\n" + childIndent + "\n" + indent + "}"; setText(before + insert + after); @@ -1425,6 +2151,116 @@ public class GuiScriptTextArea extends GuiNpcTextField { return false; } + + /** + * Generates a JSDoc stub for a function declaration. + * Looks at the text after the cursor to find function signature and generates + * appropriate @param and @return tags. + * + * @param after Text after the /** to search for function + * @param indent Current line indentation + * @return The JSDoc stub string including newlines + */ + private String generateJSDocStub(String after, String indent) { + StringBuilder stub = new StringBuilder(); + stub.append("\n").append(indent).append(" * "); // Description line + + // Try to find a function/method declaration or field declaration following the JSDoc + // Skip whitespace and newlines + String trimmed = after.replaceFirst("^[\\s\\n\\r]*", ""); + + // First, try to match function/method pattern + java.util.regex.Pattern funcPattern = java.util.regex.Pattern.compile( + // Group 1: Optional return type (Java) or 'function' keyword (JS) + "^(?:(\\w+(?:<[^>]+>)?|function)\\s+)?" + + // Group 2: Method/function name + "(\\w+)\\s*" + + // Group 3: Parameters inside parentheses + "\\(([^)]*)\\)" + ); + + java.util.regex.Matcher funcMatcher = funcPattern.matcher(trimmed); + if (funcMatcher.find()) { + // Handle function/method + String returnOrKeyword = funcMatcher.group(1); + String funcName = funcMatcher.group(2); + String paramsStr = funcMatcher.group(3) != null ? funcMatcher.group(3).trim() : ""; + + // Determine if this is JavaScript (function keyword or no return type) + boolean isJS = "function".equals(returnOrKeyword) || returnOrKeyword == null || + (container != null && container.getDocument() != null && container.getDocument().isJavaScript()); + + // Parse parameters + if (!paramsStr.isEmpty()) { + String[] params = paramsStr.split(","); + for (String param : params) { + param = param.trim(); + if (param.isEmpty()) continue; + + String paramName; + String paramType = "any"; + + // Split on whitespace to get type and name + String[] parts = param.split("\\s+"); + if (parts.length >= 2) { + // Java style: Type name + paramType = parts[parts.length - 2]; + paramName = parts[parts.length - 1]; + } else { + // JS style: just name + paramName = parts[0]; + } + + // Remove any trailing array brackets or varargs + paramName = paramName.replaceAll("[\\[\\]\\.]", ""); + + if (isJS) { + stub.append("\n").append(indent).append(" * @param {").append(paramType).append("} ").append(paramName); + } else { + stub.append("\n").append(indent).append(" * @param ").append(paramName); + } + } + } + + // Add @return/@returns tag if applicable + if (returnOrKeyword != null && !"function".equals(returnOrKeyword) && !"void".equals(returnOrKeyword)) { + if (isJS) { + stub.append("\n").append(indent).append(" * @returns {").append(returnOrKeyword).append("}"); + } else { + stub.append("\n").append(indent).append(" * @return"); + } + } else if (isJS) { + // For JS functions without explicit return type, add empty @returns + stub.append("\n").append(indent).append(" * @returns {any}"); + } + } else { + // Try to match field declaration: [modifiers] Type name or var/let/const name + java.util.regex.Pattern fieldPattern = java.util.regex.Pattern.compile( + "^(?:(?:public|private|protected|static|final|var|let|const)\\s+)*" + // Optional modifiers + "(\\w+(?:<[^>]+>)?)\\s+" + // Type (Group 1) + "(\\w+)" + // Field name (Group 2) + "(?:\\s*=|\\s*;)" // Followed by = or ; + ); + + java.util.regex.Matcher fieldMatcher = fieldPattern.matcher(trimmed); + if (fieldMatcher.find()) { + String fieldType = fieldMatcher.group(1); + + // Check if this is JavaScript + boolean isJS = container != null && container.getDocument() != null && container.getDocument().isJavaScript(); + + if (isJS && fieldType != null) { + // For JS fields, add @type annotation + stub.append("\n").append(indent).append(" * @type {").append("any").append("}"); + } + } + } + + // Close the JSDoc block + stub.append("\n").append(indent).append(" */"); + + return stub.toString(); + } /** * Handles deletion keys: Delete, Backspace, and Ctrl+Backspace. @@ -1439,7 +2275,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (!s.isEmpty() && !selection.hasSelection()) // remove single character after caret when nothing is selected s = s.substring(1); - setText(getSelectionBeforeText() + s); + setText(getSelectionBeforeText() + s, true); // Use atomic undo // Keep caret at same start selection selection.reset(selection.getStartSelection()); return true; @@ -1447,46 +2283,33 @@ public class GuiScriptTextArea extends GuiNpcTextField { // CTRL+BACKSPACE: delete to previous word or whitespace boundary. if (isKeyComboCtrlBackspace(i)) { - String s = getSelectionBeforeText(); + String before = getSelectionBeforeText(); if (selection.getStartSelection() > 0 && !selection.hasSelection()) { - int nearestCondition = selection.getCursorPosition(); - int g; - // If the char left of caret is whitespace, find the first non-space to the left; - // otherwise find first whitespace/newline to the left (word boundary). - boolean cursorInWhitespace = Character.isWhitespace(s.charAt(selection.getCursorPosition() - 1)); - if (cursorInWhitespace) { - // Scan left until non-whitespace (start of previous word) - for (g = selection.getCursorPosition() - 1; g >= 0; g--) { - char currentChar = s.charAt(g); - if (!Character.isWhitespace(currentChar)) { - nearestCondition = g; - break; - } - if (g == 0) { - nearestCondition = 0; - } - } + int pos = selection.getCursorPosition(); + int g = pos; + + // Helper: treat letters, digits and underscore as word characters + java.util.function.IntPredicate isWordChar = ch -> Character.isLetterOrDigit(ch) || ch == '_'; + + // If caret is after whitespace, delete contiguous whitespace first + char left = before.charAt(pos - 1); + if (Character.isWhitespace(left)) { + while (g - 1 >= 0 && Character.isWhitespace(before.charAt(g - 1))) + g--; + } else if (isWordChar.test(left)) { + // Delete contiguous word characters (letters/digits/_) + while (g - 1 >= 0 && isWordChar.test(before.charAt(g - 1))) + g--; } else { - // Scan left until whitespace/newline is found (word boundary) - for (g = selection.getCursorPosition() - 1; g >= 0; g--) { - char currentChar = s.charAt(g); - if (Character.isWhitespace(currentChar) || currentChar == '\n') { - nearestCondition = g; - break; - } - if (g == 0) { - nearestCondition = 0; - } - } + // Delete contiguous non-word, non-whitespace characters (punctuation) + while (g - 1 >= 0 && !Character.isWhitespace(before.charAt(g - 1)) && !isWordChar.test(before.charAt(g - 1))) + g--; } - // Trim the prefix up to the discovered boundary - s = s.substring(0, nearestCondition); - // Adjust selection start to match removed characters - selection.setStartSelection( - selection.getStartSelection() - (selection.getCursorPosition() - nearestCondition)); + before = before.substring(0, g); + selection.setStartSelection(selection.getStartSelection() - (pos - g)); } - setText(s + getSelectionAfterText()); + setText(before + getSelectionAfterText(), true); // Use atomic undo selection.reset(selection.getStartSelection()); return true; } @@ -1501,7 +2324,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { // 1) selection deletion if (selection.hasSelection()) { String s = getSelectionBeforeText(); - setText(s + getSelectionAfterText()); + setText(s + getSelectionAfterText(), true); // Use atomic undo selection.reset(selection.getStartSelection()); scrollToCursor(); return true; @@ -1512,21 +2335,17 @@ public class GuiScriptTextArea extends GuiNpcTextField { return true; } - // If the current line is whitespace-only, delete the whole line - // (including the trailing newline if present). This makes Backspace - // intuitive on blank/indented lines outside any recognized scope. + // If the current line is whitespace-only, remove it by deleting the + // preceding newline and the line's content, but preserve any trailing + // newline so the following line (e.g. a closing brace) stays in place. LineData currCheck = selection.findCurrentLine(container.lines); if (currCheck != null && currCheck.text.trim().length() == 0) { - int removeEnd = text.indexOf('\n', currCheck.start - 1); - if (removeEnd == -1) { - removeEnd = text.length(); - } else { - removeEnd = removeEnd + 1; // include the newline - } - String before = text.substring(0, ValueUtil.clamp(currCheck.start - 1, 0, text.length())); - String after = removeEnd <= text.length() ? text.substring(removeEnd) : ""; - setText(before + after); - int newCursor = Math.max(0, currCheck.start - 1); + int removeStart = ValueUtil.clamp(currCheck.start - 1, 0, text.length()); + int contentEnd = Math.min(currCheck.start + currCheck.text.length(), text.length()); + String before = text.substring(0, removeStart); + String after = text.substring(contentEnd); + setText(before + after, true); + int newCursor = Math.max(0, removeStart); selection.reset(newCursor); scrollToCursor(); return true; @@ -1554,7 +2373,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { } String before = text.substring(0, curr.start); String after = removeEnd <= text.length() ? text.substring(removeEnd) : ""; - setText(before + after); + setText(before + after, true); // Use atomic undo // Place caret at end of previous line int newCursor = Math.max(0, curr.start - 1); selection.reset(newCursor); @@ -1572,16 +2391,16 @@ public class GuiScriptTextArea extends GuiNpcTextField { char lastChar = before.charAt(before.length() - 1); char firstChar = content.charAt(0); // Avoid adding space when punctuation/brackets are adjacent - if (!Character.isWhitespace(lastChar) && + if (!Character.isWhitespace(lastChar) && lastChar != '{' && lastChar != '(' && lastChar != '[' && - firstChar != '}' && firstChar != ')' && firstChar != ']' && + firstChar != '}' && firstChar != ')' && firstChar != ']' && firstChar != ';' && firstChar != ',' && firstChar != '.' && firstChar != '\n') { spacer = " "; } } - setText(before + spacer + content); + setText(before + spacer + content, true); // Use atomic undo int newCursor = before.length() + spacer.length(); selection.reset(newCursor); scrollToCursor(); @@ -1595,15 +2414,15 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (selection.getStartSelection() > 0 && selection.getStartSelection() < text.length()) { char prev = text.charAt(selection.getStartSelection() - 1); char nextc = text.charAt(selection.getStartSelection()); - if ((prev == '(' && nextc == ')') || - (prev == '[' && nextc == ']') || - (prev == '{' && nextc == '}') || - (prev == '\'' && nextc == '\'') || + if ((prev == '(' && nextc == ')') || + (prev == '[' && nextc == ']') || + (prev == '{' && nextc == '}') || + (prev == '\'' && nextc == '\'') || (prev == '"' && nextc == '"')) { String before = text.substring(0, selection.getStartSelection() - 1); String after = selection.getStartSelection() + 1 < text.length() ? text.substring( - selection.getStartSelection() + 1) : ""; - setText(before + after); + selection.getStartSelection() + 1) : ""; + setText(before + after, true); // Use atomic undo selection.setStartSelection(selection.getStartSelection() - 1); selection.reset(selection.getStartSelection()); scrollToCursor(); @@ -1615,9 +2434,11 @@ public class GuiScriptTextArea extends GuiNpcTextField { String s = getSelectionBeforeText(); s = s.substring(0, s.length() - 1); selection.setStartSelection(selection.getStartSelection() - 1); - setText(s + getSelectionAfterText()); + setText(s + getSelectionAfterText(), true); // Use atomic undo selection.reset(selection.getStartSelection()); scrollToCursor(); + // Notify autocomplete of deletion + autocompleteManager.onDeleteKey(text, selection.getCursorPosition()); return true; } @@ -1763,63 +2584,413 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (ChatAllowedCharacters.isAllowedCharacter(c)) { String before = getSelectionBeforeText(); String after = getSelectionAfterText(); + int cursorPos = selection.getCursorPosition(); - // If the user types a closing character and that same closer is - // already immediately after the caret, move caret past it instead - // of inserting another closer. This prevents duplicate closers - // when the editor auto-inserts pairs. - if ((c == ')' || c == ']' || c == '"' || c == '\'') && after.length() > 0 && after.charAt(0) == c) { - // Move caret forward by one (skip over existing closer) + // Diamond/generic angle bracket handling + if (c == '<') { + if (!container.getDocument().isExcludedInclusive(cursorPos) && isGenericContext(before)) { + if (hasUnmatchedCloserAhead(after, '<', '>')) { + // There's already an unmatched '>' ahead — just insert '<' + setText(before + "<" + after, true); + selection.reset(before.length() + 1); + } else { + setText(before + "<>" + after, true); + selection.reset(before.length() + 1); + } + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + } + + if (c == '>') { + if (after.length() > 0 && after.charAt(0) == '>') { + if (shouldSkipAngleBracketClose(before)) { + selection.reset(before.length() + 1); + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + } + } + + if ((c == ')' || c == ']' || c == '}') && after.length() > 0 && after.charAt(0) == c) { selection.reset(before.length() + 1); scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + + if (c == '"' || c == '\'') { + if (after.length() > 0 && after.charAt(0) == c) { + // Move caret forward by one (skip over existing closer) + selection.reset(before.length() + 1); + scrollToCursor(); + // Notify autocomplete of the character + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + + // Auto-pair only when it looks like we're starting a new string. If the current + // logical line already has an unclosed quote of this type, treat the typed quote + // as a closer to avoid producing triple quotes. + boolean allowAutoPair = !container.getDocument().isExcludedInclusive(cursorPos) + && !isLikelyClosingQuote(before, c); + + if (allowAutoPair) { + if (c == '"') { + setText(before + "\"\"" + after, true); + } else { + setText(before + "''" + after, true); + } + selection.reset(before.length() + 1); + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + + addText(Character.toString(c)); + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); return true; } // Auto-pair insertion: when opening a quote/brace/bracket is typed, // insert a matching closer and place caret between the pair. - if (c == '"') { - setText(before + "\"\"" + after); - selection.reset(before.length() + 1); - scrollToCursor(); - return true; + // But only if the current position is not excluded (e.g., inside a comment or string) + if (!container.getDocument().isExcludedInclusive(cursorPos)) { + if (c == '[') { + if (hasUnmatchedCloserAhead(after, '[', ']')) { + setText(before + c + after, true); + selection.reset(before.length() + 1); + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + setText(before + "[]" + after, true); + selection.reset(before.length() + 1); + scrollToCursor(); + // Notify autocomplete of the character + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + if (c == '(') { + if (hasUnmatchedCloserAhead(after, '(', ')')) { + setText(before + c + after, true); + selection.reset(before.length() + 1); + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + setText(before + "()" + after, true); + selection.reset(before.length() + 1); + scrollToCursor(); + // Notify autocomplete of the character + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + if (c == '{') { + if (hasUnmatchedCloserAhead(after, '{', '}')) { + setText(before + c + after, true); + selection.reset(before.length() + 1); + scrollToCursor(); + autocompleteManager.onCharTyped(c, text, cursorPos); + return true; + } + } } - if (c == '\'') { - setText(before + "''" + after); - selection.reset(before.length() + 1); - scrollToCursor(); - return true; - } - if (c == '[') { - setText(before + "[]" + after); - selection.reset(before.length() + 1); - scrollToCursor(); - return true; - } - if (c == '(') { - setText(before + "()" + after); - selection.reset(before.length() + 1); - scrollToCursor(); - return true; - } - // Default insertion for printable characters: insert at caret (replacing selection) addText(Character.toString(c)); scrollToCursor(); + // Notify autocomplete of the character + autocompleteManager.onCharTyped(c, text, cursorPos); return true; } return false; } + private boolean isLikelyClosingQuote(String before, char quote) { + if (before == null || before.isEmpty()) { + return false; + } + int lineStart = before.lastIndexOf('\n'); + int start = lineStart == -1 ? 0 : lineStart + 1; + int count = 0; + for (int i = start; i < before.length(); i++) { + if (before.charAt(i) == quote && !isEscaped(before, i)) { + count++; + } + } + return (count % 2) == 1; + } + + private boolean isEscaped(String s, int index) { + int backslashes = 0; + for (int i = index - 1; i >= 0 && s.charAt(i) == '\\'; i--) { + backslashes++; + } + return (backslashes % 2) == 1; + } + + private boolean isGenericContext(String before) { + if (before == null || before.isEmpty()) return false; + + int i = before.length() - 1; + while (i >= 0 && (before.charAt(i) == ' ' || before.charAt(i) == '\t')) { + i--; + } + if (i < 0) return false; + + char last = before.charAt(i); + + if (last == '>' || last == ')' || last == ']') return true; + if (last == ',') return true; + + if (Character.isJavaIdentifierPart(last)) { + int end = i + 1; + while (i >= 0 && Character.isJavaIdentifierPart(before.charAt(i))) { + i--; + } + String word = before.substring(i + 1, end); + + if (isComparisonKeyword(word)) return false; + if (isNumericLiteral(word)) return false; + + return true; + } + + return false; + } + + private boolean isComparisonKeyword(String word) { + return "if".equals(word) || "while".equals(word) || "for".equals(word) + || "return".equals(word) || "else".equals(word) || "case".equals(word) + || "assert".equals(word) || "throw".equals(word) || "true".equals(word) + || "false".equals(word) || "null".equals(word); + } + + private boolean isNumericLiteral(String word) { + if (word.isEmpty()) return false; + char first = word.charAt(0); + return first >= '0' && first <= '9'; + } + + private boolean shouldSkipAngleBracketClose(String before) { + if (before == null || before.isEmpty()) return false; + int depth = 0; + boolean inLineComment = false; + boolean inBlockComment = false; + boolean inString = false; + boolean escape = false; + char stringDelimiter = 0; + + for (int i = 0; i < before.length(); i++) { + char c = before.charAt(i); + char next = i + 1 < before.length() ? before.charAt(i + 1) : 0; + + if (inString) { + if (escape) { escape = false; } + else if (c == '\\') { escape = true; } + else if (c == stringDelimiter || c == '\n') { inString = false; } + continue; + } + if (inBlockComment) { + if (c == '*' && next == '/') { inBlockComment = false; i++; } + continue; + } + if (inLineComment) { + if (c == '\n') { inLineComment = false; } + continue; + } + if (c == '/' && next == '/') { inLineComment = true; i++; continue; } + if (c == '/' && next == '*') { inBlockComment = true; i++; continue; } + if (c == '"' || c == '\'') { inString = true; stringDelimiter = c; escape = false; continue; } + + if (c == '<') depth++; + else if (c == '>') depth--; + } + return depth > 0; + } + + private boolean hasUnmatchedCloserAhead(String after, char opener, char closer) { + int balance = 0; + int len = after.length(); + for (int idx = 0; idx < len; idx++) { + char ch = after.charAt(idx); + if (ch == '\n') break; + // Bail out at string / comment boundaries to avoid false matches + if (ch == '"' || ch == '\'') return false; + if (ch == '/' && idx + 1 < len) { + char next = after.charAt(idx + 1); + if (next == '/' || next == '*') return false; + } + if (ch == opener) { + balance++; + } else if (ch == closer) { + if (balance == 0) return true; + balance--; + } + } + return false; + } + + private String getLogicalLineIndentAt(int pos) { + if (text == null || text.isEmpty()) { + return ""; + } + int safePos = Math.max(0, Math.min(pos, text.length())); + int lineStart = text.lastIndexOf('\n', Math.max(0, safePos - 1)) + 1; + int p = lineStart; + while (p < text.length()) { + char ch = text.charAt(p); + if (ch == ' ' || ch == '\t') { + p++; + } else { + break; + } + } + return text.substring(lineStart, p); + } + + private boolean isLambdaOpening(int bracePos, String fullText) { + if (fullText == null || bracePos <= 1) { + return false; + } + int scan = bracePos - 1; + while (scan >= 0 && (fullText.charAt(scan) == ' ' || fullText.charAt(scan) == '\t')) { + scan--; + } + if (scan < 1) { + return false; + } + char c1 = fullText.charAt(scan - 1); + char c2 = fullText.charAt(scan); + return (c1 == '-' && c2 == '>') || (c1 == '=' && c2 == '>'); + } + + // Reverse-scans from bracePos to find the unmatched '(' that this lambda is an + // argument of. Properly handles nested parens/braces, strings, and comments. + // Returns the position of the enclosing '(' or -1 if not found. + private int findLambdaParentParen(int bracePos, String fullText) { + if (fullText == null || bracePos <= 0) { + return -1; + } + + int parenDepth = 0; + int braceDepth = 0; + boolean inString = false; + boolean inBlockComment = false; + char stringDelim = 0; + + for (int i = bracePos - 1; i >= 0; i--) { + char c = fullText.charAt(i); + char prev = i > 0 ? fullText.charAt(i - 1) : 0; + + // Reverse block-comment: entered at '*/', exits at '/*' + if (inBlockComment) { + if (c == '*' && prev == '/') { + inBlockComment = false; + i--; + } + continue; + } + + if (c == '/' && prev == '*') { + inBlockComment = true; + i--; + continue; + } + + if (inString) { + if (c == stringDelim) { + int bs = 0; + for (int j = i - 1; j >= 0 && fullText.charAt(j) == '\\'; j--) { + bs++; + } + if (bs % 2 == 0) { + inString = false; + } + } + continue; + } + + if (c == '"' || c == '\'' || c == '`') { + inString = true; + stringDelim = c; + continue; + } + + // For line comments: when scanning backwards and hitting a newline, + // check if the preceding line contains a // comment. If so, skip + // backwards past it to avoid counting brackets inside comments. + if (c == '\n') { + int lineStart = fullText.lastIndexOf('\n', i - 1) + 1; + int commentIdx = findLineCommentStart(fullText, lineStart, i); + if (commentIdx >= 0) { + i = commentIdx; + } + continue; + } + + if (c == '}') { + braceDepth++; + } else if (c == '{') { + if (braceDepth > 0) { + braceDepth--; + } + if (braceDepth == 0) { + return -1; + } + } else if (c == ')') { + parenDepth++; + } else if (c == '(') { + if (parenDepth > 0) { + parenDepth--; + } else { + return i; + } + } + } + return -1; + } + + private int findLineCommentStart(String text, int lineStart, int lineEnd) { + boolean inStr = false; + char strDelim = 0; + for (int i = lineStart; i < lineEnd; i++) { + char c = text.charAt(i); + if (inStr) { + if (c == strDelim && (i == 0 || text.charAt(i - 1) != '\\')) { + inStr = false; + } + continue; + } + if (c == '"' || c == '\'' || c == '`') { + inStr = true; + strDelim = c; + continue; + } + if (c == '/' && i + 1 < lineEnd && text.charAt(i + 1) == '/') { + return i; + } + } + return -1; + } + + private String getParentIndentForLambda(int parenPos, List lines) { + return getLogicalLineIndentAt(parenPos); + } + private boolean isShiftKeyDown() { return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54); } // ==================== COMMENT TOGGLING ==================== // Uses CommentHandler helper for comment operations - + private void toggleCommentSelection() { CommentHandler.SelectionToggleResult result = CommentHandler.toggleCommentSelection( - text, container.lines, selection.getStartSelection(), selection.getEndSelection()); + text, container.lines, selection.getStartSelection(), selection.getEndSelection()); setText(result.newText); selection.setStartSelection(result.newStartSelection); selection.setEndSelection(result.newEndSelection); @@ -1827,15 +2998,17 @@ public class GuiScriptTextArea extends GuiNpcTextField { private void toggleCommentLineAtCursor() { CommentHandler.SingleLineToggleResult result = CommentHandler.toggleCommentAtCursor( - text, container.lines, selection.getCursorPosition()); + text, container.lines, selection.getCursorPosition()); setText(result.newText); setCursor(result.newCursorPosition, false); } - - public boolean closeOnEsc() { - return !KEYS_OVERLAY.isVisible() && !searchBar.isVisible() && !goToLineDialog.isVisible() && !renameHandler.isActive(); + + public boolean closeOnEsc(){ + return !KEYS_OVERLAY.isVisible() && !searchBar.isVisible() && !goToLineDialog.isVisible() + && !renameHandler.isActive() && !autocompleteManager.isVisible() + && !(hoverState.isTooltipVisible() && (hoverState.hasOverriddenPosition() || hoverState.hasOverriddenSize())); } - + // ==================== KEYBOARD MODIFIERS ==================== private boolean isAltKeyDown() { @@ -1883,7 +3056,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { return IndentHelper.getAutoIndentForEnter(currentLine.text, selection.getCursorPosition() - currentLine.start); } // ==================== TEXT FORMATTING ==================== - + private int getTabSize() { return IndentHelper.TAB_SIZE; } @@ -1893,13 +3066,15 @@ public class GuiScriptTextArea extends GuiNpcTextField { } private void formatText() { - // Calculate viewport width for line wrapping (account for gutter and scrollbar) - int viewportWidth = this.width - LINE_NUMBER_GUTTER_WIDTH - 10; - IndentHelper.FormatResult result = IndentHelper.formatText(text, selection.getCursorPosition(), viewportWidth); + int viewportPixels = this.width - LINE_NUMBER_GUTTER_WIDTH - 10; + int avgCharWidth = Math.max(1, ClientProxy.Font.width("abcdefghijklmnopqrstuvwxyz") / 26); + int viewportChars = (int) (viewportPixels * 0.8f / avgCharWidth); + int maxLineLength = Math.max(60, Math.min(viewportChars, 120)); + IndentHelper.FormatResult result = IndentHelper.formatText(text, selection.getCursorPosition(), maxLineLength); setText(result.text); selection.reset(Math.max(0, Math.min(result.cursorPosition, this.text.length()))); } - + // ==================== TAB HANDLING ==================== private void handleTab() { @@ -1961,43 +3136,24 @@ public class GuiScriptTextArea extends GuiNpcTextField { return; int tab = getTabSize(); int indentLen = IndentHelper.getLineIndent(currentLine.text); - int textStartPos = currentLine.start + indentLen; - if (selection.getCursorPosition() <= textStartPos) { - // Cursor before any text: reduce leading indent to previous tab stop - int targetIndent = Math.max(0, ((indentLen - 1) / tab) * tab); - String newIndent = repeatSpace(targetIndent); - String rest = currentLine.text.substring(indentLen); - String before = text.substring(0, currentLine.start); - int contentEnd = Math.min(currentLine.start + currentLine.text.length(), text.length()); - int sepEnd = Math.min(currentLine.end, text.length()); - String sep = contentEnd < sepEnd ? text.substring(contentEnd, sepEnd) : ""; - String after = text.substring(sepEnd); - setText(before + newIndent + rest + sep + after); - int newCursor = currentLine.start + targetIndent; - selection.reset(Math.min(newCursor, this.text.length())); - } else { - // Cursor after start of text: remove up to previous tab stop worth of spaces immediately before cursor - int column = selection.getCursorPosition() - currentLine.start; - int mod = column % tab; - int toRemove = mod == 0 ? tab : mod; - int removed = 0; - int pos = selection.getCursorPosition() - 1; - while (pos >= currentLine.start && removed < toRemove && text.charAt(pos) == ' ') { - pos--; - removed++; - } - if (removed > 0) { - int removeStart = pos + 1; - String before = text.substring(0, removeStart); - String after = text.substring(selection.getCursorPosition()); - setText(before + after); - int newCursor = removeStart; - selection.reset(Math.min(newCursor, this.text.length())); - } - } + if (indentLen == 0) + return; + + int targetIndent = Math.max(0, ((indentLen - 1) / tab) * tab); + int removed = indentLen - targetIndent; + String newIndent = repeatSpace(targetIndent); + String rest = currentLine.text.substring(indentLen); + String before = text.substring(0, currentLine.start); + int contentEnd = Math.min(currentLine.start + currentLine.text.length(), text.length()); + int sepEnd = Math.min(currentLine.end, text.length()); + String sep = contentEnd < sepEnd ? text.substring(contentEnd, sepEnd) : ""; + String after = text.substring(sepEnd); + setText(before + newIndent + rest + sep + after); + int newCursor = Math.max(currentLine.start, selection.getCursorPosition() - removed); + selection.reset(Math.min(newCursor, this.text.length())); } - + // ==================== CURSOR MANAGEMENT ==================== private void setCursor(int i, boolean select) { @@ -2006,7 +3162,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { private void addText(String s) { int insertPos = selection.getStartSelection(); - this.setText(this.getSelectionBeforeText() + s + this.getSelectionAfterText()); + this.setText(this.getSelectionBeforeText() + s + this.getSelectionAfterText(), true); // Use atomic undo for typing selection.afterTextInsert(insertPos + s.length()); } @@ -2025,32 +3181,121 @@ public class GuiScriptTextArea extends GuiNpcTextField { public String getSelectionAfterText() { return selection.getTextAfter(text); } - + // ==================== MOUSE HANDLING ==================== public void mouseClicked(int xMouse, int yMouse, int mouseButton) { + // HIGHEST PRIORITY: tooltip panel absorbs all clicks — no click-through to panels beneath it + if (hoverState.isTooltipVisible() && hoverState.isMouseOverTooltipPanel(xMouse, yMouse)) { + if (mouseButton == 0) { + if (hoverState.isMouseOverResizeHandle(xMouse, yMouse)) { + hoverState.startTooltipResize(xMouse, yMouse); + } else if (hoverState.isMouseOverScrollbarThumb(xMouse, yMouse)) { + hoverState.startScrollbarDrag(yMouse); + } else { + hoverState.startTooltipDrag(xMouse, yMouse); + } + } + return; // consume — nothing below receives this click + } + // M1 outside a dragged/resized tooltip — dismiss it and fall through to editor + if (mouseButton == 0 && (hoverState.hasOverriddenPosition() || hoverState.hasOverriddenSize()) + && !hoverState.isMouseOverTooltipPanel(xMouse, yMouse)) { + hoverState.clearHover(); + } + // Check autocomplete menu clicks first + if (autocompleteManager.isVisible() && autocompleteManager.mouseClicked(xMouse, yMouse, mouseButton)) { + return; + } + + // Dismiss autocomplete if clicking elsewhere + if (autocompleteManager.isVisible()) { + autocompleteManager.dismiss(); + } + + if (parent != null && parent.fullscreenButton.mouseClicked(xMouse, yMouse, mouseButton)) + return; + + // Check go to line dialog clicks first if (goToLineDialog.isVisible() && goToLineDialog.mouseClicked(xMouse, yMouse, mouseButton)) { return; } - + // Check search bar clicks first if (searchBar.isVisible() && searchBar.mouseClicked(xMouse, yMouse, mouseButton)) { return; } - + // If search bar is visible but click was outside it, unfocus the search bar if (searchBar.isVisible()) { searchBar.unfocus(); } - + // Let the overlay consume clicks (it returns true when it handled the event) if (KEYS_OVERLAY.mouseClicked(xMouse, yMouse, mouseButton)) return; - + // Determine whether click occurred inside the text area bounds this.active = xMouse >= this.x && xMouse < this.x + this.width && yMouse >= this.y && yMouse < this.y + this.height; if (this.active) { + // Ctrl+Click: Go to definition + if (mouseButton == 0 && isCtrlKeyDown()) { + Object[] tokenInfo = getTokenAtScreenPosition(xMouse, yMouse); + if (tokenInfo != null) { + Token token = (Token) tokenInfo[0]; + int targetOffset = -1; + + // Check if token has method info with declaration + if (token.getMethodInfo() != null) { + MethodInfo methodInfo = token.getMethodInfo(); + if (methodInfo.getNameOffset() >= 0) { + targetOffset = methodInfo.getNameOffset(); + } + } + // Check if token has method call info with resolved declaration + else if (token.getMethodCallInfo() != null) { + MethodCallInfo callInfo = token.getMethodCallInfo(); + MethodInfo resolvedMethod = callInfo.getResolvedMethod(); + if (resolvedMethod != null && resolvedMethod.getNameOffset() >= 0) { + targetOffset = resolvedMethod.getNameOffset(); + } + } + // Check if token has field info with declaration + else if (token.getFieldInfo() != null) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo.getDeclarationOffset() >= 0) { + targetOffset = fieldInfo.getDeclarationOffset(); + } + } + // Check if token has field access info with resolved declaration + else if (token.getFieldAccessInfo() != null) { + FieldAccessInfo accessInfo = token.getFieldAccessInfo(); + FieldInfo resolvedField = accessInfo.getResolvedField(); + if (resolvedField != null && resolvedField.getDeclarationOffset() >= 0) { + targetOffset = resolvedField.getDeclarationOffset(); + } + } + // Check if token is a script-defined type + else if (token.getTypeInfo() != null && token.getTypeInfo() instanceof ScriptTypeInfo) { + ScriptTypeInfo scriptType = + (ScriptTypeInfo) token.getTypeInfo(); + if (scriptType.getDeclarationOffset() >= 0) { + targetOffset = scriptType.getDeclarationOffset(); + } + } + + // Jump to definition if found + if (targetOffset >= 0) { + selection.reset(targetOffset); + scrollToCursor(); + this.clicked = false; + activeTextfield = this; + return; // Consume the event + } + } + } + // Compute logical click position in text int clickPos = this.getSelectionPos(xMouse, yMouse); @@ -2078,7 +3323,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { if (this.clicked && getPaddedLineCount() * this.container.lineHeight > this.height && xMouse > this.x + this.width - 8) { // We consumed the mouse-down as a scrollbar drag start this.clicked = false; - scroll.startScrollbarDrag(yMouse, this.y, this.height, getPaddedLineCount()); + scroll.startScrollbarDrag(yMouse,this.y,this.height, getPaddedLineCount()); } else { // Handle double/triple click selection counting if (time - this.lastClicked < 300L) { @@ -2108,6 +3353,29 @@ public class GuiScriptTextArea extends GuiNpcTextField { this.lastClicked = time; activeTextfield = this; + + // Click-to-pin handling: if enabled, clicking a token will pin/unpin its tooltip + if (mouseButton == 0 && hoverState.isClickToPinEnabled()) { + Object[] tokenInfo = getTokenAtScreenPosition(xMouse, yMouse); + if (tokenInfo != null) { + Token clickedToken = (Token) tokenInfo[0]; + int tokenScreenX = (Integer) tokenInfo[1]; + int tokenScreenY = (Integer) tokenInfo[2]; + int tokenWidth = (Integer) tokenInfo[3]; + + // If already pinned on same token, unpin; otherwise pin this token + if (hoverState.isPinned() && hoverState.getHoveredToken() == clickedToken) { + hoverState.unpin(); + } else { + hoverState.pinToken(clickedToken, tokenScreenX, tokenScreenY, tokenWidth); + } + } else { + // Clicked outside any token -> unpin any pinned tooltip + if (hoverState.isPinned()) { + hoverState.unpin(); + } + } + } } } @@ -2122,10 +3390,20 @@ public class GuiScriptTextArea extends GuiNpcTextField { renameHandler.updateCursor(); ++this.cursorCounter; } - + // ==================== TEXT MANAGEMENT ==================== public void setText(String text) { + setText(text, false); + } + + /** + * Set text with optional atomic undo support. + * + * @param text The new text content + * @param allowAtomic If true, allows grouping consecutive typing into single undo steps + */ + private void setText(String text, boolean allowAtomic) { if (text == null) { return; } @@ -2139,19 +3417,53 @@ public class GuiScriptTextArea extends GuiNpcTextField { this.listener.textUpdate(text); } - if (!this.undoing) { + // Atomic undo logic: group consecutive typing into word-based undo steps + if (!this.undoing && allowAtomic && !undoList.isEmpty()) { + long now = System.currentTimeMillis(); + int cursorPos = selection.getCursorPosition(); + + // Check if we should merge with the previous undo entry + boolean shouldMerge = + (now - lastTypingTime < 2000) && // Within 2 seconds + Math.abs(cursorPos - lastTypingPos) <= 1; // Contiguous edit + + // If typing a space or newline, break the undo group + if (shouldMerge && text.length() > 0 && cursorPos > 0 && cursorPos <= text.length()) { + char lastChar = text.charAt(cursorPos - 1); + if (Character.isWhitespace(lastChar)) { + shouldMerge = false; + } + } + + if (shouldMerge) { + // Don't add a new undo entry - just update the text + // The existing undo entry will remain unchanged + } else { + // Add new undo entry + this.undoList.add(new GuiScriptTextArea.UndoData(this.text, selection.getCursorPosition())); + this.redoList.clear(); + } + + lastTypingTime = now; + lastTypingPos = cursorPos; + } else if (!this.undoing) { + // Normal undo entry (non-atomic) this.undoList.add(new GuiScriptTextArea.UndoData(this.text, selection.getCursorPosition())); this.redoList.clear(); + + // Reset atomic undo tracking + lastTypingTime = System.currentTimeMillis(); + lastTypingPos = selection.getCursorPosition(); } this.text = text; //this.container = new TextContainer(text); if (this.container == null) - this.container = new JavaTextContainer(text); + this.container = new ScriptTextContainer(text); this.container.init(text, this.width, this.height); - if (this.enableCodeHighlighting) + if (this.enableCodeHighlighting) this.container.formatCodeText(); // Ensure scroll state stays in bounds after text change @@ -2163,6 +3475,9 @@ public class GuiScriptTextArea extends GuiNpcTextField { // Consider text changes user activity to pause caret blinking briefly selection.markActivity(); searchBar.updateMatches(); + + // Update autocomplete manager with current container + autocompleteManager.setContainer(this.container); } } @@ -2183,6 +3498,26 @@ public class GuiScriptTextArea extends GuiNpcTextField { this.enableCodeHighlighting = true; this.container.formatCodeText(); } + + /** + * Set the scripting language for syntax highlighting and type inference. + * @param language The language name (e.g., "ECMAScript", "Groovy") + */ + public void setLanguage(String language) { + if (this.container != null) { + this.container.setLanguage(language); + if (this.enableCodeHighlighting) { + this.container.formatCodeText(); + } + } + } + + /** + * Get the current scripting language. + */ + public String getLanguage() { + return this.container != null ? this.container.getLanguage() : "ECMAScript"; + } /** * Set the script context (NPC, PLAYER, BLOCK, ITEM, etc.). @@ -2192,7 +3527,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { */ public void setScriptContext(ScriptContext context) { if (this.container != null) { - // this.container.setScriptContext(context); + this.container.setScriptContext(context); } } @@ -2202,8 +3537,23 @@ public class GuiScriptTextArea extends GuiNpcTextField { * @return The script context (NPC, PLAYER, BLOCK, ITEM, etc.) */ public ScriptContext getScriptContext() { - // return this.container != null ? this.container.getScriptContext() : ScriptContext.GLOBAL; - return ScriptContext.GLOBAL; + return this.container != null ? this.container.getScriptContext() : ScriptContext.GLOBAL; + } + + public ScriptTextContainer getContainer() { + return this.container; + } + + /** + * Add implicit imports that should be resolved without explicit import statements. + * Used for JaninoScript default imports and hook parameter types. + * + * @param patterns Array of import patterns to add (wildcard packages like "noppes.npcs.api.*" or FQ class names) + */ + public void addImplicitImports(String... patterns) { + if (this.container != null) { + this.container.addImplicitImports(patterns); + } } public void setListener(ITextChangeListener listener) { @@ -2213,7 +3563,164 @@ public class GuiScriptTextArea extends GuiNpcTextField { private void clampSelectionBounds() { selection.clamp(text != null ? text.length() : 0); } + + // ==================== AUTOCOMPLETE VISIBILITY ==================== + + /** + * Check if a click position is within the bounds of the autocomplete menu. + * Returns false if autocomplete is not visible. + */ + public boolean isPointOnAutocompleteMenu(int mouseX, int mouseY) { + if (autocompleteManager == null || !autocompleteManager.isVisible()) { + return false; + } + + + AutocompleteMenu menu = autocompleteManager.getMenu(); + if (menu == null) { + return false; + } + + int menuX = menu.getX(); + int menuY = menu.getY(); + int menuWidth = menu.getWidth(); + int menuHeight = menu.getHeight(); + + return mouseX >= menuX && mouseX <= menuX + menuWidth && + mouseY >= menuY && mouseY <= menuY + menuHeight; + } + + // ==================== AUTO-IMPORT ==================== + + /** + * Add an import statement and sort all imports. + */ + private void addAndSortImport(String importPath) { + String currentText = this.text; + int savedCursorPos = selection.getCursorPosition(); + + // Find all existing imports + java.util.regex.Pattern importPattern = java.util.regex.Pattern.compile( + "(?m)^\\s*import\\s+(?:static\\s+)?([A-Za-z_][A-Za-z0-9_]*(?:\\s*\\.\\s*[A-Za-z_*][A-Za-z0-9_]*)*)\\s*;\\s*$" + ); + java.util.regex.Matcher matcher = importPattern.matcher(currentText); + + java.util.List imports = new java.util.ArrayList<>(); + int firstImportStart = -1; + int lastImportEnd = -1; + + while (matcher.find()) { + String importStatement = matcher.group(0); + String importPathFound = matcher.group(1).replaceAll("\\s+", ""); + + if (firstImportStart == -1) { + firstImportStart = matcher.start(); + } + lastImportEnd = matcher.end(); + + // Skip if this is the import we're trying to add + if (!importPathFound.equals(importPath)) { + imports.add(new ImportEntry(importPathFound, importStatement.trim())); + } + } + + // Add the new import + imports.add(new ImportEntry(importPath, "import " + importPath + ";")); + + // Sort imports + java.util.Collections.sort(imports, new java.util.Comparator() { + @Override + public int compare(ImportEntry a, ImportEntry b) { + // Sort order: java.*, javax.*, then others alphabetically + boolean aIsJava = a.path.startsWith("java."); + boolean aIsJavax = a.path.startsWith("javax."); + boolean bIsJava = b.path.startsWith("java."); + boolean bIsJavax = b.path.startsWith("javax."); + + if (aIsJava && !bIsJava) return -1; + if (!aIsJava && bIsJava) return 1; + if (aIsJavax && !bIsJavax && !bIsJava) return -1; + if (!aIsJavax && bIsJavax && !aIsJava) return 1; + + return a.path.compareTo(b.path); + } + }); + + // Build the new import block + StringBuilder importBlock = new StringBuilder(); + String prevPackage = ""; + for (ImportEntry entry : imports) { + // Add blank line between different top-level packages + String topPackage = entry.path.contains(".") ? + entry.path.substring(0, entry.path.indexOf('.')) : entry.path; + if (!prevPackage.isEmpty() && !topPackage.equals(prevPackage)) { + importBlock.append("\n"); + } + importBlock.append(entry.statement).append("\n"); + prevPackage = topPackage; + } + + // Determine where to insert/replace imports + String newText; + int cursorAdjustment = 0; + + if (firstImportStart != -1) { + // Replace existing import block + String before = currentText.substring(0, firstImportStart); + String after = currentText.substring(lastImportEnd); + newText = before + importBlock.toString() + after; + + // Adjust cursor if it's after the import block + int newImportEnd = firstImportStart + importBlock.length(); + if (savedCursorPos >= lastImportEnd) { + cursorAdjustment = newImportEnd - lastImportEnd; + } + } else { + // No existing imports - add at top after package statement (if any) + java.util.regex.Pattern packagePattern = java.util.regex.Pattern.compile( + "(?m)^\\s*package\\s+[A-Za-z_][A-Za-z0-9_.]*\\s*;\\s*$" + ); + java.util.regex.Matcher pkgMatcher = packagePattern.matcher(currentText); + + int insertPos = 0; + if (pkgMatcher.find()) { + insertPos = pkgMatcher.end(); + // Add blank line after package + newText = currentText.substring(0, insertPos) + "\n" + + importBlock.toString() + "\n" + currentText.substring(insertPos); + cursorAdjustment = importBlock.length() + 2; // +2 for the newlines + } else { + // Insert at very beginning + newText = importBlock.toString() + "\n" + currentText; + cursorAdjustment = importBlock.length() + 1; + } + } + + // Apply the changes + setText(newText); + selection.reset(savedCursorPos + cursorAdjustment); + scrollToCursor(); + } + public void formatCodeText() { + if (this.enableCodeHighlighting && this.container != null) { + this.container.formatCodeText(); + } + } + + /** + * Helper class for tracking imports during sorting. + */ + private static class ImportEntry { + String path; + String statement; + + ImportEntry(String path, String statement) { + this.path = path; + this.statement = statement; + } + } + // ==================== INNER CLASSES ==================== public static class UndoData { diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea1.java b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea1.java new file mode 100644 index 000000000..a5a555514 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea1.java @@ -0,0 +1,2188 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.util.ChatAllowedCharacters; +import noppes.npcs.NoppesStringUtils; +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.client.gui.util.key.OverlayKeyPresetViewer; +import noppes.npcs.client.gui.util.script.*; +import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; +import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; +import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer; +import noppes.npcs.client.key.impl.ScriptEditorKeys; +import noppes.npcs.util.ValueUtil; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import java.util.regex.Matcher; + +import static net.minecraft.client.gui.GuiScreen.isCtrlKeyDown; + +/** + * Script text editor component with syntax highlighting, bracket matching, + * smooth scrolling, and IDE-like features. + * + * Helper classes used: + * - ScrollState: smooth scroll animation and state management + * - SelectionState: cursor position and text selection management + * - BracketMatcher: bracket matching and brace span computation + * - IndentHelper: indentation utilities and text formatting + * - CommentHandler: line comment toggling + * - CursorNavigation: cursor movement logic + */ +public class GuiScriptTextArea1 extends GuiNpcTextField { + + // ==================== DIMENSIONS & POSITION ==================== + public int x; + public int y; + + // ==================== STATE FLAGS ==================== + public boolean active = false; + public boolean enabled = true; + public boolean visible = true; + public boolean clicked = false; + public boolean doubleClicked = false; + public boolean tripleClicked = false; + private int clickCount = 0; + private long lastClicked = 0L; + + // ==================== TEXT & CONTAINER ==================== + public String text = null; + public String highlightedWord; + private ScriptTextContainer container = null; + private boolean enableCodeHighlighting = false; + // Extra empty lines to allow padding at the bottom of the editor viewport + private int bottomPaddingLines = 6; + + // Search bar layout tracking to allow idempotent/resilient resizing + private int searchBaseY = 0; + private int searchBaseHeight = 0; + private int searchAppliedOffset = 0; + private boolean searchBaseInitialized = false; + + private int getPaddedLineCount() { + if (container == null) return 0; + // Only add bottom padding when the content is already scrollable. This avoids + // introducing a scrollbar when there's nothing to scroll for. + if (container.linesCount > container.visibleLines - bottomPaddingLines) { + return Math.max(0, container.linesCount + bottomPaddingLines); + } else { + return container.linesCount; + } + } + + // ==================== HELPER CLASS INSTANCES ==================== + private final ScrollState scroll = new ScrollState(); + private final SelectionState selection = new SelectionState(); + + // ==================== UI COMPONENTS ==================== + private int cursorCounter; + private ITextChangeListener listener; + private static int LINE_NUMBER_GUTTER_WIDTH = 25; + + // ==================== UNDO/REDO ==================== + public List undoList = new ArrayList<>(); + public List redoList = new ArrayList<>(); + public boolean undoing = false; + + // ==================== KEYS ==================== + public static final ScriptEditorKeys KEYS = new ScriptEditorKeys(); + public OverlayKeyPresetViewer KEYS_OVERLAY = new OverlayKeyPresetViewer(KEYS); + + // ==================== SEARCH/REPLACE ==================== + public static final SearchReplaceBar searchBar = new SearchReplaceBar(); + + // ==================== GO TO LINE ==================== + private final GoToLineDialog goToLineDialog = new GoToLineDialog(); + + // ==================== RENAME REFACTOR ==================== + private final RenameRefactorHandler renameHandler = new RenameRefactorHandler(); + + // ==================== CONSTRUCTOR ==================== + + public GuiScriptTextArea1(GuiScreen guiScreen, int id, int x, int y, int width, int height, String text) { + super(id, guiScreen, x, y, width, height, null); + init(x, y, width, height, text); + } + + public void init(int x, int y, int width, int height, String text) { + this.x = xPosition = x; + this.y = yPosition = y; + this.width = width; + this.height = height; + this.undoing = true; + this.setText(text); + this.undoing = false; + setCallbacks(); + // Reset search-base tracking whenever the editor is (re)initialized + this.searchBaseY = 0; + this.searchBaseHeight = 0; + this.searchAppliedOffset = 0; + this.searchBaseInitialized = false; + + KEYS_OVERLAY.openOnClick = true; + initGui(); + initializeKeyBindings(); + } + public void initGui() { + int endX = x + width, endY = y + height; + int xOffset = hasVerticalScrollbar() ? -8 : -2; + KEYS_OVERLAY.scale = 0.75f; + KEYS_OVERLAY.borderCol1 = KEYS_OVERLAY.borderCol2 = 0xFF3c3c3c; + int overlayWidth = 160; + KEYS_OVERLAY.initGui(x + (width - overlayWidth) / 2 + 5, y + height / 10, overlayWidth, + height - height / 5 - 10); + + KEYS_OVERLAY.viewButton.scale = 0.45f; + KEYS_OVERLAY.viewButton.initGui(endX + xOffset, endY - 26); + + // Initialize search bar (preserves state across initGui calls) + searchBar.initGui(x, y, width); + if (searchBar.isVisible()) { // If open + // Shift viewport down again using the bar's current height + searchBar.callback.resizeEditor(true, searchBar.getTotalHeight()); + if (!active) // Focus search if opening another script tab & bar is open + searchBar.focus(false); + } + + // Initialize Go To Line dialog + goToLineDialog.initGui(x, y, width); + } + + public void setCallbacks() { + searchBar.setCallback(new SearchReplaceBar.SearchCallback() { + @Override + public String getText() { + return GuiScriptTextArea1.this.text; + } + + public String getHighlightedWord() { + return GuiScriptTextArea1.this.highlightedWord; + } + + @Override + public int getSelectionStart() { + return GuiScriptTextArea1.this.selection.getStartSelection(); + } + + @Override + public int getSelectionEnd() { + return GuiScriptTextArea1.this.selection.getEndSelection(); + } + + @Override + public void setText(String newText) { + GuiScriptTextArea1.this.setText(newText); + } + + @Override + public void scrollToPosition(int position) { + // Find line containing position and scroll to it + if (container == null || container.lines == null) + return; + + // Calculate offset to account for search bar height + int searchBarOffset = searchBar.getTotalHeight(); + int effectiveHeight = GuiScriptTextArea1.this.height - searchBarOffset; + int visibleLines = effectiveHeight / container.lineHeight; + // Calculate how many lines the search bar covers + int linesHiddenBySRB = searchBarOffset > 0 ? (int) Math.ceil( + (double) searchBarOffset / container.lineHeight) : 0; + + for (int i = 0; i < container.lines.size(); i++) { + LineData ld = container.lines.get(i); + if (position >= ld.start && position < ld.end) { + int visible = Math.max(1, visibleLines); + int effectiveVisible = Math.max(1, visible - bottomPaddingLines); + int maxScroll = Math.max(0, getPaddedLineCount() - visible); + int targetLine = i; + + // If search bar is visible and would hide this line, scroll down so it's visible + // The target line should appear below the search bar, not under it + int currentScroll = scroll.getScrolledLine(); + int firstVisibleLine = currentScroll + linesHiddenBySRB; + + if (searchBarOffset > 0 && targetLine < firstVisibleLine) { + // Force scroll so target line appears just below the search bar + scroll.setTargetScroll(Math.max(0, targetLine - linesHiddenBySRB), maxScroll); + } else { + scroll.scrollToLine(targetLine, effectiveVisible, maxScroll); + } + break; + } + } + } + + @Override + public void setSelection(int start, int end) { + selection.setSelection(start, end); + selection.setCursorPositionDirect(end); + } + + @Override + public int getGutterWidth() { + return LINE_NUMBER_GUTTER_WIDTH; + } + + @Override + public void unfocusMainEditor() { + // Save position but unfocus + active = false; + } + + @Override + public void focusMainEditor() { + active = true; + searchBar.resetSelection(); + } + + @Override + public void onMatchesUpdated() { + // Called when matches change - could be used for UI updates + } + + // Robust resize: use base editor bounds and apply the requested offset + public void resizeEditor(boolean open, int barHeight) { + int desiredOffset = Math.max(0, barHeight); + // Initialize base values if not set + if (!searchBaseInitialized) { + searchBaseY = GuiScriptTextArea1.this.y; + searchBaseHeight = GuiScriptTextArea1.this.height; + searchAppliedOffset = 0; + searchBaseInitialized = true; + } + + int targetOffset = open ? desiredOffset : 0; + if (targetOffset == searchAppliedOffset) + return; // already in desired state + + // Compute new bounds from base values (idempotent) + int newY = searchBaseY + targetOffset; + int newHeight = Math.max(12, searchBaseHeight - targetOffset); + + GuiScriptTextArea1.this.y = newY; + GuiScriptTextArea1.this.height = newHeight; + searchAppliedOffset = targetOffset; + + if (container != null) + container.visibleLines = Math.max(GuiScriptTextArea1.this.height / container.lineHeight - 1, 1); + } + }); + // Initialize Go To Line dialog with callback + goToLineDialog.setCallback(new GoToLineDialog.GoToLineCallback() { + @Override + public int getLineCount() { + return container != null ? container.linesCount : 0; + } + + @Override + public int getColumnCount(int lineIndex) { + if (container == null || container.lines == null || lineIndex < 0 || lineIndex >= container.lines.size()) { + return 0; + } + LineData ld = container.lines.get(lineIndex); + return ld.end - ld.start; + } + + @Override + public void goToLineColumn(int line, int column) { + if (container == null || container.lines == null) + return; + + // Convert 1-indexed line to 0-indexed + int lineIdx = line - 1; + if (lineIdx < 0 || lineIdx >= container.lines.size()) + return; + + LineData ld = container.lines.get(lineIdx); + int lineLength = ld.end - ld.start; + + // Convert 1-indexed column to 0-indexed, clamp to line length + // lineLength - 1 because the line's end is the start of the next line + int col = Math.max(0, Math.min(column - 1, lineLength - 1)); + int position = ld.start + col; + + // Set cursor position + selection.reset(position); + + // Scroll to make the line visible + int visible = GuiScriptTextArea1.this.height / (container != null ? container.lineHeight : 12); + int effectiveVisible = Math.max(1, visible - bottomPaddingLines); + int maxScroll = Math.max(0, getPaddedLineCount() - visible); + scroll.scrollToLine(lineIdx, effectiveVisible, maxScroll); + } + + @Override + public void unfocusMainEditor() { + // Save position but unfocus + active = false; + } + + @Override + public void focusMainEditor() { + active = true; + selection.markActivity(); + } + + @Override + public void onDialogClose() { + active = true; + selection.markActivity(); + } + }); + + // Initialize Rename Refactor handler with callback + renameHandler.setCallback(new RenameRefactorHandler.RenameCallback() { + @Override + public String getText() { + return GuiScriptTextArea1.this.text; + } + + @Override + public void setText(String newText) { + GuiScriptTextArea1.this.setText(newText); + } + + @Override + public List getLines() { + return container != null ? container.lines : new ArrayList<>(); + } + + @Override + public int getCursorPosition() { + return selection.getCursorPosition(); + } + + public SelectionState getSelectionState() { + return selection; + } + + @Override + public void setCursorPosition(int pos) { + selection.reset(pos); + } + + @Override + public void unfocusMainEditor() { + active = false; + } + + @Override + public void focusMainEditor() { + active = true; + selection.markActivity(); + } + + @Override + public int getGutterWidth() { + return LINE_NUMBER_GUTTER_WIDTH; + } + + @Override + public int getLineHeight() { + return container != null ? container.lineHeight : 12; + } + + @Override + public int getScrolledLine() { + return scroll.getScrolledLine(); + } + + @Override + public double getFractionalOffset() { + return scroll.getFractionalOffset(); + } + + @Override + public void scrollToPosition(int pos) { + if (container == null || container.lines == null) + return; + for (int i = 0; i < container.lines.size(); i++) { + LineData ld = container.lines.get(i); + if (pos >= ld.start && pos < ld.end) { + int visible = Math.max(1, container.visibleLines); + int effectiveVisible = Math.max(1, visible - bottomPaddingLines); + int maxScroll = Math.max(0, getPaddedLineCount() - visible); + scroll.scrollToLine(i, effectiveVisible, maxScroll); + break; + } + } + } + + @Override + public ScriptTextContainer getContainer() { + return container; + } + + @Override + public void setTextWithoutUndo(String newText) { + // Set text without creating an undo entry (for live rename preview) + boolean wasUndoing = undoing; + undoing = true; + setText(newText); + undoing = wasUndoing; + } + + @Override + public void pushUndoState(String textState, int cursor) { + // Push a specific text state to the undo list + if (!undoing) { + undoList.add(new UndoData(textState, cursor)); + redoList.clear(); + } + } + + @Override + public int getViewportWidth() { + return width - LINE_NUMBER_GUTTER_WIDTH - 8; // Account for gutter and scrollbar + } + }); + } + + public boolean fullscreen() { + return GuiScriptInterface.isFullscreen; + } + // ==================== RENDERING ==================== + public void drawTextBox(int xMouse, int yMouse) { + if (!visible) + return; + clampSelectionBounds(); + + // Dynamically calculate gutter width based on line count digits + if (container != null && container.linesCount > 0) { + int maxLineNum = container.linesCount; + String maxLineStr = String.valueOf(maxLineNum); + int digitWidth = ClientProxy.Font.width(maxLineStr); + LINE_NUMBER_GUTTER_WIDTH = digitWidth + 10; // 10px total padding (5px left + 5px right) + } + // Draw outer border around entire area + int offset = fullscreen() ? 2 : 1; + drawRect(x - offset, y - offset - searchBar.getTotalHeight(), x + width + offset, y + height + offset, + 0xffa0a0a0); + + int searchHeight = searchBar.getTotalHeight(); + + + // Draw line number gutter background + drawRect(x, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, 0xff000000); + // Draw text viewport background (starts after gutter) + drawRect(x + LINE_NUMBER_GUTTER_WIDTH, y, x + width, y + height, 0xff000000); + // Draw separator line between gutter and text area + drawRect(x + LINE_NUMBER_GUTTER_WIDTH-1, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, 0xff3c3f41); + + // Enable scissor test to clip drawing to the TEXT viewport rectangle (excludes gutter) + GL11.glEnable(GL11.GL_SCISSOR_TEST); + scissorViewport(); + + container.visibleLines = (height / container.lineHeight); + + int maxScroll = Math.max(0, getPaddedLineCount() - container.visibleLines); + + // Handle mouse wheel scroll + // Take whatever the parent screen has left for this frame rather than polling the wheel + // again - the poll is destructive and the parent has already drained it. + int wheelDelta = listener instanceof GuiNPCInterface ? ((GuiNPCInterface) listener).mouseScroll : Mouse.getDWheel(); + if (listener instanceof GuiNPCInterface) { + ((GuiNPCInterface) listener).mouseScroll = 0; + boolean canScroll = !KEYS_OVERLAY.isVisible() || KEYS_OVERLAY.isVisible() && !KEYS_OVERLAY.aboveOverlay; + if (wheelDelta != 0 && canScroll) + scroll.applyWheelScroll(wheelDelta, maxScroll); + } + + // Handle scrollbar dragging (delegated to ScrollState) + if (scroll.isClickScrolling()) + scroll.handleClickScrolling(yMouse, x, y, height, container.visibleLines, getPaddedLineCount(), maxScroll); + + // Update scroll animation + scroll.initializeIfNeeded(scroll.getScrolledLine()); + scroll.update(maxScroll); + + // Handle click-dragging for selection + if (clicked) { + clicked = Mouse.isButtonDown(0); + int i = getSelectionPos(xMouse, yMouse); + if (i != selection.getCursorPosition()) { + if (doubleClicked || tripleClicked) { + selection.reset(selection.getCursorPosition()); + doubleClicked = false; + tripleClicked = false; + } + setCursor(i, true); + } + } else if (doubleClicked || tripleClicked) { + doubleClicked = false; + tripleClicked = false; + } + // y += searchHeight; + // height -= searchHeight; + // Calculate braces next to cursor to highlight + int startBracket = 0, endBracket = 0; + if (selection.getStartSelection() >= 0 && text != null && text.length() > 0 && + (selection.getEndSelection() - selection.getStartSelection() == 1 || !selection.hasSelection())) { + int[] span = BracketMatcher.findBracketSpanAt(text,selection.getStartSelection()); + if (span != null) { + startBracket = span[0]; + endBracket = span[1]; + } + } + + List list = new ArrayList<>(container.lines); + + // Build brace spans: {origDepth, open line, close line, adjustedDepth} + List braceSpans = BracketMatcher.computeBraceSpans(text, list); + // Always highlight unmatched braces (positions in text) + List unmatchedBraces = BracketMatcher.findUnmatchedBracePositions(text); + + // Determine which exact brace span (openLine/closeLine) to highlight indent guides for + int highlightedOpenLine = -1; + int highlightedCloseLine = -1; + if (startBracket != endBracket && startBracket >= 0) { + int bracketLineIdx = -1; + // Only consider curly braces for highlighting the indent guides + boolean isCurlyBracket = false; + char bc = text.charAt(startBracket); + if (text != null && startBracket >= 0 && startBracket < text.length()) { + if (bc == '{' || bc == '}') isCurlyBracket = true; + } + for (int li = 0; li < list.size(); li++) { + LineData ld = list.get(li); + if (startBracket >= ld.start && startBracket < ld.end) { + bracketLineIdx = li; + break; + } + } + if (bracketLineIdx >= 0 && isCurlyBracket) { + // Prefer a span that directly matches the bracket character's line: + // - if the bracket is an opening '{', prefer spans where openLine == bracketLineIdx + // - if the bracket is a closing '}', prefer spans where closeLine == bracketLineIdx + // If no exact match is found, fall back to the smallest enclosing span (innermost). + int bestSize = Integer.MAX_VALUE; + boolean foundExact = false; + char bracketChar = bc; // from earlier + for (int[] span : braceSpans) { + int openLine = span[1]; + int closeLine = span[2]; + if (bracketLineIdx >= openLine && bracketLineIdx <= closeLine) { + int size = closeLine - openLine; + boolean exactMatch = (bracketChar == '{' && openLine == bracketLineIdx) || (bracketChar == '}' && closeLine == bracketLineIdx); + if (exactMatch) { + // Prefer exact matches immediately (still choose smallest exact span) + if (!foundExact || size < bestSize) { + foundExact = true; + bestSize = size; + highlightedOpenLine = openLine; + highlightedCloseLine = closeLine; + } + } else if (!foundExact) { + // keep the smallest enclosing span as a fallback + if (size < bestSize) { + bestSize = size; + highlightedOpenLine = openLine; + highlightedCloseLine = closeLine; + } + } + } + } + } + } + + highlightedWord = null; + if (selection.hasSelection()) { + Matcher m = container.regexWord.matcher(text); + while (m.find()) { + if (m.start() == selection.getStartSelection() && m.end() == selection.getEndSelection()) { + highlightedWord = text.substring(selection.getStartSelection(), selection.getEndSelection()); + } + } + } + + // Apply fractional GL translate for sub-pixel smooth scrolling + double fracOffset = scroll.getFractionalOffset(); + float fracPixels = (float) (fracOffset * container.lineHeight); + GL11.glPushMatrix(); + GL11.glTranslatef(0.0f, -fracPixels, 0.0f); + + + // Expand render range by one line above/below so partially-visible lines are drawn + int renderStart = Math.max(0, scroll.getScrolledLine() - 1); + // Compute the last line index to render, including the last partially-visible line if any. + // Adds the fractional scroll offset (fracOffset * lineHeight) to ensure the bottom line is drawn + // when only part of it is visible in the viewport. + int renderEnd = (int) Math.min(list.size() - 1, + scroll.getScrolledLine() + container.visibleLines + fracPixels + 1); + + // Strings start drawing vertically this much into the line. + int stringYOffset = 2; + + // Render LINE GUTTER numbers + for (int i = renderStart; i <= renderEnd; i++) { + int posY = y + (i - scroll.getScrolledLine()) * container.lineHeight + stringYOffset; + String lineNum = String.valueOf(i + 1); + int lineNumWidth = ClientProxy.Font.width(lineNum); + int lineNumX = x + LINE_NUMBER_GUTTER_WIDTH - lineNumWidth - 5; // right-align with 5px padding + int lineNumY = posY + 1; + // Highlight current line number + int lineNumColor = 0xFF606366; + if (active && isEnabled()) { + for (int li = 0; li < list.size(); li++) { + LineData ld = list.get(li); + if (selection.getCursorPosition() >= ld.start && selection.getCursorPosition() < ld.end || (li == list.size() - 1 && selection.getCursorPosition() == text.length())) { + if (li == i) { + lineNumColor = 0xFFb9c7d6; + break; + } + } + } + } + ClientProxy.Font.drawString(lineNum, lineNumX, lineNumY, lineNumColor); + } + + // Render Viewport + for (int i = renderStart; i <= renderEnd; i++) { + LineData data = list.get(i); + ScriptLine scriptLine = container.getDocument().getLineAt(i); + String line = data.text; + int w = line.length(); + // Use integer Y relative to scrolledLine; fractional offset applied via GL translate + int posY = y + (i - scroll.getScrolledLine()) * container.lineHeight; + if (i >= renderStart && i <= renderEnd) { + //Highlight braces the cursor position is on + if (startBracket != endBracket) { + if (startBracket >= data.start && startBracket < data.end) { + int s = ClientProxy.Font.width(line.substring(0, startBracket - data.start)); + int e = ClientProxy.Font.width(line.substring(0, startBracket - data.start + 1)) + 1; + drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight + 0, 0x9900cc00); + } + if (endBracket >= data.start && endBracket < data.end) { + int s = ClientProxy.Font.width(line.substring(0, endBracket - data.start)); + int e = ClientProxy.Font.width(line.substring(0, endBracket - data.start + 1)) + 1; + drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight + 0, 0x9900cc00); + } + } + + // Highlight unmatched braces in this line (always red) + if (unmatchedBraces != null && !unmatchedBraces.isEmpty()) { + for (int ubPos : unmatchedBraces) { + if (ubPos >= data.start && ubPos < data.end) { + int rel = ubPos - data.start; + int s = ClientProxy.Font.width(line.substring(0, rel)); + int e = ClientProxy.Font.width(line.substring(0, rel + 1)) + 1; + drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0xffcc0000); + } + } + } + //Highlight words + if (highlightedWord != null) { + Matcher m = container.regexWord.matcher(line); + while (m.find()) { + if (line.substring(m.start(), m.end()).equals(highlightedWord)) { + int s = ClientProxy.Font.width(line.substring(0, m.start())); + int e = ClientProxy.Font.width(line.substring(0, m.end())) + 1; + drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0x99004c00); + } + } + } + + // Highlight search matches + if (searchBar.isVisible()) { + List searchMatches = searchBar.getMatches(); + int currentMatchIdx = searchBar.getCurrentMatchIndex(); + for (int mi = 0; mi < searchMatches.size(); mi++) { + int[] match = searchMatches.get(mi); + // Check if match overlaps with this line + if (match[1] > data.start && match[0] < data.end) { + int matchStart = Math.max(match[0] - data.start, 0); + int matchEnd = Math.min(match[1] - data.start, line.length()); + if (matchStart < matchEnd) { + int s = ClientProxy.Font.width(line.substring(0, matchStart)); + int e = ClientProxy.Font.width(line.substring(0, matchEnd)) + 1; + boolean isExcluded = searchBar.isMatchExcluded(mi); + // Current match gets brighter highlight, others get dimmer + int highlightColor = (mi == currentMatchIdx) ? 0xBB4488ff : 0x662266aa; + if (isExcluded) { + highlightColor = 0x33666666; // Dimmer for excluded matches + } + int highlightX = x + LINE_NUMBER_GUTTER_WIDTH + 1 + s; + int highlightEndX = x + LINE_NUMBER_GUTTER_WIDTH + 1 + e; + drawRect(highlightX, posY, highlightEndX, posY + container.lineHeight, highlightColor); + + // Draw strikethrough line for excluded matches + if (isExcluded) { + int strikeY = posY + container.lineHeight / 2; + drawRect(highlightX, strikeY, highlightEndX, strikeY + 1, 0xFFaa4444); + } + } + } + } + } + + // Highlight rename refactor occurrences + if (renameHandler.isActive()) { + List renameOccurrences = renameHandler.getOccurrences(); + for (int[] occ : renameOccurrences) { + // Check if occurrence overlaps with this line + if (occ[1] >= data.start && occ[0] <= data.end) { + int occStart = Math.max(occ[0] - data.start, 0); + int occEnd = Math.min(occ[1] - data.start, line.length()); + + // Handle empty word case - draw 1 pixel wide box + boolean isEmpty = (occ[0] == occ[1]); + + if (occStart <= occEnd) { // Changed from < to <= to handle empty case + int s = ClientProxy.Font.width(line.substring(0, occStart)); + int e = isEmpty ? s + 2 : ClientProxy.Font.width( + line.substring(0, occEnd)) + 1; // 2px wide for empty + int occX = x + LINE_NUMBER_GUTTER_WIDTH + s; + int occEndX = x + LINE_NUMBER_GUTTER_WIDTH + 2 + e; + boolean isPrimary = renameHandler.isPrimaryOccurrence(occ[0]); + + // Draw background highlight + int bgColor = isPrimary ? 0x55335577 : 0x33224466; + drawRect(occX, posY, occEndX, posY + container.lineHeight, bgColor); + + // Draw white border for primary occurrence (IntelliJ-like) + if (isPrimary) { + int borderColor = 0xDDFFFFFF; + //RED BG + drawRect(occX, posY, occEndX, posY + container.lineHeight, 0x33ff0000); + + // Top border + drawRect(occX, posY, occEndX, posY + 1, borderColor); + // Bottom border + drawRect(occX, posY + container.lineHeight - 1, occEndX, + posY + container.lineHeight, borderColor); + // Left border + drawRect(occX, posY, occX + 1, posY + container.lineHeight, borderColor); + // Right border + drawRect(occEndX - 1, posY, occEndX, posY + container.lineHeight, borderColor); + + // Draw cursor inside the primary occurrence + if (renameHandler.shouldShowCursor()) { + int cursorInWord = renameHandler.getCursorInWord(); + String currentWord = renameHandler.getCurrentWord(); + if (currentWord != null && cursorInWord >= 0 && cursorInWord <= currentWord.length()) { + String beforeCursor = currentWord.substring(0, + Math.min(cursorInWord, currentWord.length())); + int cursorX = occX + ClientProxy.Font.width(beforeCursor); + // drawRect(cursorX, posY + 1, cursorX + 1, posY + container.lineHeight - 1, + // 0xFFFFFFFF); + } + } + } + } + } + } + } + + // Highlight the current line (light gray) under any selection + if (active && isEnabled() && (selection.getCursorPosition() >= data.start && selection.getCursorPosition() < data.end || (i == list.size() - 1 && selection.getCursorPosition() == text.length()))) { + drawRect(x , posY, x + width - 1, posY + container.lineHeight, 0x22e0e0e0); + } + // Highlight selection + if (selection.hasSelection() && selection.getEndSelection() > data.start && selection.getStartSelection() <= data.end) { + if (selection.getStartSelection() < data.end) { + int s = ClientProxy.Font.width( + line.substring(0, Math.max(selection.getStartSelection() - data.start, 0))); + int e = ClientProxy.Font.width( + line.substring(0, Math.min(selection.getEndSelection() - data.start, w))) + 1; + drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0x992172ff); + } + } + + // Draw indent guides once per visible block based on brace spans + if (i == Math.max(0, scroll.getScrolledLine()) && !braceSpans.isEmpty()) { + int visStart = Math.max(0, scroll.getScrolledLine()); + int visEnd = Math.min(list.size() - 1, visStart + container.visibleLines - 0); + for (int[] span : braceSpans) { + int originalDepth = span[0]; + int openLine = span[1]; + int closeLine = span[2]; + int depth = span.length > 3 ? span[3] : originalDepth; + // Skip top-level (depth 1) using the original depth to avoid hiding nested guides when adjusted + if (originalDepth <= 1) + continue; + int startLine = openLine + 1; // start under the opening brace + int endLine = closeLine - 1; // stop before the closing brace + if (startLine > endLine) + continue; + if (endLine < visStart || startLine > visEnd) + continue; + + int drawStart = Math.max(startLine, visStart); + int drawEnd = Math.min(endLine, visEnd); + // Compute horizontal position: 4 spaces per indent level, minus a tiny left offset + int safeDepth = Math.max(1, depth); + int spaces = (safeDepth - 1) * 4; + StringBuilder sb = new StringBuilder(); + for (int k = 0; k < spaces; k++) + sb.append(' '); + int px = ClientProxy.Font.width(sb.toString()); + int gx = x + LINE_NUMBER_GUTTER_WIDTH + 4 + px - 2; // shift left ~2px for the IntelliJ feel + + boolean highlighted = (openLine == highlightedOpenLine && closeLine == highlightedCloseLine); + int guideColor = highlighted ? 0x9933cc00 : 0x33FFFFFF; + + int topY = y + (drawStart - scroll.getScrolledLine()) * container.lineHeight; + int bottomY = y + (endLine - scroll.getScrolledLine() + 1) * container.lineHeight; + if(highlighted) + bottomY-=2; + drawRect(gx, topY, gx + 1, bottomY, guideColor); + } + } + int yPos = posY + stringYOffset; + + // data.drawString(x + LINE_NUMBER_GUTTER_WIDTH + 1, yPos, 0xFFe0e0e0); + scriptLine.drawString(x+LINE_NUMBER_GUTTER_WIDTH + 1, yPos, 0xFFe0e0e0); + + // Draw cursor: pause blinking while user is active recently + boolean recentInput = selection.hadRecentInput(); + if (active && isEnabled() && (recentInput || (cursorCounter / 10) % 2 == 0) && (selection.getCursorPosition() >= data.start && selection.getCursorPosition() < data.end || (i == list.size() - 1 && selection.getCursorPosition() == text.length()))) { + int posX = x + LINE_NUMBER_GUTTER_WIDTH + ClientProxy.Font.width( + line.substring(0, Math.min(selection.getCursorPosition() - data.start, line.length()))); + drawRect(posX + 1, posY, posX + 2, posY + container.lineHeight, 0xffffffff); + } + } + } + GL11.glPopMatrix(); + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + + if (hasVerticalScrollbar()) { + Minecraft.getMinecraft().renderEngine.bindTexture(GuiCustomScroll.resource); + int effLines = Math.max(1, getPaddedLineCount()); + int sbSize = Math.max((int) (1f * (container.visibleLines) / effLines * height), 2); + + int posX = x + width - 6; + double linesCount = (double) effLines; + int posY = (int) (y + 1f * scroll.getScrollPos() / linesCount * (height - 4)) + 1; + + drawRect(posX, posY, posX + 5, posY + sbSize + 2, 0xFFe0e0e0); + } + + // Draw search/replace bar (overlays viewport) + searchBar.draw(xMouse, yMouse); + + // Draw go to line dialog (overlays everything) + goToLineDialog.draw(xMouse, yMouse); + KEYS_OVERLAY.draw(xMouse, yMouse, wheelDelta); + } + + private void scissorViewport() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + int scissorX = (this.x) * scaleFactor; + int scissorY = (sr.getScaledHeight() - (this.y + this.height)) * scaleFactor; + int scissorW = (this.width) * scaleFactor; + int scissorH = this.height * scaleFactor; + GL11.glScissor(scissorX, scissorY, scissorW, scissorH); + } + // ==================== SELECTION & CURSOR POSITION ==================== + + // Get cursor position from mouse coordinates + private int getSelectionPos(int xMouse, int yMouse) { + xMouse -= (this.x + LINE_NUMBER_GUTTER_WIDTH + 1); + yMouse -= this.y + 1; + // Adjust yMouse to account for fractional GL translation (negative offset applied in rendering). + // Use a double here (no integer rounding) so clicks that land on partially + // visible lines (fractional positions) correctly hit that line. + double fracPixels = scroll.getFractionalOffset() * container.lineHeight; + double yMouseD = yMouse + fracPixels; + + ArrayList list = new ArrayList(this.container.lines); + + for (int i = 0; i < list.size(); ++i) { + LineData data = (LineData) list.get(i); + //+1 to account for the fractional line + if (i >= scroll.getScrolledLine() && i <= scroll.getScrolledLine() + this.container.visibleLines +1) { + double yPos = (i - scroll.getScrolledLine()) * this.container.lineHeight; + if (yMouseD >= yPos && yMouseD < yPos + this.container.lineHeight) { + int lineWidth = 0; + char[] chars = data.text.toCharArray(); + + for (int j = 1; j <= chars.length; ++j) { + int w = ClientProxy.Font.width(data.text.substring(0, j)); + if (xMouse < lineWidth + (w - lineWidth) / 2) { + return data.start + j - 1; + } + + lineWidth = w; + } + + // Place cursor after the last visible character of the line. + // `data.end - 1` previously pointed at the newline for non-last lines + // which made clicks land on the newline rather than after the text. + // Use data.start + chars.length to return the position directly + // after the line's characters, clamped to the total text length. + int posAfterChars = data.start + chars.length; + return Math.min(posAfterChars, text.length()); + } + } + } + + return this.container.text.length(); + } + + // Find which line the cursor is on (0-indexed) + private int getCursorLineIndex() { + return selection.getCursorLineIndex(container.lines, text != null ? text.length() : 0); + } + + + // Scroll viewport to keep cursor visible (minimal adjustment, like IntelliJ) + // Only scrolls if cursor is outside the visible area + private void scrollToCursor() { + if (container == null || container.lines == null || container.lines.isEmpty()) return; + + int lineIdx = getCursorLineIndex(); + int visible = Math.max(1, container.visibleLines); + int effectiveVisible = Math.max(1, visible - bottomPaddingLines); + int maxScroll = Math.max(0, getPaddedLineCount() - visible); + + scroll.scrollToLine(lineIdx, effectiveVisible, maxScroll); + } + + // ==================== KEY BINDINGS INITIALIZATION ==================== + + /** + * Initialize key bindings for editor shortcuts using ScriptEditorKeys. + * Centralized active/enabled checking ensures shortcuts only fire when appropriate. + */ + private void initializeKeyBindings() { + // Helper: execute action only if text area is active and enabled + Supplier isActive = () -> active && isEnabled() && !KEYS_OVERLAY.isVisible(); + Supplier openBoxes = () -> !KEYS_OVERLAY.isVisible(); + + // CUT: Copy selection to clipboard and delete it. If no selection, cut the current sentence. + KEYS.CUT.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + if (selection.hasSelection()) { + NoppesStringUtils.setClipboardContents(selection.getSelectedText(text)); + String s = getSelectionBeforeText(); + setText(s + getSelectionAfterText()); + selection.reset(s.length()); + scrollToCursor(); + return; + } + + // No selection: cut the current sentence (heuristic based on .!? or newline) + if (text == null || text.isEmpty()) + return; + int cursor = selection.getCursorPosition(); + int start = cursor; + int pos = cursor - 1; + while (pos >= 0) { + char ch = text.charAt(pos); + if (ch == '.' || ch == '!' || ch == '?' || ch == '\n') { + start = pos + 1; + break; + } + pos--; + } + while (start < cursor && Character.isWhitespace(text.charAt(start))) start++; + + int end = cursor; + pos = cursor; + while (pos < text.length()) { + char ch = text.charAt(pos); + if (ch == '.' || ch == '!' || ch == '?' || ch == '\n') { + end = pos + 1; + break; + } + pos++; + } + if (end == cursor) end = text.length(); + while (end > start && Character.isWhitespace(text.charAt(end - 1))) end--; + + if (start >= end) { + // fallback: cut whole current line + int ls = text.lastIndexOf('\n', Math.max(0, cursor - 1)); + start = ls == -1 ? 0 : ls + 1; + int le = text.indexOf('\n', cursor); + end = le == -1 ? text.length() : le; + } + + if (start < end) { + String cut = text.substring(start, end); + NoppesStringUtils.setClipboardContents(cut); + setText(text.substring(0, start) + text.substring(end)); + selection.reset(start); + scrollToCursor(); + } + }); + + // COPY: Copy selection to clipboard + KEYS.COPY.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + if (selection.hasSelection()) + NoppesStringUtils.setClipboardContents(selection.getSelectedText(text)); + }); + + // PASTE: Insert clipboard contents at caret + KEYS.PASTE.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + addText(NoppesStringUtils.getClipboardContents()); + scrollToCursor(); + }); + + // UNDO: Restore last edit from undo list + // Works in search bar. + KEYS.UNDO.setTask(e -> { + if ((!e.isPress() && !e.isHold()) || !openBoxes.get()) + return; + + if (searchBar.hasFocus()) { + searchBar.undo(); + } else { + if (undoList.isEmpty()) + return; + undoing = true; + redoList.add(new UndoData(this.text, selection.getCursorPosition())); + UndoData data = undoList.remove(undoList.size() - 1); + setText(data.text); + selection.reset(data.cursorPosition); + undoing = false; + scrollToCursor(); + searchBar.updateMatches(); + if (!active) + active = true; + } + }); + + // REDO: Restore last undone edit from redo list + // Works in search bar. + KEYS.REDO.setTask(e -> { + if ((!e.isPress() && !e.isHold()) || !openBoxes.get()) + return; + + if (searchBar.hasFocus()) { + searchBar.redo(); + } else { + if (redoList.isEmpty()) + return; + undoing = true; + undoList.add(new UndoData(this.text, selection.getCursorPosition())); + UndoData data = redoList.remove(redoList.size() - 1); + setText(data.text); + selection.reset(data.cursorPosition); + undoing = false; + scrollToCursor(); + searchBar.updateMatches(); + if (!active) + active = true; + } + }); + + // FORMAT: Format/indent code + KEYS.FORMAT.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + formatText(); + }); + + // TOGGLE_COMMENT: Toggle comment for selection or current line + KEYS.TOGGLE_COMMENT.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + if (selection.hasSelection()) + toggleCommentSelection(); + else + toggleCommentLineAtCursor(); + }); + + // DUPLICATE: Duplicate selection or current line + KEYS.DUPLICATE.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + if (selection.hasSelection()) { + // Multi-line selection duplication + LineData firstLine = null, lastLine = null; + for (LineData line : container.lines) { + if (line.end > selection.getStartSelection() && line.start < selection.getEndSelection()) { + if (firstLine == null) + firstLine = line; + lastLine = line; + } + } + if (firstLine != null && lastLine != null) { + String selectedText = text.substring(firstLine.start, lastLine.end); + int savedStart = selection.getStartSelection(); + int savedEnd = selection.getEndSelection(); + int insertAt = lastLine.end; + setText(text.substring(0, insertAt) + selectedText + text.substring(insertAt)); + selection.setStartSelection(savedStart); + selection.setEndSelection(savedEnd); + selection.setCursorPositionDirect(savedEnd); + } + } else { + // Duplicate current line + for (LineData line : container.lines) { + if (selection.getCursorPosition() >= line.start && selection.getCursorPosition() <= line.end) { + int safeStart = Math.max(0, Math.min(line.start, text.length())); + int safeEnd = Math.max(safeStart, Math.min(line.end, text.length())); + String lineText = text.substring(safeStart, safeEnd); + String insertText = lineText.endsWith("\n") ? lineText : "\n" + lineText; + int insertionPoint = Math.min(line.end, text.length()); + setText(text.substring(0, insertionPoint) + insertText + text.substring(insertionPoint)); + int newCursor = insertionPoint + insertText.length() - (insertText.endsWith("\n") ? 1 : 0); + selection.reset(Math.max(0, Math.min(newCursor, this.text.length()))); + break; + } + } + } + }); + + + // Check if can open just for SearchReplaceBar and GoToLine + + // SEARCH: Open search bar (Ctrl+R) + // Works in search bar. + KEYS.SEARCH.setTask(e -> { + if (!e.isPress() || !openBoxes.get()) + return; + + unfocusAll(); + searchBar.openSearch(); + }); + + // SEARCH_REPLACE: Open search+replace bar (Ctrl+Shift+R) + // Works in search bar. + KEYS.SEARCH_REPLACE.setTask(e -> { + if (!e.isPress() || !openBoxes.get()) + return; + + unfocusAll(); + searchBar.openSearchReplace(); + }); + + // GO_TO_LINE: Open go to line dialog (Ctrl+G) + // Works in search bar. + KEYS.GO_TO_LINE.setTask(e -> { + if (!e.isPress() || !openBoxes.get()) + return; + + unfocusAll(); + goToLineDialog.toggle(); + }); + + // RENAME: Start rename refactoring (Shift+F6) + KEYS.RENAME.setTask(e -> { + if (!e.isPress() || !openBoxes.get()) + return; + + + if (!renameHandler.isActive()) { + unfocusAll(); + active = true; + renameHandler.startRename(); + } + }); + } + + public void unfocusAll() { + if (searchBar.hasFocus()) searchBar.unfocus(); + if (goToLineDialog.hasFocus()) goToLineDialog.unfocus(); + if (renameHandler.isActive()) + renameHandler.cancel(); + } + // ==================== KEYBOARD INPUT HANDLING ==================== + + /** + * Handles keyboard input for the text area, delegating to specialized handlers + * for different types of input: navigation, deletion, shortcuts, and character input. + */ + @Override + public boolean textboxKeyTyped(char c, int i) { + if (KEYS_OVERLAY.keyTyped(c, i)) + return true; + + // Handle rename refactor input first if active + if (renameHandler.isActive() && renameHandler.keyTyped(c, i)) + return true; + + // Handle Go To Line dialog input first if it has focus + if (goToLineDialog.isVisible() &&goToLineDialog.keyTyped(c, i)) + return true; + + // Handle search bar input first if it has focus + if (searchBar.isVisible() && searchBar.keyTyped(c, i)) + return true; + + if (!active) + return false; + + if (this.isKeyComboCtrlA(i)) { + selection.selectAll(text.length()); + return true; + } + + if (!isEnabled()) return false; + + if (handleNavigationKeys(i)) return true; + if (handleInsertionKeys(i)) return true; + if (handleDeletionKeys(i)) return true; + if (handleCharacterInput(c)) return true; + + return true; + } + + /** + * Handles cursor navigation keys (arrows) with support for word-jumping (Ctrl) + * and selection (Shift). Updates cursor position and scrolls viewport if needed. + */ + private boolean handleNavigationKeys(int i) { + // LEFT ARROW: move cursor left; with Ctrl -> jump by word + if (i == Keyboard.KEY_LEFT) { + int j = 1; // default: move one character + if (isCtrlKeyDown()) { + // When Ctrl is down, compute distance to previous word boundary. + // We match words in the text slice before the cursor and pick + // the last match start as the new boundary. + Matcher m = container.regexWord.matcher(text.substring(0, selection.getCursorPosition())); + while (m.find()) { + if (m.start() == m.end()) + continue; // skip empty matches + // j becomes the number of chars to move left to reach word start + j = selection.getCursorPosition() - m.start(); + } + } + int newPos = Math.max(selection.getCursorPosition() - j, 0); + // If Shift is held, extend selection; otherwise place caret. + setCursor(newPos, GuiScreen.isShiftKeyDown()); + return true; + } + + // RIGHT ARROW: move cursor right; with Ctrl -> jump to next word start + if (i == Keyboard.KEY_RIGHT) { + int j = 1; // default: move one character + if (isCtrlKeyDown()) { + String after = text.substring(selection.getCursorPosition()); + Matcher m = container.regexWord.matcher(after); + if (m.find()) { + if (m.start() == 0) { + // If the first match starts at 0 (cursor at word start), + // try to find the next match so we advance past the current word. + if (m.find()) + j = m.start(); + else + j = Math.max(1, after.length()); + } else { + j = m.start(); + } + } else { + // No word match found after cursor -> jump to end + j = Math.max(1, after.length()); + } + } + int newPos = Math.min(selection.getCursorPosition() + j, text.length()); + setCursor(newPos, GuiScreen.isShiftKeyDown()); + return true; + } + + // UP/DOWN: logical cursor movement across lines while preserving + // column where possible. After moving, ensure the caret remains visible + // by adjusting the scroll if necessary. + if (i == Keyboard.KEY_UP) { + setCursor(cursorUp(), GuiScreen.isShiftKeyDown()); + scrollToCursor(); + return true; + } + if (i == Keyboard.KEY_DOWN) { + setCursor(cursorDown(), GuiScreen.isShiftKeyDown()); + scrollToCursor(); + return true; + } + + return false; // not a navigation key + } + + /** + * Handles insertion-related keys such as Tab indentation and Enter behavior. + */ + private boolean handleInsertionKeys(int i) { + // TAB: indent or unindent depending on Shift + if (i == Keyboard.KEY_TAB) { + boolean shift = isShiftKeyDown(); + if (shift) { + handleShiftTab(); + } else { + handleTab(); + } + scrollToCursor(); + return true; + } + + // RETURN/ENTER: special handling when preceding char is an opening brace '{' + if (i == Keyboard.KEY_RETURN) { + int cursorPos = selection.getCursorPosition(); + int prevNonWs = cursorPos - 1; + while (prevNonWs >= 0 && prevNonWs < (text != null ? text.length() : 0) && Character.isWhitespace( + text.charAt(prevNonWs))) { + prevNonWs--; + } + + if (prevNonWs >= 0 && cursorPos <= (text != null ? text.length() : 0) && text.charAt(prevNonWs) == '{') { + String indent = ""; + for (LineData ld : this.container.lines) { + if (prevNonWs >= ld.start && prevNonWs < ld.end) { + indent = ld.text.substring(0, IndentHelper.getLineIndent(ld.text)); + break; + } + } + if (indent == null) + indent = ""; + String childIndent = indent + " "; + String before = getSelectionBeforeText(); + String after = getSelectionAfterText(); + + int firstNewline = after.indexOf('\n'); + String leadingSegment = firstNewline == -1 ? after : after.substring(0, firstNewline); + if (leadingSegment.trim().length() > 0) { + addText("\n" + childIndent); + scrollToCursor(); + return true; + } + + boolean hasMatchingCloseSameIndent = false; + try { + int openLineIdx = -1; + int bracePos = prevNonWs; + for (int li = 0; li < this.container.lines.size(); li++) { + LineData ld = this.container.lines.get(li); + if (bracePos >= ld.start && bracePos < ld.end) { + openLineIdx = li; + break; + } + } + + if (openLineIdx >= 0) { + List spans = BracketMatcher.computeBraceSpans(text, this.container.lines); + for (int[] span : spans) { + int spanOpen = span[1]; + int spanClose = span[2]; + if (spanOpen == openLineIdx) { + int closeIndent = IndentHelper.getLineIndent(this.container.lines.get(spanClose).text); + if (closeIndent == indent.length()) { + hasMatchingCloseSameIndent = true; + } + break; + } + } + } + } catch (Exception ex) { + hasMatchingCloseSameIndent = false; + } + + if (hasMatchingCloseSameIndent) { + addText("\n" + childIndent); + scrollToCursor(); + } else { + String insert = "\n" + childIndent + "\n" + indent + "}"; + setText(before + insert + after); + int newCursor = before.length() + 1 + childIndent.length(); + selection.reset(newCursor); + scrollToCursor(); + } + } else { + addText(Character.toString('\n') + getAutoIndentForEnter()); + scrollToCursor(); + } + return true; + } + + return false; + } + + /** + * Handles deletion keys: Delete, Backspace, and Ctrl+Backspace. + * Includes smart backspace behavior for indentation-aware line merging, + * auto-pair deletion for brackets/quotes, and word-level deletion. + */ + private boolean handleDeletionKeys(int i) { + // DELETE key: remove the character under the cursor if no selection, + // otherwise remove the selected region's tail. + if (i == Keyboard.KEY_DELETE) { + String s = getSelectionAfterText(); + if (!s.isEmpty() && !selection.hasSelection()) + // remove single character after caret when nothing is selected + s = s.substring(1); + setText(getSelectionBeforeText() + s); + // Keep caret at same start selection + selection.reset(selection.getStartSelection()); + return true; + } + + // CTRL+BACKSPACE: delete to previous word or whitespace boundary. + if (isKeyComboCtrlBackspace(i)) { + String s = getSelectionBeforeText(); + if (selection.getStartSelection() > 0 && !selection.hasSelection()) { + int nearestCondition = selection.getCursorPosition(); + int g; + // If the char left of caret is whitespace, find the first non-space to the left; + // otherwise find first whitespace/newline to the left (word boundary). + boolean cursorInWhitespace = Character.isWhitespace(s.charAt(selection.getCursorPosition() - 1)); + if (cursorInWhitespace) { + // Scan left until non-whitespace (start of previous word) + for (g = selection.getCursorPosition() - 1; g >= 0; g--) { + char currentChar = s.charAt(g); + if (!Character.isWhitespace(currentChar)) { + nearestCondition = g; + break; + } + if (g == 0) { + nearestCondition = 0; + } + } + } else { + // Scan left until whitespace/newline is found (word boundary) + for (g = selection.getCursorPosition() - 1; g >= 0; g--) { + char currentChar = s.charAt(g); + if (Character.isWhitespace(currentChar) || currentChar == '\n') { + nearestCondition = g; + break; + } + if (g == 0) { + nearestCondition = 0; + } + } + } + + // Trim the prefix up to the discovered boundary + s = s.substring(0, nearestCondition); + // Adjust selection start to match removed characters + selection.setStartSelection( + selection.getStartSelection() - (selection.getCursorPosition() - nearestCondition)); + } + setText(s + getSelectionAfterText()); + selection.reset(selection.getStartSelection()); + return true; + } + + // BACKSPACE: complex handling with a few cases: + // 1) If a selection exists, delete it + // 2) If at start, nothing to do + // 3) Smart indent-aware merge with previous line when caret is at/near expected indent + // 4) Auto-pair deletion (remove both opening and closing chars when deleting an opener) + // 5) Fallback: delete a single char to the left + if (i == Keyboard.KEY_BACK) { + // 1) selection deletion + if (selection.hasSelection()) { + String s = getSelectionBeforeText(); + setText(s + getSelectionAfterText()); + selection.reset(selection.getStartSelection()); + scrollToCursor(); + return true; + } + + // 2) nothing to delete + if (selection.getStartSelection() <= 0) { + return true; + } + + // If the current line is whitespace-only, delete the whole line + // (including the trailing newline if present). This makes Backspace + // intuitive on blank/indented lines outside any recognized scope. + LineData currCheck = selection.findCurrentLine(container.lines); + if (currCheck != null && currCheck.text.trim().length() == 0) { + int removeEnd = text.indexOf('\n', currCheck.start - 1); + if (removeEnd == -1) { + removeEnd = text.length(); + } else { + removeEnd = removeEnd + 1; // include the newline + } + String before = text.substring(0, ValueUtil.clamp(currCheck.start - 1, 0, text.length())); + String after = removeEnd <= text.length() ? text.substring(removeEnd) : ""; + setText(before + after); + int newCursor = Math.max(0, currCheck.start - 1); + selection.reset(newCursor); + scrollToCursor(); + return true; + } + + // 3) indent-aware merge: find current line and compute expected indent + LineData curr = selection.findCurrentLine(container.lines); + if (curr != null && curr.start > 0) { + int col = selection.getCursorPosition() - curr.start; + int actualIndent = IndentHelper.getLineIndent(curr.text); + int expectedIndent = IndentHelper.getExpectedIndent(curr, container.lines); + + // Trigger smart merge only when caret is at or before the expected indent. + if (col <= expectedIndent) { + boolean lineHasContent = curr.text.trim().length() > 0; + int newlinePos = curr.start - 1; // index of newline before this line + + if (!lineHasContent) { + // Empty or whitespace-only line: remove it including its trailing newline + int removeEnd = text.indexOf('\n', curr.start); + if (removeEnd == -1) { + removeEnd = text.length(); + } else { + removeEnd = removeEnd + 1; // include the newline in removal + } + String before = text.substring(0, curr.start); + String after = removeEnd <= text.length() ? text.substring(removeEnd) : ""; + setText(before + after); + // Place caret at end of previous line + int newCursor = Math.max(0, curr.start - 1); + selection.reset(newCursor); + scrollToCursor(); + return true; + } else { + // Merge current line content with the previous line preserving spacing + int contentStart = curr.start + actualIndent; + String before = newlinePos >= 0 ? text.substring(0, newlinePos) : ""; + String content = contentStart <= text.length() ? text.substring(contentStart) : ""; + + // Decide whether a space is needed between concatenated fragments. + String spacer = ""; + if (before.length() > 0 && content.length() > 0) { + char lastChar = before.charAt(before.length() - 1); + char firstChar = content.charAt(0); + // Avoid adding space when punctuation/brackets are adjacent + if (!Character.isWhitespace(lastChar) && + lastChar != '{' && lastChar != '(' && lastChar != '[' && + firstChar != '}' && firstChar != ')' && firstChar != ']' && + firstChar != ';' && firstChar != ',' && firstChar != '.' && + firstChar != '\n') { + spacer = " "; + } + } + + setText(before + spacer + content); + int newCursor = before.length() + spacer.length(); + selection.reset(newCursor); + scrollToCursor(); + return true; + } + } + } + + // 4) Auto-pair deletion: when deleting an opener and a matching closer follows, + // remove both so the pair is cleaned up in one backspace. + if (selection.getStartSelection() > 0 && selection.getStartSelection() < text.length()) { + char prev = text.charAt(selection.getStartSelection() - 1); + char nextc = text.charAt(selection.getStartSelection()); + if ((prev == '(' && nextc == ')') || + (prev == '[' && nextc == ']') || + (prev == '{' && nextc == '}') || + (prev == '\'' && nextc == '\'') || + (prev == '"' && nextc == '"')) { + String before = text.substring(0, selection.getStartSelection() - 1); + String after = selection.getStartSelection() + 1 < text.length() ? text.substring( + selection.getStartSelection() + 1) : ""; + setText(before + after); + selection.setStartSelection(selection.getStartSelection() - 1); + selection.reset(selection.getStartSelection()); + scrollToCursor(); + return true; + } + } + + // 5) Normal single-character backspace + String s = getSelectionBeforeText(); + s = s.substring(0, s.length() - 1); + selection.setStartSelection(selection.getStartSelection() - 1); + setText(s + getSelectionAfterText()); + selection.reset(selection.getStartSelection()); + scrollToCursor(); + return true; + } + + return false; + } + + /** + * Handles keyboard shortcuts: clipboard operations (cut/copy/paste), + * undo/redo, tab indentation, code formatting, enter with brace handling, + * comment toggling, and line duplication. + */ + private boolean handleShortcutKeys(int i) { + // CTRL+X: Cut + if (this.isKeyComboCtrlX(i)) { + if (selection.hasSelection()) { + // Copy selected text into clipboard, then remove the selection + NoppesStringUtils.setClipboardContents(selection.getSelectedText(text)); + String s = getSelectionBeforeText(); + setText(s + getSelectionAfterText()); + selection.reset(s.length()); + scrollToCursor(); + } + return true; + } + + // CTRL+C: Copy + if (this.isKeyComboCtrlC(i)) { + if (selection.hasSelection()) { + NoppesStringUtils.setClipboardContents(selection.getSelectedText(text)); + } + return true; + } + + // CTRL+V: Paste (insert clipboard contents at caret) + if (this.isKeyComboCtrlV(i)) { + addText(NoppesStringUtils.getClipboardContents()); + scrollToCursor(); + return true; + } + + // UNDO (Ctrl+Z): restore last entry from undoList and push current state to redoList + if (i == Keyboard.KEY_Z && isCtrlKeyDown()) { + if (undoList.isEmpty()) + return false; // nothing to undo + undoing = true; + redoList.add(new UndoData(this.text, selection.getCursorPosition())); + UndoData data = undoList.remove(undoList.size() - 1); + setText(data.text); + selection.reset(data.cursorPosition); + undoing = false; + scrollToCursor(); + return true; + } + + // REDO (Ctrl+Y): opposite of undo + if (i == Keyboard.KEY_Y && isCtrlKeyDown()) { + if (redoList.isEmpty()) + return false; + undoing = true; + undoList.add(new UndoData(this.text, selection.getCursorPosition())); + UndoData data = redoList.remove(redoList.size() - 1); + setText(data.text); + selection.reset(data.cursorPosition); + undoing = false; + scrollToCursor(); + return true; + } + + // CTRL+F: format the text according to IndentHelper rules + if (i == Keyboard.KEY_F && isCtrlKeyDown()) { + formatText(); + return true; + } + + // CTRL+/ : toggle comment for selection or current line + if (i == Keyboard.KEY_SLASH && isCtrlKeyDown()) { + if (selection.hasSelection()) { + toggleCommentSelection(); + } else { + toggleCommentLineAtCursor(); + } + return true; + } + + // CTRL+D : duplicate selection or current line + if (i == Keyboard.KEY_D && isCtrlKeyDown()) { + if (selection.hasSelection()) { + // Multi-line selection duplication: find first and last covered lines, + // then insert the whole block after the last line without adding extra newline. + LineData firstLine = null, lastLine = null; + for (LineData line : container.lines) { + if (line.end > selection.getStartSelection() && line.start < selection.getEndSelection()) { + if (firstLine == null) firstLine = line; + lastLine = line; + } + } + if (firstLine != null && lastLine != null) { + String selectedText = text.substring(firstLine.start, lastLine.end); + String insertText = selectedText; + int savedStart = selection.getStartSelection(); + int savedEnd = selection.getEndSelection(); + int insertAt = lastLine.end; + setText(text.substring(0, insertAt) + insertText + text.substring(insertAt)); + // Restore prior selection / cursor positions + selection.setStartSelection(savedStart); + selection.setEndSelection(savedEnd); + selection.setCursorPositionDirect(savedEnd); + return true; + } + } else { + // Duplicate current line when nothing is selected + for (LineData line : container.lines) { + if (selection.getCursorPosition() >= line.start && selection.getCursorPosition() <= line.end) { + int lineStart = line.start, lineEnd = line.end; + String lineText = text.substring(lineStart, lineEnd); + // If the line already ends with a newline, reuse it; otherwise + // prefix a newline so duplicate appears after current line. + String insertText; + if (lineText.endsWith("\n")) { + insertText = lineText; + } else { + insertText = "\n" + lineText; + } + int insertionPoint = lineEnd; + setText(text.substring(0, insertionPoint) + insertText + text.substring(insertionPoint)); + int newCursor = insertionPoint + insertText.length() - (insertText.endsWith("\n") ? 1 : 0); + selection.reset(Math.max(0, Math.min(newCursor, this.text.length()))); + return true; + } + } + } + return true; + } + + return false; + } + + /** + * Handles printable character input with auto-pairing for quotes and brackets, + * and smart skipping over existing closing characters. + */ + private boolean handleCharacterInput(char c) { + if (ChatAllowedCharacters.isAllowedCharacter(c)) { + String before = getSelectionBeforeText(); + String after = getSelectionAfterText(); + + // If the user types a closing character and that same closer is + // already immediately after the caret, move caret past it instead + // of inserting another closer. This prevents duplicate closers + // when the editor auto-inserts pairs. + if ((c == ')' || c == ']' || c == '"' || c == '\'' ) && after.length() > 0 && after.charAt(0) == c) { + // Move caret forward by one (skip over existing closer) + selection.reset(before.length() + 1); + scrollToCursor(); + return true; + } + + // Auto-pair insertion: when opening a quote/brace/bracket is typed, + // insert a matching closer and place caret between the pair. + if (c == '"') { + setText(before + "\"\"" + after); + selection.reset(before.length() + 1); + scrollToCursor(); + return true; + } + if (c == '\'') { + setText(before + "''" + after); + selection.reset(before.length() + 1); + scrollToCursor(); + return true; + } + if (c == '[') { + setText(before + "[]" + after); + selection.reset(before.length() + 1); + scrollToCursor(); + return true; + } + if (c == '(') { + setText(before + "()" + after); + selection.reset(before.length() + 1); + scrollToCursor(); + return true; + } + + // Default insertion for printable characters: insert at caret (replacing selection) + addText(Character.toString(c)); + scrollToCursor(); + return true; + } + return false; + } + + private boolean isShiftKeyDown() { + return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54); + } + + // ==================== COMMENT TOGGLING ==================== + // Uses CommentHandler helper for comment operations + + private void toggleCommentSelection() { + CommentHandler.SelectionToggleResult result = CommentHandler.toggleCommentSelection( + text, container.lines, selection.getStartSelection(), selection.getEndSelection()); + setText(result.newText); + selection.setStartSelection(result.newStartSelection); + selection.setEndSelection(result.newEndSelection); + } + + private void toggleCommentLineAtCursor() { + CommentHandler.SingleLineToggleResult result = CommentHandler.toggleCommentAtCursor( + text, container.lines, selection.getCursorPosition()); + setText(result.newText); + setCursor(result.newCursorPosition, false); + } + + public boolean closeOnEsc(){ + return !KEYS_OVERLAY.isVisible() && !searchBar.isVisible() && !goToLineDialog.isVisible() && !renameHandler.isActive(); + } + + // ==================== KEYBOARD MODIFIERS ==================== + + private boolean isAltKeyDown() { + return Keyboard.isKeyDown(56) || Keyboard.isKeyDown(184); + } + + private boolean isKeyComboCtrlX(int keyID) { + return keyID == 45 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + private boolean isKeyComboCtrlBackspace(int keyID) { + return keyID == Keyboard.KEY_BACK && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + private boolean isKeyComboCtrlV(int keyID) { + return keyID == 47 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + private boolean isKeyComboCtrlC(int keyID) { + return keyID == 46 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + private boolean isKeyComboCtrlA(int keyID) { + return keyID == 30 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + private String getIndentCurrentLine() { + for (LineData data : this.container.lines) { + if (selection.getCursorPosition() > data.start && selection.getCursorPosition() <= data.end) { + int i; + for (i = 0; i < data.text.length() && data.text.charAt(i) == ' '; ++i) { + } + return data.text.substring(0, i); + } + } + return ""; + } + + private String getAutoIndentForEnter() { + LineData currentLine = selection.findCurrentLine(container.lines); + + if (currentLine == null) { + return ""; + } + return IndentHelper.getAutoIndentForEnter(currentLine.text, selection.getCursorPosition() - currentLine.start); + } + // ==================== TEXT FORMATTING ==================== + + private int getTabSize() { + return IndentHelper.TAB_SIZE; + } + + private String repeatSpace(int count) { + return IndentHelper.spaces(count); + } + + private void formatText() { + // Calculate viewport width for line wrapping (account for gutter and scrollbar) + int viewportWidth = this.width - LINE_NUMBER_GUTTER_WIDTH - 10; + IndentHelper.FormatResult result = IndentHelper.formatText(text, selection.getCursorPosition(), viewportWidth); + setText(result.text); + selection.reset(Math.max(0, Math.min(result.cursorPosition, this.text.length()))); + } + + // ==================== TAB HANDLING ==================== + + private void handleTab() { + LineData currentLine = selection.findCurrentLine(container.lines); + if (currentLine == null) { + addText(" "); + return; + } + int tab = getTabSize(); + int indentLen = IndentHelper.getLineIndent(currentLine.text); + int textStartPos = currentLine.start + indentLen; + + if (selection.getCursorPosition() <= textStartPos) { + // Cursor before any text: if cursor is exactly at text start, move forward to next tab stop. + // If cursor is inside leading whitespace (before text start), choose nearest tab stop (tie -> forward). + int targetIndent; + if (selection.getCursorPosition() == textStartPos) { + targetIndent = ((indentLen / tab) + 1) * tab; + } else { + int remainder = indentLen % tab; + if (remainder == 0) { + targetIndent = indentLen + tab; // already aligned -> next level + } else { + int down = indentLen - remainder; + int up = indentLen + (tab - remainder); + int distDown = remainder; + int distUp = tab - remainder; + if (distUp < distDown) targetIndent = up; + else if (distUp > distDown) targetIndent = down; + else targetIndent = up; // tie -> forward + } + } + if (targetIndent < 0) targetIndent = 0; + String newIndent = repeatSpace(targetIndent); + String rest = currentLine.text.substring(indentLen); + String before = text.substring(0, currentLine.start); + int contentEnd = Math.min(currentLine.start + currentLine.text.length(), text.length()); + int sepEnd = Math.min(currentLine.end, text.length()); + String sep = contentEnd < sepEnd ? text.substring(contentEnd, sepEnd) : ""; + String after = text.substring(sepEnd); + setText(before + newIndent + rest + sep + after); + int newCursor = currentLine.start + targetIndent; + selection.reset(Math.min(newCursor, this.text.length())); + } else { + // Cursor is after start of text: insert spaces at cursor to move following text to next tab stop + int column = selection.getCursorPosition() - currentLine.start; + int targetColumn = ((column / tab) + 1) * tab; + int toInsert = Math.max(0, targetColumn - column); + if (toInsert > 0) { + String spaces = repeatSpace(toInsert); + addText(spaces); + } + } + } + + private void handleShiftTab() { + LineData currentLine = selection.findCurrentLine(container.lines); + if (currentLine == null) + return; + int tab = getTabSize(); + int indentLen = IndentHelper.getLineIndent(currentLine.text); + int textStartPos = currentLine.start + indentLen; + + if (selection.getCursorPosition() <= textStartPos) { + // Cursor before any text: reduce leading indent to previous tab stop + int targetIndent = Math.max(0, ((indentLen - 1) / tab) * tab); + String newIndent = repeatSpace(targetIndent); + String rest = currentLine.text.substring(indentLen); + String before = text.substring(0, currentLine.start); + int contentEnd = Math.min(currentLine.start + currentLine.text.length(), text.length()); + int sepEnd = Math.min(currentLine.end, text.length()); + String sep = contentEnd < sepEnd ? text.substring(contentEnd, sepEnd) : ""; + String after = text.substring(sepEnd); + setText(before + newIndent + rest + sep + after); + int newCursor = currentLine.start + targetIndent; + selection.reset(Math.min(newCursor, this.text.length())); + } else { + // Cursor after start of text: remove up to previous tab stop worth of spaces immediately before cursor + int column = selection.getCursorPosition() - currentLine.start; + int mod = column % tab; + int toRemove = mod == 0 ? tab : mod; + int removed = 0; + int pos = selection.getCursorPosition() - 1; + while (pos >= currentLine.start && removed < toRemove && text.charAt(pos) == ' ') { + pos--; + removed++; + } + if (removed > 0) { + int removeStart = pos + 1; + String before = text.substring(0, removeStart); + String after = text.substring(selection.getCursorPosition()); + setText(before + after); + int newCursor = removeStart; + selection.reset(Math.min(newCursor, this.text.length())); + } + } + } + + // ==================== CURSOR MANAGEMENT ==================== + + private void setCursor(int i, boolean select) { + selection.setCursor(i, text != null ? text.length() : 0, select); + } + + private void addText(String s) { + int insertPos = selection.getStartSelection(); + this.setText(this.getSelectionBeforeText() + s + this.getSelectionAfterText()); + selection.afterTextInsert(insertPos + s.length()); + } + + private int cursorUp() { + return CursorNavigation.cursorUp(selection.getCursorPosition(), container.lines, text); + } + + private int cursorDown() { + return CursorNavigation.cursorDown(selection.getCursorPosition(), container.lines, text); + } + + public String getSelectionBeforeText() { + return selection.getTextBefore(text); + } + + public String getSelectionAfterText() { + return selection.getTextAfter(text); + } + + // ==================== MOUSE HANDLING ==================== + + public void mouseClicked(int xMouse, int yMouse, int mouseButton) { + // Check go to line dialog clicks first + if (goToLineDialog.isVisible() && goToLineDialog.mouseClicked(xMouse, yMouse, mouseButton)) { + return; + } + + // Check search bar clicks first + if (searchBar.isVisible() && searchBar.mouseClicked(xMouse, yMouse, mouseButton)) { + return; + } + + // If search bar is visible but click was outside it, unfocus the search bar + if (searchBar.isVisible()) { + searchBar.unfocus(); + } + + // Let the overlay consume clicks (it returns true when it handled the event) + if (KEYS_OVERLAY.mouseClicked(xMouse, yMouse, mouseButton)) + return; + + // Determine whether click occurred inside the text area bounds + this.active = xMouse >= this.x && xMouse < this.x + this.width && yMouse >= this.y && yMouse < this.y + this.height; + if (this.active) { + // Compute logical click position in text + int clickPos = this.getSelectionPos(xMouse, yMouse); + + // Check if rename refactoring is active and click is in the rename box + if (renameHandler.isActive() && renameHandler.handleClick(clickPos)) { + // Click was handled by rename handler - don't reset selection or do other click handling + this.clicked = false; + activeTextfield = this; + return; + } + + // Normal click handling - reset selection/caret + selection.reset(clickPos); + selection.markActivity(); + + // Prepare click state (left button starts most interactions) + this.clicked = mouseButton == 0; + this.doubleClicked = false; + this.tripleClicked = false; + long time = System.currentTimeMillis(); + + // Prefer delegating scrollbar-start logic to ScrollState. If the click + // is on the scrollbar area and the scrollbar can be dragged, we start + // click-scrolling mode and cancel the normal text click-drag behavior. + if (this.clicked && getPaddedLineCount() * this.container.lineHeight > this.height && xMouse > this.x + this.width - 8) { + // We consumed the mouse-down as a scrollbar drag start + this.clicked = false; + scroll.startScrollbarDrag(yMouse,this.y,this.height, getPaddedLineCount()); + } else { + // Handle double/triple click selection counting + if (time - this.lastClicked < 300L) { + this.clickCount++; + } else { + this.clickCount = 1; + } + + if (this.clickCount == 2) { + // Double-click: select the word under the caret using the container's word regex + this.doubleClicked = true; + selection.selectWordAtCursor(this.text, this.container.regexWord); + // Prevent subsequent mouse-drag handling in the render loop from + // treating this double-click as a normal click-drag which would + // immediately reset and extend the selection. Clearing `clicked` + // keeps the double-click selection stable. + this.clicked = false; + } else if (this.clickCount >= 3) { + // Triple-click: select the entire logical line that contains the caret + this.tripleClicked = true; + selection.selectLineAtCursor(container.lines); + // Same as double-click: clear `clicked` to avoid accidental drag-extension + this.clicked = false; + this.clickCount = 0; + } + } + + this.lastClicked = time; + activeTextfield = this; + } + } + + // Called from GuiScreen.updateScreen() + public void updateCursorCounter() { + // Only process KeyPresets if search bar and go-to-line dialog don't have focus + // This prevents COPY, PASTE, UNDO, etc. from firing when typing in dialogs + KEYS.tick(); + + searchBar.updateCursor(); + goToLineDialog.updateCursor(); + renameHandler.updateCursor(); + ++this.cursorCounter; + } + + // ==================== TEXT MANAGEMENT ==================== + + public void setText(String text) { + if (text == null) { + return; + } + + text = text.replace("\r", ""); + text = text.replace("\t", " "); + // preserve trailing newlines here — JavaTextContainer.init will + // ignore an extra empty final split when rendering lines. + if (this.text == null || !this.text.equals(text)) { + if (this.listener != null) { + this.listener.textUpdate(text); + } + + if (!this.undoing) { + this.undoList.add(new GuiScriptTextArea1.UndoData(this.text, selection.getCursorPosition())); + this.redoList.clear(); + } + + this.text = text; + //this.container = new TextContainer(text); + if (this.container == null) + this.container = new ScriptTextContainer(text); + + this.container.init(text, this.width, this.height); + + if (this.enableCodeHighlighting) + this.container.formatCodeText(); + + // Ensure scroll state stays in bounds after text change + int maxScroll = Math.max(0, getPaddedLineCount() - this.container.visibleLines); + scroll.clampToBounds(maxScroll); + + selection.clamp(this.text.length()); + + // Consider text changes user activity to pause caret blinking briefly + selection.markActivity(); + searchBar.updateMatches(); + + } + } + + public String getText() { + return this.text; + } + + public boolean isEnabled() { + return this.enabled && this.visible; + } + + public boolean hasVerticalScrollbar() { + return this.container != null && this.container.visibleLines < getPaddedLineCount(); + } + + public void enableCodeHighlighting() { + this.enableCodeHighlighting = true; + this.container.formatCodeText(); + } + + public void setListener(ITextChangeListener listener) { + this.listener = listener; + } + + private void clampSelectionBounds() { + selection.clamp(text != null ? text.length() : 0); + } + + // ==================== INNER CLASSES ==================== + + public static class UndoData { + public String text; + public int cursorPosition; + + public UndoData(String text, int cursorPosition) { + this.text = text; + this.cursorPosition = cursorPosition; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java b/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java index ab6e612d4..8a20a635c 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java @@ -251,12 +251,6 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } GL11.glPopMatrix(); - - // Draw hover texts in screen space (after scissor/translation are undone) - // so tooltips are not clipped and are positioned correctly - if (isMouseOver(mouseX, mouseY)) { - drawHoverTexts(mouseX, mouseY); - } } public void drawScreen(int mouseX, int mouseY, float partialTicks, int mouseScroll) { @@ -293,16 +287,21 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC * Draws hover texts for buttons in screen space (called after GL scissor/translate are undone). * Hover state was already computed during drawComponents with scroll-local coords. */ - private void drawHoverTexts(int mouseX, int mouseY) { + public void drawHoverTexts(int mouseX, int mouseY) { boolean subGui = parent.hasSubGui(); for (GuiNpcButton button : buttons.values()) { if (!button.hoverableText.isEmpty()) { button.drawHover(mouseX, mouseY, subGui); } } - // Label hover: convert screen mouse to scroll-local coords for hit testing int localMouseX = mouseX - xPos; int localMouseY = (int) (mouseY - yPos + scrollY); + for (GuiNpcTextField textField : textfields.values()) { + if (textField.hasHoverText()) { + textField.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui); + } + } + // Label hover: convert screen mouse to scroll-local coords for hit testing for (GuiNpcLabel label : labels.values()) { if (!label.hoverableText.isEmpty()) { label.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui, fontRendererObj); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiUtil.java b/src/main/java/noppes/npcs/client/gui/util/GuiUtil.java index 7350668b8..10f0efc53 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiUtil.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiUtil.java @@ -10,11 +10,19 @@ import org.lwjgl.opengl.GL11; public class GuiUtil { public static void setScissorClip(int x, int y, int width, int height) { + setScissorClip(x, y, width, height, null); + } + + public static void setScissorClip(int x, int y, int width, int height, GuiNPCInterface gui) { Minecraft mc = Minecraft.getMinecraft(); ScaledResolution res = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); int scale = res.getScaleFactor(); - + if (gui != null) { + x -= (int) gui.getPanX(); + y -= (int) gui.getPanY(); + } + // Adjust position to Top-Left origin (OpenGL window/screen space uses bottom-left origin) y = mc.displayHeight - y * scale; height *= scale; @@ -159,6 +167,32 @@ public class GuiUtil { tessellator.draw(); } + /** + * Draw a scaled textured rectangle (for rendering icons). + */ + public static void drawScaledTexturedRect(int x, int y, int u, int v, int srcWidth, int srcHeight, + int destWidth, int destHeight, int textureWidth, int textureHeight) { + float uScale = 1.0f / textureWidth; + float vScale = 1.0f / textureHeight; + + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + GL11.glBegin(GL11.GL_QUADS); + GL11.glTexCoord2f(u * uScale, v * vScale); + GL11.glVertex2f(x, y); + GL11.glTexCoord2f(u * uScale, (v + srcHeight) * vScale); + GL11.glVertex2f(x, y + destHeight); + GL11.glTexCoord2f((u + srcWidth) * uScale, (v + srcHeight) * vScale); + GL11.glVertex2f(x + destWidth, y + destHeight); + GL11.glTexCoord2f((u + srcWidth) * uScale, v * vScale); + GL11.glVertex2f(x + destWidth, y); + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + } + + public static void setMouse(int guiX, int guiY) { Minecraft mc = Minecraft.getMinecraft(); ScaledResolution scaledResolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); diff --git a/src/main/java/noppes/npcs/client/gui/util/IChainedAbilityConfigCallback.java b/src/main/java/noppes/npcs/client/gui/util/IChainedAbilityConfigCallback.java new file mode 100644 index 000000000..4584b7072 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/IChainedAbilityConfigCallback.java @@ -0,0 +1,10 @@ +package noppes.npcs.client.gui.util; + +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; + +/** + * Callback for when a chained ability is saved from the config SubGui. + */ +public interface IChainedAbilityConfigCallback { + void onChainedAbilitySaved(ChainedAbility chain); +} diff --git a/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java b/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java index db4989b56..60346560a 100644 --- a/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java +++ b/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java @@ -8,6 +8,8 @@ import java.util.UUID; public interface IClonerGui { int getShowingClones(); + HashMap getTags(); + TagMap getTagMap(); } diff --git a/src/main/java/noppes/npcs/client/gui/util/IGuiData.java b/src/main/java/noppes/npcs/client/gui/util/IGuiData.java index 36ba683ac..9f1796c8a 100644 --- a/src/main/java/noppes/npcs/client/gui/util/IGuiData.java +++ b/src/main/java/noppes/npcs/client/gui/util/IGuiData.java @@ -1,7 +1,108 @@ package noppes.npcs.client.gui.util; +import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.sync.SyncHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.nbt.NBTTagCompound; +/** + * OVERHAULED IGuiData FRAMEWORK! + * Based on the new {@link SyncController} and {@link SyncHandler} infrastructure + */ public interface IGuiData { - public void setGuiData(NBTTagCompound compound); + + /** + * Legacy data setter + * @Deprecated Use {@link #onDataUpdated(NBTTagCompound)} or {@link #onDataRemoved(String)} instead + */ + default void setGuiData(NBTTagCompound compound) { + + } + + // ═══════════════════════════════════════════════════════════════════════ + // USE THESE !!! + // ═══════════════════════════════════════════════════════════════════════ + + /** NOTE: + * No need for full object dataset onDataReload on GUI open, as these datasets are + * always freshly synced to their client's controllers thanks to {@link SyncController} + */ + + /** + * When a controller's object gets saved on server side, the updated object is synced to the client + * @param compound the compound of the updated object + */ + default void onDataUpdated(NBTTagCompound compound) { + } + + /** + * When a controller's object gets saved on server side, the updated object is synced to the client + * @param key key of updated object + * @param compound compound of updated object + */ + default void onDataUpdated(NBTTagCompound compound, String key) { + } + + /** + * When a controller's object gets saved on server side, the updated object is synced to the client + * @param id id of updated object + * @param compound compound of updated object + */ + default void onDataUpdated(NBTTagCompound compound, int id) { + } + + /** + * When a controller's object gets deleted on server side, the deleted object is removed from the client + * @param key key of removed object + */ + default void onDataRemoved(String key) { + } + + /** + * When a controller's object gets deleted on server side, the deleted object is removed from the client + * @param id id of removed object + */ + default void onDataRemoved(int id) { + } + + // ═══════════════════════════════════════════════════════════════════════ + // Static dispatchers + // ═══════════════════════════════════════════════════════════════════════ + + static void legacySetGuiData(NBTTagCompound nbt) { + GuiScreen gui = activeGui(); + if (gui instanceof IGuiData) + ((IGuiData) gui).setGuiData(nbt); + } + + static void notifyUpdate(NBTTagCompound nbt, String key, int id) { + GuiScreen gui = activeGui(); + if (gui instanceof IGuiData) { + ((IGuiData) gui).onDataUpdated(nbt); + ((IGuiData) gui).onDataUpdated(nbt, key); + ((IGuiData) gui).onDataUpdated(nbt, id); + } + } + + static void notifyRemove(String key, int id) { + GuiScreen gui = activeGui(); + if (gui instanceof IGuiData) { + ((IGuiData) gui).onDataRemoved(key); + ((IGuiData) gui).onDataRemoved(id); + } + } + + // ═══════════════════════════════════════════════════════════════════════ + // Active Gui fetcher + // ═══════════════════════════════════════════════════════════════════════ + + static GuiScreen activeGui() { + GuiScreen gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiNPCInterface && ((GuiNPCInterface) gui).hasSubGui()) + return ((GuiNPCInterface) gui).getSubGui(); + if (gui instanceof GuiContainerNPCInterface && ((GuiContainerNPCInterface) gui).hasSubGui()) + return ((GuiContainerNPCInterface) gui).getSubGui(); + return gui; + } } diff --git a/src/main/java/noppes/npcs/client/gui/util/SubGuiAPISelect.java b/src/main/java/noppes/npcs/client/gui/util/SubGuiAPISelect.java new file mode 100644 index 000000000..092fd6579 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/SubGuiAPISelect.java @@ -0,0 +1,59 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.controllers.APIRegistry; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +public class SubGuiAPISelect extends SubGuiInterface implements ISubGuiListener { + private final List names; + private final List urls; + + public SubGuiAPISelect() { + LinkedHashMap entries = APIRegistry.Instance.getEntries(); + this.names = new ArrayList<>(entries.keySet()); + this.urls = new ArrayList<>(entries.values()); + + this.xSize = 180; + this.ySize = 40 + names.size() * 24; + this.closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + addLabel(new GuiNpcLabel(0, "gui.api", guiLeft + 10, guiTop + 10, 0xFFFFFF)); + + for (int i = 0; i < names.size(); i++) { + addButton(new GuiNpcButton(i, guiLeft + 10, guiTop + 28 + i * 24, 160, 20, names.get(i))); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawGradientRect(guiLeft, guiTop, guiLeft + xSize, guiTop + ySize, 0xC0101010, 0xC0101010); + super.drawScreen(mouseX, mouseY, partialTicks); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + if (id >= 0 && id < urls.size()) { + setSubGui(new SubGuiConfirmLink(urls.get(id))); + } + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiConfirmLink && ((SubGuiConfirmLink) subgui).confirmed) { + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/SubGuiCategoryMoveConfirm.java b/src/main/java/noppes/npcs/client/gui/util/SubGuiCategoryMoveConfirm.java new file mode 100644 index 000000000..d4b7e79ea --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/SubGuiCategoryMoveConfirm.java @@ -0,0 +1,48 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; + +public class SubGuiCategoryMoveConfirm extends SubGuiInterface { + public boolean confirmed = false; + + private final int count; + public final String destCategoryName; + + public SubGuiCategoryMoveConfirm(int count, String destCategoryName) { + this.count = count; + this.destCategoryName = destCategoryName; + xSize = 220; + ySize = 90; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + String line1 = String.format(StatCollector.translateToLocal("gui.move.confirmLine"), count); + addLabel(new GuiNpcLabel(0, line1, guiLeft + 10, guiTop + 10, 0xFFFFFF)); + + String dest = StatCollector.translateToLocal("gui.category") + ": \"" + destCategoryName + "\""; + addLabel(new GuiNpcLabel(1, " " + dest, guiLeft + 10, guiTop + 25, 0xFFFFFF)); + + addButton(new GuiNpcButton(0, guiLeft + 10, guiTop + 55, 95, 20, "gui.yes")); + addButton(new GuiNpcButton(1, guiLeft + 115, guiTop + 55, 95, 20, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + confirmed = true; + close(); + } + if (guibutton.id == 1) { + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/SubGuiConfirmLink.java b/src/main/java/noppes/npcs/client/gui/util/SubGuiConfirmLink.java new file mode 100644 index 000000000..f821bdc67 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/SubGuiConfirmLink.java @@ -0,0 +1,61 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.resources.I18n; +import noppes.npcs.NoppesStringUtils; + +public class SubGuiConfirmLink extends SubGuiInterface { + private final String url; + public boolean confirmed = false; + + public SubGuiConfirmLink(String url) { + this.url = url; + this.xSize = 260; + this.ySize = 120; + this.closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + GuiNpcLabel titleLabel = new GuiNpcLabel(0, I18n.format("chat.link.confirmTrusted"), guiLeft, guiTop + 10, 0xFFFFFF); + titleLabel.center(xSize); + addLabel(titleLabel); + + GuiNpcLabel urlLabel = new GuiNpcLabel(1, url, guiLeft, guiTop + 28, 0xCCCCFF); + urlLabel.center(xSize); + addLabel(urlLabel); + + int btnWidth = 115; + int spacing = 10; + int totalWidth = btnWidth * 2 + spacing; + int startX = guiLeft + (xSize - totalWidth) / 2; + + addButton(new GuiNpcButton(0, startX, guiTop + 52, btnWidth, 20, "chat.link.open")); + addButton(new GuiNpcButton(1, startX + btnWidth + spacing, guiTop + 52, btnWidth, 20, "chat.copy")); + addButton(new GuiNpcButton(2, guiLeft + (xSize - btnWidth) / 2, guiTop + 78, btnWidth, 20, "gui.cancel")); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawGradientRect(0, 0, width, height, 0xC0101010, 0xC0101010); + super.drawScreen(mouseX, mouseY, partialTicks); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + confirmed = true; + openLink(url); + } else if (guibutton.id == 1) { + confirmed = true; + NoppesStringUtils.setClipboardContents(url); + } + close(); + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/SubGuiInterface.java b/src/main/java/noppes/npcs/client/gui/util/SubGuiInterface.java index b10ba84bd..f95bb59f0 100644 --- a/src/main/java/noppes/npcs/client/gui/util/SubGuiInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/SubGuiInterface.java @@ -12,6 +12,7 @@ public class SubGuiInterface extends GuiNPCInterface { @Override public void close() { + GuiNpcTextField.unfocus(); save(); if (parent instanceof ISubGuiListener) diff --git a/src/main/java/noppes/npcs/client/gui/util/SubGuiNpcCooldownPicker.java b/src/main/java/noppes/npcs/client/gui/util/SubGuiNpcCooldownPicker.java index 36d902f58..330b631bf 100644 --- a/src/main/java/noppes/npcs/client/gui/util/SubGuiNpcCooldownPicker.java +++ b/src/main/java/noppes/npcs/client/gui/util/SubGuiNpcCooldownPicker.java @@ -15,7 +15,7 @@ public class SubGuiNpcCooldownPicker extends SubGuiInterface implements ITextfie public SubGuiNpcCooldownPicker(boolean isMCCustom, long currentCooldown) { this.isMCCustom = isMCCustom; this.cooldownValue = currentCooldown; - setBackground("smallbg.png"); + setBackground("menubg.png"); xSize = 220; ySize = 222; closeOnEsc = true; diff --git a/src/main/java/noppes/npcs/client/gui/util/script/BracketMatcher.java b/src/main/java/noppes/npcs/client/gui/util/script/BracketMatcher.java index b7b9ab63a..d2ec240e7 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/BracketMatcher.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/BracketMatcher.java @@ -326,7 +326,8 @@ public class BracketMatcher { } /** - * Check if a brace at given position has a matching close with same indent + * Check if a brace at given position has a matching close with compatible indent. + * Uses <= to handle multi-line declarations where '{' is on a continuation line. */ public static boolean hasMatchingCloseWithSameIndent(String text, int bracePos, List lines, int currentIndent) { if (text == null || lines == null || bracePos < 0) return false; @@ -350,7 +351,7 @@ public class BracketMatcher { if (closeLineIdx < lines.size()) { String closeLine = lines.get(closeLineIdx).text; int closeIndent = getLineIndent(closeLine); - return closeIndent == currentIndent; + return closeIndent <= currentIndent; } } } diff --git a/src/main/java/noppes/npcs/client/gui/util/script/ClassPathFinder.java b/src/main/java/noppes/npcs/client/gui/util/script/ClassPathFinder.java index 844da165b..9b6567b1e 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/ClassPathFinder.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/ClassPathFinder.java @@ -375,7 +375,8 @@ public class ClassPathFinder { if (p == null || p.isEmpty()) continue; String[] segs = p.split("\\."); String last = segs[segs.length - 1]; - boolean lastIsClass = last.length() > 0 && Character.isUpperCase(last.charAt(0)); + // Check if last segment is actually a class (try to resolve it) + boolean lastIsClass = last.length() > 0 && tryResolveClass(p) != null; // Try package wildcard: pkg.SimpleName if (!lastIsClass) { @@ -539,6 +540,8 @@ public class ClassPathFinder { private int findFirstUppercaseSegment(String[] segments) { for (int i = 0; i < segments.length; i++) { if (segments[i].length() > 0 && Character.isUpperCase(segments[i].charAt(0))) { + // Keep uppercase check here as it's a heuristic for package splitting + // This is about Java naming conventions, not actual type resolution return i; } } @@ -653,10 +656,10 @@ public class ClassPathFinder { } String typeName = content.substring(start, i); - // Only process if it looks like a type name (starts with uppercase) - if (Character.isUpperCase(typeName.charAt(0))) { - // Resolve the type - ClassInfo info = resolveSimpleName(typeName, importedClasses, importedPackages); + // Try to resolve as an actual type + ClassInfo info = resolveSimpleName(typeName, importedClasses, importedPackages); + if (info != null) { + // Only process if it actually resolves to a type ClassType classType = (info != null) ? info.type : ClassType.CLASS; results.add(new TypeOccurrence(baseOffset + start, baseOffset + i, typeName, classType)); diff --git a/src/main/java/noppes/npcs/client/gui/util/script/FormatHelper.java b/src/main/java/noppes/npcs/client/gui/util/script/FormatHelper.java index a1eedce0b..5877c5a13 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/FormatHelper.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/FormatHelper.java @@ -2,24 +2,156 @@ package noppes.npcs.client.gui.util.script; import java.util.ArrayList; import java.util.List; -import java.util.regex.Pattern; /** * Configurable code formatter with IntelliJ-like settings. *

+ * Architecture: Token-based pipeline (tokenize → format → reconstruct). + *

+ * The formatter processes code in three phases: + *

    + *
  1. Tokenize — Splits code segments into typed tokens + * (operators, keywords, identifiers, literals, punctuation, whitespace). + * Multi-character operators are matched longest-first to avoid sub-token clobbering.
  2. + *
  3. Format — Applies spacing rules to each token pair based on their types + * and the current {@link FormatSettings}. Context-aware: distinguishes unary from + * binary operators, generic brackets from comparison operators, etc.
  4. + *
  5. Reconstruct — Joins formatted tokens back into a code string.
  6. + *
+ *

+ * String literals and comments are identified before tokenization and passed through + * unchanged (the "preserve regions" approach). Line-by-line processing preserves + * original structure and indentation. + *

* Features: - * - Operator spacing (a+b → a + b) - * - Whitespace normalization (a b → a b) - * - Long line wrapping - * - Bracket spacing configuration - * - Preserves string content and comments + *

    + *
  • Operator spacing (a+b → a + b)
  • + *
  • Whitespace normalization (a b → a b)
  • + *
  • Long line wrapping
  • + *
  • Bracket spacing configuration
  • + *
  • Preserves string content and comments
  • + *
*/ public class FormatHelper { + // ==================== TOKEN TYPES ==================== + + /** + * Token type classification for the formatter tokenizer. + */ + enum TokenType { + /** String literal: "..." or '...' (with escape handling) */ + STRING_LITERAL, + /** Block comment: /* ... */ */ + BLOCK_COMMENT, + /** Line comment: // ... */ + LINE_COMMENT, + /** Multi-char or single-char operator: ==, !=, >=, +, -, etc. */ + OPERATOR, + /** Control-flow keyword: if, while, for, switch, catch, else, return, etc. */ + KEYWORD, + /** ( */ + PAREN_OPEN, + /** ) */ + PAREN_CLOSE, + /** [ */ + BRACKET_OPEN, + /** ] */ + BRACKET_CLOSE, + /** { */ + BRACE_OPEN, + /** } */ + BRACE_CLOSE, + /** , */ + COMMA, + /** ; */ + SEMICOLON, + /** : */ + COLON, + /** . */ + DOT, + /** Variable name, method name, type name, etc. */ + IDENTIFIER, + /** Numeric literal */ + NUMBER, + /** Spaces, tabs (not newlines — those are line delimiters) */ + WHITESPACE + } + + // ==================== TOKEN CLASS ==================== + + /** + * A single token produced by the tokenizer. + */ + static class Token { + final TokenType type; + final String value; + final int position; // position in original code segment + + Token(TokenType type, String value, int position) { + this.type = type; + this.value = value; + this.position = position; + } + + @Override + public String toString() { + return type + "(" + value + ")@" + position; + } + } + + // ==================== OPERATOR CLASSIFICATION ==================== + + /** + * Multi-character operators ordered longest-first for greedy matching. + */ + private static final String[] MULTI_CHAR_OPERATORS = { + ">>>=", // unsigned right shift assign + "===", "!==", // JS strict equality + "<<=", ">>=", // shift assign + ">>>", // unsigned right shift + "+=", "-=", "*=", "/=", "%=", // compound assign + "&=", "|=", "^=", // bitwise compound assign + "&&", "||", // logical + "==", "!=", // equality + "<=", ">=", // comparison + "<<", ">>", // shift + "++", "--", // increment/decrement + "->", "=>", // arrow operators (Java lambda, JS arrow) + }; + + /** + * Single-character operators. Note: < and > are handled specially + * (could be generics). + */ + private static final String SINGLE_CHAR_OPERATORS = "=+-*/%&|^!~<>?"; + + /** + * Keywords that get special spacing before parentheses. + */ + private static final String[] CONTROL_KEYWORDS = { + "if", "while", "for", "switch", "catch", + "else", "return", "new", "throw", "typeof", "instanceof", + "in", "of", "var", "let", "const", "function", "class", + "try", "finally", "do", "case", "default", "break", "continue", + "void", "delete", "yield", "await", "async", "extends", "implements", + "import", "export", "package", "interface", "enum", "abstract", + "static", "final", "synchronized", "volatile", "transient", "native", + "this", "super", "null", "true", "false", "undefined", + "public", "private", "protected" + }; + + /** + * Keywords that require a space before '(' when setting is enabled. + */ + private static final String[] PAREN_KEYWORDS = { + "if", "while", "for", "switch", "catch" + }; + // ==================== SETTINGS ==================== /** - * Formatting configuration - similar to IntelliJ Code Style settings + * Formatting configuration — similar to IntelliJ Code Style settings. */ public static class FormatSettings { // Spaces around operators @@ -117,22 +249,31 @@ public class FormatHelper { // ==================== MAIN FORMAT METHOD ==================== /** - * Format the entire text with all configured options + * Format the entire text with all configured options. */ public String format(String text) { if (text == null || text.isEmpty()) return text; - // Process line by line to preserve structure String[] lines = text.split("\n", -1); StringBuilder result = new StringBuilder(); + List lambdaIndentStack = new ArrayList<>(); + for (int i = 0; i < lines.length; i++) { - String line = formatLine(lines[i], text, getLineStartOffset(lines, i)); + String line = lines[i]; + + if (!lambdaIndentStack.isEmpty()) { + line = fixLambdaBlockIndent(line, lambdaIndentStack); + } + + line = formatLine(line); if (settings.trimTrailingWhitespace) { line = trimTrailing(line); } + updateLambdaBlockStack(line, lambdaIndentStack); + result.append(line); if (i < lines.length - 1) { result.append("\n"); @@ -142,6 +283,124 @@ public class FormatHelper { return result.toString(); } + /** + * Scan a formatted line for arrow-block patterns ({@code -> {} or {@code => {}) + * and track open/close braces to maintain a stack of lambda block indent levels. + *

+ * When an arrow-block opens, the line's leading indent is pushed onto the stack. + * When a closing brace {@code }} is found and the stack is non-empty, the top + * entry is popped (the brace closes the innermost lambda block). + */ + private void updateLambdaBlockStack(String line, List stack) { + String trimmed = line.trim(); + if (trimmed.isEmpty()) return; + + String indent = extractIndent(line); + String contentNoStrings = stripStringLiterals(trimmed); + + int opens = 0; + int closes = 0; + for (int i = 0; i < contentNoStrings.length(); i++) { + char c = contentNoStrings.charAt(i); + if (c == '{') opens++; + else if (c == '}') closes++; + } + + boolean hasArrowBlock = endsWithArrowBlock(contentNoStrings); + + // Process closes first (a line like "});" closes the current block) + int netCloses = closes - opens; + if (netCloses > 0) { + for (int j = 0; j < netCloses && !stack.isEmpty(); j++) { + stack.remove(stack.size() - 1); + } + } + + if (hasArrowBlock) { + stack.add(indent); + } else if (opens > closes) { + // Non-arrow block opened — only push if inside a lambda context already + // to track nested depth correctly + int netOpens = opens - closes; + if (!stack.isEmpty()) { + for (int j = 0; j < netOpens; j++) { + stack.add(indent); + } + } + } + } + + /** + * Fix indentation for a line that's inside a lambda block body. + * Body lines get parent indent + 4 spaces; closing braces get parent indent. + */ + private String fixLambdaBlockIndent(String line, List stack) { + if (stack.isEmpty()) return line; + + String trimmed = line.trim(); + if (trimmed.isEmpty()) return line; + + String currentIndent = extractIndent(line); + String parentIndent = stack.get(stack.size() - 1); + String bodyIndent = parentIndent + " "; + + boolean isClosingBrace = trimmed.startsWith("}"); + + String requiredIndent = isClosingBrace ? parentIndent : bodyIndent; + + if (getVisualLength(currentIndent) < getVisualLength(requiredIndent)) { + return requiredIndent + trimmed; + } + + return line; + } + + private boolean endsWithArrowBlock(String contentNoStrings) { + int lastOpenBrace = contentNoStrings.lastIndexOf('{'); + if (lastOpenBrace < 0) return false; + + int matchingClose = contentNoStrings.indexOf('}', lastOpenBrace); + if (matchingClose >= 0) return false; + + int searchEnd = lastOpenBrace; + while (searchEnd > 0 && contentNoStrings.charAt(searchEnd - 1) == ' ') searchEnd--; + + if (searchEnd >= 2) { + String beforeBrace = contentNoStrings.substring(searchEnd - 2, searchEnd); + return beforeBrace.equals("->") || beforeBrace.equals("=>"); + } + + return false; + } + + private String stripStringLiterals(String content) { + StringBuilder sb = new StringBuilder(content.length()); + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < content.length(); i++) { + char c = content.charAt(i); + if (!inString) { + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + sb.append(' '); + } else { + sb.append(c); + } + } else { + sb.append(' '); + if (c == '\\' && i + 1 < content.length()) { + i++; + sb.append(' '); + } else if (c == stringChar) { + inString = false; + } + } + } + return sb.toString(); + } + /** * Split multiple statements on one line into separate lines with proper indentation. * E.g., " this.a = 1; this.b = 2;" becomes two lines @@ -206,7 +465,7 @@ public class FormatHelper { } /** - * Split content by semicolons, preserving those in strings and for-loops + * Split content by semicolons, preserving those in strings and for-loops. */ private List splitBySemicolons(String content) { List statements = new ArrayList<>(); @@ -215,11 +474,10 @@ public class FormatHelper { boolean inString = false; boolean inChar = false; boolean escaped = false; - int forLoopDepth = 0; // Track for(...) depth to preserve semicolons + int forLoopDepth = 0; for (int i = 0; i < content.length(); i++) { char c = content.charAt(i); - char prev = i > 0 ? content.charAt(i - 1) : ' '; // Track strings if (c == '\"' && !escaped && !inChar) { @@ -267,18 +525,10 @@ public class FormatHelper { return statements; } - private int getLineStartOffset(String[] lines, int lineIndex) { - int offset = 0; - for (int i = 0; i < lineIndex; i++) { - offset += lines[i].length() + 1; // +1 for \n - } - return offset; - } - /** - * Format a single line of code + * Format a single line of code. */ - private String formatLine(String line, String fullText, int lineOffset) { + private String formatLine(String line) { if (line.trim().isEmpty()) return line; // Preserve leading indentation @@ -304,14 +554,14 @@ public class FormatHelper { } // Format the content - String formatted = formatContent(content, fullText, lineOffset + indent); + String formatted = formatContent(content); return indentation + formatted; } /** * Check if a line appears to be a continuation of a previous line - * (i.e., starts with an operator, dot, or other continuation character) + * (i.e., starts with an operator, dot, or other continuation character). */ private boolean isContinuationLine(String trimmedContent) { if (trimmedContent.isEmpty()) return false; @@ -331,43 +581,71 @@ public class FormatHelper { } /** - * Format line content, preserving strings and comments + * Format line content, preserving strings and comments. + * Splits content into code segments and preserved regions (strings/comments), + * then tokenizes and formats each code segment. */ - private String formatContent(String content, String fullText, int offset) { - // Find string/comment regions to preserve + private String formatContent(String content) { List preserveRegions = findPreserveRegions(content); if (preserveRegions.isEmpty()) { - // No strings/comments, format everything return formatCodeSegment(content); } - // Build result by formatting non-preserved regions StringBuilder result = new StringBuilder(); int lastEnd = 0; for (int[] region : preserveRegions) { - // Format code before this preserved region if (region[0] > lastEnd) { String codeSegment = content.substring(lastEnd, region[0]); - result.append(formatCodeSegment(codeSegment)); + String formatted = formatCodeSegment(codeSegment); + result.append(formatted); + + // Ensure space between code ending with operator and following preserved region + if (!formatted.isEmpty() && !formatted.endsWith(" ")) { + char lastChar = formatted.charAt(formatted.length() - 1); + boolean operatorEnd = SINGLE_CHAR_OPERATORS.indexOf(lastChar) >= 0; + boolean identifierEnd = Character.isJavaIdentifierPart(lastChar); + if (operatorEnd || identifierEnd) { + result.append(' '); + } + } } - // Append preserved region unchanged - result.append(content.substring(region[0], region[1])); + // Ensure space before line comments (// ...) + String preserved = content.substring(region[0], region[1]); + if (preserved.startsWith("//") && result.length() > 0 && result.charAt(result.length() - 1) != ' ') { + result.append(' '); + } + + // Normalize line comment: ensure space after // prefix + if (preserved.startsWith("//") && preserved.length() > 2 && preserved.charAt(2) != ' ') { + preserved = "// " + preserved.substring(2); + } + + result.append(preserved); lastEnd = region[1]; } - // Format remaining code after last preserved region if (lastEnd < content.length()) { - result.append(formatCodeSegment(content.substring(lastEnd))); + String codeSegment = content.substring(lastEnd); + String formatted = formatCodeSegment(codeSegment); + // Ensure space after block comment end (*/) before code tokens + if (result.length() > 1 && !formatted.isEmpty()) { + String tail = result.substring(result.length() - 2); + char nextChar = formatted.charAt(0); + if (tail.equals("*/") && nextChar != ';' && nextChar != ',' && nextChar != ')') { + result.append(' '); + } + } + result.append(formatted); } return result.toString(); } /** - * Find string literals and comments that should not be formatted + * Find string literals and comments that should not be formatted. */ private List findPreserveRegions(String content) { List regions = new ArrayList<>(); @@ -418,7 +696,7 @@ public class FormatHelper { } /** - * Find end of string/char literal + * Find end of string/char literal. */ private int findStringEnd(String content, int start, char quote) { int i = start + 1; @@ -436,434 +714,873 @@ public class FormatHelper { return content.length(); } - // ==================== CODE SEGMENT FORMATTING ==================== + // ==================== TOKEN-BASED CODE SEGMENT FORMATTING ==================== /** - * Format a code segment (no strings/comments) + * Format a code segment (no strings/comments) using the token pipeline: + * tokenize → format → reconstruct. */ private String formatCodeSegment(String code) { if (code.isEmpty()) return code; - String result = code; + // Phase 1: Tokenize + List tokens = tokenize(code); - // Normalize whitespace first + // Phase 1.5: Merge split operators (e.g. = = → ==, > = → >=) if (settings.normalizeWhitespace) { - result = normalizeWhitespace(result); + tokens = mergeSplitOperators(tokens); } - // Apply operator spacing - result = formatOperators(result); + // Phase 1.75: Split >> and >>> into individual > tokens when in generic context. + // Must run AFTER merge so that merged >> tokens get split back when generic. + tokens = splitGenericShiftOperators(tokens); - // Apply bracket spacing - result = formatBrackets(result); + // Phase 2: Format (apply spacing rules) + List formatted = formatTokens(tokens); - // Apply keyword spacing - result = formatKeywords(result); + // Phase 3: Reconstruct + return reconstruct(formatted); + } - // Apply punctuation spacing - result = formatPunctuation(result); + // ==================== PHASE 1: TOKENIZER ==================== + + /** + * Tokenize a code segment into a list of typed tokens. + * Multi-character operators are matched longest-first. + * Whitespace is collapsed into single-space tokens when normalizeWhitespace is enabled. + */ + private List tokenize(String code) { + List tokens = new ArrayList<>(); + int i = 0; + int len = code.length(); + + while (i < len) { + char c = code.charAt(i); + + // Whitespace + if (c == ' ' || c == '\t') { + int start = i; + while (i < len && (code.charAt(i) == ' ' || code.charAt(i) == '\t')) { + i++; + } + String ws = settings.normalizeWhitespace ? " " : code.substring(start, i); + tokens.add(new Token(TokenType.WHITESPACE, ws, start)); + continue; + } + + // Try multi-char operators (longest first) + String multiOp = matchMultiCharOperator(code, i); + if (multiOp != null) { + tokens.add(new Token(TokenType.OPERATOR, multiOp, i)); + i += multiOp.length(); + continue; + } + + // Punctuation (single-char tokens with specific types) + if (c == '(') { tokens.add(new Token(TokenType.PAREN_OPEN, "(", i)); i++; continue; } + if (c == ')') { tokens.add(new Token(TokenType.PAREN_CLOSE, ")", i)); i++; continue; } + if (c == '[') { tokens.add(new Token(TokenType.BRACKET_OPEN, "[", i)); i++; continue; } + if (c == ']') { tokens.add(new Token(TokenType.BRACKET_CLOSE, "]", i)); i++; continue; } + if (c == '{') { tokens.add(new Token(TokenType.BRACE_OPEN, "{", i)); i++; continue; } + if (c == '}') { tokens.add(new Token(TokenType.BRACE_CLOSE, "}", i)); i++; continue; } + if (c == ',') { tokens.add(new Token(TokenType.COMMA, ",", i)); i++; continue; } + if (c == ';') { tokens.add(new Token(TokenType.SEMICOLON, ";", i)); i++; continue; } + if (c == ':' && i + 1 < len && code.charAt(i + 1) == ':') { + tokens.add(new Token(TokenType.OPERATOR, "::", i)); + i += 2; + continue; + } + if (c == ':') { tokens.add(new Token(TokenType.COLON, ":", i)); i++; continue; } + if (c == '.') { tokens.add(new Token(TokenType.DOT, ".", i)); i++; continue; } + + // Single-char operators (=, +, -, *, /, %, &, |, ^, !, ~, <, >, ?) + if (SINGLE_CHAR_OPERATORS.indexOf(c) >= 0) { + tokens.add(new Token(TokenType.OPERATOR, String.valueOf(c), i)); + i++; + continue; + } + + // Number + if (Character.isDigit(c) || (c == '.' && i + 1 < len && Character.isDigit(code.charAt(i + 1)))) { + int start = i; + // Handle hex (0x...), binary (0b...), octal (0o...) + if (c == '0' && i + 1 < len) { + char next = code.charAt(i + 1); + if (next == 'x' || next == 'X' || next == 'b' || next == 'B' || next == 'o' || next == 'O') { + i += 2; + while (i < len && isHexDigit(code.charAt(i))) i++; + tokens.add(new Token(TokenType.NUMBER, code.substring(start, i), start)); + continue; + } + } + while (i < len && (Character.isDigit(code.charAt(i)) || code.charAt(i) == '.')) i++; + // Handle suffixes like L, f, d + if (i < len && "LlFfDd".indexOf(code.charAt(i)) >= 0) i++; + tokens.add(new Token(TokenType.NUMBER, code.substring(start, i), start)); + continue; + } + + // Annotation: @ followed by identifier → single token (@Override, @Deprecated) + if (c == '@') { + int start = i; + i++; + // Skip whitespace between @ and annotation name + while (i < len && (code.charAt(i) == ' ' || code.charAt(i) == '\t')) i++; + if (i < len && Character.isJavaIdentifierStart(code.charAt(i))) { + while (i < len && Character.isJavaIdentifierPart(code.charAt(i))) i++; + String annotation = "@" + code.substring(start + 1, i).trim(); + tokens.add(new Token(TokenType.IDENTIFIER, annotation, start)); + } else { + tokens.add(new Token(TokenType.IDENTIFIER, "@", start)); + } + continue; + } + + // Identifier or keyword + if (Character.isJavaIdentifierStart(c)) { + int start = i; + while (i < len && Character.isJavaIdentifierPart(code.charAt(i))) i++; + String word = code.substring(start, i); + if (isKeyword(word)) { + tokens.add(new Token(TokenType.KEYWORD, word, start)); + } else { + tokens.add(new Token(TokenType.IDENTIFIER, word, start)); + } + continue; + } + + // Anything else — emit as identifier (safety fallback) + tokens.add(new Token(TokenType.IDENTIFIER, String.valueOf(c), i)); + i++; + } + + return tokens; + } + + /** + * Try to match a multi-character operator at the given position. + * Checks longest operators first for correct greedy matching. + */ + private String matchMultiCharOperator(String code, int pos) { + for (String op : MULTI_CHAR_OPERATORS) { + if (pos + op.length() <= code.length() && + code.substring(pos, pos + op.length()).equals(op)) { + return op; + } + } + return null; + } + + private boolean isHexDigit(char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c == '_'; + } + + private boolean isKeyword(String word) { + for (String kw : CONTROL_KEYWORDS) { + if (kw.equals(word)) return true; + } + return false; + } + + // ==================== PHASE 1.25: SPLIT GENERIC SHIFT OPERATORS ==================== + + /** + * Split {@code >>} and {@code >>>} operator tokens into individual {@code >} + * tokens when they appear inside a generic type context (e.g., {@code List>}). + *

+ * Without this, the greedy tokenizer matches {@code >>} as the right-shift operator, + * causing the formatter to add spaces around it as an arithmetic/bitwise operator. + */ + private List splitGenericShiftOperators(List tokens) { + int genericDepth = 0; + List result = new ArrayList<>(); + + for (int i = 0; i < tokens.size(); i++) { + Token t = tokens.get(i); + + if (t.type == TokenType.OPERATOR && t.value.equals("<")) { + Token before = findPrevNonWhitespaceInList(result); + if (before != null && before.type == TokenType.IDENTIFIER && !before.value.isEmpty() + && Character.isUpperCase(before.value.charAt(0))) { + genericDepth++; + } + } + + if (genericDepth > 0 && t.type == TokenType.OPERATOR + && (t.value.equals(">>") || t.value.equals(">>>"))) { + for (int c = 0; c < t.value.length(); c++) { + result.add(new Token(TokenType.OPERATOR, ">", t.position + c)); + genericDepth--; + if (genericDepth < 0) genericDepth = 0; + } + continue; + } + + if (t.type == TokenType.OPERATOR && t.value.equals(">")) { + if (genericDepth > 0) { + genericDepth--; + } + } + + result.add(t); + } return result; } - /** - * Normalize whitespace (multiple spaces → single space) - */ - private String normalizeWhitespace(String code) { - // Replace multiple spaces with single space, but preserve indentation - return code.replaceAll(" +", " "); + private Token findPrevNonWhitespaceInList(List tokens) { + for (int i = tokens.size() - 1; i >= 0; i--) { + if (tokens.get(i).type != TokenType.WHITESPACE) { + return tokens.get(i); + } + } + return null; } + // ==================== PHASE 1.5: MERGE SPLIT OPERATORS ==================== + /** - * Format operator spacing + * Merge operator tokens that were split by whitespace in the original code. + * Example: tokens [=] [ws] [=] → single token [==]. + * This handles the case where users type "x = = y" and the formatter + * should recognize it as "x == y" (the == operator was split). + * + * Merge candidates (longest first): + * > > > = → >>>= = = = → === ! = = → !== + * > > = → >>= < < = → <<= > > > → >>> + * > > → >> < < → << = = → == + * ! = → != > = → >= < = → <= + * + = → += - = → -= * = → *= + * / = → /= % = → %= & = → &= + * | = → |= ^ = → ^= & & → && + * | | → || */ - private String formatOperators(String code) { - String result = code; + private List mergeSplitOperators(List tokens) { + // Extract only operator values (ignoring whitespace between them) + // and try to merge consecutive operators into known multi-char operators + List result = new ArrayList<>(); + int i = 0; - // Assignment operators - if (settings.spaceAroundAssignment) { - // Compound assignments first (longer patterns first) - result = formatBinaryOp(result, "+=", " += "); - result = formatBinaryOp(result, "-=", " -= "); - result = formatBinaryOp(result, "*=", " *= "); - result = formatBinaryOp(result, "/=", " /= "); - result = formatBinaryOp(result, "%=", " %= "); - result = formatBinaryOp(result, "&=", " &= "); - result = formatBinaryOp(result, "|=", " |= "); - result = formatBinaryOp(result, "^=", " ^= "); - result = formatBinaryOp(result, "<<=", " <<= "); - result = formatBinaryOp(result, ">>=", " >>= "); - result = formatBinaryOp(result, ">>>=", " >>>= "); + while (i < tokens.size()) { + Token t = tokens.get(i); - // Simple assignment (but not ==, !=, <=, >=) - result = formatSimpleAssignment(result); - } + if (t.type == TokenType.OPERATOR) { + // Try to merge with following operator tokens (skipping whitespace) + String merged = tryMergeOperators(tokens, i); + if (merged != null && merged.length() > t.value.length()) { + result.add(new Token(TokenType.OPERATOR, merged, t.position)); + // Skip past all the tokens we consumed + i = skipMergedTokens(tokens, i, merged); + continue; + } + } - // Comparison operators - if (settings.spaceAroundComparison) { - result = formatBinaryOp(result, "==", " == "); - result = formatBinaryOp(result, "!=", " != "); - result = formatBinaryOp(result, "<=", " <= "); - result = formatBinaryOp(result, ">=", " >= "); - // Simple < > (but not generics) - result = formatComparisonOperators(result); - } + // Merge split :: (method reference) — two COLON tokens with optional whitespace + if (t.type == TokenType.COLON) { + int next = i + 1; + while (next < tokens.size() && tokens.get(next).type == TokenType.WHITESPACE) next++; + if (next < tokens.size() && tokens.get(next).type == TokenType.COLON) { + result.add(new Token(TokenType.OPERATOR, "::", t.position)); + i = next + 1; + continue; + } + } - // Logical operators - if (settings.spaceAroundLogical) { - result = formatBinaryOp(result, "&&", " && "); - result = formatBinaryOp(result, "||", " || "); - } - - // Arithmetic operators - if (settings.spaceAroundArithmetic) { - // Handle ++ and -- first to avoid conflicts - result = formatArithmeticOperators(result); - } - - // Bitwise operators (but not in generics) - if (settings.spaceAroundBitwise) { - result = formatBitwiseOperators(result); + result.add(t); + i++; } return result; } /** - * Format a binary operator with proper spacing + * Try to merge operator tokens starting at index, skipping whitespace between them. + * Returns the merged operator string if a known multi-char operator is formed, + * or null if no merge is possible. */ - private String formatBinaryOp(String code, String op, String replacement) { - // First normalize: remove extra spaces around the operator - String pattern = "\\s*" + Pattern.quote(op) + "\\s*"; - return code.replaceAll(pattern, replacement); + private String tryMergeOperators(List tokens, int startIdx) { + StringBuilder ops = new StringBuilder(); + List opIndices = new ArrayList<>(); + boolean hasWhitespaceBetween = false; + + for (int i = startIdx; i < tokens.size(); i++) { + Token t = tokens.get(i); + if (t.type == TokenType.OPERATOR) { + ops.append(t.value); + opIndices.add(i); + } else if (t.type == TokenType.WHITESPACE) { + if (!opIndices.isEmpty()) { + hasWhitespaceBetween = true; + } + continue; + } else { + break; + } + } + + String allOps = ops.toString(); + + for (String multiOp : MULTI_CHAR_OPERATORS) { + if (allOps.startsWith(multiOp) && multiOp.length() > 1) { + // Don't merge ++ or -- when whitespace separated the operators. + // Whitespace-separated +/+ or -/- means binary op + unary op (e.g. a - -b), + // not increment/decrement. Real ++ and -- are tokenized as single tokens. + if (hasWhitespaceBetween && (multiOp.equals("++") || multiOp.equals("--"))) { + continue; + } + return multiOp; + } + } + + return null; } /** - * Format simple assignment = (not ==, !=, <=, >=, etc.) + * Skip past the tokens that were consumed by the merge. + * Returns the index of the first token AFTER the merged sequence. */ - private String formatSimpleAssignment(String code) { - StringBuilder result = new StringBuilder(); - int i = 0; - while (i < code.length()) { - char c = code.charAt(i); - if (c == '=') { - // Check it's not part of ==, !=, <=, >=, +=, etc. - char prev = i > 0 ? code.charAt(i - 1) : ' '; - char next = i + 1 < code.length() ? code.charAt(i + 1) : ' '; + private int skipMergedTokens(List tokens, int startIdx, String merged) { + int charsConsumed = 0; + int i = startIdx; - boolean isCompound = prev == '!' || prev == '<' || prev == '>' || - prev == '+' || prev == '-' || prev == '*' || - prev == '/' || prev == '%' || prev == '&' || - prev == '|' || prev == '^'; - boolean isEquality = next == '='; - - if (!isCompound && !isEquality) { - // Ensure space before = - if (result.length() > 0 && result.charAt(result.length() - 1) != ' ') { - result.append(' '); - } - result.append('='); - // Ensure space after = - if (next != ' ') { - result.append(' '); - } - } else { - result.append(c); - } - } else { - result.append(c); + while (i < tokens.size() && charsConsumed < merged.length()) { + Token t = tokens.get(i); + if (t.type == TokenType.OPERATOR) { + charsConsumed += t.value.length(); } + // Skip whitespace tokens between operators i++; } - return result.toString(); + + return i; } + // ==================== PHASE 2: TOKEN FORMATTER ==================== + /** - * Format < and > comparison operators (avoiding generics) + * Apply formatting rules to a token list, producing a new list with + * whitespace tokens inserted/removed/adjusted according to settings. + *

+ * The formatter works by iterating through tokens and deciding what + * whitespace should appear between each pair of non-whitespace tokens. */ - private String formatComparisonOperators(String code) { - StringBuilder result = new StringBuilder(); - int i = 0; - while (i < code.length()) { - char c = code.charAt(i); - - if ((c == '<' || c == '>') && !isLikelyGeneric(code, i, c)) { - char prev = i > 0 ? code.charAt(i - 1) : ' '; - char next = i + 1 < code.length() ? code.charAt(i + 1) : ' '; - - // Skip if part of <<, >>, <=, >= - if ((c == '<' && next == '<') || (c == '>' && next == '>') || - next == '=' || prev == '<' || prev == '>') { - result.append(c); - } else { - // Add spacing - if (result.length() > 0 && result.charAt(result.length() - 1) != ' ') { - result.append(' '); - } - result.append(c); - if (next != ' ' && next != '=') { - result.append(' '); - } - } - } else { - result.append(c); + private List formatTokens(List tokens) { + // First, strip existing whitespace tokens to normalize + List stripped = new ArrayList<>(); + for (Token t : tokens) { + if (t.type != TokenType.WHITESPACE) { + stripped.add(t); } - i++; } - return result.toString(); + + if (stripped.isEmpty()) return tokens; + + // Now rebuild with correct spacing + List result = new ArrayList<>(); + result.add(stripped.get(0)); + + for (int i = 1; i < stripped.size(); i++) { + Token prev = stripped.get(i - 1); + Token curr = stripped.get(i); + + // Determine the previous non-whitespace before prev (for context) + Token prevPrev = i >= 2 ? stripped.get(i - 2) : null; + + String spacing = determineSpacing(prevPrev, prev, curr, stripped, i); + + if (!spacing.isEmpty()) { + result.add(new Token(TokenType.WHITESPACE, spacing, -1)); + } + result.add(curr); + } + + return result; } /** - * Check if < or > is likely part of a generic type declaration + * Determine the spacing string that should appear between prev and curr tokens. + * Returns "" for no space, " " for single space. + * + * @param prevPrev token before prev (may be null) + * @param prev the token before the gap + * @param curr the token after the gap + * @param allTokens all stripped tokens + * @param currIdx index of curr in allTokens */ - private boolean isLikelyGeneric(String code, int pos, char bracket) { - if (bracket == '<') { - // Check for pattern like List<, Map<, etc. - if (pos > 0) { - int start = pos - 1; - while (start > 0 && Character.isLetterOrDigit(code.charAt(start - 1))) { - start--; + private String determineSpacing(Token prevPrev, Token prev, Token curr, + List allTokens, int currIdx) { + + // ---- DOT: never space around dots (method chains, property access) ---- + if (prev.type == TokenType.DOT || curr.type == TokenType.DOT) { + return ""; + } + + // ---- OPERATOR SPACING ---- + if (prev.type == TokenType.OPERATOR || curr.type == TokenType.OPERATOR) { + return determineOperatorSpacing(prevPrev, prev, curr, allTokens, currIdx); + } + + // ---- KEYWORD before PAREN_OPEN: if (...), while (...), etc. ---- + if (prev.type == TokenType.KEYWORD && curr.type == TokenType.PAREN_OPEN) { + return determineKeywordParenSpacing(prev); + } + + // ---- IDENTIFIER before PAREN_OPEN: method call foo(...) ---- + if (prev.type == TokenType.IDENTIFIER && curr.type == TokenType.PAREN_OPEN) { + return settings.spaceBeforeMethodParens ? " " : ""; + } + + // ---- PAREN_CLOSE before BRACE_OPEN: ) { ---- + if (prev.type == TokenType.PAREN_CLOSE && curr.type == TokenType.BRACE_OPEN) { + return settings.spaceBeforeOpenBrace ? " " : ""; + } + + // ---- KEYWORD before BRACE_OPEN: else {, try {, finally { ---- + if (prev.type == TokenType.KEYWORD && curr.type == TokenType.BRACE_OPEN) { + return settings.spaceBeforeOpenBrace ? " " : ""; + } + + // ---- IDENTIFIER/NUMBER/OPERATOR(>) before BRACE_OPEN: class Foo {, enum Bar { ---- + if ((prev.type == TokenType.IDENTIFIER || prev.type == TokenType.NUMBER || + (prev.type == TokenType.OPERATOR && prev.value.equals(">"))) + && curr.type == TokenType.BRACE_OPEN) { + return settings.spaceBeforeOpenBrace ? " " : ""; + } + + // ---- PAREN_OPEN / PAREN_CLOSE: inner spacing ---- + if (prev.type == TokenType.PAREN_OPEN) { + if (curr.type == TokenType.PAREN_CLOSE) return ""; // empty () + return settings.spaceWithinParens ? " " : ""; + } + if (curr.type == TokenType.PAREN_CLOSE) { + return settings.spaceWithinParens ? " " : ""; + } + + // ---- BRACKET_OPEN / BRACKET_CLOSE: inner spacing ---- + if (prev.type == TokenType.BRACKET_OPEN) { + if (curr.type == TokenType.BRACKET_CLOSE) return ""; // empty [] + return settings.spaceWithinBrackets ? " " : ""; + } + if (curr.type == TokenType.BRACKET_CLOSE) { + return settings.spaceWithinBrackets ? " " : ""; + } + + // ---- COMMA spacing ---- + if (prev.type == TokenType.COMMA) { + return settings.spaceAfterComma ? " " : ""; + } + if (curr.type == TokenType.COMMA) { + return settings.spaceBeforeComma ? " " : ""; + } + + // ---- SEMICOLON spacing ---- + if (prev.type == TokenType.SEMICOLON) { + return settings.spaceAfterSemicolon ? " " : ""; + } + if (curr.type == TokenType.SEMICOLON) { + return settings.spaceBeforeSemicolon ? " " : ""; + } + + // ---- COLON spacing (ternary : always gets space, enhanced-for : always gets space, label : uses settings) ---- + if (prev.type == TokenType.COLON) { + if (isTernaryColon(allTokens, currIdx - 1)) return " "; + if (isEnhancedForLoopColon(allTokens, currIdx - 1)) return " "; + return settings.spaceAfterColon ? " " : ""; + } + if (curr.type == TokenType.COLON) { + if (isTernaryColon(allTokens, currIdx)) return " "; + if (isEnhancedForLoopColon(allTokens, currIdx)) return " "; + return settings.spaceBeforeColon ? " " : ""; + } + + // ---- IDENTIFIER/NUMBER next to BRACKET_OPEN: arr[0] no space ---- + if ((prev.type == TokenType.IDENTIFIER || prev.type == TokenType.NUMBER || + prev.type == TokenType.PAREN_CLOSE) && curr.type == TokenType.BRACKET_OPEN) { + return ""; + } + + // ---- BRACKET_CLOSE before IDENTIFIER/KEYWORD: int[] name, String[] args ---- + if (prev.type == TokenType.BRACKET_CLOSE && + (curr.type == TokenType.IDENTIFIER || curr.type == TokenType.KEYWORD || + curr.type == TokenType.NUMBER)) { + return " "; + } + + // ---- KEYWORD next to KEYWORD, IDENTIFIER, etc: must have space ---- + if (prev.type == TokenType.KEYWORD && + (curr.type == TokenType.KEYWORD || curr.type == TokenType.IDENTIFIER || + curr.type == TokenType.NUMBER)) { + return " "; + } + if (curr.type == TokenType.KEYWORD && + (prev.type == TokenType.KEYWORD || prev.type == TokenType.IDENTIFIER || + prev.type == TokenType.NUMBER || prev.type == TokenType.PAREN_CLOSE || + prev.type == TokenType.BRACE_CLOSE)) { + return " "; + } + + // ---- IDENTIFIER/NUMBER adjacency: need space ---- + if ((prev.type == TokenType.IDENTIFIER || prev.type == TokenType.NUMBER) && + (curr.type == TokenType.IDENTIFIER || curr.type == TokenType.NUMBER)) { + return " "; + } + + // ---- PAREN_CLOSE before IDENTIFIER/KEYWORD: ) instanceof, (int) x ---- + if (prev.type == TokenType.PAREN_CLOSE && + (curr.type == TokenType.IDENTIFIER || curr.type == TokenType.NUMBER)) { + return " "; + } + + // ---- BRACE_OPEN: space after { when followed by code ---- + if (prev.type == TokenType.BRACE_OPEN) { + if (curr.type == TokenType.BRACE_CLOSE) return ""; // empty {} + return settings.spaceWithinBraces ? " " : ""; + } + // ---- BRACE_CLOSE: space before } when preceded by code ---- + if (curr.type == TokenType.BRACE_CLOSE) { + return settings.spaceWithinBraces ? " " : ""; + } + + // Default: no space + return ""; + } + + /** + * Determine spacing around an operator token, considering whether it's + * unary, binary, assignment, comparison, logical, arithmetic, or bitwise. + */ + private String determineOperatorSpacing(Token prevPrev, Token prev, Token curr, + List allTokens, int currIdx) { + // When prev is the operator + if (prev.type == TokenType.OPERATOR) { + String op = prev.value; + + // ++ and -- : never add spaces around them (they bind tightly) + if (op.equals("++") || op.equals("--")) { + return settings.spaceAroundUnaryIncDec ? " " : ""; + } + + // :: method reference: no spaces + if (op.equals("::")) { + return ""; + } + + // Arrow operators -> and => always get spaces + if (op.equals("->") || op.equals("=>")) { + return " "; + } + + // Determine operator category and apply setting + if (isAssignmentOperator(op)) { + return settings.spaceAroundAssignment ? " " : ""; + } + if (isComparisonOperator(op)) { + if ((op.equals("<") || op.equals(">")) && isGenericContext(allTokens, currIdx - 1)) { + if (op.equals(">") && (curr.type == TokenType.IDENTIFIER || curr.type == TokenType.KEYWORD)) { + return " "; + } + return ""; } - String before = code.substring(start, pos); - // Common generic types or capital letter start (type name) - if (!before.isEmpty() && Character.isUpperCase(before.charAt(0))) { + return settings.spaceAroundComparison ? " " : ""; + } + if (isLogicalOperator(op)) { + return settings.spaceAroundLogical ? " " : ""; + } + // Unary ! and ~ — check before bitwise since ~ is in both categories + if (op.equals("!") || op.equals("~")) { + return settings.spaceAroundUnaryNot ? " " : ""; + } + if (isBitwiseOperator(op)) { + return settings.spaceAroundBitwise ? " " : ""; + } + if (isArithmeticOperator(op)) { + // Check unary context: was this operator unary? + // prevPrev is the token before this operator + if (isUnaryOperatorToken(op, null, prevPrev)) { + return ""; // No space after unary operator + } + return settings.spaceAroundArithmetic ? " " : ""; + } + // Ternary ? + if (op.equals("?")) { + return " "; + } + + // Default for unknown operators + return " "; + } + + // When curr is the operator + if (curr.type == TokenType.OPERATOR) { + String op = curr.value; + + // ++ and -- : never add spaces around them + if (op.equals("++") || op.equals("--")) { + return settings.spaceAroundUnaryIncDec ? " " : ""; + } + + // :: method reference: no spaces + if (op.equals("::")) { + return ""; + } + + if (op.equals("->") || op.equals("=>")) { + return " "; + } + + if (isAssignmentOperator(op)) { + return settings.spaceAroundAssignment ? " " : ""; + } + if (isComparisonOperator(op)) { + if ((op.equals("<") || op.equals(">")) && isGenericContext(allTokens, currIdx)) { + // Space before < when preceded by a keyword (e.g. public ) + if (op.equals("<") && prev.type == TokenType.KEYWORD) { + return " "; + } + return ""; + } + return settings.spaceAroundComparison ? " " : ""; + } + if (isLogicalOperator(op)) { + return settings.spaceAroundLogical ? " " : ""; + } + // Unary ! and ~ — check before bitwise since ~ is in both categories + if (op.equals("!") || op.equals("~")) { + return settings.spaceAroundUnaryNot ? " " : ""; + } + if (isBitwiseOperator(op)) { + return settings.spaceAroundBitwise ? " " : ""; + } + if (isArithmeticOperator(op)) { + // Check if unary + if (isUnaryOperatorToken(op, prevPrev, prev)) { + return ""; // No space before unary operator + } + return settings.spaceAroundArithmetic ? " " : ""; + } + // Ternary ? + if (op.equals("?")) { + return " "; + } + + return " "; + } + + return " "; + } + + /** + * Determine spacing between a keyword and a following open-paren. + * Applies settings for if/while/for/switch/catch keywords. + */ + private String determineKeywordParenSpacing(Token keyword) { + String kw = keyword.value; + if (kw.equals("if")) return settings.spaceBeforeIfParens ? " " : ""; + if (kw.equals("while")) return settings.spaceBeforeWhileParens ? " " : ""; + if (kw.equals("for")) return settings.spaceBeforeForParens ? " " : ""; + if (kw.equals("switch")) return settings.spaceBeforeSwitchParens ? " " : ""; + if (kw.equals("catch")) return settings.spaceBeforeCatchParens ? " " : ""; + // For other keywords followed by paren (e.g. return(...) — unusual but allowed) + return " "; + } + + // ---- Operator classification helpers ---- + + /** + * Check if a colon at the given index is part of a ternary expression (? :) + * by scanning backwards for a matching ? operator. + */ + private boolean isTernaryColon(List tokens, int colonIdx) { + for (int i = colonIdx - 1; i >= 0; i--) { + Token t = tokens.get(i); + if (t.type == TokenType.OPERATOR && t.value.equals("?")) return true; + if (t.type == TokenType.SEMICOLON || t.type == TokenType.BRACE_OPEN || + t.type == TokenType.BRACE_CLOSE) return false; + } + return false; + } + + /** + * Check if a colon at the given index is the separator in an enhanced for-loop + * ({@code for (Type var : collection)}) by scanning backwards from the colon + * for an opening paren preceded by the {@code for} keyword. + */ + private boolean isEnhancedForLoopColon(List tokens, int colonIdx) { + int depth = 0; + for (int i = colonIdx - 1; i >= 0; i--) { + Token t = tokens.get(i); + if (t.type == TokenType.PAREN_CLOSE) depth++; + else if (t.type == TokenType.PAREN_OPEN) { + if (depth > 0) { + depth--; + } else { + // Found the opening paren at our depth — check if preceded by 'for' + for (int j = i - 1; j >= 0; j--) { + if (tokens.get(j).type != TokenType.WHITESPACE) { + return tokens.get(j).type == TokenType.KEYWORD + && tokens.get(j).value.equals("for"); + } + } + return false; + } + } + // Stop at statement boundaries + if (t.type == TokenType.SEMICOLON || t.type == TokenType.BRACE_OPEN || + t.type == TokenType.BRACE_CLOSE) { + return false; + } + } + return false; + } + + private boolean isAssignmentOperator(String op) { + switch (op) { + case "=": case "+=": case "-=": case "*=": case "/=": case "%=": + case "&=": case "|=": case "^=": case "<<=": case ">>=": case ">>>=": + return true; + default: + return false; + } + } + + private boolean isComparisonOperator(String op) { + switch (op) { + case "==": case "!=": case "===": case "!==": + case "<": case ">": case "<=": case ">=": + return true; + default: + return false; + } + } + + private boolean isLogicalOperator(String op) { + return op.equals("&&") || op.equals("||"); + } + + private boolean isBitwiseOperator(String op) { + switch (op) { + case "&": case "|": case "^": case "~": + case "<<": case ">>": case ">>>": + return true; + default: + return false; + } + } + + private boolean isArithmeticOperator(String op) { + return op.equals("+") || op.equals("-") || op.equals("*") || + op.equals("/") || op.equals("%"); + } + + /** + * Determine if an operator is in unary context based on the previous token. + * Unary context: after operator, open paren/bracket/brace, comma, semicolon, + * colon, keyword, or at start of expression. + */ + private boolean isUnaryOperatorToken(String op, Token prevPrev, Token prevToken) { + // Only +, - can be unary in arithmetic context + if (!op.equals("+") && !op.equals("-")) return false; + + // If prevToken is null (start of expression) → unary + if (prevToken == null) return true; + + // After these token types → unary + switch (prevToken.type) { + case OPERATOR: + case PAREN_OPEN: + case BRACKET_OPEN: + case BRACE_OPEN: + case COMMA: + case SEMICOLON: + case COLON: + case KEYWORD: + return true; + default: + return false; + } + } + + /** + * Check if a < or > operator at the given token index is likely part of a + * generic type declaration (e.g., List). + * Uses surrounding token context rather than regex. + */ + private boolean isGenericContext(List tokens, int opIdx) { + if (opIdx < 0 || opIdx >= tokens.size()) return false; + + Token opToken = tokens.get(opIdx); + String op = opToken.value; + + if (op.equals("<")) { + // Check if preceded by an identifier that looks like a type (starts with uppercase) + // or by known generic-compatible keywords (var, let, const) + Token before = findPrevNonWhitespace(tokens, opIdx); + if (before != null) { + if (before.type == TokenType.IDENTIFIER && !before.value.isEmpty() && + Character.isUpperCase(before.value.charAt(0))) { + return true; + } + if (before.type == TokenType.KEYWORD && + (before.value.equals("var") || before.value.equals("let") || + before.value.equals("const"))) { return true; } } - // Check if there's a matching > + // Check if there's a matching > ahead int depth = 1; - for (int i = pos + 1; i < code.length() && depth > 0; i++) { - char c = code.charAt(i); - if (c == '<') depth++; - else if (c == '>') depth--; - else if (c == ';' || c == '{' || c == '}') break; // Not a generic + for (int i = opIdx + 1; i < tokens.size() && depth > 0; i++) { + Token t = tokens.get(i); + if (t.type == TokenType.WHITESPACE) continue; + if (t.type == TokenType.OPERATOR && t.value.equals("<")) depth++; + else if (t.type == TokenType.OPERATOR && t.value.equals(">")) depth--; + else if (t.type == TokenType.SEMICOLON || t.type == TokenType.BRACE_OPEN || + t.type == TokenType.BRACE_CLOSE) break; // Not a generic } return depth == 0; - } else { // '>' + } else if (op.equals(">")) { // Check if there's a matching < before int depth = 1; - for (int i = pos - 1; i >= 0 && depth > 0; i--) { - char c = code.charAt(i); - if (c == '>') depth++; - else if (c == '<') depth--; - else if (c == ';' || c == '{' || c == '}') break; + for (int i = opIdx - 1; i >= 0 && depth > 0; i--) { + Token t = tokens.get(i); + if (t.type == TokenType.WHITESPACE) continue; + if (t.type == TokenType.OPERATOR && t.value.equals(">")) depth++; + else if (t.type == TokenType.OPERATOR && t.value.equals("<")) depth--; + else if (t.type == TokenType.SEMICOLON || t.type == TokenType.BRACE_OPEN || + t.type == TokenType.BRACE_CLOSE) break; } return depth == 0; } + + return false; } /** - * Format arithmetic operators (+, -, *, /, %) + * Find the previous non-whitespace token before the given index. */ - private String formatArithmeticOperators(String code) { - StringBuilder result = new StringBuilder(); - int i = 0; - while (i < code.length()) { - char c = code.charAt(i); - char next = i + 1 < code.length() ? code.charAt(i + 1) : ' '; - char prev = i > 0 ? code.charAt(i - 1) : ' '; - - boolean isArithOp = c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; - - if (isArithOp) { - // Skip ++, --, +=, -=, *=, /=, %=, and unary +/- - if ((c == '+' && next == '+') || (c == '-' && next == '-') || - (c == '+' && prev == '+') || (c == '-' && prev == '-') || - next == '=') { - result.append(c); - } else if (isUnaryContext(code, i)) { - // Unary + or - (after operator, open paren, comma, etc.) - result.append(c); - } else { - // Binary operator - add spacing - if (result.length() > 0 && result.charAt(result.length() - 1) != ' ') { - result.append(' '); - } - result.append(c); - if (next != ' ' && next != '=' && !((c == '+' && next == '+') || (c == '-' && next == '-'))) { - result.append(' '); - } - } - } else { - result.append(c); + private Token findPrevNonWhitespace(List tokens, int idx) { + for (int i = idx - 1; i >= 0; i--) { + if (tokens.get(i).type != TokenType.WHITESPACE) { + return tokens.get(i); } - i++; } - return result.toString(); + return null; } - /** - * Check if position is in a unary context (operator is unary, not binary) - */ - private boolean isUnaryContext(String code, int pos) { - if (pos == 0) return true; - - // Look back for context - int i = pos - 1; - while (i >= 0 && code.charAt(i) == ' ') { - i--; - } - - if (i < 0) return true; - - char prev = code.charAt(i); - // Unary context after: ( [ { , ; = + - * / % < > & | ^ ? : - return prev == '(' || prev == '[' || prev == '{' || prev == ',' || - prev == ';' || prev == '=' || prev == '+' || prev == '-' || - prev == '*' || prev == '/' || prev == '%' || prev == '<' || - prev == '>' || prev == '&' || prev == '|' || prev == '^' || - prev == '?' || prev == ':' || prev == '!'; - } + // ==================== PHASE 3: RECONSTRUCTOR ==================== /** - * Format bitwise operators + * Reconstruct formatted code from a list of tokens. */ - private String formatBitwiseOperators(String code) { - String result = code; - - // Shift operators first - result = formatBinaryOp(result, ">>>", " >>> "); - result = formatBinaryOp(result, "<<", " << "); - result = formatBinaryOp(result, ">>", " >> "); - - // Single & | ^ (not && ||) + private String reconstruct(List tokens) { StringBuilder sb = new StringBuilder(); - int i = 0; - while (i < result.length()) { - char c = result.charAt(i); - char next = i + 1 < result.length() ? result.charAt(i + 1) : ' '; - char prev = i > 0 ? result.charAt(i - 1) : ' '; - - if ((c == '&' && next != '&' && prev != '&' && next != '=') || - (c == '|' && next != '|' && prev != '|' && next != '=') || - (c == '^' && next != '=')) { - if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { - sb.append(' '); - } - sb.append(c); - if (next != ' ') { - sb.append(' '); - } - } else { - sb.append(c); - } - i++; + for (Token t : tokens) { + sb.append(t.value); } - return sb.toString(); } - // ==================== BRACKET FORMATTING ==================== - /** - * Format bracket spacing - */ - private String formatBrackets(String code) { - String result = code; - - // Parentheses - if (settings.spaceWithinParens) { - result = result.replaceAll("\\(\\s*", "( "); - result = result.replaceAll("\\s*\\)", " )"); - } else { - result = result.replaceAll("\\(\\s+", "("); - result = result.replaceAll("\\s+\\)", ")"); - } - - // Square brackets - if (settings.spaceWithinBrackets) { - result = result.replaceAll("\\[\\s*", "[ "); - result = result.replaceAll("\\s*\\]", " ]"); - } else { - result = result.replaceAll("\\[\\s+", "["); - result = result.replaceAll("\\s+\\]", "]"); - } - - // Curly braces (for array initializers inline) - // Note: standalone braces for blocks are handled by indentation logic - - return result; - } - - // ==================== KEYWORD FORMATTING ==================== - - /** - * Format keyword spacing (if, while, for, etc.) - */ - private String formatKeywords(String code) { - String result = code; - - if (settings.spaceBeforeIfParens) { - result = result.replaceAll("\\bif\\s*\\(", "if ("); - } else { - result = result.replaceAll("\\bif\\s+\\(", "if("); - } - - if (settings.spaceBeforeWhileParens) { - result = result.replaceAll("\\bwhile\\s*\\(", "while ("); - } else { - result = result.replaceAll("\\bwhile\\s+\\(", "while("); - } - - if (settings.spaceBeforeForParens) { - result = result.replaceAll("\\bfor\\s*\\(", "for ("); - } else { - result = result.replaceAll("\\bfor\\s+\\(", "for("); - } - - if (settings.spaceBeforeSwitchParens) { - result = result.replaceAll("\\bswitch\\s*\\(", "switch ("); - } else { - result = result.replaceAll("\\bswitch\\s+\\(", "switch("); - } - - if (settings.spaceBeforeCatchParens) { - result = result.replaceAll("\\bcatch\\s*\\(", "catch ("); - } else { - result = result.replaceAll("\\bcatch\\s+\\(", "catch("); - } - - // Space before opening brace - if (settings.spaceBeforeOpenBrace) { - result = result.replaceAll("\\)\\s*\\{", ") {"); - } else { - result = result.replaceAll("\\)\\s+\\{", "){"); - } - - return result; - } - - // ==================== PUNCTUATION FORMATTING ==================== - - /** - * Format punctuation spacing (commas, semicolons, colons) - */ - private String formatPunctuation(String code) { - String result = code; - - // Commas - if (settings.spaceAfterComma && !settings.spaceBeforeComma) { - result = result.replaceAll("\\s*,\\s*", ", "); - } else if (settings.spaceAfterComma && settings.spaceBeforeComma) { - result = result.replaceAll("\\s*,\\s*", " , "); - } else if (!settings.spaceAfterComma && settings.spaceBeforeComma) { - result = result.replaceAll("\\s*,\\s*", " ,"); - } else { - result = result.replaceAll("\\s*,\\s*", ","); - } - - // Semicolons (but not in for loops - handle more carefully) - // This is tricky because for(;;) should be handled differently - // For now, just handle trailing semicolons - if (settings.trimTrailingWhitespace) { - result = result.replaceAll("\\s+;", ";"); - } - - return result; - } - - /** - * Trim trailing whitespace from a line + * Trim trailing whitespace from a line. */ private String trimTrailing(String line) { int end = line.length(); @@ -876,19 +1593,76 @@ public class FormatHelper { // ==================== STATIC UTILITIES ==================== /** - * Format code with default settings + * Format code with default settings. */ public static String formatCode(String code) { return new FormatHelper().format(code); } /** - * Format code with custom settings + * Format code with custom settings. */ public static String formatCode(String code, FormatSettings settings) { return new FormatHelper(settings).format(code); } + /** + * Sanitize clipboard text for paste into the script editor. + *

+ * This is a paste-only cleanup intended to prevent large trailing + * whitespace runs from causing misleading soft-wrap splits in the editor. + *

+ * Processing: + *

    + *
  • Normalizes line separators ({@code \r\n} and bare {@code \r}) to {@code \n}.
  • + *
  • For each line, strips trailing spaces/tabs only when the trailing + * whitespace run length is ≥ {@code trimThreshold}.
  • + *
  • Preserves all leading whitespace, interior spacing, and newline structure + * (trailing empty lines are kept).
  • + *
+ * The threshold avoids clobbering intentional minor trailing spaces while still + * removing the large padding blocks that confuse soft-wrap layout. + * + * @param clipboard the raw clipboard text (may be {@code null} or empty) + * @param trimThreshold minimum trailing whitespace run length to trigger trimming; + * runs shorter than this are left intact + * @return sanitized text, or the original reference if {@code null}/empty + */ + public static String sanitizeClipboard(String clipboard, int trimThreshold) { + if (clipboard == null || clipboard.isEmpty()) { + return clipboard; + } + + // Normalize line separators: \r\n -> \n, then bare \r -> \n + String normalized = clipboard.replace("\r\n", "\n").replace("\r", "\n"); + + String[] lines = normalized.split("\n", -1); + StringBuilder result = new StringBuilder(normalized.length()); + + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + + // Measure trailing whitespace run length + int end = line.length(); + while (end > 0 && (line.charAt(end - 1) == ' ' || line.charAt(end - 1) == '\t')) { + end--; + } + int trailingLen = line.length() - end; + + if (trailingLen >= trimThreshold) { + result.append(line, 0, end); + } else { + result.append(line); + } + + if (i < lines.length - 1) { + result.append('\n'); + } + } + + return result.toString(); + } + // ==================== LINE WRAPPING ==================== /** @@ -903,7 +1677,10 @@ public class FormatHelper { if (text == null || text.isEmpty()) return text; int width = maxWidth > 0 ? maxWidth : settings.maxLineLength; - String[] lines = text.split("\n", -1); + + String joined = format(joinContinuationLines(text)); + + String[] lines = joined.split("\n", -1); StringBuilder result = new StringBuilder(); for (int i = 0; i < lines.length; i++) { @@ -932,7 +1709,93 @@ public class FormatHelper { } /** - * Get visual length of a line (tabs count as 4 spaces) + * Join continuation lines back onto their parent line so they can be + * re-evaluated and re-wrapped at the current target width. + *

+ * A "continuation line" is one whose trimmed content starts with an operator, + * dot, comma, {@code ?}, or {@code :} — i.e. the wrapping markers used by + * {@link #wrapCodeContent}. Only code continuation lines are joined; comment + * lines ({@code //}, {@code *}) and lines inside lambda/block bodies (deeper + * indent than expected) are left alone. + */ + private String joinContinuationLines(String text) { + String[] lines = text.split("\n", -1); + List out = new ArrayList<>(); + + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + String trimmed = line.trim(); + + if (trimmed.isEmpty() + || trimmed.startsWith("//") + || trimmed.startsWith("/*") + || trimmed.startsWith("*")) { + out.add(line); + continue; + } + + boolean shouldJoin = false; + int parentIdx = -1; + + if ((isContinuationLine(trimmed) || startsWithDeclarationKeyword(trimmed)) + && !out.isEmpty()) { + int idx = out.size() - 1; + while (idx >= 0 && out.get(idx).trim().isEmpty()) idx--; + if (idx >= 0) { + String parentTrimmed = out.get(idx).trim(); + char last = parentTrimmed.isEmpty() ? 0 : parentTrimmed.charAt(parentTrimmed.length() - 1); + if (last != '{' && last != '}' && last != ';') { + shouldJoin = true; + parentIdx = idx; + } + } + } + + if (!shouldJoin && !out.isEmpty()) { + int idx = out.size() - 1; + while (idx >= 0 && out.get(idx).trim().isEmpty()) idx--; + if (idx >= 0) { + String parentTrimmed = out.get(idx).trim(); + if (!parentTrimmed.isEmpty()) { + char last = parentTrimmed.charAt(parentTrimmed.length() - 1); + if (last == '&' || last == '|' || last == '<' || last == '+' + || last == '-' || last == '?' || last == ',' || last == '>') { + shouldJoin = true; + parentIdx = idx; + } + } + } + } + + if (shouldJoin) { + out.set(parentIdx, trimTrailing(out.get(parentIdx)) + " " + trimmed); + continue; + } + + out.add(line); + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < out.size(); i++) { + sb.append(out.get(i)); + if (i < out.size() - 1) sb.append("\n"); + } + return sb.toString(); + } + + private boolean startsWithDeclarationKeyword(String trimmed) { + for (String kw : DECLARATION_BREAK_KEYWORDS) { + if (trimmed.startsWith(kw) + && (trimmed.length() == kw.length() + || !Character.isJavaIdentifierPart(trimmed.charAt(kw.length())))) { + return true; + } + } + return false; + } + + /** + * Get visual length of a line (tabs count as 4 spaces). */ private int getVisualLength(String line) { int len = 0; @@ -947,7 +1810,7 @@ public class FormatHelper { } /** - * Extract leading indentation from a line + * Extract leading indentation from a line. */ private String extractIndent(String line) { int i = 0; @@ -958,7 +1821,7 @@ public class FormatHelper { } /** - * Wrap a single-line comment (// style) + * Wrap a single-line comment (// style). */ private String wrapCommentLine(String line, int maxWidth) { if (!settings.wrapComments) return line; @@ -1005,7 +1868,7 @@ public class FormatHelper { } /** - * Wrap a block comment line (* style) + * Wrap a block comment line (* style). */ private String wrapBlockCommentLine(String line, int maxWidth) { if (!settings.wrapComments) return line; @@ -1081,21 +1944,191 @@ public class FormatHelper { } /** - * Wrap a code line at appropriate break points + * Find the start position of an inline line comment ({@code //}) in a code line, + * correctly skipping {@code //} inside string literals and block comments. + * + * @return index of the {@code //} in content, or -1 if no inline comment exists + */ + private int findInlineCommentStart(String content) { + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < content.length(); i++) { + char c = content.charAt(i); + char prev = i > 0 ? content.charAt(i - 1) : 0; + + if ((c == '"' || c == '\'') && prev != '\\') { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + } + + if (inString) continue; + + // Skip block comments + if (c == '/' && i + 1 < content.length() && content.charAt(i + 1) == '*') { + int endBlock = content.indexOf("*/", i + 2); + if (endBlock >= 0) { + i = endBlock + 1; + continue; + } + } + + if (c == '/' && i + 1 < content.length() && content.charAt(i + 1) == '/') { + return i; + } + } + + return -1; + } + + /** + * Word-wrap a comment string across multiple {@code //} continuation lines. + * Each continuation line uses the given prefix (indent + "// "). + * + * @param commentText the text after {@code //} (already trimmed) + * @param prefix indent + "// " for each continuation line + * @param maxWidth maximum line width + * @param firstLineCapacity chars available on the first output line (-1 to start fresh) + * @return the wrapped comment lines joined with newlines + */ + private String wordWrapComment(String commentText, String prefix, int maxWidth, + int firstLineCapacity) { + if (commentText.isEmpty()) return "//"; + + String[] words = commentText.split("\\s+"); + int prefixLen = getVisualLength(prefix); + int contentWidth = maxWidth - prefixLen; + if (contentWidth <= 10) { + return "// " + commentText; + } + + StringBuilder result = new StringBuilder(); + boolean onFirstLine = (firstLineCapacity > 0); + int capacity = onFirstLine ? firstLineCapacity : contentWidth; + int lineLen = 0; + + if (!onFirstLine) { + result.append(prefix); + } else { + result.append("// "); + lineLen = 3; + } + + for (int i = 0; i < words.length; i++) { + String word = words[i]; + int wordLen = word.length(); + + if (lineLen + (lineLen > (onFirstLine ? 3 : 0) ? 1 : 0) + wordLen > capacity && lineLen > 0) { + result.append("\n").append(prefix); + lineLen = 0; + capacity = contentWidth; + onFirstLine = false; + } + + if (lineLen > 0) { + result.append(" "); + lineLen++; + } + + result.append(word); + lineLen += wordLen; + } + + return result.toString(); + } + + /** + * Wrap a code line at appropriate break points, with intelligent inline comment handling. + *

+ * If the line has a trailing {@code // comment}, the comment is extracted first. + * The code portion is wrapped normally, then the comment is reattached: + *

    + *
  • If code + comment fit within maxWidth → keep inline
  • + *
  • If only the code fits → comment moves to its own indented line
  • + *
  • If the comment is very long → it gets word-wrapped across multiple lines
  • + *
*/ private String wrapCodeLine(String line, int maxWidth) { String indent = extractIndent(line); String content = line.substring(indent.length()); - // Additional indent for wrapped lines - String wrapIndent = indent + spaces(settings.wrapIndentSpaces); + // --- Phase 1: Detect and extract inline comment --- + int commentStart = findInlineCommentStart(content); + String codePart = content; + String commentPart = null; + + if (commentStart >= 0) { + codePart = content.substring(0, commentStart); + commentPart = content.substring(commentStart); + // Trim trailing space from code part + while (!codePart.isEmpty() && codePart.charAt(codePart.length() - 1) == ' ') { + codePart = codePart.substring(0, codePart.length() - 1); + } + } + + // --- Phase 2: Wrap the code part (without the comment) --- + String wrappedCode = wrapCodeContent(codePart, indent, maxWidth); + + // --- Phase 3: Reattach the comment intelligently --- + if (commentPart == null) { + return wrappedCode; + } + + // Find the last line of the wrapped code to measure available space + int lastNewline = wrappedCode.lastIndexOf('\n'); + String lastLine = (lastNewline >= 0) ? wrappedCode.substring(lastNewline + 1) : wrappedCode; + int lastLineLen = getVisualLength(lastLine); + + // Measure the comment: " // comment text" + int commentLen = 1 + getVisualLength(commentPart); // +1 for the space separator + + // Strategy A: Comment fits inline on the last line + if (lastLineLen + commentLen <= maxWidth) { + return wrappedCode + " " + commentPart; + } + + // Strategy B: Comment on its own line(s), indented to match original code level + String commentIndent = indent; + String commentText = commentPart.startsWith("//") ? + commentPart.substring(2).trim() : commentPart; + String commentPrefix = commentIndent + "// "; + int availableWidth = maxWidth - getVisualLength(commentPrefix); + + if (availableWidth > 10 && getVisualLength(commentText) > availableWidth) { + // Word-wrap the long comment + String wrappedComment = wordWrapComment(commentText, commentPrefix, maxWidth, -1); + return wrappedCode + "\n" + wrappedComment; + } else { + return wrappedCode + "\n" + commentPrefix + commentText; + } + } + + /** + * Core code wrapping logic (extracted from old wrapCodeLine, operates on code without comments). + */ + private String wrapCodeContent(String content, String indent, int maxWidth) { + if (settings.wrapMethodArguments) { + String argWrapped = tryArgumentAwareWrap(content, indent, maxWidth); + if (argWrapped != null) { + return argWrapped; + } + } + + String wrapIndent = indent + spaces(settings.wrapIndentSpaces); + String fullLine = indent + content; + + if (getVisualLength(fullLine) <= maxWidth) { + return fullLine; + } - // Find break points - positions where we can break the line List breakPoints = findBreakPoints(content); if (breakPoints.isEmpty()) { - // No good break points, just return as-is - return line; + return fullLine; } StringBuilder result = new StringBuilder(); @@ -1103,41 +2136,28 @@ public class FormatHelper { int currentLen = getVisualLength(indent); int lastBreak = 0; - boolean isFirstLine = true; for (BreakPoint bp : breakPoints) { int segmentEnd = bp.position; String segment = content.substring(lastBreak, segmentEnd); int segmentLen = getVisualLength(segment); - // Check if adding this segment would exceed max width - if (currentLen + segmentLen > maxWidth && !isFirstLine) { - // Break here + if (currentLen + segmentLen > maxWidth && lastBreak > 0) { result.append("\n").append(wrapIndent); currentLen = getVisualLength(wrapIndent); - isFirstLine = false; - - // Trim leading space from continuation if any segment = trimLeading(segment); - } else if (currentLen + segmentLen > maxWidth && isFirstLine && lastBreak > 0) { - // Even first segment is too long after indent, break before it - result.append("\n").append(wrapIndent); - currentLen = getVisualLength(wrapIndent); - isFirstLine = false; } result.append(segment); currentLen += getVisualLength(segment); lastBreak = segmentEnd; - isFirstLine = false; } - // Append remaining content if (lastBreak < content.length()) { String remaining = content.substring(lastBreak); int remLen = getVisualLength(remaining); - if (currentLen + remLen > maxWidth && !isFirstLine) { + if (currentLen + remLen > maxWidth && lastBreak > 0) { result.append("\n").append(wrapIndent); remaining = trimLeading(remaining); } @@ -1149,8 +2169,188 @@ public class FormatHelper { } /** - * Trim leading whitespace (Java 8 compatible) + * Try argument-aware wrapping for method/constructor calls. + * When a call like {@code new Foo(arg1, arg2, arg3)} exceeds maxWidth, + * break after the opening paren, put each argument on its own line, + * and close paren on its own line: + *
+     * new Foo(
+     *     arg1,
+     *     arg2,
+     *     arg3
+     * )
+     * 
+ * + * @return the wrapped string, or {@code null} if this content doesn't + * qualify for argument-aware wrapping */ + private String tryArgumentAwareWrap(String content, String indent, int maxWidth) { + String fullLine = indent + content; + if (getVisualLength(fullLine) <= maxWidth) { + return null; + } + + int callParenIdx = findOutermostCallParen(content); + if (callParenIdx < 0) { + return null; + } + + int matchingClose = findMatchingClose(content, callParenIdx); + if (matchingClose < 0 || matchingClose >= content.length()) { + return null; + } + + String prefix = content.substring(0, callParenIdx + 1); + String argsBody = content.substring(callParenIdx + 1, matchingClose); + String suffix = content.substring(matchingClose); + + List args = splitArguments(argsBody); + if (args.size() < 2) { + return null; + } + + String argIndent = indent + spaces(settings.wrapIndentSpaces); + String closeIndent = indent; + + StringBuilder result = new StringBuilder(); + result.append(indent).append(prefix).append("\n"); + + for (int i = 0; i < args.size(); i++) { + String arg = args.get(i).trim(); + if (arg.isEmpty()) continue; + + result.append(argIndent).append(arg); + if (i < args.size() - 1) { + result.append(","); + } + result.append("\n"); + } + + result.append(closeIndent).append(suffix); + + String wrapped = result.toString(); + if (getVisualLength(indent + prefix) <= maxWidth) { + return wrapped; + } + + return wrapped; + } + + /** + * Find the opening paren of the outermost method/constructor call + * that should trigger argument-aware wrapping. + * Looks for patterns: {@code identifier(}, {@code new Type(}, {@code .method(} + * + * @return index of the '(' or -1 if no suitable call found + */ + private int findOutermostCallParen(String content) { + int bestIdx = -1; + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < content.length(); i++) { + char c = content.charAt(i); + char prev = i > 0 ? content.charAt(i - 1) : ' '; + + if ((c == '"' || c == '\'') && prev != '\\') { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + } + if (inString) continue; + + if (c == '(') { + if (i > 0 && (Character.isJavaIdentifierPart(content.charAt(i - 1)) || + content.charAt(i - 1) == '>')) { + bestIdx = i; + break; + } + } + } + + return bestIdx; + } + + private int findMatchingClose(String content, int openIdx) { + int depth = 1; + boolean inString = false; + char stringChar = 0; + + for (int i = openIdx + 1; i < content.length(); i++) { + char c = content.charAt(i); + char prev = i > 0 ? content.charAt(i - 1) : ' '; + + if ((c == '"' || c == '\'') && prev != '\\') { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + } + if (inString) continue; + + if (c == '(') depth++; + else if (c == ')') { + depth--; + if (depth == 0) return i; + } + } + + return -1; + } + + /** + * Split argument body by top-level commas, preserving nested parens, + * brackets, braces, strings, and lambda bodies. + */ + private List splitArguments(String argsBody) { + List args = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + int depth = 0; + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < argsBody.length(); i++) { + char c = argsBody.charAt(i); + char prev = i > 0 ? argsBody.charAt(i - 1) : ' '; + + if ((c == '"' || c == '\'') && prev != '\\') { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + } + + if (inString) { + current.append(c); + continue; + } + + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') depth--; + + if (c == ',' && depth == 0) { + args.add(current.toString()); + current = new StringBuilder(); + continue; + } + + current.append(c); + } + + if (current.length() > 0) { + args.add(current.toString()); + } + + return args; + } + private String trimLeading(String s) { int start = 0; while (start < s.length() && Character.isWhitespace(s.charAt(start))) { @@ -1160,7 +2360,7 @@ public class FormatHelper { } /** - * A potential line break point + * A potential line break point. */ private static class BreakPoint { int position; // Position in string (after this char) @@ -1173,8 +2373,12 @@ public class FormatHelper { } } + private static final String[] DECLARATION_BREAK_KEYWORDS = { + "extends", "implements", "throws", "permits" + }; + /** - * Find good positions to break a line + * Find good positions to break a line. */ private List findBreakPoints(String content) { List points = new ArrayList<>(); @@ -1218,20 +2422,51 @@ public class FormatHelper { points.add(new BreakPoint(i + 1, 1 + depth)); } + // Arrow operators (-> and =>) are atomic — never break inside them + if ((c == '-' || c == '=') && i + 1 < content.length() && content.charAt(i + 1) == '>') { + i++; + continue; + } + if (settings.wrapAfterOperator) { - // After binary operators if ((c == '+' || c == '-') && i > 0 && i < content.length() - 1) { char next = content.charAt(i + 1); if (prev != '(' && prev != '[' && prev != ',' && prev != '=' && - next != '+' && next != '-' && next != '=') { + next != '+' && next != '-' && next != '=' && next != '>') { points.add(new BreakPoint(i + 1, 3 + depth)); } } if (c == '&' && i + 1 < content.length() && content.charAt(i + 1) == '&') { points.add(new BreakPoint(i + 2, 2 + depth)); + i++; // skip second & + continue; } if (c == '|' && i + 1 < content.length() && content.charAt(i + 1) == '|') { points.add(new BreakPoint(i + 2, 2 + depth)); + i++; // skip second | + continue; + } + // Single & as type intersection operator (e.g. T extends A & B) + if (c == '&' && i > 0 && i < content.length() - 1 + && content.charAt(i + 1) != '&' && content.charAt(i + 1) != '=') { + points.add(new BreakPoint(i + 1, 3 + depth)); + } + if (c == '?' && depth == 0 && i > 0 && i < content.length() - 1) { + points.add(new BreakPoint(i, 2)); + } + if (c == ':' && depth == 0 && i > 0 && i < content.length() - 1) { + if (prev != ':' && (i + 1 >= content.length() || content.charAt(i + 1) != ':')) { + points.add(new BreakPoint(i, 2)); + } + } + if (c == '=' && depth == 0 && i > 0 && i < content.length() - 1) { + char next = content.charAt(i + 1); + if (prev != '=' && prev != '!' && prev != '<' && prev != '>' && + prev != '+' && prev != '-' && prev != '*' && prev != '/' && + prev != '%' && prev != '&' && prev != '|' && prev != '^' && + next != '=' && next != '>') { + points.add(new BreakPoint(i + 1, 4 + depth)); + } } } @@ -1240,9 +2475,28 @@ public class FormatHelper { points.add(new BreakPoint(i, 2 + depth)); } - // After opening brace - if (c == '{' && i + 1 < content.length()) { - points.add(new BreakPoint(i + 1, 1)); + // After opening brace (even when last char — allows break before {) + if (c == '{') { + if (i + 1 < content.length()) { + points.add(new BreakPoint(i + 1, 1)); + } + // Break before { so the brace can move to its own line + if (i > 0) { + points.add(new BreakPoint(i, 2)); + } + } + + // Break before declaration keywords (extends, implements, throws, permits) + if (c == ' ' && i + 1 < content.length() && Character.isLetter(content.charAt(i + 1))) { + for (String kw : DECLARATION_BREAK_KEYWORDS) { + if (i + 1 + kw.length() <= content.length() + && content.substring(i + 1, i + 1 + kw.length()).equals(kw) + && (i + 1 + kw.length() >= content.length() + || !Character.isJavaIdentifierPart(content.charAt(i + 1 + kw.length())))) { + points.add(new BreakPoint(i + 1, 2)); + break; + } + } } } @@ -1253,7 +2507,7 @@ public class FormatHelper { } /** - * Create a string of n spaces + * Create a string of n spaces. */ private String spaces(int n) { StringBuilder sb = new StringBuilder(); @@ -1264,7 +2518,7 @@ public class FormatHelper { } /** - * Format and wrap code in one step + * Format and wrap code in one step. */ public String formatAndWrap(String text, int maxWidth) { String formatted = format(text); diff --git a/src/main/java/noppes/npcs/client/gui/util/script/IndentHelper.java b/src/main/java/noppes/npcs/client/gui/util/script/IndentHelper.java index 12a5567ad..30a63dfe2 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/IndentHelper.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/IndentHelper.java @@ -157,9 +157,9 @@ public class IndentHelper { * * @param text The text to format * @param cursorPosition Current cursor position - * @param viewportWidth Viewport width for line wrapping (0 = no wrapping) + * @param maxLineLength Maximum line length in characters for wrapping (0 = no wrapping) */ - public static FormatResult formatText(String text, int cursorPosition, int viewportWidth) { + public static FormatResult formatText(String text, int cursorPosition, int maxLineLength) { // First pass: fix indentation String indented = formatIndentation(text, cursorPosition); @@ -167,19 +167,17 @@ public class IndentHelper { FormatHelper helper = new FormatHelper(); FormatHelper.FormatSettings settings = helper.getSettings(); - // Enable wrapping if viewport width is provided - if (viewportWidth > 0) { + // Enable wrapping if max line length is provided + if (maxLineLength > 0) { settings.wrapLongLines = true; settings.wrapComments = true; - // Use 75% of viewport width as max line length for some margin - int charWidth = 6; // Approximate character width - settings.maxLineLength = Math.max(60, (int) (viewportWidth * 0.8f / charWidth)); + settings.maxLineLength = maxLineLength; } String formatted = helper.format(indented); // Apply wrapping if enabled - if (viewportWidth > 0 && settings.wrapLongLines) { + if (maxLineLength > 0 && settings.wrapLongLines) { formatted = helper.wrapLines(formatted, settings.maxLineLength); } diff --git a/src/main/java/noppes/npcs/client/gui/util/script/JavaTextContainer.java b/src/main/java/noppes/npcs/client/gui/util/script/JavaTextContainer.java index 4f3470b0f..0744ed3cc 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/JavaTextContainer.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/JavaTextContainer.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +@Deprecated public class JavaTextContainer extends TextContainer { public static final Pattern MODIFIER = Pattern.compile( @@ -574,7 +575,7 @@ public class JavaTextContainer extends TextContainer { for (ImportEntry ie : importEntries) { // Highlight the 'import' keyword - marks.add(new Mark(ie.importKwStart, ie.importKwEnd, TokenType.IMPORT_KEYWORD)); + marks.add(new Mark(ie.importKwStart, ie.importKwEnd, TokenType.KEYWORD)); String fullPath = ie.fullPath; int pathStart = ie.pathStart; @@ -835,7 +836,7 @@ public class JavaTextContainer extends TextContainer { Matcher m = CLASS_DECL.matcher(text); List excluded = MethodBlock.getExcludedRanges(text); while (m.find()) { - marks.add(new Mark(m.start(1), m.end(1), TokenType.CLASS_KEYWORD)); + marks.add(new Mark(m.start(1), m.end(1), TokenType.KEYWORD)); int nameStart = m.start(2); int nameEnd = m.end(2); @@ -867,7 +868,7 @@ public class JavaTextContainer extends TextContainer { // Highlight general keywords collectPatternMatches(marks, KEYWORD, TokenType.KEYWORD); - collectPatternMatches(marks, MODIFIER, TokenType.MODIFIER); + collectPatternMatches(marks, MODIFIER, TokenType.KEYWORD); collectTypeDeclarations(marks); collectPatternMatches(marks, NEW_TYPE, TokenType.NEW_TYPE, 1); @@ -1210,10 +1211,7 @@ public class JavaTextContainer extends TextContainer { public enum TokenType { COMMENT('7', 130), STRING('5', 120), - CLASS_KEYWORD('c', 115), - IMPORT_KEYWORD('6', 110), KEYWORD('c', 100), - MODIFIER('6', 90), NEW_TYPE('d', 80), IMPORTED_CLASS('3', 75), //imported classes used in code INTERFACE_DECL('b', 85), diff --git a/src/main/java/noppes/npcs/client/gui/util/script/RenameRefactorHandler.java b/src/main/java/noppes/npcs/client/gui/util/script/RenameRefactorHandler.java index 81c346f8f..15a71a900 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/RenameRefactorHandler.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/RenameRefactorHandler.java @@ -2,6 +2,12 @@ package noppes.npcs.client.gui.util.script; import net.minecraft.client.gui.GuiScreen; import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParamTag; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; import org.lwjgl.input.Keyboard; import java.util.ArrayList; @@ -11,7 +17,7 @@ import java.util.regex.Pattern; /** * Handles IntelliJ-like rename refactoring with scope-aware renaming. - *

+ * * Features: * - Scope detection: local variables rename only within their block, global fields rename everywhere * - Visual feedback: primary occurrence has white border, others just highlighted @@ -32,7 +38,11 @@ public class RenameRefactorHandler { private int primaryOccurrenceEnd = -1; private List allOccurrences = new ArrayList<>(); private ScopeInfo scope = null; - + + // For parameter renaming: track containing method to find JSDoc + private boolean isParameterRename = false; + private MethodInfo containingMethod = null; + // For global scope, track positions that have local shadowing (to exclude them) private List localShadowedPositions = new ArrayList<>(); @@ -82,32 +92,11 @@ public class RenameRefactorHandler { void scrollToPosition(int pos); - JavaTextContainer getContainer(); + ScriptTextContainer getContainer(); int getViewportWidth(); // For determining if clicks are in rename box } - /** - * Scope information for a variable - */ - public static class ScopeInfo { - public final int startOffset; - public final int endOffset; - public final boolean isGlobal; - public final String scopeType; // "global", "method", "block" - - public ScopeInfo(int start, int end, boolean isGlobal, String type) { - this.startOffset = start; - this.endOffset = end; - this.isGlobal = isGlobal; - this.scopeType = type; - } - - public boolean containsPosition(int pos) { - return pos >= startOffset && pos < endOffset; - } - } - public void setCallback(RenameCallback callback) { this.callback = callback; } @@ -140,29 +129,62 @@ public class RenameRefactorHandler { initialWord = text.substring(wordBounds[0], wordBounds[1]); // Remember for undo originalWord = initialWord; currentWord = initialWord; - + // Determine scope for this identifier - MUST check if local shadows global scope = determineScope(text, wordBounds[0], originalWord, callback.getContainer()); - + + // Track if this is a parameter rename by checking if position is in any method's parameter declaration + isParameterRename = false; + containingMethod = null; + + ScriptTextContainer container = callback.getContainer(); + if (container != null && container.getDocument() != null) { + ScriptDocument document = container.getDocument(); + List methods = document.getAllMethods(); + + // Check if the word at cursor position is a parameter of any method + // A rename is a parameter rename if: + // 1. The word matches a parameter name + // 2. The cursor is within that method's declaration or body + for (MethodInfo method : methods) { + // Check if cursor is within this method's range + int methodStart = method.getFullDeclarationOffset(); + int methodEnd = method.getBodyEnd(); + if (methodStart < 0 || methodEnd < 0) continue; // External method + + if (wordBounds[0] >= methodStart && wordBounds[0] <= methodEnd) { + // Check if the word matches any parameter of this method + for (FieldInfo param : method.getParameters()) { + if (param.getName().equals(originalWord)) { + isParameterRename = true; + containingMethod = method; + break; + } + } + if (isParameterRename) break; + } + } + } + // If global scope, find all positions where local variables shadow this name localShadowedPositions.clear(); if (scope != null && scope.isGlobal) { findLocalShadowedPositions(text, originalWord); } - // Find all occurrences within scope + // Find all occurrences within scope (including JSDoc if it's a parameter) findOccurrences(text, originalWord); if (allOccurrences.isEmpty()) return false; active = true; - + // Set selection to full word (uses GuiScriptTextArea's selection) primaryOccurrenceStart = wordBounds[0]; primaryOccurrenceEnd = wordBounds[1]; callback.getSelectionState().setSelection(wordBounds[0], wordBounds[1]); - // callback.setCursorPosition(wordBounds[1]); + // callback.setCursorPosition(wordBounds[1]); callback.getSelectionState().markActivity(); return true; @@ -206,7 +228,7 @@ public class RenameRefactorHandler { // During live editing we used setTextWithoutUndo to avoid creating intermediate // undo entries; pushing the original snapshot here gives a single predictable // undo step back to the pre-rename state. - if (originalText != null && !originalText.isEmpty()) + if (originalText != null && !originalText.isEmpty()) callback.pushUndoState(originalText, originalCursorPos); // Calculate cursor position relative to primary occurrence @@ -230,13 +252,14 @@ public class RenameRefactorHandler { allOccurrences.clear(); localShadowedPositions.clear(); scope = null; + isParameterRename = false; + containingMethod = null; originalText = ""; originalCursorPos = 0; } /** * Handle keyboard input during rename - * * @return true if input was consumed */ public boolean keyTyped(char c, int keyCode) { @@ -264,7 +287,7 @@ public class RenameRefactorHandler { // Get selection state SelectionState sel = callback.getSelectionState(); boolean hasSelection = sel.hasSelection(); - + // Calculate cursor position within the word int cursorInWord = callback.getCursorPosition() - primaryOccurrenceStart; cursorInWord = Math.max(0, Math.min(cursorInWord, currentWord.length())); @@ -315,7 +338,7 @@ public class RenameRefactorHandler { sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart); callback.setCursorPosition(primaryOccurrenceStart); } - + // Left arrow if (keyCode == Keyboard.KEY_LEFT) { if (cursorInWord > 0) { @@ -354,7 +377,7 @@ public class RenameRefactorHandler { // Ctrl+A - select all (select the whole word) if (keyCode == Keyboard.KEY_A && - Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) { + Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) { sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart + currentWord.length()); callback.setCursorPosition(primaryOccurrenceStart + currentWord.length()); sel.markActivity(); @@ -536,23 +559,86 @@ public class RenameRefactorHandler { allOccurrences.add(new int[]{start, end}); } } + + // If this is a parameter rename, also look for JSDoc @param occurrences + if (isParameterRename && containingMethod != null) { + findJSDocParamOccurrences(text, word); + } } - + + /** + * Find JSDoc @param occurrences for a parameter name. + * Uses the JSDocInfo stored in the MethodInfo to locate the JSDoc comment, + * then searches for the parameter name pattern in the current text. + */ + private void findJSDocParamOccurrences(String text, String paramName) { + if (containingMethod == null) return; + + // Get the JSDocInfo from the method to verify it has a @param for our parameter + JSDocInfo jsDocInfo = containingMethod.getJSDocInfo(); + if (jsDocInfo == null) return; + + // Check that this parameter has a JSDoc @param tag (using initial word to find the tag definition) + JSDocParamTag paramTag = jsDocInfo.getParamTag(initialWord); + if (paramTag == null) return; + + // Get the approximate JSDoc location from the original document + int originalJsDocStart = jsDocInfo.getStartOffset(); + int originalJsDocEnd = jsDocInfo.getEndOffset(); + if (originalJsDocStart < 0 || originalJsDocEnd < 0) return; + + // Calculate how much positions have shifted due to renames before the JSDoc + // Count occurrences that are currently in the text before the original JSDoc start + int shiftBeforeJsDoc = 0; + int lengthDiff = paramName.length() - initialWord.length(); + + // The occurrences we've already found (code occurrences) - count how many are before the JSDoc + for (int[] occ : allOccurrences) { + // Map current position back to approximate original position + int approxOriginalPos = occ[0] - shiftBeforeJsDoc; + if (approxOriginalPos < originalJsDocStart) { + shiftBeforeJsDoc += lengthDiff; + } + } + + // Now search for the @param pattern in the current text around where the JSDoc should be + int adjustedJsDocStart = originalJsDocStart + shiftBeforeJsDoc; + int adjustedJsDocEnd = originalJsDocEnd + shiftBeforeJsDoc; + + // Clamp to text bounds + adjustedJsDocStart = Math.max(0, adjustedJsDocStart); + adjustedJsDocEnd = Math.min(text.length(), adjustedJsDocEnd + 50); // Add some buffer for expanded text + + if (adjustedJsDocStart >= adjustedJsDocEnd) return; + + String jsDocRegion = text.substring(adjustedJsDocStart, adjustedJsDocEnd); + + // Search for @param {Type} paramName or @param paramName pattern + Pattern pattern = Pattern.compile("@param\\s+(?:\\{[^}]*\\}\\s+)?(" + Pattern.quote(paramName) + ")(?:\\s|$|-)"); + Matcher m = pattern.matcher(jsDocRegion); + + while (m.find()) { + int paramNameStart = adjustedJsDocStart + m.start(1); + int paramNameEnd = adjustedJsDocStart + m.end(1); + allOccurrences.add(new int[]{paramNameStart, paramNameEnd}); + } + } + /** * Find all positions where local variables with the same name shadow the global variable. * This populates localShadowedPositions with ranges where local declarations exist. */ private void findLocalShadowedPositions(String text, String varName) { localShadowedPositions.clear(); - + List methods = MethodBlock.collectMethodBlocks(text); List excluded = MethodBlock.getExcludedRanges(text); - + for (MethodBlock method : methods) { // Check if this method has a local variable or parameter with the same name boolean hasLocalDecl = method.localVariables.contains(varName); boolean hasParamDecl = isParameterInMethod(text, varName, method); - + if (hasLocalDecl || hasParamDecl) { // Find where the local/param scope starts int scopeStart; @@ -564,18 +650,18 @@ public class RenameRefactorHandler { scopeStart = findLocalDeclarationPosition(text, varName, method); if (scopeStart < 0) scopeStart = method.startOffset; } - + // Find all occurrences of varName within this method's shadowed range Pattern pattern = Pattern.compile("\\b" + Pattern.quote(varName) + "\\b"); Matcher m = pattern.matcher(text); - + while (m.find()) { int pos = m.start(); - + // Skip if in string or comment if (isInExcludedRange(pos, excluded)) continue; - + // Check if within the shadowed scope of this method if (pos >= scopeStart && pos < method.endOffset) { localShadowedPositions.add(new int[]{m.start(), m.end()}); @@ -584,7 +670,7 @@ public class RenameRefactorHandler { } } } - + /** * Check if a position is within a locally shadowed range */ @@ -595,13 +681,13 @@ public class RenameRefactorHandler { } return false; } - + /** * Check if varName is a parameter in the method */ private boolean isParameterInMethod(String text, String varName, MethodBlock method) { String methodHeader = text.substring(method.startOffset, - Math.min(method.startOffset + 500, method.endOffset)); + Math.min(method.startOffset + 500, method.endOffset)); int parenStart = methodHeader.indexOf('('); int parenEnd = methodHeader.indexOf(')'); if (parenStart >= 0 && parenEnd > parenStart) { @@ -687,7 +773,7 @@ public class RenameRefactorHandler { // Cursor is inside a method // Check if it's a method parameter first String methodHeader = text.substring(containingMethod.startOffset, - Math.min(containingMethod.startOffset + 500, containingMethod.endOffset)); + Math.min(containingMethod.startOffset + 500, containingMethod.endOffset)); int parenStart = methodHeader.indexOf('('); int parenEnd = methodHeader.indexOf(')'); if (parenStart >= 0 && parenEnd > parenStart) { @@ -861,9 +947,9 @@ public class RenameRefactorHandler { public boolean isWordFullySelected() { if (callback == null) return false; SelectionState selection = callback.getSelectionState(); - return selection.hasSelection() && - selection.getStartSelection() == primaryOccurrenceStart && - selection.getEndSelection() == primaryOccurrenceEnd; + return selection.hasSelection() && + selection.getStartSelection() == primaryOccurrenceStart && + selection.getEndSelection() == primaryOccurrenceEnd; } /** @@ -884,7 +970,7 @@ public class RenameRefactorHandler { public boolean handleClick(int clickPosInText) { if (!active || callback == null) return false; - + return false; } diff --git a/src/main/java/noppes/npcs/client/gui/util/script/ScopeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/ScopeInfo.java new file mode 100644 index 000000000..f06454597 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/ScopeInfo.java @@ -0,0 +1,26 @@ +package noppes.npcs.client.gui.util.script; + +/** + * Scope information for a variable + */ +public class ScopeInfo { + public final int startOffset; + public final int endOffset; + public final boolean isGlobal; + public final String scopeType; // "global", "method", "block" + + public ScopeInfo(int start, int end, boolean isGlobal, String type) { + this.startOffset = start; + this.endOffset = end; + this.isGlobal = isGlobal; + this.scopeType = type; + } + + public boolean containsPosition(int pos) { + return pos >= startOffset && pos < endOffset; + } + + public boolean isWithin(ScopeInfo other) { + return this.startOffset >= other.startOffset && this.endOffset <= other.endOffset; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/ScrollState.java b/src/main/java/noppes/npcs/client/gui/util/script/ScrollState.java index 4d71a6b62..ecbe29c35 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/ScrollState.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/ScrollState.java @@ -21,12 +21,12 @@ public class ScrollState { private int scrollbarDragOffset = 0; // Whether currently dragging the scrollbar private boolean clickScrolling = false; - + // Animation parameters private static final double TAU = 0.1; // Time constant (~55ms feels snappy) - private static final double SNAP_THRESHOLD = 0.01; // Snap to target when this close + private static final double SNAP_THRESHOLD = 0.01; // Snap to target when this close (increased to avoid microstutters) private static final double MAX_DT = 0.05; // Max delta time for stability - + /** * Reset scroll state to initial values */ @@ -37,7 +37,7 @@ public class ScrollState { scrolledLine = 0; lastScrollTime = System.currentTimeMillis(); } - + /** * Initialize scroll position if not already initialized */ @@ -47,19 +47,18 @@ public class ScrollState { lastScrollTime = System.currentTimeMillis(); } } - + /** * Update scroll animation. Call once per frame. - * * @param maxScroll Maximum valid scroll position */ public void update(int maxScroll) { long nowMs = System.currentTimeMillis(); double dt = Math.min(MAX_DT, (nowMs - lastScrollTime) / 1000.0); lastScrollTime = nowMs; - + double dist = targetScroll - scrollPos; - + // Snap to target if close enough if (Math.abs(dist) < SNAP_THRESHOLD) { scrollPos = targetScroll; @@ -70,21 +69,21 @@ public class ScrollState { double prev = scrollPos; scrollPos += dist * alpha; scrollVelocity = (scrollPos - prev) / (dt > 0 ? dt : 1e-6); - + // Clamp overshoot if ((dist > 0 && scrollPos > targetScroll) || (dist < 0 && scrollPos < targetScroll)) { scrollPos = targetScroll; scrollVelocity = 0.0; } } - + // Keep in bounds clampToBounds(maxScroll); - + // Update integer line for rendering scrolledLine = Math.max(0, Math.min((int) Math.floor(scrollPos), maxScroll)); } - + /** * Clamp scroll position to valid bounds */ @@ -95,37 +94,35 @@ public class ScrollState { if (targetScroll > maxScroll) targetScroll = maxScroll; scrolledLine = Math.max(0, Math.min(scrolledLine, maxScroll)); } - + /** * Apply mouse wheel scroll - * * @param wheelDelta Positive = scroll up, negative = scroll down - * @param maxScroll Maximum valid scroll position + * @param maxScroll Maximum valid scroll position */ public void applyWheelScroll(int wheelDelta, int maxScroll) { double sign = Math.copySign(1, wheelDelta); targetScroll -= sign * 2.0; // 2 lines per wheel tick clampToBounds(maxScroll); } - + /** * Set target scroll directly (for scrollbar dragging) */ public void setTargetScroll(double target, int maxScroll) { targetScroll = Math.max(0, Math.min(target, maxScroll)); } - + /** * Scroll to make a specific line visible - * - * @param lineIdx Line index to make visible + * @param lineIdx Line index to make visible * @param visibleLines Number of visible lines in viewport - * @param maxScroll Maximum scroll position + * @param maxScroll Maximum scroll position */ public void scrollToLine(int lineIdx, int visibleLines, int maxScroll) { int firstVisible = scrolledLine; int lastFullyVisible = scrolledLine + visibleLines; - + if (lineIdx < firstVisible) { // Line is above viewport - scroll up targetScroll = lineIdx; @@ -135,66 +132,41 @@ public class ScrollState { } // If line is visible, don't change scroll } - + // Getters - public double getScrollPos() { - return scrollPos; - } + public double getScrollPos() { return scrollPos; } + public double getTargetScroll() { return targetScroll; } - public double getTargetScroll() { - return targetScroll; - } - - /** - * @return First visible line - **/ + /** @return First visible line **/ public int getScrolledLine() { return scrolledLine; } - - public double getScrollVelocity() { - return scrollVelocity; - } - - public boolean isClickScrolling() { - return clickScrolling; - } - - public int getScrollbarDragOffset() { - return scrollbarDragOffset; - } - + public double getScrollVelocity() { return scrollVelocity; } + public boolean isClickScrolling() { return clickScrolling; } + public int getScrollbarDragOffset() { return scrollbarDragOffset; } + /** * Get fractional offset for sub-pixel rendering */ public double getFractionalOffset() { return scrollPos - scrolledLine; } - + // Setters for scrollbar interaction - public void setClickScrolling(boolean scrolling) { - this.clickScrolling = scrolling; - } - - public void setScrollbarDragOffset(int offset) { - this.scrollbarDragOffset = offset; - } - - public void setScrolledLine(int line) { - this.scrolledLine = line; - } + public void setClickScrolling(boolean scrolling) { this.clickScrolling = scrolling; } + public void setScrollbarDragOffset(int offset) { this.scrollbarDragOffset = offset; } + public void setScrolledLine(int line) { this.scrolledLine = line; } /** * Handle scrollbar dragging interaction. This encapsulates the logic that was * previously in the GUI class for handling thumb clicks/drags. - * - * @param yMouse current mouse Y coordinate - * @param areaX GUI area X (unused but kept for parity) - * @param areaY GUI area Y (top of text area) - * @param areaHeight height of the scroll track area + * @param yMouse current mouse Y coordinate + * @param areaX GUI area X (unused but kept for parity) + * @param areaY GUI area Y (top of text area) + * @param areaHeight height of the scroll track area * @param visibleLines number of visible lines in viewport - * @param linesCount total number of lines - * @param maxScroll maximum allowed scroll value + * @param linesCount total number of lines + * @param maxScroll maximum allowed scroll value */ public void handleClickScrolling(int yMouse, int areaX, int areaY, int areaHeight, int visibleLines, int linesCount, int maxScroll) { // Keep dragging while mouse button is down @@ -238,4 +210,4 @@ public class ScrollState { int thumbTop = (int) (areaY + 1f * getScrollPos() / linesCountD * (areaHeight - 4)) + 1; setScrollbarDragOffset(yMouse - thumbTop); } -} +} \ No newline at end of file diff --git a/src/main/java/noppes/npcs/client/gui/util/script/SearchReplaceBar.java b/src/main/java/noppes/npcs/client/gui/util/script/SearchReplaceBar.java index 32e835aaf..5e783d227 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/SearchReplaceBar.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/SearchReplaceBar.java @@ -5,6 +5,7 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.GuiScriptTextArea.UndoData; import noppes.npcs.client.gui.util.GuiUtil; import noppes.npcs.client.gui.util.key.OverlayKeyPresetViewer; @@ -35,6 +36,7 @@ public class SearchReplaceBar { // ==================== DIMENSIONS ==================== private int x, y, width; + public GuiNPCInterface ownerGui; private int barHeight = 24; private int replaceBarHeight = 22; private int textFieldWidth = 150; @@ -538,7 +540,7 @@ public class SearchReplaceBar { } GL11.glEnable(GL11.GL_SCISSOR_TEST); - GuiUtil.setScissorClip(fieldX + 2, fieldY, fieldWidth - 4, fieldHeight); + GuiUtil.setScissorClip(fieldX + 2, fieldY, fieldWidth - 4, fieldHeight, ownerGui); // Draw selection highlight @@ -604,7 +606,7 @@ public class SearchReplaceBar { } GL11.glEnable(GL11.GL_SCISSOR_TEST); - GuiUtil.setScissorClip(fieldX + 2, fieldY, fieldWidth - 4, fieldHeight); + GuiUtil.setScissorClip(fieldX + 2, fieldY, fieldWidth - 4, fieldHeight, ownerGui); { // Draw selection highlight diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteItem.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteItem.java new file mode 100644 index 000000000..6d2f5ff42 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteItem.java @@ -0,0 +1,859 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import noppes.npcs.client.gui.util.script.autocomplete.weighter.CompletionWeigher; +import noppes.npcs.client.gui.util.script.autocomplete.weighter.WeigherChain; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSFieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSMethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticField; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticMethod; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticParameter; + +/** + * Represents a single autocomplete suggestion. + * Unified representation for both Java and JavaScript completions. + */ +public class AutocompleteItem implements Comparable { + + /** + * The kind of completion item. + */ + public enum Kind { + ENUM_CONSTANT(-1), // Enum constant value (highest priority for enums) + METHOD(0), // Method or function + FIELD(10), // Field or property + PARAMETER(19), // Local variable or parameter + VARIABLE(20), // Local variable or parameter + CLASS(30), // Class or interface type + ENUM(40), // Enum type + KEYWORD(60), // Language keyword + SNIPPET(70); // Code snippet + + private final int priority; + + Kind(int priority) { + this.priority = priority; + } + + public int getPriority() { + return priority; + } + } + + private final String name; // Display name (e.g., "getPlayer" or "getPlayer(UUID id)" for methods) + private final String searchName; // Name to search against (just the identifier, e.g., "getPlayer") + private final String insertText; // Text to insert (e.g., "getPlayer()") + private final Kind kind; // Type of completion + private final String typeLabel; // Type label (e.g., "IPlayer", "void") + private final TypeInfo typeInfo; // TypeInfo for the typeLabel + private final String signature; // Full signature for methods + private final String documentation; // Documentation/description + private final Object sourceData; // Original source (MethodInfo, FieldInfo, etc.) + private final boolean deprecated; // Whether this item is deprecated + + // Import tracking + private final boolean requiresImport; // Whether selecting this item requires adding an import + private final String importPath; // Full path for import (e.g., "net.minecraft.client.Minecraft") + + // Inheritance tracking (for JS types) + private final int inheritanceDepth; // Depth in inheritance tree (0 = child, 1 = parent, 2 = grandparent, etc.) + + // Match scoring + private int matchScore = 0; // How well this matches the query + private int[] matchIndices; // Indices of matched characters for highlighting + + private int color = -1; + + private AutocompleteItem(String name, String searchName, String insertText, Kind kind, String typeLabel, + TypeInfo typeLabelTypeInfo, String signature, String documentation, Object sourceData, + boolean deprecated, boolean requiresImport, String importPath, int inheritanceDepth) { + this.name = name; + this.searchName = searchName != null ? searchName : name; // Default to name if not provided + this.insertText = insertText; + this.kind = kind; + this.typeLabel = typeLabel; + this.typeInfo = typeLabelTypeInfo; + this.signature = signature; + this.documentation = documentation; + this.sourceData = sourceData; + this.deprecated = deprecated; + this.requiresImport = requiresImport; + this.importPath = importPath; + this.inheritanceDepth = inheritanceDepth; + } + + // ==================== FACTORY METHODS ==================== + + /** + * Create from a Java MethodInfo. + */ + public static AutocompleteItem fromMethod(MethodInfo method) { + return fromMethod(method, false); + } + + /** + * Create from a Java MethodInfo, optionally for method reference context. + * @param method The method info + * @param forMethodReference If true, insert text will NOT include parentheses + */ + public static AutocompleteItem fromMethod(MethodInfo method, boolean forMethodReference) { + String name = method.getName(); + StringBuilder insertText = new StringBuilder(name); + + // For method references, don't add () since it's ::methodName not ::methodName() + if (!forMethodReference) { + insertText.append("("); + // Add placeholders for parameters if any + if (method.getParameterCount() > 0) { + // Just add () - user will fill in params + } + insertText.append(")"); + } + + String returnType = method.getReturnType() != null ? + getName(method.getReturnType()) : "void"; + + String signature = buildMethodSignature(method); + + // Build display name with parameters like "read(byte[] b)" + StringBuilder displayName = new StringBuilder(name); + displayName.append("("); + for (int i = 0; i < method.getParameterCount(); i++) { + if (i > 0) displayName.append(", "); + FieldInfo param = method.getParameters().get(i); + String paramType = param.getTypeInfo() != null ? + getName(param.getTypeInfo()) : "?"; + displayName.append(paramType); + if (param.isVarArg()) displayName.append("..."); + if (param.getName() != null && !param.getName().isEmpty()) { + displayName.append(" ").append(param.getName()); + } + } + displayName.append(")"); + + return new AutocompleteItem( + displayName.toString(), + name, // Search against just the method name, not the params + insertText.toString(), + Kind.METHOD, + returnType, + method.getReturnType(), // TypeInfo for return type + signature, + method.getDocumentation(), + method, + method.getJavaMethod() != null && method.getJavaMethod().isAnnotationPresent(Deprecated.class), + false, // Methods don't require imports + null, + -1 // Java methods don't use inheritance depth sorting + ); + } + + /** + * Create from a Java FieldInfo. + */ + public static AutocompleteItem fromField(FieldInfo field) { + String typeLabel = field.getTypeInfo() != null ? + getName(field.getTypeInfo()) : "?"; + + Kind kind; + switch (field.getScope()) { + case PARAMETER: + kind = Kind.PARAMETER; + break; + case LOCAL: + kind = Kind.VARIABLE; + break; + case ENUM_CONSTANT: + kind = Kind.ENUM_CONSTANT; + break; + default: + kind = Kind.FIELD; + } + + return new AutocompleteItem( + field.getName(), + field.getName(), // searchName same as display name for fields + field.getName(), + kind, + typeLabel, + field.getTypeInfo(), // TypeInfo for field type + typeLabel + " " + field.getName(), + null, + field, + false, + false, // Fields don't require imports + null, + -1// Java fields don't use inheritance depth sorting + ); + } + + /** + * Create from a Java TypeInfo. + */ + public static AutocompleteItem fromType(TypeInfo type) { + Kind kind; + switch (type.getKind()) { + case INTERFACE: + kind = Kind.CLASS; + break; + case ENUM: + kind = Kind.ENUM; + break; + default: + kind = Kind.CLASS; + } + String name = getName(type); + return new AutocompleteItem( + name, + name, // searchName same as display name for types + name, + kind, + type.getPackageName(), + type, // TypeInfo for package name + type.getFullName(), + null, + type, + false, + false, // Will be overridden for unimported types + null, + -1 // Java types don't use inheritance depth sorting + ); + } + + /** + * Create from a JavaScript JSMethodInfo. + */ + public static AutocompleteItem fromJSMethod(JSMethodInfo method) { + return fromJSMethod(method, null, 0, false); + } + + /** + * Create from a JavaScript JSMethodInfo with inheritance depth. + * @param method The method info + * @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.) + */ + public static AutocompleteItem fromJSMethod(JSMethodInfo method, int inheritanceDepth) { + return fromJSMethod(method, null, inheritanceDepth, false); + } + + /** + * Create from a JavaScript JSMethodInfo with type parameter resolution for display. + * @param method The method info + * @param contextType The TypeInfo context for resolving type parameters (e.g., IPlayer to resolve T → EntityPlayerMP) + * @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.) + */ + public static AutocompleteItem fromJSMethod(JSMethodInfo method, TypeInfo contextType, int inheritanceDepth) { + return fromJSMethod(method, contextType, inheritanceDepth, false); + } + + /** + * Create from a JavaScript JSMethodInfo with type parameter resolution for display. + * @param method The method info + * @param contextType The TypeInfo context for resolving type parameters (e.g., IPlayer to resolve T → EntityPlayerMP) + * @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.) + * @param forMethodReference If true, insert text will NOT include parentheses + */ + public static AutocompleteItem fromJSMethod(JSMethodInfo method, TypeInfo contextType, int inheritanceDepth, boolean forMethodReference) { + String name = method.getName(); + StringBuilder insertText = new StringBuilder(name); + + // For method references, don't add () since it's ::methodName not ::methodName() + if (!forMethodReference) { + insertText.append("("); + insertText.append(")"); + } + + // Build display name with resolved parameter types + StringBuilder displayName = new StringBuilder(name); + displayName.append("("); + for (int i = 0; i < method.getParameters().size(); i++) { + if (i > 0) displayName.append(", "); + JSMethodInfo.JSParameterInfo param = method.getParameters().get(i); + + // Use resolved type with full generic display + TypeInfo paramType = param.getResolvedType(contextType); + String paramTypeName = paramType.isResolved() ? paramType.getDisplayName() : param.getType(); + if (param.isVarArg()) paramTypeName = paramTypeName + "..."; + displayName.append(paramTypeName).append(" ").append(param.getName()); + } + displayName.append(")"); + + // Get return type using the new method with full generic display + TypeInfo returnTypeInfo = method.getResolvedReturnType(contextType); + String returnType = returnTypeInfo.isResolved() ? returnTypeInfo.getDisplayName() : method.getReturnType(); + + return new AutocompleteItem( + displayName.toString(), + name, // Search against just the method name + insertText.toString(), + Kind.METHOD, + returnType, + returnTypeInfo, // TypeInfo for return type + method.getSignature(), + method.getDocumentation(), + method, + false, + false, + null, + inheritanceDepth + ); + } + + /** + * Create from a JavaScript JSFieldInfo. + */ + public static AutocompleteItem fromJSField(JSFieldInfo field) { + return fromJSField(field, null, 0); + } + + /** + * Create from a JavaScript JSFieldInfo with inheritance depth. + * @param field The field info + * @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.) + */ + public static AutocompleteItem fromJSField(JSFieldInfo field, int inheritanceDepth) { + return fromJSField(field, null, inheritanceDepth); + } + + /** + * Create from a JavaScript JSFieldInfo with type parameter resolution for display. + * @param field The field info + * @param contextType The TypeInfo context for resolving type parameters + * @param inheritanceDepth Depth in inheritance tree (0 = child, 1 = parent, etc.) + */ + public static AutocompleteItem fromJSField(JSFieldInfo field, TypeInfo contextType, int inheritanceDepth) { + // Get field type using the new method with full generic display + TypeInfo fieldTypeInfo = field.getResolvedType(contextType); + String fieldType = fieldTypeInfo.isResolved() ? fieldTypeInfo.getDisplayName() : field.getType(); + + return new AutocompleteItem( + field.getName(), + field.getName(), // searchName same as display name + field.getName(), + Kind.FIELD, + fieldType, + fieldTypeInfo, // TypeInfo for field type + field.toString(), + field.getDocumentation(), + field, + false, + false, + null, + inheritanceDepth + ); + } + + /** + * Create a keyword item. + */ + public static AutocompleteItem keyword(String keyword) { + return new AutocompleteItem( + keyword, + keyword, // searchName same as display name + keyword, + Kind.KEYWORD, + "keyword", + null, // TypeInfo for keyword + null, + null, + null, + false, + false, + null, + -1 // Keywords don't use inheritance depth sorting + ); + } + + /** + * Create from a synthetic method (e.g., Nashorn built-in like Java.type). + */ + public static AutocompleteItem fromSyntheticMethod( + SyntheticMethod method, + TypeInfo containingType) { + return fromSyntheticMethod(method, containingType, false); + } + + /** + * Create from a synthetic method (e.g., Nashorn built-in like Java.type). + * @param method The synthetic method + * @param containingType The containing type info + * @param forMethodReference If true, insert text will NOT include parentheses + */ + public static AutocompleteItem fromSyntheticMethod( + SyntheticMethod method, + TypeInfo containingType, + boolean forMethodReference) { + String name = method.name; + StringBuilder insertText = new StringBuilder(name); + + // For method references, don't add () since it's ::methodName not ::methodName() + if (!forMethodReference) { + insertText.append("("); + insertText.append(")"); + } + + // Build display name with parameters - use simple names for types + StringBuilder displayName = new StringBuilder(name); + displayName.append("("); + for (int i = 0; i < method.parameters.size(); i++) { + if (i > 0) displayName.append(", "); + SyntheticParameter param = + method.parameters.get(i); + // Use simple name for display (e.g., "Class" instead of "java.lang.Class") + String simpleTypeName = getSimpleTypeName(param.typeName); + displayName.append(simpleTypeName).append(" ").append(param.name); + } + displayName.append(")"); + + // Use simple name for return type display too + String simpleReturnType = getSimpleTypeName(method.returnType); + + return new AutocompleteItem( + displayName.toString(), + name, // Search against just the method name + insertText.toString(), + Kind.METHOD, + simpleReturnType, + method.getReturnTypeInfo(), // TypeInfo for return type - would need to resolve from TypeResolver + method.getSignature(), + method.documentation, + method, + false, + false, + null, + 0 // Synthetic types are at depth 0 + ); + } + + /** + * Get simple name from a fully-qualified type name. + */ + private static String getSimpleTypeName(String typeName) { + if (typeName == null) return "void"; + int lastDot = typeName.lastIndexOf('.'); + return lastDot >= 0 ? typeName.substring(lastDot + 1) : typeName; + } + + /** + * Create from a synthetic field (e.g., Nashorn built-in). + */ + public static AutocompleteItem fromSyntheticField( + SyntheticField field) { + return new AutocompleteItem( + field.name, + field.name, // searchName same as display name + field.name, + Kind.FIELD, + field.typeName, + field.getTypeInfo(), // TypeInfo for field type - would need to resolve from TypeResolver + field.typeName + " " + field.name, + field.documentation, + field, + false, + false, + null, + 0 // Synthetic types are at depth 0 + ); + } + + // ==================== HELPER METHODS ==================== + + private static String buildMethodSignature(MethodInfo method) { + StringBuilder sb = new StringBuilder(); + String returnType = method.getReturnType() != null ? + getName(method.getReturnType()) : "void"; + sb.append(returnType).append(" ").append(method.getName()).append("("); + + for (int i = 0; i < method.getParameterCount(); i++) { + if (i > 0) sb.append(", "); + FieldInfo param = method.getParameters().get(i); + String paramType = param.getTypeInfo() != null ? + getName(param.getTypeInfo()) : "?"; + sb.append(paramType); + if (param.isVarArg()) sb.append("..."); + sb.append(" ").append(param.getName()); + } + + sb.append(")"); + return sb.toString(); + } + + // ==================== MATCHING ==================== + + /** + * Calculate fuzzy match score against a query string. + * Returns -1 if no match, or a positive score (higher = better match). + * + * @param query The search query + * @param requirePrefix If true, only match items that start with the query (no fuzzy/contains matching) + */ + public int calculateMatchScore(String query, boolean requirePrefix) { + if (query == null || query.isEmpty()) { + matchScore = 100; // Everything matches empty query + matchIndices = new int[0]; + return matchScore; + } + + String lowerName = searchName.toLowerCase(); + String lowerQuery = query.toLowerCase(); + + // Exact prefix match is best + if (lowerName.startsWith(lowerQuery)) { + matchScore = 1000 - query.length(); // Shorter prefixes score higher + matchIndices = new int[query.length()]; + for (int i = 0; i < query.length(); i++) { + matchIndices[i] = i; + } + return matchScore; + } + + // If requirePrefix is true, stop here - no fuzzy/substring matching + if (requirePrefix) { + matchScore = -1; + matchIndices = new int[0]; + return matchScore; + } + + // Exact substring match + int subIndex = lowerName.indexOf(lowerQuery); + if (subIndex >= 0) { + matchScore = 500 - subIndex; // Earlier substrings score higher + matchIndices = new int[query.length()]; + for (int i = 0; i < query.length(); i++) { + matchIndices[i] = subIndex + i; + } + return matchScore; + } + + // Fuzzy match - characters must appear in order + int[] indices = new int[query.length()]; + int nameIdx = 0; + int queryIdx = 0; + int gaps = 0; + int consecutiveBonus = 0; + int lastMatchIdx = -2; + + while (queryIdx < query.length() && nameIdx < searchName.length()) { + if (Character.toLowerCase(searchName.charAt(nameIdx)) == lowerQuery.charAt(queryIdx)) { + indices[queryIdx] = nameIdx; + + // Bonus for consecutive matches + if (nameIdx == lastMatchIdx + 1) { + consecutiveBonus += 10; + } + + // Bonus for matching at word boundaries (camelCase) + if (nameIdx == 0 || !Character.isLetterOrDigit(searchName.charAt(nameIdx - 1)) || + (Character.isUpperCase(searchName.charAt(nameIdx)) && nameIdx > 0 && + Character.isLowerCase(searchName.charAt(nameIdx - 1)))) { + consecutiveBonus += 20; + } + + lastMatchIdx = nameIdx; + queryIdx++; + } else { + gaps++; + } + nameIdx++; + } + + if (queryIdx < query.length()) { + // Didn't match all characters + matchScore = -1; + matchIndices = null; + return -1; + } + + matchScore = 100 + consecutiveBonus - gaps; + matchIndices = indices; + return matchScore; + } + + /** + * Backward compatibility overload - defaults to fuzzy matching (no prefix requirement). + */ + public int calculateMatchScore(String query) { + return calculateMatchScore(query, false); + } + + /** + * @deprecated Use {@link WeigherChain} instead. This method is no longer + * called by the autocomplete system. Score boosts are now handled by + * individual {@link CompletionWeigher} implementations that return + * independent comparable values per scoring dimension. + */ + @Deprecated + public void addScoreBoost(int boost) { + this.matchScore += boost; + } + + // ==================== GETTERS ==================== + + public String getName() { return name; } + public String getSearchName() { return searchName; } + public String getInsertText() { return insertText; } + public Kind getKind() { return kind; } + public String getTypeLabel() { return typeLabel; } + public TypeInfo getTypeInfo() { return typeInfo; } + public String getSignature() { return signature; } + public String getDocumentation() { return documentation; } + public Object getSourceData() { return sourceData; } + public boolean isDeprecated() { return deprecated; } + public boolean requiresImport() { return requiresImport; } + public String getImportPath() { return importPath; } + public int getMatchScore() { return matchScore; } + public int[] getMatchIndices() { return matchIndices; } + public int getInheritanceDepth() { return inheritanceDepth; } + public int getColor() { return color; }; + public AutocompleteItem setColor(int col){ this.color = col;return this; } + /** + * Get the display name for a type, including generic arguments. + * Uses the unified getDisplayName() method which handles: + * - Simple types: "String" + * - Parameterized types: "List", "Map" + * - Nested generics: "List>" + * - JS types with namespace: "IPlayerEvent.InteractEvent" + */ + public static String getName(TypeInfo type) { + return type.getDisplayName(); + } + + public int getParameterCount() { + if (sourceData instanceof MethodInfo) { + return ((MethodInfo) sourceData).getParameterCount(); + } else if (sourceData instanceof JSMethodInfo) { + return ((JSMethodInfo) sourceData).getParameterCount(); + } else if (sourceData instanceof SyntheticMethod) { + return ((SyntheticMethod) sourceData).parameters.size(); + } + return 0; + } + + /** + * Check if this item represents a static member. + */ + public boolean isStatic() { + if (sourceData instanceof MethodInfo) { + return ((MethodInfo) sourceData).isStatic(); + } else if (sourceData instanceof FieldInfo) { + return ((FieldInfo) sourceData).isStatic(); + } else if (sourceData instanceof JSMethodInfo) { + return ((JSMethodInfo) sourceData).isStatic(); + } else if (sourceData instanceof JSFieldInfo) { + return ((JSFieldInfo) sourceData).isStatic(); + } + return false; + } + + /** + * Check if this item represents a final member. + */ + public boolean isFinal() { + if (sourceData instanceof MethodInfo) { + return ((MethodInfo) sourceData).isFinal(); + } else if (sourceData instanceof FieldInfo) { + return ((FieldInfo) sourceData).isFinal(); + }else if (sourceData instanceof JSFieldInfo) { + return ((JSFieldInfo) sourceData).isReadonly(); + } + return false; + } + + /** + * Check if this method is inherited from Object class and NOT overridden. + * These methods should be deprioritized in autocomplete. + */ + public boolean isInheritedObjectMethod() { + if (kind != Kind.METHOD) return false; + + if (sourceData instanceof MethodInfo) { + MethodInfo methodInfo = (MethodInfo) sourceData; + java.lang.reflect.Method javaMethod = methodInfo.getJavaMethod(); + if (javaMethod != null) { + return Object.class.equals(javaMethod.getDeclaringClass()); + } + TypeInfo containingType = methodInfo.getContainingType(); + return containingType != null + && containingType.getFullName().equals("java.lang.Object") + && !methodInfo.isStatic() + && !methodInfo.isOverride(); + } + + if (sourceData instanceof JSMethodInfo) { + JSMethodInfo jsMethod = (JSMethodInfo) sourceData; + JSTypeInfo definingType = jsMethod.getContainingType(); + return definingType != null + && "Object".equals(definingType.getSimpleName()) + && !jsMethod.isStatic() + && inheritanceDepth > 0; + } + + return false; + } + + /** + * Get icon identifier based on kind. + */ + public String getIconId() { + switch (kind) { + case METHOD: return "m"; + case FIELD: return "f"; + case VARIABLE: return "v"; + case PARAMETER: return "p"; + case CLASS: return "C"; + case ENUM: return "E"; + case ENUM_CONSTANT: return "e"; + case KEYWORD: return "k"; + case SNIPPET: return "s"; + default: return "?"; + } + } + + /** + * Get color for the kind icon. + */ + public int getIconColor() { + switch (kind) { + case METHOD: return 0xFFB877DB; // Purple for methods + case FIELD: return 0xFF79C0FF; // Blue for fields + case VARIABLE: return 0xFF7EE787; // Green for variables + case PARAMETER: return 0XFFFF00FF; // Green for variables + case CLASS: return 0xFFFFA657; // Orange for classes + case ENUM: return 0xFFFFD866; // Yellow for enums + case ENUM_CONSTANT: return 0xFFFFD866; + case KEYWORD: return 0xFFFF7B72; // Red for keywords + case SNIPPET: return 0xFFCCCCCC; // Gray for snippets + default: return 0xFFCCCCCC; + } + } + + /** + * Note: No longer used for autocomplete sorting (weigher chain used instead). + * Kept for backward compatibility and collections sorting. + */ + @Override + public int compareTo(AutocompleteItem other) { + // First by match score (descending) - this includes all penalties and boosts + if (this.matchScore != other.matchScore) { + return other.matchScore - this.matchScore; + } + + // Then by kind priority + if (this.kind.getPriority() != other.kind.getPriority()) { + return this.kind.getPriority() - other.kind.getPriority(); + } + + // For JS types, prioritize by inheritance depth (child class members first) + // Only apply if both items have valid inheritance depth (>= 0) + if (this.inheritanceDepth >= 0 && other.inheritanceDepth >= 0) { + if (this.inheritanceDepth != other.inheritanceDepth) { + return this.inheritanceDepth - other.inheritanceDepth; // Lower depth = closer to child = higher priority + } + } + + // Finally alphabetically + return this.name.compareToIgnoreCase(other.name); + } + + @Override + public String toString() { + return name + " (" + kind + ")"; + } + + // ==================== BUILDER ==================== + + /** + * Builder for creating AutocompleteItem instances without source data. + */ + public static class Builder { + private String name; + private String searchName; + private String insertText; + private Kind kind = Kind.FIELD; + private String typeLabel = ""; + private TypeInfo typeInfo; + private String signature; + private String documentation; + private Object sourceData; + private boolean deprecated = false; + private boolean requiresImport = false; + private String importPath = null; + private int color = -1; + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder searchName(String searchName) { + this.searchName = searchName; + return this; + } + + public Builder insertText(String insertText) { + this.insertText = insertText; + return this; + } + + public Builder kind(Kind kind) { + this.kind = kind; + return this; + } + + public Builder typeLabel(String typeLabel) { + this.typeLabel = typeLabel; + return this; + } + + public Builder typeInfo(TypeInfo typeInfo) { + this.typeInfo = typeInfo; + return this; + } + + public Builder signature(String signature) { + this.signature = signature; + return this; + } + + public Builder documentation(String documentation) { + this.documentation = documentation; + return this; + } + + public Builder sourceData(Object sourceData) { + this.sourceData = sourceData; + return this; + } + + public Builder deprecated(boolean deprecated) { + this.deprecated = deprecated; + return this; + } + + public Builder requiresImport(boolean requiresImport) { + this.requiresImport = requiresImport; + return this; + } + + public Builder importPath(String importPath) { + this.importPath = importPath; + return this; + } + + public Builder color(int color) { + this.color = color; + return this; + } + + public AutocompleteItem build() { + if (insertText == null) { + insertText = name; + } + return new AutocompleteItem(name, searchName, insertText, kind, typeLabel, + typeInfo, signature, documentation, sourceData, deprecated, requiresImport, importPath, -1).setColor(color); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteManager.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteManager.java new file mode 100644 index 000000000..729a8dd74 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteManager.java @@ -0,0 +1,1145 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import noppes.npcs.api.handler.data.IAction; +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import org.lwjgl.input.Mouse; + +import java.util.List; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +/** + * Manages autocomplete state and coordinates between providers and UI. + * This is the main entry point for autocomplete functionality. + */ +public class AutocompleteManager { + + // ==================== CONSTANTS ==================== + + /** Characters that trigger autocomplete */ + private static final String TRIGGER_CHARS = "."; + + /** Characters that should close autocomplete */ + private static final String CLOSE_CHARS = ";{}()[]<>,\"'`"; + + /** Minimum characters before showing suggestions (for non-dot triggers) */ + private static final int MIN_PREFIX_LENGTH = 1; + + /** Maximum number of suggestions to show (performance/UX) */ + private static final int MAX_SUGGESTIONS = 150; + + /** Pattern for identifier characters */ + private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("[a-zA-Z_$][a-zA-Z0-9_$]*"); + + // ==================== STATE ==================== + + private final AutocompleteMenu menu; + private final JavaAutocompleteProvider javaProvider; + private final JSAutocompleteProvider jsProvider; + + private ScriptTextContainer container; + private ScriptDocument document; + + /** Whether autocomplete is currently active */ + private boolean active = false; + + /** The prefix being typed */ + private String currentPrefix = ""; + + /** Start position of the current prefix */ + private int prefixStartPosition = -1; + + /** Whether this was an explicit trigger (Ctrl+Space) */ + private boolean explicitTrigger = false; + + /** The full class name of the current receiver type (for member access tracking) */ + private String currentReceiverFullName = null; + + /** Whether current context is member access */ + private boolean currentIsMemberAccess = false; + + /** Callback for text insertion */ + private InsertCallback insertCallback; + + /** + * Callback interface for inserting autocomplete results. + */ + public interface InsertCallback { + /** + * Insert text, replacing from start to current cursor position. + * @param text Text to insert + * @param startPosition Position to start replacing from + */ + void insertText(String text, int startPosition); + + /** + * Replace text in a specific range. + * @param text Text to insert + * @param startPosition Position to start replacing from + * @param endPosition Position to end replacing at + */ + void replaceTextRange(String text, int startPosition, int endPosition); + + /** + * Add an import statement and sort all imports. + * @param importPath Full path of the class to import (e.g., "net.minecraft.client.Minecraft") + */ + void addImport(String importPath); + + /** + * Get current cursor position. + */ + int getCursorPosition(); + + /** + * Set cursor position. + * @param position New cursor position + */ + void setCursorPosition(int position); + + /** + * Get current document text. + */ + String getText(); + + /** + * Get cursor screen coordinates for menu positioning. + */ + int[] getCursorScreenPosition(); + + /** + * Get viewport dimensions. + */ + int[] getViewportDimensions(); + } + + // ==================== CONSTRUCTOR ==================== + + public AutocompleteManager() { + this.menu = new AutocompleteMenu(); + this.javaProvider = new JavaAutocompleteProvider(); + this.jsProvider = new JSAutocompleteProvider(); + + // Set up menu callback + menu.setCallback(new AutocompleteMenu.AutocompleteCallback() { + @Override + public void onItemSelected(AutocompleteItem item) { + handleItemSelected(item); + } + + @Override + public void onDismiss() { + active = false; + } + }); + } + + // ==================== CONFIGURATION ==================== + + /** + * Set the script container for type resolution. + */ + public void setContainer(ScriptTextContainer container) { + this.container = container; + if (container != null) { + this.document = container.getDocument(); + javaProvider.setDocument(document); + jsProvider.setDocument(document); + } + } + + /** + * Set the callback for text insertion. + */ + public void setInsertCallback(InsertCallback callback) { + this.insertCallback = callback; + } + + // ==================== TRIGGER LOGIC ==================== + + /** + * Called when a character is typed. + * Determines whether to show, update, or hide autocomplete. + */ + public void onCharTyped(char c, String text, int cursorPosition) { + // Check if we should close autocomplete + if (CLOSE_CHARS.indexOf(c) >= 0 || document.isExcludedInclusive(cursorPosition)) { + dismiss(); + return; + } + + // Check if this is a trigger character + if (TRIGGER_CHARS.indexOf(c) >= 0) { + // Trigger after dot + triggerAfterDot(text, cursorPosition); + return; + } + + // Check if this completes a :: (method reference) + if (c == ':') { + // Normalize cursor position - some callers pass pre-insert position + int effectiveCursor = cursorPosition; + if (effectiveCursor >= 0 && effectiveCursor < text.length() && text.charAt(effectiveCursor) == c) { + effectiveCursor = effectiveCursor + 1; + } + + effectiveCursor = Math.max(0, Math.min(effectiveCursor, text.length())); + + // Check if the previous character is also : + if (effectiveCursor >= 2 && text.charAt(effectiveCursor - 2) == ':') { + triggerAfterMethodReference(text, effectiveCursor); + return; + } + } + + // Check if we're typing an identifier + if (Character.isJavaIdentifierPart(c)) { + // GuiScriptTextArea passes a cursor position captured BEFORE insertion while `text` + // is already the post-insert text. When this happens, cursorPosition points at the + // newly inserted character, not the caret-after-insert. Normalize to a caret position + // for prefix extraction/update. + int effectiveCursor = cursorPosition; + if (effectiveCursor >= 0 && effectiveCursor < text.length() && text.charAt(effectiveCursor) == c) { + effectiveCursor = effectiveCursor + 1; + } + + effectiveCursor = Math.max(0, Math.min(effectiveCursor, text.length())); + + if (active) { + // Update existing autocomplete + updatePrefix(text, effectiveCursor); + } else if (Character.isJavaIdentifierStart(c)) { + // Check if we're after a dot with whitespace (e.g., "obj. |" where | is cursor) + int dotPos = findDotBeforeWhitespace(text, effectiveCursor - 1); + if (dotPos >= 0) { + // We're typing after a dot (with possible whitespace), trigger member access + triggerAfterDot(text, effectiveCursor); + } else { + // Potentially start new autocomplete + maybeStartAutocomplete(text, effectiveCursor, false); + } + } + return; + } + + // Any other character closes autocomplete + if (active && !Character.isWhitespace(c)) { + dismiss(); + } + } + + /** + * Called when backspace/delete is pressed. + */ + public void onDeleteKey(String text, int cursorPosition) { + if (active) { + updatePrefix(text, cursorPosition); + + // Close if prefix is now empty and not after dot + if (currentPrefix.isEmpty() && !isAfterDot(text, cursorPosition)) { + dismiss(); + } + } + } + + /** + * Called when cursor position changes (e.g., arrow keys). + * Updates the autocomplete prefix based on the new cursor position. + */ + public void onCursorMove(String text, int cursorPosition) { + if (!active) + return; + + // Check if we're still in a valid identifier position + if (cursorPosition < 0 || cursorPosition > text.length()) { + dismiss(); + return; + } + + // Find the word boundaries at the current position + int wordStart = cursorPosition; + while (wordStart > 0 && Character.isJavaIdentifierPart(text.charAt(wordStart - 1))) { + wordStart--; + } + + int wordEnd = cursorPosition; + while (wordEnd < text.length() && Character.isJavaIdentifierPart(text.charAt(wordEnd))) { + wordEnd++; + } + + // Check if we moved out of the current word + if (cursorPosition < prefixStartPosition || cursorPosition > prefixStartPosition + currentPrefix.length()) { + // Check if we're in a different word that we can autocomplete + boolean isMemberAccess = wordStart > 0 && text.charAt(wordStart - 1) == '.'; + + if (isMemberAccess || wordStart < cursorPosition) { + // Update to the new word + prefixStartPosition = wordStart; + updatePrefix(text, cursorPosition); + } else { + // Moved to empty space or invalid position + dismiss(); + } + } else { + // Still in same word, just update the prefix + updatePrefix(text, cursorPosition); + } + } + + /** + * Explicitly trigger autocomplete (Ctrl+Space). + */ + public void triggerExplicit() { + if (insertCallback == null) return; + + String text = insertCallback.getText(); + int cursorPosition = insertCallback.getCursorPosition(); + + explicitTrigger = true; + + // Check if after dot + if (isAfterDot(text, cursorPosition)) { + triggerAfterDot(text, cursorPosition); + } else { + maybeStartAutocomplete(text, cursorPosition, true); + } + } + + /** + * Trigger autocomplete after a dot is typed. + */ + private void triggerAfterDot(String text, int cursorPosition) { + // Normalize cursor semantics. + // Some callers pass a pre-insert cursor index (points at '.') even though the caret + // is visually after the inserted '.' in the current text. + int caretPos = Math.max(0, Math.min(cursorPosition, text.length())); + + int dotPos = -1; + if (caretPos > 0 && caretPos <= text.length() && text.charAt(caretPos - 1) == '.') { + // Caret-after-dot case + dotPos = caretPos - 1; + } else if (caretPos >= 0 && caretPos < text.length() && text.charAt(caretPos) == '.') { + // Pre-insert cursor case: cursorPosition points at the dot itself + dotPos = caretPos; + caretPos = Math.min(caretPos + 1, text.length()); + } else { + // Look backwards skipping whitespace/identifier to find dot + dotPos = findDotBeforeWhitespace(text, caretPos - 1); + } + + if (dotPos < 0) return; + + String receiverExpr = findReceiverExpression(text, dotPos); + String prefix = findCurrentWord(text, caretPos); + + // Find where the prefix actually starts (after dot + any whitespace) + int prefixStart = dotPos + 1; + while (prefixStart < caretPos && Character.isWhitespace(text.charAt(prefixStart))) { + prefixStart++; + } + + prefixStartPosition = prefixStart; + currentPrefix = prefix; + + showSuggestions(text, caretPos, prefix, prefixStartPosition, true, receiverExpr, false); + } + + /** + * Trigger autocomplete after :: is typed (method reference). + * Shows only method suggestions filtered for method references. + */ + private void triggerAfterMethodReference(String text, int cursorPosition) { + int doubleColonPos = cursorPosition - 2; + + // Find the receiver expression before :: + String receiverExpr = findMethodRefReceiverExpression(text, doubleColonPos); + if (receiverExpr == null || receiverExpr.isEmpty()) return; + + // Skip whitespace after :: when establishing prefix start position + int prefixStart = cursorPosition; + while (prefixStart < text.length() && Character.isWhitespace(text.charAt(prefixStart))) { + prefixStart++; + } + + String prefix = ""; + + prefixStartPosition = prefixStart; + currentPrefix = prefix; + + // Show suggestions filtered for methods only + showSuggestions(text, cursorPosition, prefix, prefixStart, true, receiverExpr, true); + } + + /** + * Find the receiver expression before :: for method references. + * Similar to findReceiverExpression but stops at :: + */ + private String findMethodRefReceiverExpression(String text, int doubleColonPos) { + if (text == null || doubleColonPos <= 0) return ""; + + int pos = doubleColonPos - 1; + + // Skip whitespace immediately left of :: + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--; + if (pos < 0) return ""; + + int end = pos + 1; + + // Walk left across a dotted receiver chain + while (pos >= 0) { + // Skip excluded regions (comments/strings) to avoid reading dots from inside them + if (document != null && document.isExcluded(pos)) { + int jumped = jumpBeforeExcluded(pos); + if (jumped == pos) { + pos--; + } else { + pos = jumped; + } + continue; + } + + char c = text.charAt(pos); + + if (Character.isWhitespace(c)) { + pos--; + continue; + } + + if (c == ')') { + int open = findMatchingBackward(text, pos, '(', ')'); + if (open < 0) break; + pos = open - 1; + continue; + } + + if (c == ']') { + int open = findMatchingBackward(text, pos, '[', ']'); + if (open < 0) break; + pos = open - 1; + continue; + } + + if (Character.isJavaIdentifierPart(c)) { + // Consume identifier + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) pos--; + + // If preceded by a dot, keep going (skip excluded ranges when looking for the dot) + int checkPos = pos; + while (checkPos >= 0) { + char ch = text.charAt(checkPos); + if (Character.isWhitespace(ch)) { + checkPos--; + continue; + } + if (document != null && document.isExcluded(checkPos)) { + int jumped = jumpBeforeExcluded(checkPos); + if (jumped == checkPos) { + checkPos--; + } else { + checkPos = jumped; + } + continue; + } + break; + } + if (checkPos >= 0 && text.charAt(checkPos) == '.') { + pos = checkPos - 1; + continue; + } + break; + } + + // Anything else terminates the receiver + break; + } + + int start = pos + 1; + if (start < 0) start = 0; + if (end > text.length()) end = text.length(); + if (start >= end) return ""; + + String expr = text.substring(start, end).replaceAll("\\s+", " ").trim(); + return expr; + } + + /** + * Maybe start autocomplete based on current context. + */ + private void maybeStartAutocomplete(String text, int cursorPosition, boolean force) { + String prefix = findCurrentWord(text, cursorPosition); + int prefixStart = cursorPosition - prefix.length(); + + // Check minimum prefix length (unless forced) + if (!force && prefix.length() < MIN_PREFIX_LENGTH) { + return; + } + + // Don't auto-trigger if we're in the middle of a word + if (!force && prefixStart > 0 && Character.isJavaIdentifierPart(text.charAt(prefixStart - 1))) { + return; + } + + prefixStartPosition = prefixStart; + currentPrefix = prefix; + + showSuggestions(text, cursorPosition, prefix, prefixStart, false, null, false); + } + + /** + * Update the prefix and refresh suggestions. + */ + private void updatePrefix(String text, int cursorPosition) { + if (text == null || cursorPosition < 0 || cursorPosition > text.length()) { + dismiss(); + return; + } + + // Re-calculate prefix from the original start position + if (prefixStartPosition < 0 || prefixStartPosition > cursorPosition) { + dismiss(); + return; + } + + String newPrefix = text.substring(prefixStartPosition, cursorPosition); + + // Validate prefix (should be valid identifier or empty) + if (!newPrefix.isEmpty() && !isValidPrefix(newPrefix)) { + dismiss(); + return; + } + + currentPrefix = newPrefix; + + // Check if this is a method reference context (after ::) + boolean isMethodReference = isAfterMethodReference(text, prefixStartPosition); + + // Check if after dot (skipping whitespace) + int dotPos = findDotBeforeWhitespace(text, prefixStartPosition - 1); + boolean isMemberAccess = dotPos >= 0 || isMethodReference; + + String receiverExpr = null; + if (isMethodReference) { + // Find :: position + int doubleColonPos = findDoubleColonBefore(text, prefixStartPosition); + if (doubleColonPos >= 0) { + receiverExpr = findMethodRefReceiverExpression(text, doubleColonPos); + } + } else if (isMemberAccess) { + receiverExpr = findReceiverExpression(text, dotPos); + } + + showSuggestions(text, cursorPosition, currentPrefix, prefixStartPosition, + isMemberAccess, receiverExpr, isMethodReference); + } + + /** + * Check if position is after :: (method reference). + */ + private boolean isAfterMethodReference(String text, int pos) { + int checkPos = pos - 1; + // Skip whitespace + while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) { + checkPos--; + } + // Check for :: + if (checkPos >= 1 && text.charAt(checkPos) == ':' && text.charAt(checkPos - 1) == ':') { + return true; + } + return false; + } + + /** + * Find the position of :: before the given position. + */ + private int findDoubleColonBefore(String text, int pos) { + int checkPos = pos - 1; + // Skip whitespace + while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) { + checkPos--; + } + // Check for :: + if (checkPos >= 1 && text.charAt(checkPos) == ':' && text.charAt(checkPos - 1) == ':') { + return checkPos - 1; + } + return -1; + } + + // ==================== SUGGESTION LOGIC ==================== + + /** + * Show autocomplete suggestions. + */ + private void showSuggestions(String text, int cursorPosition, String prefix, + int prefixStart, boolean isMemberAccess, String receiverExpr, + boolean methodsOnly) { + if (insertCallback == null || document == null) return; + + // Track context for usage recording when item is selected + currentIsMemberAccess = isMemberAccess; + currentReceiverFullName = null; + + // Resolve receiver type if member access + if (isMemberAccess && receiverExpr != null) { + // Use a position inside the receiver/scope for resolution. + // `prefixStart` can land on end-exclusive boundaries (e.g., right at bodyEnd), + // causing findInnermostScopeAt(prefixStart) to return null. + int dotPos = findDotBeforeWhitespace(text, prefixStart - 1); + int resolvePos = dotPos >= 0 ? dotPos : prefixStart; + TypeInfo receiverType = document.resolveExpressionType(receiverExpr, resolvePos); + if (receiverType != null && receiverType.isResolved()) { + currentReceiverFullName = receiverType.getFullName(); + } + } + + // Build context + int lineNumber = getLineNumber(text, cursorPosition); + String currentLine = getCurrentLine(text, cursorPosition); + int columnPosition = getColumnPosition(text, cursorPosition); + + AutocompleteProvider.Context context = new AutocompleteProvider.Context( + text, cursorPosition, lineNumber, columnPosition, currentLine, + prefix, prefixStart, isMemberAccess, receiverExpr, explicitTrigger, methodsOnly + ); + + // Get suggestions from appropriate provider + AutocompleteProvider provider = document.isJavaScript() ? jsProvider : javaProvider; + + // No need to update variable types - JSAutocompleteProvider now gets them directly from ScriptDocument + + List suggestions = provider.getSuggestions(context); + + // Limit suggestions to prevent overwhelming the UI and improve performance + // Items are already sorted by relevance in the provider + if (suggestions.size() > MAX_SUGGESTIONS) { + // Disabled for now to show all suggestions + // suggestions = suggestions.subList(0, MAX_SUGGESTIONS); + } + + // Show menu + if (suggestions.isEmpty()) { + if (explicitTrigger) { + // Show "No suggestions" message + suggestions.add(new AutocompleteItem.Builder() + .name("No suggestions") + .kind(AutocompleteItem.Kind.SNIPPET) + .typeLabel("") + .build()); + } else { + dismiss(); + return; + } + } + + // Get screen position for menu + int[] screenPos = insertCallback.getCursorScreenPosition(); + int[] viewport = insertCallback.getViewportDimensions(); + + menu.show(screenPos[0], screenPos[1] + 15, suggestions, viewport[0], viewport[1]); + active = true; + explicitTrigger = false; + } + + // ==================== KEY HANDLING ==================== + + /** + * Handle key press. + * @return true if the key was consumed + */ + public boolean keyPressed(int keyCode) { + if (!active || !menu.isVisible()) return false; + + switch (keyCode) { + case 200: // UP + menu.selectPrevious(); + return true; + + case 208: // DOWN + menu.selectNext(); + return true; + + case 28: // ENTER + case 15: // TAB + if (menu.hasItems()) { + menu.confirmSelection(); + return true; + } + return false; + + case 1: // ESCAPE + dismiss(); + return true; + + default: + return false; + } + } + + /** + * Handle mouse click. + * @return true if the click was consumed + */ + public boolean mouseClicked(int mouseX, int mouseY, int button) { + if (!active) return false; + return menu.mouseClicked(mouseX, mouseY, button); + } + + /** + * Handle mouse scroll. + * @return true if the scroll was consumed + */ + public boolean mouseScrolled(int mouseX, int mouseY, int delta) { + if (!active) return false; + return menu.mouseScrolled(mouseX, mouseY, delta); + } + + /** + * Handle mouse release. + * @return true if the release was consumed + */ + public boolean mouseReleased(int mouseX, int mouseY, int button) { + if (!active) + return false; + return menu.mouseReleased(mouseX, mouseY, button); + } + + /** + * Handle mouse drag. + * @return true if the drag was consumed + */ + public boolean mouseDragged(int mouseX, int mouseY) { + if (!active) + return false; + return menu.mouseDragged(mouseX, mouseY); + } + + public boolean isDraggingPanel() { return active && menu.isDraggingPanel(); } + public boolean isDraggingScrollbarMenu() { return active && menu.isDraggingScrollbarMenu(); } + public boolean isResizingPanel() { return active && menu.isResizingPanel(); } + public boolean isMouseOverResizeHandle(int mx, int my) { return active && menu.isMouseOverResizeHandle(mx, my); } + public void updatePanelDrag(int x, int y) { if (active) menu.updatePanelDrag(x, y); } + public void releasePanelDrag() { if (active) menu.releasePanelDrag(); } + public void updateScrollbarDrag(int y) { if (active) menu.updateScrollbarDragDraw(y); } + public void releaseScrollbarDrag() { if (active) menu.releaseScrollbarDrag(); } + public void updatePanelResize(int x, int y) { if (active) menu.updatePanelResize(x, y); } + public void releasePanelResize() { if (active) menu.releasePanelResize(); } + + // ==================== ITEM SELECTION ==================== + + /** + * Handle when an item is selected from the menu. + */ + private void handleItemSelected(AutocompleteItem item) { + if (insertCallback == null || item == null) return; + + // Don't insert "No suggestions" placeholder + if (item.getName().equals("No suggestions")) { + return; + } + + // Record usage for learning + recordUsage(item); + + String insertText = item.getInsertText(); + + // Smart tab completion: replace till next separator + // Find the end position (current word till next separator) + String text = insertCallback.getText(); + int cursorPos = insertCallback.getCursorPosition(); + int endPos = cursorPos; + + // Extend to consume rest of current word + while (endPos < text.length() && Character.isJavaIdentifierPart(text.charAt(endPos))) { + endPos++; + } + + // Also consume following parentheses and their content if present + if (endPos < text.length() && text.charAt(endPos) == '(') { + int parenDepth = 1; + endPos++; // Skip opening paren + while (endPos < text.length() && parenDepth > 0) { + char c = text.charAt(endPos); + if (c == '(') parenDepth++; + else if (c == ')') parenDepth--; + endPos++; + } + } + + // IMPORTANT: Do the text replacement FIRST, then add import + // This prevents position corruption since import adds text at the TOP + insertCallback.replaceTextRange(insertText, prefixStartPosition, endPos); + + // If the inserted text ends with (), move cursor inside only when parameters exist + if (insertText.endsWith("()") && item.getParameterCount() > 0) { + int currentCursor = insertCallback.getCursorPosition(); + insertCallback.setCursorPosition(currentCursor - 1); + } + + // If this item requires an import, add it AFTER the text replacement + if (item.requiresImport() && item.getImportPath() != null) { + insertCallback.addImport(item.getImportPath()); + } + + active = false; + } + + /** + * Record that the user selected an autocomplete item for usage tracking. + */ + private void recordUsage(AutocompleteItem item) { + if (document == null) return; + + UsageTracker tracker = document.isJavaScript() ? + UsageTracker.getJSInstance() : UsageTracker.getJavaInstance(); + + // For member access, use the resolved receiver type + // For standalone items (types, keywords, variables), owner is null + String owner = currentIsMemberAccess ? currentReceiverFullName : null; + + tracker.recordUsage(item, owner); + } + + // ==================== DISMISS ==================== + + /** + * Dismiss autocomplete. + */ + public void dismiss() { + if (active) { + menu.hide(); + active = false; + currentPrefix = ""; + prefixStartPosition = -1; + explicitTrigger = false; + } + } + + // ==================== DRAWING ==================== + + /** + * Draw the autocomplete menu. + */ + public void draw(int mouseX, int mouseY) { + if (active) { + menu.draw(mouseX, mouseY); + + if (Mouse.isButtonDown(0)) + mouseDragged(mouseX, mouseY); + else + mouseReleased(mouseX, mouseY, 0); + } + } + + // ==================== STATE QUERIES ==================== + + public boolean isActive() { + return active; + } + + public boolean isVisible() { + return active && menu.isVisible(); + } + + public AutocompleteMenu getMenu() { + return menu; + } + + // ==================== HELPER METHODS ==================== + + /** + * Find the word being typed at the cursor position. + */ + private String findCurrentWord(String text, int cursorPos) { + if (text == null || text.isEmpty()) return ""; + + int safeCursorPos = Math.max(0, Math.min(cursorPos, text.length())); + if (safeCursorPos <= 0) return ""; + + int start = safeCursorPos; + while (start > 0 && Character.isJavaIdentifierPart(text.charAt(start - 1))) { + start--; + } + + return text.substring(start, safeCursorPos); + } + + /** + * Find the receiver expression before a dot. + * Handles multiline chains and whitespace intelligently. + * + * Stops at statement boundaries: + * - Semicolons (Java) + * - Blank lines or newlines not part of chain continuation + * + * Continues through: + * - Dots at start/end of lines (chain continuation pattern) + * - Whitespace within expressions + */ + private String findReceiverExpression(String text, int dotPos) { + if (text == null || dotPos <= 0) return ""; + if (dotPos >= text.length()) return ""; + + int end = dotPos; + int pos = dotPos - 1; + + // Skip whitespace immediately left of dot + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--; + if (pos < 0) return ""; + + // Walk left across a dotted receiver chain. + while (pos >= 0) { + // Skip excluded regions (comments/strings) if the document knows them + if (document != null && document.isExcluded(pos)) { + int jumped = jumpBeforeExcluded(pos); + if (jumped == pos) { + pos--; // Safety fallback + } else { + pos = jumped; + } + continue; + } + + char c = text.charAt(pos); + if (Character.isWhitespace(c)) { + pos--; + continue; + } + + if (c == ')') { + int open = findMatchingBackward(text, pos, '(', ')'); + if (open < 0) break; + pos = open - 1; + continue; + } + + if (c == ']') { + int open = findMatchingBackward(text, pos, '[', ']'); + if (open < 0) break; + pos = open - 1; + continue; + } + + if (Character.isJavaIdentifierPart(c)) { + // Consume identifier + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) pos--; + + // If preceded by a dot (allowing whitespace/newlines between), keep going. + int checkPos = pos; + while (checkPos >= 0) { + char ch = text.charAt(checkPos); + if (Character.isWhitespace(ch)) { + checkPos--; + continue; + } + // Critical for cases like: "). // comment\n setData(...)" + // The last non-whitespace char before the newline is inside an excluded range, + // so we need to skip excluded ranges when searching for the dot. + if (document != null && document.isExcluded(checkPos)) { + int jumped = jumpBeforeExcluded(checkPos); + if (jumped == checkPos) { + checkPos--; // Safety fallback + } else { + checkPos = jumped; + } + continue; + } + break; + } + if (checkPos >= 0 && text.charAt(checkPos) == '.') { + pos = checkPos - 1; + continue; + } + break; + } + + // Anything else terminates the receiver + break; + } + + int start = pos + 1; + if (start < 0) start = 0; + if (end > text.length()) end = text.length(); + if (start >= end) return ""; + + String expr = text.substring(start, end); + + // Mask comment ranges so comment words don't get parsed as identifiers/segments. + // Keep string literal ranges intact so argument type resolution still works. + if (document != null) { + char[] chars = expr.toCharArray(); + for (int[] range : document.getExcludedRanges()) { + if (range == null || range.length < 2) continue; + if (!isCommentRange(text, range[0])) continue; + + int a = Math.max(range[0], start) - start; + int b = Math.min(range[1], end) - start; + if (b <= 0 || a >= chars.length) continue; + if (a < 0) a = 0; + if (b > chars.length) b = chars.length; + + for (int i = a; i < b; i++) { + char ch = chars[i]; + if (ch != '\n' && ch != '\r') { + chars[i] = ' '; + } + } + } + expr = new String(chars); + } + expr = expr.replaceAll("\\s+", " ").trim(); + return expr; + } + + private boolean isCommentRange(String text, int start) { + if (start < 0 || start + 1 >= text.length()) return false; + if (text.charAt(start) != '/') return false; + char next = text.charAt(start + 1); + return next == '/' || next == '*'; + } + + /** + * Jump to just before the excluded range that contains position, or return position if unknown. + */ + private int jumpBeforeExcluded(int position) { + if (document == null) return position; + for (int[] range : document.getExcludedRanges()) { + if (position >= range[0] && position < range[1]) { + return range[0] - 1; + } + } + return position; + } + + /** + * Find the matching opening delimiter scanning backward from closePos. + * Skips excluded ranges and ignores delimiters inside string literals. + */ + private int findMatchingBackward(String text, int closePos, char openChar, char closeChar) { + int depth = 0; + boolean inString = false; + char stringChar = 0; + + for (int i = closePos; i >= 0; i--) { + char c = text.charAt(i); + + // Handle strings (backward), respecting escapes + if (!inString && (c == '"' || c == '\'')) { + int backslashCount = 0; + for (int j = i - 1; j >= 0 && text.charAt(j) == '\\'; j--) backslashCount++; + if (backslashCount % 2 == 0) { + inString = true; + stringChar = c; + } + } else if (inString && c == stringChar) { + int backslashCount = 0; + for (int j = i - 1; j >= 0 && text.charAt(j) == '\\'; j--) backslashCount++; + if (backslashCount % 2 == 0) { + inString = false; + } + } + + if (inString) continue; + + if (document != null && document.isExcluded(i)) continue; + + if (c == closeChar) depth++; + else if (c == openChar) { + depth--; + if (depth == 0) return i; + } + } + return -1; + } + + /** + * Find dot position before cursor, skipping whitespace. + * Returns -1 if no dot found. + */ + private int findDotBeforeWhitespace(String text, int fromPos) { + if (text == null || text.isEmpty()) return -1; + + int pos = Math.min(fromPos, text.length() - 1); + if (pos < 0) return -1; + // Skip backwards over whitespace + + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + + // Check if we found a dot + if (pos >= 0 && text.charAt(pos) == '.') { + if (document != null && document.isExcluded(pos)) return -1; + return pos; + } else { + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) + pos--; + + if (pos >= 0 && text.charAt(pos) == '.') { + if (document != null && document.isExcluded(pos)) return -1; + return pos; + } + } + return -1; + } + + /** + * Check if cursor is after a dot. + */ + private boolean isAfterDot(String text, int cursorPos) { + if (text == null || text.isEmpty()) return false; + + // Look backwards, skipping any identifier characters + int pos = Math.min(cursorPos - 1, text.length() - 1); + if (pos < 0) return false; + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) { + pos--; + } + // Also skip whitespace to check for dot + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + return pos >= 0 && text.charAt(pos) == '.'; + } + + /** + * Check if a prefix is valid (identifier characters only). + */ + private boolean isValidPrefix(String prefix) { + if (prefix.isEmpty()) return true; + if (!Character.isJavaIdentifierStart(prefix.charAt(0))) return false; + for (int i = 1; i < prefix.length(); i++) { + if (!Character.isJavaIdentifierPart(prefix.charAt(i))) return false; + } + return true; + } + + /** + * Get line number (0-indexed) for a position. + */ + private int getLineNumber(String text, int position) { + int line = 0; + for (int i = 0; i < position && i < text.length(); i++) { + if (text.charAt(i) == '\n') line++; + } + return line; + } + + /** + * Get the current line text. + */ + private String getCurrentLine(String text, int position) { + int lineStart = text.lastIndexOf('\n', position - 1) + 1; + int lineEnd = text.indexOf('\n', position); + if (lineEnd < 0) lineEnd = text.length(); + return text.substring(lineStart, lineEnd); + } + + /** + * Get column position within the current line. + */ + private int getColumnPosition(String text, int position) { + int lineStart = text.lastIndexOf('\n', position - 1) + 1; + return position - lineStart; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteMenu.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteMenu.java new file mode 100644 index 000000000..4fc78de21 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteMenu.java @@ -0,0 +1,1009 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import noppes.npcs.client.gui.util.GuiNPCInterface; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +/** + * UI component for displaying autocomplete suggestions. + * Styled similar to SearchReplaceBar with IntelliJ-like appearance. + */ +public class AutocompleteMenu extends Gui { + + // ==================== CONSTANTS ==================== + private static final int MAX_VISIBLE_ITEMS = 10; + private static final int ITEM_HEIGHT = 16; + private static final int PADDING = 4; + private static final int ICON_WIDTH = 16; + private static final int MIN_WIDTH = 200; + private static final int MAX_WIDTH = 400; + private static final int HINT_HEIGHT = 18; + + // ==================== COLORS ==================== + private static final int BG_COLOR = 0xFF2d2d30; + private static final int BORDER_COLOR = 0xFF3c3c3c; + private static final int SELECTED_BG = 0xFF094771; + private static final int HOVER_BG = 0xFF37373d; + private static final int TEXT_COLOR = 0xFFe0e0e0; + private static final int DIM_TEXT_COLOR = 0xFF808080; + private static final int HIGHLIGHT_COLOR = 0xFFFFD866; + private static final int HINT_BG_COLOR = 0xFF252526; + private static final int SCROLLBAR_BG = 0xFF3c3c3c; + private static final int SCROLLBAR_FG = 0xFF606060; + + // ==================== STATE ==================== + private boolean visible = false; + private List items = new ArrayList<>(); + private int selectedIndex = 0; + private int scrollOffset = 0; + private int hoveredIndex = -1; + + // Scrollbar drag state + private boolean isDraggingScrollbar = false; + private int dragStartY = 0; + private int dragStartScroll = 0; + + // Panel pan/drag state + private boolean isDraggingPanel; + private int panelDragOffsetX, panelDragOffsetY; + private boolean panelPositionOverridden; + private int overriddenX, overriddenY; + private boolean hasPendingPanelDrag; + private int pendingDragStartX, pendingDragStartY; + private boolean pendingItemConfirm; + + // Panel resize state + private boolean isResizingPanel; + private int resizeInitMouseX, resizeInitMouseY; + private int resizeInitW, resizeInitH; + private boolean panelSizeOverridden; + private int overriddenW, overriddenH; + private static final int MIN_RESIZE_W = 140; + private static final int MIN_RESIZE_H = 60; + private static final int DRAG_THRESHOLD = 4; + + // ==================== POSITION ==================== + private int x, y; + public GuiNPCInterface ownerGui; + private int width, height; + private int menuWidth; + private int visibleItemsCount; // Actual number of items that fit in the menu + + // ==================== FONT ==================== + private final FontRenderer font; + + // ==================== CALLBACK ==================== + private AutocompleteCallback callback; + + /** + * Callback interface for autocomplete events. + */ + public interface AutocompleteCallback { + void onItemSelected(AutocompleteItem item); + void onDismiss(); + } + + public AutocompleteMenu() { + this.font = Minecraft.getMinecraft().fontRenderer; + this.visibleItemsCount = MAX_VISIBLE_ITEMS; + } + + private int getVisibleItemCapacity() { + if (items == null || items.isEmpty()) + return 0; + int cap = visibleItemsCount > 0 ? visibleItemsCount : MAX_VISIBLE_ITEMS; + if (!panelSizeOverridden) cap = Math.min(cap, MAX_VISIBLE_ITEMS); + return Math.max(1, Math.min(cap, items.size())); + } + + private int getMaxScrollOffset() { + int cap = getVisibleItemCapacity(); + if (cap <= 0) + return 0; + return Math.max(0, items.size() - cap); + } + + public void setCallback(AutocompleteCallback callback) { + this.callback = callback; + } + + // ==================== VISIBILITY ==================== + + /** + * Show the menu at the specified position with the given items. + */ + public void show(int x, int y, List items, int viewportWidth, int viewportHeight) { + this.items = items != null ? new ArrayList<>(items) : new ArrayList<>(); + this.selectedIndex = 0; + this.scrollOffset = 0; + this.hoveredIndex = -1; + + // Calculate menu dimensions + calculateDimensions(x, y, viewportWidth, viewportHeight); + + this.visible = !this.items.isEmpty(); + } + + /** + * Update the items while keeping the menu open. + */ + public void updateItems(List newItems) { + this.items = newItems != null ? new ArrayList<>(newItems) : new ArrayList<>(); + + // Clamp selection + if (selectedIndex >= items.size()) { + selectedIndex = Math.max(0, items.size() - 1); + } + + // Clamp scroll + int maxScroll = getMaxScrollOffset(); + if (scrollOffset > maxScroll) { + scrollOffset = maxScroll; + } + + visible = !items.isEmpty(); + } + + /** + * Hide the menu. + */ + public void hide() { + visible = false; + isDraggingPanel = false; + isResizingPanel = false; + panelPositionOverridden = false; + panelSizeOverridden = false; + hasPendingPanelDrag = false; + pendingItemConfirm = false; + if (callback != null) { + callback.onDismiss(); + } + } + + public boolean isVisible() { + return visible; + } + + public boolean hasItems() { + return !items.isEmpty(); + } + + // ==================== DIMENSIONS ==================== + + private void calculateDimensions(int cursorX, int cursorY, int viewportWidth, int viewportHeight) { + // Calculate width based on item content + int maxItemWidth = MIN_WIDTH; + for (AutocompleteItem item : items) { + int itemWidth = ICON_WIDTH + PADDING + font.getStringWidth(item.getName()) + PADDING; + if (item.getTypeLabel() != null) { + itemWidth += font.getStringWidth(item.getTypeLabel()) + PADDING * 2; + } + maxItemWidth = Math.max(maxItemWidth, itemWidth); + } + menuWidth = Math.min(maxItemWidth + 20, MAX_WIDTH); // +20 for scrollbar + + // Calculate initial height + int visibleItems = Math.min(items.size(), MAX_VISIBLE_ITEMS); + int menuHeight = visibleItems * ITEM_HEIGHT + HINT_HEIGHT + PADDING * 2; + + // Line height estimation (cursor position is typically at baseline) + int lineHeight = 20; + + // Calculate available space + int spaceBelow = viewportHeight - cursorY - 10; // Space below cursor + int spaceAbove = cursorY - lineHeight - 10; // Space above current line + + // Determine if we should use horizontal positioning + // Use horizontal if both vertical positions would be cramped or block the cursor line + boolean useHorizontalPosition = false; + if (spaceBelow < menuHeight && spaceAbove < menuHeight) { + // Check if horizontal positioning would work better + int spaceRight = viewportWidth - (cursorX + 50) - 10; // 50 = offset from cursor + if (spaceRight >= menuWidth && viewportHeight > menuHeight + 20) { + useHorizontalPosition = true; + } else { + // Reduce height to fit in the best available vertical space + int availableVerticalSpace = Math.max(spaceBelow, spaceAbove); + if (availableVerticalSpace < menuHeight) { + // Calculate how many items we can show in available space + int maxItemsForSpace = (availableVerticalSpace - HINT_HEIGHT - PADDING * 2) / ITEM_HEIGHT; + maxItemsForSpace = Math.max(3, Math.min(maxItemsForSpace, items.size())); // At least 3 items + visibleItems = maxItemsForSpace; + menuHeight = visibleItems * ITEM_HEIGHT + HINT_HEIGHT + PADDING * 2; + } + } + } + + // Store the calculated visible items count + this.visibleItemsCount = visibleItems; + + // Position the menu + if (useHorizontalPosition) { + // Position to the right of the cursor + this.x = cursorX + 50; + this.y = cursorY - lineHeight; // Align with current line + + // Ensure doesn't go off bottom + if (y + menuHeight > viewportHeight - 10) { + y = viewportHeight - menuHeight - 10; + } + } else { + // Standard vertical positioning + this.x = cursorX; + + // Try below first + if (spaceBelow >= menuHeight) { + this.y = cursorY ; + } else if (spaceAbove >= menuHeight) { + // Show above cursor line + this.y = cursorY - menuHeight - lineHeight; + } else { + // Use the larger space + if (spaceBelow >= spaceAbove) { + this.y = cursorY; + } else { + this.y = cursorY - menuHeight - lineHeight; + } + } + + // Check if menu would go off-screen to the right + if (x + menuWidth > viewportWidth - 10) { + x = viewportWidth - menuWidth - 10; + } + } + + // Ensure not off-screen to the left or top + x = Math.max(5, x); + y = Math.max(5, y); + + this.width = menuWidth; + this.height = menuHeight; + // Apply position override if user has dragged the panel + if (panelPositionOverridden) { this.x = overriddenX; this.y = overriddenY; } + // Apply size override if user has resized the panel + if (panelSizeOverridden) { + this.menuWidth = overriddenW; + this.width = overriddenW; + this.height = overriddenH; + this.visibleItemsCount = Math.max(1, (overriddenH - HINT_HEIGHT - PADDING * 2) / ITEM_HEIGHT); + } + } + + // ==================== SELECTION ==================== + + /** + * Move selection up. + */ + public void selectPrevious() { + if (items.isEmpty()) return; + + selectedIndex--; + if (selectedIndex < 0) { + selectedIndex = items.size() - 1; + scrollOffset = getMaxScrollOffset(); + } else if (selectedIndex < scrollOffset) { + scrollOffset = selectedIndex; + } + } + + /** + * Move selection down. + */ + public void selectNext() { + if (items.isEmpty()) return; + + selectedIndex++; + if (selectedIndex >= items.size()) { + selectedIndex = 0; + scrollOffset = 0; + } else { + int cap = getVisibleItemCapacity(); + if (cap > 0 && selectedIndex >= scrollOffset + cap) { + scrollOffset = selectedIndex - cap + 1; + } + } + } + + /** + * Confirm the current selection. + */ + public void confirmSelection() { + if (items.isEmpty() || selectedIndex < 0 || selectedIndex >= items.size()) { + hide(); + return; + } + + AutocompleteItem selected = items.get(selectedIndex); + if (callback != null) { + callback.onItemSelected(selected); + } + hide(); + } + + /** + * Get the currently selected item. + */ + public AutocompleteItem getSelectedItem() { + if (items.isEmpty() || selectedIndex < 0 || selectedIndex >= items.size()) { + return null; + } + return items.get(selectedIndex); + } + + // ==================== DRAWING ==================== + + /** + * Draw the autocomplete menu. + */ + public void draw(int mouseX, int mouseY) { + if (!visible || items.isEmpty()) return; + + // Update hover state + updateHoverState(mouseX, mouseY); + + // Enable scissoring to clip content + GL11.glEnable(GL11.GL_SCISSOR_TEST); + setScissor(x - 2, y - 2, width + 4, height + 4); + + // Draw background + drawRect(x, y, x + width, y + height, BG_COLOR); + + // Draw border + drawRect(x, y, x + width, y + 1, BORDER_COLOR); + drawRect(x, y + height - 1, x + width, y + height, BORDER_COLOR); + drawRect(x, y, x + 1, y + height, BORDER_COLOR); + drawRect(x + width - 1, y, x + width, y + height, BORDER_COLOR); + + // Draw items — tighter scissor so partial last item is clipped at the items-area boundary + int itemAreaH = height - HINT_HEIGHT - PADDING * 2; + setScissor(x + 1, y + PADDING , width - 2, itemAreaH); + int itemY = y + PADDING; + + int visibleCount = getVisibleItemCapacity(); + int renderCount = Math.min(visibleCount + 1, items.size() - scrollOffset); + for (int i = 0; i < renderCount; i++) { + int itemIndex = scrollOffset + i; + if (itemIndex >= items.size()) break; + + AutocompleteItem item = items.get(itemIndex); + boolean isSelected = (itemIndex == selectedIndex); + boolean isHovered = (itemIndex == hoveredIndex); + + drawItem(item, x + PADDING, itemY, width - PADDING * 2 - 8, isSelected, isHovered); + itemY += ITEM_HEIGHT; + } + + // Restore full-panel scissor for scrollbar and hint bar + setScissor(x - 2, y - 2, width + 4, height + 4); + + // Draw scrollbar if needed + if (items.size() > visibleCount) { + drawScrollbar(mouseX, mouseY); + } + + // Draw hint bar at bottom + drawHintBar(); + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + // Draw resize handle outside scissor + drawResizeHandle(mouseX, mouseY); + } + + /** + * Draw a single autocomplete item. + */ + private void drawItem(AutocompleteItem item, int itemX, int itemY, int itemWidth, + boolean selected, boolean hovered) { + // Background + if (selected) { + drawRect(itemX - 2, itemY, itemX + itemWidth + 2, itemY + ITEM_HEIGHT, SELECTED_BG); + } else if (hovered) { + drawRect(itemX - 2, itemY, itemX + itemWidth + 2, itemY + ITEM_HEIGHT, HOVER_BG); + } + + int textX = itemX; + int textY = itemY + (ITEM_HEIGHT - font.FONT_HEIGHT) / 2; + + // Draw modifier text (static/final) if present + boolean isStatic = item.isStatic(); + boolean isFinal = item.isFinal(); + if (isStatic || isFinal) { + GL11.glPushMatrix(); + float scale = 0.5f; + GL11.glScalef(scale, scale, scale); + int col = TokenType.KEYWORD.getHexColor(); + + if (isStatic) + font.drawString("s", (int) (textX / scale), (int) (textY / scale), col); + if (isFinal) + font.drawString("f", (int) (textX / scale), (int) (textY / scale) + 10, col); + GL11.glPopMatrix(); + } + + // Draw icon + String icon = item.getIconId(); + int iconColor = item.getIconColor(); + font.drawString(icon, textX + (ICON_WIDTH - font.getStringWidth(icon)) / 2, textY, iconColor); + textX += ICON_WIDTH; + + // Calculate available width for text (leave space for type label) + int availableWidth = itemWidth - (textX - itemX); + if (item.getTypeLabel() != null && !item.getTypeLabel().isEmpty()) { + int typeLabelWidth = font.getStringWidth(item.getTypeLabel()); + availableWidth -= typeLabelWidth + PADDING * 2; + } + + // Determine text color - gray for inherited Object methods + int textColor = getColor(item); + if (item.getKind() == AutocompleteItem.Kind.METHOD) { + drawMethodNameTruncated(item.getName(), item.getMatchIndices(), textX, textY, + textColor, availableWidth); + } else { + drawHighlightedTextTruncated(item.getName(), item.getMatchIndices(), textX, textY, + textColor, availableWidth); + } + + // Draw type label on the right + if (item.getTypeLabel() != null && !item.getTypeLabel().isEmpty()) { + String typeLabel = item.getTypeLabel(); + int typeLabelWidth = font.getStringWidth(typeLabel); + int typeLabelX = itemX + itemWidth - typeLabelWidth - PADDING; + + TypeInfo type = item.getTypeInfo(); + int col = type != null ? type.getTokenType().getHexColor() : DIM_TEXT_COLOR; + drawTypeLabel(item, typeLabel, typeLabelX, textY, col, type); + } + } + + public int getColor(AutocompleteItem item) { + int col = item.getColor(); + if (col != -1) + return col; + + if (item.isInheritedObjectMethod() || item.isDeprecated()) + return DIM_TEXT_COLOR; + + switch (item.getKind()) { + case METHOD: + return TokenType.METHOD_CALL.getHexColor(); + case FIELD: + return TokenType.GLOBAL_FIELD.getHexColor(); + case ENUM_CONSTANT: + return TokenType.ENUM_CONSTANT.getHexColor(); + case CLASS: + return TokenType.getColor(item.getTypeInfo()); + case VARIABLE: + return TokenType.LOCAL_FIELD.getHexColor(); + case PARAMETER: + return TokenType.PARAMETER.getHexColor(); + case KEYWORD: + return TokenType.KEYWORD.getHexColor(); + default: + return TEXT_COLOR; + } + } + + /** + * Draw method name with parameters colored gray. + */ + private void drawMethodName(String text, int[] matchIndices, int x, int y, int baseColor) { + // Find the opening parenthesis + int parenIndex = text.indexOf('('); + if (parenIndex == -1) { + // No parameters, just draw normally + drawHighlightedText(text, matchIndices, x, y, baseColor); + return; + } + + // Draw method name part with highlighting + String methodName = text.substring(0, parenIndex); + drawHighlightedText(methodName, matchIndices, x, y, baseColor); + + // Draw parameters part in gray (no highlighting) + String params = text.substring(parenIndex); + int paramX = x + font.getStringWidth(methodName); + font.drawString(params, paramX, y, DIM_TEXT_COLOR); + } + + /** + * Draw method name with parameters colored gray, truncated if too long. + */ + private void drawMethodNameTruncated(String text, int[] matchIndices, int x, int y, int baseColor, int maxWidth) { + // Find the opening parenthesis + int parenIndex = text.indexOf('('); + if (parenIndex == -1) { + // No parameters, just draw normally + drawHighlightedTextTruncated(text, matchIndices, x, y, baseColor, maxWidth); + return; + } + + String methodName = text.substring(0, parenIndex); + String params = text.substring(parenIndex); + + int methodNameWidth = font.getStringWidth(methodName); + int paramsWidth = font.getStringWidth(params); + int totalWidth = methodNameWidth + paramsWidth; + + if (totalWidth <= maxWidth) { + // Fits, draw normally + drawHighlightedText(methodName, matchIndices, x, y, baseColor); + int paramX = x + methodNameWidth; + font.drawString(params, paramX, y, DIM_TEXT_COLOR); + } else { + // Need to truncate + String ellipsis = "..."; + int ellipsisWidth = font.getStringWidth(ellipsis); + + // Always show method name, truncate params if needed + if (methodNameWidth + ellipsisWidth < maxWidth) { + drawHighlightedText(methodName, matchIndices, x, y, baseColor); + int paramX = x + methodNameWidth; + + // Truncate parameters + int availableForParams = maxWidth - methodNameWidth - ellipsisWidth; + String truncatedParams = truncateString(params, availableForParams); + font.drawString(truncatedParams + ellipsis, paramX, y, DIM_TEXT_COLOR); + } else { + // Even method name doesn't fit, truncate it too + int availableForMethod = maxWidth - ellipsisWidth; + String truncatedMethod = truncateString(methodName, availableForMethod); + drawHighlightedText(truncatedMethod, matchIndices, x, y, baseColor); + font.drawString(ellipsis, x + font.getStringWidth(truncatedMethod), y, baseColor); + } + } + } + + /** + * Draw text with specific characters highlighted. + */ + private void drawHighlightedText(String text, int[] matchIndices, int x, int y, int baseColor) { + if (matchIndices == null || matchIndices.length == 0) { + font.drawString(text, x, y, baseColor); + return; + } + + // Create a set of highlighted indices for quick lookup + java.util.Set highlightSet = new java.util.HashSet<>(); + for (int idx : matchIndices) { + highlightSet.add(idx); + } + + // Draw character by character + int currentX = x; + for (int i = 0; i < text.length(); i++) { + String ch = String.valueOf(text.charAt(i)); + int color = highlightSet.contains(i) ? HIGHLIGHT_COLOR : baseColor; + font.drawString(ch, currentX, y, color); + currentX += font.getStringWidth(ch); + } + } + + /** + * Draw text with highlighting, truncated if too long. + */ + private void drawHighlightedTextTruncated(String text, int[] matchIndices, int x, int y, int baseColor, int maxWidth) { + int textWidth = font.getStringWidth(text); + + if (textWidth <= maxWidth) { + // Fits, draw normally + drawHighlightedText(text, matchIndices, x, y, baseColor); + } else { + // Truncate with ellipsis + String ellipsis = "..."; + int ellipsisWidth = font.getStringWidth(ellipsis); + String truncated = truncateString(text, maxWidth - ellipsisWidth); + + // Adjust match indices for truncated text + int[] adjustedIndices = null; + if (matchIndices != null) { + java.util.List validIndices = new java.util.ArrayList<>(); + for (int idx : matchIndices) { + if (idx < truncated.length()) { + validIndices.add(idx); + } + } + adjustedIndices = new int[validIndices.size()]; + for (int i = 0; i < validIndices.size(); i++) { + adjustedIndices[i] = validIndices.get(i); + } + } + + drawHighlightedText(truncated, adjustedIndices, x, y, baseColor); + font.drawString(ellipsis, x + font.getStringWidth(truncated), y, baseColor); + } + } + + /** + * Truncate a string to fit within the given width. + */ + private String truncateString(String text, int maxWidth) { + if (text.isEmpty()) return text; + + int width = 0; + for (int i = 0; i < text.length(); i++) { + width += font.getStringWidth(String.valueOf(text.charAt(i))); + if (width > maxWidth) { + return text.substring(0, Math.max(0, i)); + } + } + return text; + } + + private void drawTypeLabel(AutocompleteItem item, String typeLabel, int x, int y, int typeColor, TypeInfo typeInfo) { + if (typeInfo == null || item.getKind() == AutocompleteItem.Kind.CLASS) { //draw package on right + // draw default package color instead of interface/enum colors + if (typeInfo != null && !typeInfo.isClass()) + typeColor = TokenType.getPackageColor(); + drawSimpleTypeWithArraySuffix(typeLabel, x, y, typeColor); + return; + } + drawTypeLabel(x, y, typeInfo, 0); + } + + private int drawTypeLabel(int x, int y, TypeInfo typeInfo, int depth) { + if (depth > 25) { + String name = typeInfo.getDisplayName(); + font.drawString(name, x, y, TokenType.getColor(typeInfo)); + return x + font.getStringWidth(name); + } + int defaultColor = TokenType.DEFAULT.getHexColor(); + if (typeInfo.isParameterized()) { + TypeInfo raw = typeInfo.getRawType(); + x = drawSimpleTypeWithArraySuffix(raw.getDisplayName(), x, y, TokenType.getColor(raw)); + font.drawString("<", x, y, defaultColor); + x += font.getStringWidth("<"); + java.util.List args = typeInfo.getAppliedTypeArgs(); + for (int i = 0; i < args.size(); i++) { + if (i > 0) { + font.drawString(", ", x, y, defaultColor); + x += font.getStringWidth(", "); + } + x = drawTypeLabel(x, y, args.get(i), depth + 1); + } + font.drawString(">", x, y, defaultColor); + return x + font.getStringWidth(">"); + } + return drawSimpleTypeWithArraySuffix(typeInfo.getDisplayName(), x, y, TokenType.getColor(typeInfo)); + } + + /** @return x position after last drawn character */ + private int drawSimpleTypeWithArraySuffix(String typeLabel, int x, int y, int typeColor) { + if (!typeLabel.endsWith("[]")) { + font.drawString(typeLabel, x, y, typeColor); + return x + font.getStringWidth(typeLabel); + } + int suffixStart = typeLabel.length() - 2; + while (suffixStart >= 2 && typeLabel.charAt(suffixStart - 2) == '[' && typeLabel.charAt(suffixStart - 1) == ']') { + suffixStart -= 2; + } + String core = typeLabel.substring(0, suffixStart); + String suffix = typeLabel.substring(suffixStart); + font.drawString(core, x, y, typeColor); + int coreWidth = font.getStringWidth(core); + font.drawString(suffix, x + coreWidth, y, TokenType.DEFAULT.getHexColor()); + return x + coreWidth + font.getStringWidth(suffix); + } + + private void drawScrollbar(int mouseX, int mouseY) { + int scrollbarX = x + width - 8; + int scrollbarY = y + PADDING; + int visibleCount = getVisibleItemCapacity(); + if (visibleCount <= 0) + return; + int scrollbarHeight = visibleCount * ITEM_HEIGHT - 8; // leave room for resize handle + + // Background + drawRect(scrollbarX, scrollbarY, scrollbarX + 6, scrollbarY + scrollbarHeight, SCROLLBAR_BG); + + // Thumb + float thumbRatio = (float) visibleCount / items.size(); + int thumbHeight = Math.max(20, (int) (scrollbarHeight * thumbRatio)); + float thumbPosRatio = Math.min(1f, (float) scrollOffset / Math.max(1, items.size() - visibleCount)); + int thumbY = scrollbarY + (int) ((scrollbarHeight - thumbHeight) * thumbPosRatio); + thumbY = Math.max(scrollbarY, Math.min(scrollbarY + scrollbarHeight - thumbHeight, thumbY)); + + // Check if mouse is above the scrollbar thumb + boolean isAboveScrollbar = mouseX >= scrollbarX && mouseX <= scrollbarX + 6 && + mouseY >= thumbY && mouseY < thumbY + thumbHeight; + + int col = isDraggingScrollbar || isAboveScrollbar? 0xFF808080 : SCROLLBAR_FG; + + drawRect(scrollbarX + 1, thumbY, scrollbarX + 5, thumbY + thumbHeight, col); + } + + /** + * Draw the hint bar at the bottom (shows Tab/Enter to confirm). + */ + private void drawHintBar() { + int hintY = y + height - HINT_HEIGHT; + + // Darker background for hint area + drawRect(x + 1, hintY, x + width - 1, y + height - 1, HINT_BG_COLOR); + + // Draw hints + int hintTextY = hintY + (HINT_HEIGHT - font.FONT_HEIGHT) / 2; + int hintX = x + PADDING; + + // Tab hint + drawKeyHint("Tab", hintX, hintTextY); + hintX += font.getStringWidth("Tab") + 8; + font.drawString("or", hintX, hintTextY, DIM_TEXT_COLOR); + hintX += font.getStringWidth("or") + 4; + + // Enter hint + drawKeyHint("Enter", hintX, hintTextY); + hintX += font.getStringWidth("Enter") + 8; + font.drawString("to insert", hintX, hintTextY, DIM_TEXT_COLOR); + } + + /** + * Draw a key hint with a darker background box. + */ + private void drawKeyHint(String key, int x, int y) { + int keyWidth = font.getStringWidth(key); + int boxPadding = 2; + + // Draw box + drawRect(x - boxPadding, y - boxPadding, + x + keyWidth + boxPadding, y + font.FONT_HEIGHT + boxPadding, + 0xFF404040); + + // Draw key text + font.drawString(key, x, y, TEXT_COLOR); + } + + // ==================== MOUSE HANDLING ==================== + + /** + * Update hover state based on mouse position. + */ + private void updateHoverState(int mouseX, int mouseY) { + hoveredIndex = -1; + + if (!isMouseInBounds(mouseX, mouseY)) return; + + int itemY = y + PADDING; + + int visibleItems = getVisibleItemCapacity(); + + for (int i = 0; i <= visibleItems; i++) { + int idx = scrollOffset + i; + if (idx >= items.size()) break; + if (mouseY >= itemY && mouseY < itemY + ITEM_HEIGHT) { + hoveredIndex = idx; + break; + } + itemY += ITEM_HEIGHT; + } + } + + /** + * Handle mouse click. + * @return true if click was consumed + */ + public boolean mouseClicked(int mouseX, int mouseY, int button) { + if (!visible) return false; + + // Check if click is outside menu + if (!isMouseInBounds(mouseX, mouseY)) { + hide(); + return false; + } + + // Resize handle has top priority + if (button == 0 && isMouseOverResizeHandle(mouseX, mouseY)) { + isResizingPanel = true; + resizeInitMouseX = mouseX; resizeInitMouseY = mouseY; + resizeInitW = width; resizeInitH = height; + return true; + } + + // Scrollbar + if (button == 0 && items.size() > getVisibleItemCapacity()) { + int scrollbarX = x + width - 8; + if (mouseX >= scrollbarX && mouseX <= scrollbarX + 6) { + isDraggingScrollbar = true; + dragStartY = mouseY; + dragStartScroll = scrollOffset; + return true; + } + } + + // Anywhere inside panel body — start pending drag, defer item confirm to release + if (button == 0) { + hasPendingPanelDrag = true; + pendingDragStartX = mouseX; + pendingDragStartY = mouseY; + panelDragOffsetX = mouseX - x; + panelDragOffsetY = mouseY - y; + if (hoveredIndex >= 0 && hoveredIndex < items.size()) { + selectedIndex = hoveredIndex; + pendingItemConfirm = true; + } + return true; + } + + return true; // Consume click if inside menu + } + + /** + * Handle mouse release. + * @return true if release was consumed + */ + public boolean mouseReleased(int mouseX, int mouseY, int button) { + if (button == 0) { + if (isDraggingScrollbar) { isDraggingScrollbar = false; return true; } + if (isDraggingPanel) { isDraggingPanel = false; return true; } + if (isResizingPanel) { isResizingPanel = false; return true; } + hasPendingPanelDrag = false; + if (pendingItemConfirm) { + pendingItemConfirm = false; + confirmSelection(); + return true; + } + } + return false; + } + + /** + * Handle mouse drag. + * @return true if drag was consumed + */ + public boolean mouseDragged(int mouseX, int mouseY) { + if (!visible) return false; + if (isDraggingPanel) { updatePanelDrag(mouseX, mouseY); return true; } + if (isResizingPanel) { updatePanelResize(mouseX, mouseY); return true; } + + // Activate panel drag once movement exceeds threshold + if (hasPendingPanelDrag) { + int dx = Math.abs(mouseX - pendingDragStartX); + int dy = Math.abs(mouseY - pendingDragStartY); + if (dx > DRAG_THRESHOLD || dy > DRAG_THRESHOLD) { + isDraggingPanel = true; + hasPendingPanelDrag = false; + pendingItemConfirm = false; // cancel any pending selection + updatePanelDrag(mouseX, mouseY); + return true; + } + return true; + } + + if (!isDraggingScrollbar) return false; + // Scrollbar drag (kept for backward compat — also handled via draw loop) + int visibleCount = getVisibleItemCapacity(); + if (visibleCount <= 0) return false; + int scrollbarHeight = visibleCount * ITEM_HEIGHT - 8; + int thumbHeight = Math.max(20, (int) (scrollbarHeight * (float) visibleCount / Math.max(1, items.size()))); + int scrollTrackHeight = Math.max(1, scrollbarHeight - thumbHeight); + int maxScroll = items.size() - visibleCount; + int deltaY = mouseY - dragStartY; + int scrollDelta = (deltaY * maxScroll) / scrollTrackHeight; + scrollOffset = Math.max(0, Math.min(maxScroll, dragStartScroll + scrollDelta)); + return true; + } + + /** + * Handle mouse scroll. + * @return true if scroll was consumed + */ + public boolean mouseScrolled(int mouseX, int mouseY, int delta) { + if (!visible || !isMouseInBounds(mouseX, mouseY)) return false; + + int visibleCount = getVisibleItemCapacity(); + if (items.size() > visibleCount) { + if (delta > 0) { + scrollOffset = Math.max(0, scrollOffset - 1); + } else { + scrollOffset = Math.min(items.size() - visibleCount, scrollOffset + 1); + } + return true; + } + + return false; + } + + private boolean isMouseInBounds(int mouseX, int mouseY) { + return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height; + } + + // ==================== UTILITY ==================== + + private void setScissor(int x, int y, int width, int height) { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + + if (ownerGui != null) { + x -= (int) ownerGui.getPanX(); + y -= (int) ownerGui.getPanY(); + } + + int scissorX = x * scaleFactor; + int scissorY = mc.displayHeight - (y + height) * scaleFactor; + int scissorW = width * scaleFactor; + int scissorH = height * scaleFactor; + + GL11.glScissor(scissorX, scissorY, scissorW, scissorH); + } + + // ==================== GETTERS ==================== + + public int getX() { return x; } + public int getY() { return y; } + public int getWidth() { return width; } + public int getHeight() { return height; } + public List getItems() { return items; } + // ==================== PANEL DRAG / RESIZE ==================== + + public boolean isMouseOverResizeHandle(int mx, int my) { + if (!visible) return false; + return mx >= x + width - 8 && mx <= x + width && my >= y + height - 8 && my <= y + height; + } + + public void updatePanelDrag(int mouseX, int mouseY) { + if (!isDraggingPanel) return; + x = mouseX - panelDragOffsetX; + y = mouseY - panelDragOffsetY; + overriddenX = x; + overriddenY = y; + panelPositionOverridden = true; + } + + public void releasePanelDrag() { isDraggingPanel = false; hasPendingPanelDrag = false; } + + public void updatePanelResize(int mouseX, int mouseY) { + if (!isResizingPanel) return; + overriddenW = Math.max(MIN_RESIZE_W, resizeInitW + (mouseX - resizeInitMouseX)); + overriddenH = Math.max(MIN_RESIZE_H, resizeInitH + (mouseY - resizeInitMouseY)); + panelSizeOverridden = true; + menuWidth = overriddenW; + width = overriddenW; + height = overriddenH; + visibleItemsCount = Math.max(1, (overriddenH - HINT_HEIGHT - PADDING * 2) / ITEM_HEIGHT); + } + + public void releasePanelResize() { isResizingPanel = false; } + + /** Used by draw-loop scrollbar update in GuiScriptTextArea */ + public void updateScrollbarDragDraw(int mouseY) { + if (!isDraggingScrollbar || items.isEmpty()) return; + int visibleCount = getVisibleItemCapacity(); + if (visibleCount <= 0) return; + int scrollbarHeight = visibleCount * ITEM_HEIGHT - 8; + int thumbHeight = Math.max(20, (int) (scrollbarHeight * (float) visibleCount / items.size())); + int scrollTrackHeight = Math.max(1, scrollbarHeight - thumbHeight); + int maxScroll = items.size() - visibleCount; + int deltaY = mouseY - dragStartY; + int scrollDelta = (deltaY * maxScroll) / scrollTrackHeight; + scrollOffset = Math.max(0, Math.min(maxScroll, dragStartScroll + scrollDelta)); + } + + public void releaseScrollbarDrag() { isDraggingScrollbar = false; } + + public boolean isDraggingPanel() { return isDraggingPanel; } + public boolean isDraggingScrollbarMenu() { return isDraggingScrollbar; } + public boolean isResizingPanel() { return isResizingPanel; } + + private void drawResizeHandle(int mouseX, int mouseY) { + boolean resizeActive = isResizingPanel || isMouseOverResizeHandle(mouseX, mouseY); + int dotColor = resizeActive ? 0xFFCCCCCC : 0x80888888; + int rhX = x + width - 2; + int rhY = y + height - 2; + // Three-dot diagonal pattern (◢) + drawRect(rhX - 1, rhY - 1, rhX, rhY, dotColor); + drawRect(rhX - 3, rhY - 1, rhX - 2, rhY, dotColor); + drawRect(rhX - 1, rhY - 3, rhX, rhY - 2, dotColor); + drawRect(rhX - 5, rhY - 1, rhX - 4, rhY, dotColor); + drawRect(rhX - 3, rhY - 3, rhX - 2, rhY - 2, dotColor); + drawRect(rhX - 1, rhY - 5, rhX, rhY - 4, dotColor); + } + +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteProvider.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteProvider.java new file mode 100644 index 000000000..a11282d24 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteProvider.java @@ -0,0 +1,74 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import java.util.List; + +/** + * Abstract provider for autocomplete suggestions. + * Implementations handle different contexts (after dot, in identifier, etc.) + */ +public interface AutocompleteProvider { + + /** + * Context information for autocomplete requests. + */ + class Context { + /** Full text of the document */ + public final String text; + /** Current cursor position in the document */ + public final int cursorPosition; + /** The current line number (0-indexed) */ + public final int lineNumber; + /** Position of cursor within the current line */ + public final int columnPosition; + /** The current line text */ + public final String currentLine; + /** The word being typed (prefix before cursor, after last separator) */ + public final String prefix; + /** Start position of the prefix in the document */ + public final int prefixStart; + /** Whether this is after a dot (member access) */ + public final boolean isMemberAccess; + /** Expression before the dot (for member access) */ + public final String receiverExpression; + /** Whether autocomplete was explicitly triggered (CTRL+Space) */ + public final boolean explicitTrigger; + /** Whether to show only methods (for method reference context ::) */ + public final boolean methodsOnly; + + public Context(String text, int cursorPosition, int lineNumber, int columnPosition, + String currentLine, String prefix, int prefixStart, + boolean isMemberAccess, String receiverExpression, boolean explicitTrigger) { + this(text, cursorPosition, lineNumber, columnPosition, currentLine, prefix, prefixStart, + isMemberAccess, receiverExpression, explicitTrigger, false); + } + + public Context(String text, int cursorPosition, int lineNumber, int columnPosition, + String currentLine, String prefix, int prefixStart, + boolean isMemberAccess, String receiverExpression, boolean explicitTrigger, + boolean methodsOnly) { + this.text = text; + this.cursorPosition = cursorPosition; + this.lineNumber = lineNumber; + this.columnPosition = columnPosition; + this.currentLine = currentLine; + this.prefix = prefix; + this.prefixStart = prefixStart; + this.isMemberAccess = isMemberAccess; + this.receiverExpression = receiverExpression; + this.explicitTrigger = explicitTrigger; + this.methodsOnly = methodsOnly; + } + } + + /** + * Get autocomplete suggestions for the given context. + * @param context The context containing cursor position, text, etc. + * @return List of autocomplete items, sorted by relevance + */ + List getSuggestions(Context context); + + /** + * Check if this provider can handle the given context. + */ + boolean canProvide(Context context); +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/CompletionWeigherChains.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/CompletionWeigherChains.java new file mode 100644 index 000000000..010e2dea1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/CompletionWeigherChains.java @@ -0,0 +1,33 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import noppes.npcs.client.gui.util.script.autocomplete.weighter.*; + +import java.util.Arrays; + +public class CompletionWeigherChains { + + public static WeigherChain javaChain() { + return new WeigherChain(Arrays.asList( + new MatchQualityWeigher(), + new MemberKindWeigher(), + new ContextFitWeigher(), + new ImportStatusWeigher(), + new UsageFrequencyWeigher(), + new DeprecatedWeigher(), + new AlphabeticalWeigher() + )); + } + + public static WeigherChain jsChain() { + return new WeigherChain(Arrays.asList( + new MatchQualityWeigher(), + new MemberKindWeigher(), + new ContextFitWeigher(), + new ImportStatusWeigher(), + new UsageFrequencyWeigher(), + new InheritanceDepthWeigher(), + new DeprecatedWeigher(), + new AlphabeticalWeigher() + )); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JSAutocompleteProvider.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JSAutocompleteProvider.java new file mode 100644 index 000000000..d6a49846e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JSAutocompleteProvider.java @@ -0,0 +1,361 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import noppes.npcs.client.gui.util.script.autocomplete.weighter.WeigherChain; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.*; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.*; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.config.ConfigScript; + +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * Autocomplete provider for JavaScript/ECMAScript scripts. + * Uses ScriptDocument's unified TypeInfo/TypeResolver system for type resolution. + */ +public class JSAutocompleteProvider extends JavaAutocompleteProvider { + + private final JSTypeRegistry registry; + + public JSAutocompleteProvider() { + this.registry = JSTypeRegistry.getInstance(); + if (!registry.isInitialized()) { + registry.initializeFromResources(); + } + } + + @Override + public boolean canProvide(Context context) { + return document != null && document.isJavaScript(); + } + + + /** + * Add suggestions for member access (after dot). + * Uses ScriptDocument's unified type resolution system. + * + * Fixes applied vs original implementation: + * - Single getMemberAccessResolvePosition() call (was duplicated) + * - Single getMergeRegistryType() call (was duplicated) + * - Shared addedMethods/addedFields sets across ALL sources for cross-source deduplication + * - Unified nested type lookup via getAllNestedTypes() instead of raw reflection + * - Single Object method injection path (registry-based via fromJSMethod) + * - Name-based Object.class guard instead of fragile Class identity comparison + * - Logged SecurityException instead of silently swallowed + */ + protected void addMemberSuggestions(Context context, List items) { + String receiverExpr = context.receiverExpression; + if (receiverExpr == null || receiverExpr.isEmpty()) { + return; + } + + // Resolve position once — used for both type resolution and static context detection + int resolvePos = getMemberAccessResolvePosition(context); + + // Use ScriptDocument's resolveExpressionType - handles both Java and JS + TypeInfo receiverType = document.resolveExpressionType(receiverExpr, resolvePos); + if (receiverType == null || !receiverType.isResolved()) { + return; + } + + // --- JS-SPECIFIC: synthetic type early return --- + SyntheticType syntheticType = document.getTypeResolver().getSyntheticType(receiverType.getSimpleName()); + if (syntheticType != null) { + addSyntheticTypeSuggestions(syntheticType, items, context.methodsOnly); + return; + } + + boolean isStaticContext = isStaticAccess(receiverExpr, resolvePos); + + // Resolve merge-registry type once — used for both method and field fallback + Class javaClass = receiverType.getJavaClass(); + JSTypeInfo mergeRegistryType = (javaClass != null + && receiverType.getSyntheticMethods().isEmpty() + && receiverType.getSyntheticFields().isEmpty()) + ? getMergeRegistryType(javaClass) : null; + + // Shared deduplication sets — prevent the same method/field appearing from multiple sources + Set addedMethods = new HashSet<>(); + Set addedFields = new HashSet<>(); + + // ---- SHARED: unified method enumeration (TypeInfo.getAllMethods covers reflection + synthetics) ---- + for (MethodInfo method : receiverType.getAllMethods()) { + if (isStaticContext && !Modifier.isStatic(method.getModifiers())) + continue; + String sig = method.getName() + "(" + method.getParameterCount() + ")"; + if (addedMethods.add(sig)) + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + + // --- JS-SPECIFIC: merge registry type fallback for methods --- + if (mergeRegistryType != null) { + addMethodsFromType(mergeRegistryType, receiverType, items, addedMethods, context.methodsOnly, + isStaticContext); + } + + if (!context.methodsOnly) { + // ---- SHARED: unified field enumeration with deduplication ---- + for (FieldInfo field : receiverType.getAllFields()) { + if (isStaticContext && !Modifier.isStatic(field.getModifiers())) + continue; + if (addedFields.add(field.getName())) + items.add(AutocompleteItem.fromField(field)); + } + + // --- JS-SPECIFIC: merge registry type fallback for fields --- + if (mergeRegistryType != null) { + addFieldsFromType(mergeRegistryType, receiverType, items, addedFields, isStaticContext); + } + } + + // ---- SHARED: nested types (inner classes) in static context via getAllNestedTypes() ---- + if (isStaticContext && !context.methodsOnly) { + // ScriptTypeInfo.getAllNestedTypes() returns script inner classes directly; + // TypeInfo.getAllNestedTypes() uses reflection. No duplicate logic needed. + for (TypeInfo nestedType : receiverType.getAllNestedTypes()) { + items.add(AutocompleteItem.fromType(nestedType)); + } + } + + // Enum constants — polymorphic via TypeInfo.getEnumConstants() + if (!context.methodsOnly) { + for (EnumConstantInfo enumConstant : receiverType.getEnumConstants().values()) { + items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo())); + } + } + + // --- JS-SPECIFIC: Object methods from JS registry (single unified path) --- + // Add Object.class JS methods for instance access, unless receiver IS Object itself. + // Uses name comparison instead of Class identity for robustness across classloaders. + if (!isStaticContext && (javaClass == null || !"java.lang.Object".equals(javaClass.getName()))) { + JSTypeInfo objJSType = registry.getType("Object"); + if (objJSType != null) { + for (JSMethodInfo m : objJSType.getMethods().values()) { + if (!m.isStatic()) { + String sig = m.getName() + "(" + m.getParameterCount() + ")"; + if (addedMethods.add(sig)) { + items.add(AutocompleteItem.fromJSMethod(m, receiverType, 1, context.methodsOnly)); + } + } + } + } + } + + // --- JS-SPECIFIC: pure JS type fallback (javaClass == null, not ScriptTypeInfo) --- + if (javaClass == null && !(receiverType instanceof ScriptTypeInfo)) { + JSTypeInfo jsTypeInfo = receiverType.getJSTypeInfo(); + if (jsTypeInfo != null) { + addMethodsFromType(jsTypeInfo, receiverType, items, addedMethods, context.methodsOnly, isStaticContext); + if (!context.methodsOnly && ConfigScript.ShowImplementationFieldsInAutocomplete) { + addFieldsFromType(jsTypeInfo, receiverType, items, addedFields, isStaticContext); + } + } + } + } + + private JSTypeInfo getMergeRegistryType(Class javaClass) { + return document.getTypeResolver().findJSTypeForJavaClass(javaClass); + } + + /** + * Add autocomplete suggestions for a synthetic type's methods and fields. + * @param syntheticType The synthetic type + * @param items The list to add items to + * @param forMethodReference If true, only add methods with no parentheses in insert text + */ + private void addSyntheticTypeSuggestions(SyntheticType syntheticType, List items, boolean forMethodReference) { + // Add methods + for (SyntheticMethod method : syntheticType.getMethods()) { + AutocompleteItem item = AutocompleteItem.fromSyntheticMethod(method, syntheticType.getTypeInfo(), forMethodReference); + items.add(item); + } + + // Add fields (skip if forMethodReference is true) + if (!forMethodReference) { + for (SyntheticField field : syntheticType.getFields()) { + AutocompleteItem item = AutocompleteItem.fromSyntheticField(field); + items.add(item); + } + } + } + + /** + * Recursively add methods from a type and its parents. + * @param type The current JS type to get methods from (changes as we walk up inheritance) + * @param contextType The original TypeInfo context for resolving type parameters (stays constant) + */ + protected void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added) { + addMethodsFromType(type, contextType, items, added, 0, false, false); + } + + /** + * Recursively add methods from a type and its parents. + * @param type The current JS type to get methods from (changes as we walk up inheritance) + * @param contextType The original TypeInfo context for resolving type parameters (stays constant) + * @param forMethodReference If true, insert text will NOT include parentheses + */ + protected void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, boolean forMethodReference) { + addMethodsFromType(type, contextType, items, added, 0, forMethodReference, false); + } + + /** + * Recursively add methods from a type and its parents. + * @param type The current JS type to get methods from (changes as we walk up inheritance) + * @param contextType The original TypeInfo context for resolving type parameters (stays constant) + * @param forMethodReference If true, insert text will NOT include parentheses + * @param isStaticContext If true, only add static methods + */ + protected void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, boolean forMethodReference, boolean isStaticContext) { + addMethodsFromType(type, contextType, items, added, 0, forMethodReference, isStaticContext); + } + + /** + * Recursively add methods from a type and its parents with inheritance depth tracking. + * Shows all overloads - one autocomplete item per overload. + * @param type The current JS type in inheritance chain + * @param contextType The original TypeInfo context for resolving type parameters (e.g., IPlayer with T → EntityPlayerMP) + */ + private void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, int depth) { + addMethodsFromType(type, contextType, items, added, depth, false, false); + } + + /** + * Recursively add methods from a type and its parents with inheritance depth tracking. + * Shows all overloads - one autocomplete item per overload. + * @param type The current JS type in inheritance chain + * @param contextType The original TypeInfo context for resolving type parameters (e.g., IPlayer with T → EntityPlayerMP) + * @param forMethodReference If true, insert text will NOT include parentheses + */ + private void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, int depth, boolean forMethodReference) { + addMethodsFromType(type, contextType, items, added, depth, forMethodReference, false); + } + + private void addMethodsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, int depth, boolean forMethodReference, boolean isStaticContext) { + // Collect base method names (without $N suffix) that we haven't processed yet + Set baseNames = new HashSet<>(); + for (String key : type.getMethods().keySet()) { + String baseName = key.contains("$") ? key.substring(0, key.indexOf('$')) : key; + if (!added.contains(baseName)) { + baseNames.add(baseName); + } + } + + // For each base method name, add all overloads + for (String baseName : baseNames) { + added.add(baseName); + // Use getMethodOverloads to get all overloads for this method (excluding inherited) + List overloads = new ArrayList<>(); + if (type.getMethods().containsKey(baseName)) { + overloads.add(type.getMethods().get(baseName)); + } + int index = 1; + while (type.getMethods().containsKey(baseName + "$" + index)) { + overloads.add(type.getMethods().get(baseName + "$" + index)); + index++; + } + // Add one autocomplete item per overload + for (JSMethodInfo method : overloads) { + if (isStaticContext && !method.isStatic()) continue; + items.add(AutocompleteItem.fromJSMethod(method, contextType, depth, forMethodReference)); + } + } + + // Add from parent type with incremented depth - keep same contextType + if (type.getResolvedParent() != null) { + addMethodsFromType(type.getResolvedParent(), contextType, items, added, depth + 1, forMethodReference, isStaticContext); + } + } + + /** + * Recursively add fields from a type and its parents. + * @param type The current JS type to get fields from (changes as we walk up inheritance) + * @param contextType The original TypeInfo context for resolving type parameters (stays constant) + */ + protected void addFieldsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added) { + addFieldsFromType(type, contextType, items, added, 0, false); + } + + protected void addFieldsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, boolean isStaticContext) { + addFieldsFromType(type, contextType, items, added, 0, isStaticContext); + } + + /** + * Recursively add fields from a type and its parents with inheritance depth tracking. + * @param type The current JS type in inheritance chain + * @param contextType The original TypeInfo context for resolving type parameters + */ + private void addFieldsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, int depth) { + addFieldsFromType(type, contextType, items, added, depth, false); + } + + private void addFieldsFromType(JSTypeInfo type, TypeInfo contextType, List items, Set added, int depth, boolean isStaticContext) { + for (JSFieldInfo field : type.getFields().values()) { + if (!added.contains(field.getName())) { + if (isStaticContext && !field.isStatic()) continue; + added.add(field.getName()); + // Pass contextType (original receiver) for type parameter resolution, not current type + items.add(AutocompleteItem.fromJSField(field, contextType, depth)); + } + } + + // Add from parent type with incremented depth - keep same contextType + if (type.getResolvedParent() != null) { + addFieldsFromType(type.getResolvedParent(), contextType, items, added, depth + 1, isStaticContext); + } + } + + protected void addUnimportedClassSuggestions(String prefix, List items) { + // For JavaScript, we typically don't suggest unimported classes + // as imports are handled differently. This can be customized + // if needed to suggest global JS types. + } + + @Override + protected void addLanguageUniqueSuggestions(Context context, List items) { + super.addLanguageUniqueSuggestions(context, items); + + // Add global variables from both global engine objects and document editor/DataScript globals + List globalNames = new ArrayList<>(); + globalNames.addAll(registry.getGlobalEngineObjects().keySet()); + globalNames.addAll(document.getEditorGlobals().keySet()); + + for (String name : globalNames) { + FieldInfo fieldInfo = document.resolveVariable(name, context.cursorPosition); + if (fieldInfo == null || !fieldInfo.isResolved()) + continue; + + items.add(AutocompleteItem.fromField(fieldInfo)); + } + + // Add global imports in JSTypeRegistry.globalEngineImports + for (String importName : registry.getGlobalEngineImports().keySet()) { + JSTypeInfo jsTypeInfo = registry.getGlobalImportType(importName); + if (jsTypeInfo != null) { + items.add(AutocompleteItem.fromType(TypeInfo.fromJSTypeInfo(jsTypeInfo))); + } + } + + // Add global engine functions (parseInt, parseFloat, isNaN, isFinite, etc.) + for (JSMethodInfo fn : registry.getGlobalEngineFunctions().values()) { + items.add(AutocompleteItem.fromJSMethod(fn, 0)); + } + } + + protected UsageTracker getUsageTracker() { + return UsageTracker.getJSInstance(); + } + + @Override + protected WeigherChain getWeigherChain() { + return CompletionWeigherChains.jsChain(); + } + + public String[] getKeywords() { + return TypeChecker.getJavaScriptKeywords(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JavaAutocompleteProvider.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JavaAutocompleteProvider.java new file mode 100644 index 000000000..acb9cee3f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JavaAutocompleteProvider.java @@ -0,0 +1,398 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import noppes.npcs.client.gui.util.script.autocomplete.weighter.ScoringContext; +import noppes.npcs.client.gui.util.script.autocomplete.weighter.WeigherChain; +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * Autocomplete provider for Java/Groovy scripts. + * Uses ScriptDocument for type resolution and scope analysis. + */ +public class JavaAutocompleteProvider implements AutocompleteProvider { + + protected ScriptDocument document; + + public void setDocument(ScriptDocument document) { + this.document = document; + } + + @Override + public boolean canProvide(Context context) { + return document != null && !document.isJavaScript(); + } + + @Override + public List getSuggestions(Context context) { + List items = new ArrayList<>(); + + if (document == null) { + return items; + } + + // Resolve owner type for usage tracking and static context detection + String ownerFullName = null; + boolean isStaticContext = false; + if (context.isMemberAccess && context.receiverExpression != null) { + int resolvePos = getMemberAccessResolvePosition(context); + TypeInfo receiverType = document.resolveExpressionType( + context.receiverExpression, resolvePos); + if (receiverType != null && receiverType.isResolved()) { + ownerFullName = receiverType.getFullName(); + } + // Check if accessing through a class (static context) vs instance + isStaticContext = isStaticAccess(context.receiverExpression, resolvePos); + } + + if (context.isMemberAccess) { + // Member access: resolve type of receiver and get its members + addMemberSuggestions(context, items); + } else { + // Identifier context: show variables, methods, types in scope + addScopeSuggestions(context, items); + } + + // For method reference context, filter to show only methods (and constructor "new") + if (context.methodsOnly) { + items.removeIf(item -> item.getKind() != AutocompleteItem.Kind.METHOD); + + // Add "new" constructor reference option if the receiver is a class + if (context.receiverExpression != null) { + int resolvePos = getMemberAccessResolvePosition(context); + TypeInfo receiverType = document.resolveExpressionType( + context.receiverExpression, resolvePos); + if (receiverType != null && receiverType.isResolved() && isStaticContext) { + items.add(new AutocompleteItem.Builder() + .name("new") + .insertText("new") + .kind(AutocompleteItem.Kind.KEYWORD) + .typeLabel("constructor") + .signature(receiverType.getSimpleName() + "::new") + .build()); + } + } + } + + // Filter by prefix, then sort using weigher chain + filterAndScore(items, context.prefix, context.isMemberAccess, isStaticContext, ownerFullName); + + return items; + } + + /** + * Add suggestions for member access (after dot). + */ + protected void addMemberSuggestions(Context context, List items) { + String receiverExpr = context.receiverExpression; + if (receiverExpr == null || receiverExpr.isEmpty()) { + return; + } + + // Resolve position once — used for both type resolution and static context detection + int resolvePos = getMemberAccessResolvePosition(context); + + TypeInfo receiverType = document.resolveExpressionType(receiverExpr, resolvePos); + + if (receiverType == null || !receiverType.isResolved()) { + return; + } + + boolean isStaticContext = isStaticAccess(receiverExpr, resolvePos); + + // Shared deduplication sets across all member sources + Set addedMethods = new HashSet<>(); + Set addedFields = new HashSet<>(); + + // Unified method enumeration — works for Java types, ScriptTypeInfo, and intersection bounds + for (MethodInfo method : receiverType.getAllMethods()) { + if (isStaticContext && !Modifier.isStatic(method.getModifiers())) continue; + String sig = method.getName() + "(" + method.getParameterCount() + ")"; + if (addedMethods.add(sig)) + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + + if (!context.methodsOnly) { + // Unified field enumeration with deduplication + for (FieldInfo field : receiverType.getAllFields()) { + if (isStaticContext && !Modifier.isStatic(field.getModifiers())) continue; + if (addedFields.add(field.getName())) + items.add(AutocompleteItem.fromField(field)); + } + } + + // Nested types (inner classes) in static context via getAllNestedTypes() + if (isStaticContext && !context.methodsOnly) { + for (TypeInfo nestedType : receiverType.getAllNestedTypes()) { + items.add(AutocompleteItem.fromType(nestedType)); + } + } + + // Enum constants — polymorphic via TypeInfo.getEnumConstants() + if (!context.methodsOnly) { + for (EnumConstantInfo enumConstant : receiverType.getEnumConstants().values()) { + items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo())); + } + } + } + + /** + * Pick a stable position for resolving member-access receiver types. + * + * Using `prefixStart` can land on end-exclusive scope boundaries (position == bodyEnd) + * depending on caller cursor semantics and surrounding syntax, causing scope lookups + * to fail. For member access we prefer the dot position (or nearest non-whitespace) + * immediately before prefixStart. + */ + protected int getMemberAccessResolvePosition(Context context) { + if (context == null || context.text == null || context.text.isEmpty()) { + return 0; + } + + int pos = Math.max(0, Math.min(context.prefixStart, context.text.length())); + int i = Math.min(pos - 1, context.text.length() - 1); + + // Skip whitespace backwards + while (i >= 0 && Character.isWhitespace(context.text.charAt(i))) { + i--; + } + + // Prefer the dot index if present + if (i >= 0 && context.text.charAt(i) == '.') { + return i; + } + + // Fallback: use the provided prefixStart (caret context) + return Math.max(0, Math.min(context.prefixStart, context.text.length())); + } + + /** + * Add suggestions based on current scope (not after a dot). + */ + protected void addScopeSuggestions(Context context, List items) { + int pos = context.cursorPosition; + + // Find containing method + MethodInfo containingMethod = document.findContainingMethod(pos); + + // Add local variables + if (containingMethod != null) { + List available = document.getAvailableVariablesAt(pos); + Set seenNames = new HashSet<>(); + for (FieldInfo field : available) { + if (!(field.isLocal() || field.isParameter())) { + continue; + } + if (seenNames.add(field.getName())) { + items.add(AutocompleteItem.fromField(field)); + } + } + } + + // Add global fields + for (FieldInfo globalField : document.getGlobalFields().values()) { + if (globalField.isVisibleAt(pos)) { + items.add(AutocompleteItem.fromField(globalField)); + } + } + + // Add enclosing type fields (find via script types map) + ScriptTypeInfo enclosingType = findEnclosingType(pos); + if (enclosingType != null) { + for (FieldInfo field : enclosingType.getFields().values()) { + if (field.isVisibleAt(pos)) { + items.add(AutocompleteItem.fromField(field)); + } + } + + // Add methods from enclosing type + for (List overloads : enclosingType.getMethods().values()) { + for (MethodInfo method : overloads) { + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + } + + // Add inner classes of the enclosing type as type suggestions + for (ScriptTypeInfo inner : enclosingType.getInnerClasses()) { + items.add(AutocompleteItem.fromType(inner)); + } + + // Walk up the outerClass chain to include outer class members and sibling types. + // Inside a nested class, users can access outer class fields/methods/sibling types. + ScriptTypeInfo outer = enclosingType.getOuterClass(); + while (outer != null) { + for (ScriptTypeInfo sibling : outer.getInnerClasses()) { + if (sibling != enclosingType) { + items.add(AutocompleteItem.fromType(sibling)); + } + } + for (FieldInfo field : outer.getFields().values()) { + items.add(AutocompleteItem.fromField(field)); + } + for (List overloads : outer.getMethods().values()) { + for (MethodInfo method : overloads) { + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + } + outer = outer.getOuterClass(); + } + } + + // Add script-defined methods + for (MethodInfo method : document.getAllMethods()) { + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + + addLanguageUniqueSuggestions(context, items); + + // Add keywords + addKeywords(items); + } + + protected void addLanguageUniqueSuggestions(Context context, List items) { + // Add imported types + for (TypeInfo type : document.getImportedTypes()) { + items.add(AutocompleteItem.fromType(type)); + } + + // Add script-defined types + for (ScriptTypeInfo scriptType : document.getScriptTypesMap().values()) { + items.add(AutocompleteItem.fromType(scriptType)); + } + + // Add unimported classes that match the prefix (for auto-import) + if (context.prefix != null && context.prefix.length() >= 2 && Character.isUpperCase(context.prefix.charAt(0))) { + addUnimportedClassSuggestions(context.prefix, items); + } + } + + + /** + * Add suggestions for unimported classes that match the prefix. + * These will trigger auto-import when selected. + */ + protected void addUnimportedClassSuggestions(String prefix, List items) { + // Get the type resolver + TypeResolver resolver = TypeResolver.getInstance(); + // Find classes matching this prefix (not just exact matches) + List matchingClasses = resolver.findClassesByPrefix(prefix, -1); + + // Track what's already imported to avoid duplicates + Set importedFullNames = new HashSet<>(); + for (TypeInfo imported : document.getImportedTypes()) { + importedFullNames.add(imported.getFullName()); + } + + // Also track simple names already in the list to avoid showing both + // imported and unimported versions of the same class + Set existingSimpleNames = new HashSet<>(); + for (AutocompleteItem item : items) { + if (item.getKind() == AutocompleteItem.Kind.CLASS || + item.getKind() == AutocompleteItem.Kind.ENUM) { + existingSimpleNames.add(item.getName()); + } + } + + for (String fullName : matchingClasses) { + // Skip if already imported + if (importedFullNames.contains(fullName)) { + continue; + } + + TypeInfo type = resolver.resolveFullName(fullName); + if (type != null && type.isResolved()) { + // Skip if a class with this simple name is already in the list + if (existingSimpleNames.contains(type.getSimpleName())) { + continue; + } + AutocompleteItem item = new AutocompleteItem.Builder() + .name(type.getSimpleName()) + .insertText(type.getSimpleName()) + .kind(type.getKind() == TypeInfo.Kind.ENUM ? + AutocompleteItem.Kind.ENUM : AutocompleteItem.Kind.CLASS) + .typeLabel(type.getPackageName()) + .typeInfo(type) + .signature(type.getFullName()) + .sourceData(type) + .requiresImport(true) + .importPath(fullName) + .color(TokenType.UNUSED_IMPORT.getHexColor()) + .build(); + items.add(item); + existingSimpleNames.add(type.getSimpleName()); + } + } + } + + /** + * Add Java keywords. + */ + protected void addKeywords(List items) { + for (String keyword : getKeywords()) { + items.add(AutocompleteItem.keyword(keyword)); + } + } + + public String[] getKeywords() { + return TypeChecker.getJavaKeywords(); + } + + /** + * Find the enclosing script type at a position. + * Delegates to ScriptDocument's recursive descent implementation + * which correctly returns the innermost enclosing type for nested classes. + */ + protected ScriptTypeInfo findEnclosingType(int position) { + return document.findEnclosingScriptType(position); + } + + /** + * Check if the receiver expression represents static access (class type). + * Returns true if the expression is a TYPE NAME (not a variable). + */ + protected boolean isStaticAccess(String receiverExpr, int position) { + // Use unified static access checker + return TypeResolver.isStaticAccessExpression(receiverExpr, position, document); + } + + protected UsageTracker getUsageTracker() { + return UsageTracker.getJavaInstance(); + } + + protected WeigherChain getWeigherChain() { + return CompletionWeigherChains.javaChain(); + } + + protected void filterAndScore(List items, String prefix, + boolean isMemberAccess, boolean isStaticContext, String ownerFullName) { + boolean requirePrefix = !isMemberAccess; + + Iterator iter = items.iterator(); + while (iter.hasNext()) { + AutocompleteItem item = iter.next(); + int score = item.calculateMatchScore( + prefix != null ? prefix : "", requirePrefix); + if (score < 0) { + iter.remove(); + } + } + + ScoringContext context = new ScoringContext( + prefix, isMemberAccess, isStaticContext, + ownerFullName, getUsageTracker(), requirePrefix + ); + + WeigherChain weigherChain = getWeigherChain(); + Comparator comparator = weigherChain.buildComparator(context); + items.sort(comparator); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/UsageTracker.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/UsageTracker.java new file mode 100644 index 000000000..ee95f2fdf --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/UsageTracker.java @@ -0,0 +1,284 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import noppes.npcs.CustomNpcs; + +import java.io.*; +import java.lang.reflect.Type; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Tracks user autocomplete selections to improve suggestion ranking. + * Usage counts are persisted to JSON and used to boost frequently selected items. + * + * Key format: "ownerFullName|memberName|KIND" + * - ownerFullName: Full class name for members, empty for standalone items + * - memberName: The item name (method, field, type, etc.) + * - KIND: The item kind (METHOD, FIELD, CLASS, ENUM, etc.) + * + * Examples: + * - "net.minecraft.client.Minecraft|getMinecraft|METHOD" + * - "net.minecraft.entity.player.EntityPlayer|inventory|FIELD" + * - "|EntityPlayer|CLASS" (standalone type suggestion) + * - "|if|KEYWORD" + */ +public class UsageTracker { + + private static final String JAVA_FILE = "java_usages.json"; + private static final String JS_FILE = "js_usages.json"; + private static final long SAVE_INTERVAL_MS = 60_000; // Auto-save every 60 seconds + private static final int USAGE_SCORE_MULTIPLIER = 50; // Score boost per usage + private static final int MAX_USAGE_BOOST = 5000; // Cap the boost to prevent runaway scores + + private static UsageTracker javaInstance; + private static UsageTracker jsInstance; + private static boolean initialized = false; + + private final Map usageCounts = new ConcurrentHashMap<>(); + private final File file; + private final AtomicBoolean dirty = new AtomicBoolean(false); + private final AtomicBoolean loaded = new AtomicBoolean(false); + + private static ScheduledExecutorService scheduler; + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + // ==================== SINGLETON ACCESS ==================== + + public static synchronized UsageTracker getJavaInstance() { + ensureInitialized(); + if (javaInstance == null) { + javaInstance = new UsageTracker(JAVA_FILE); + javaInstance.load(); + } + return javaInstance; + } + + public static synchronized UsageTracker getJSInstance() { + ensureInitialized(); + if (jsInstance == null) { + jsInstance = new UsageTracker(JS_FILE); + jsInstance.load(); + } + return jsInstance; + } + + /** + * Ensure the tracker system is initialized with auto-save and shutdown hook. + */ + private static void ensureInitialized() { + if (!initialized) { + initialized = true; + initialize(); + + // Add shutdown hook to save on JVM exit + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + shutdown(); + }, "UsageTracker-Shutdown")); + } + } + + /** + * Initialize the auto-save scheduler. Call once on client startup. + */ + public static void initialize() { + if (scheduler == null || scheduler.isShutdown()) { + scheduler = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "UsageTracker-AutoSave"); + t.setDaemon(true); + return t; + }); + + scheduler.scheduleAtFixedRate(() -> { + saveAllIfDirty(); + }, SAVE_INTERVAL_MS, SAVE_INTERVAL_MS, TimeUnit.MILLISECONDS); + } + } + + /** + * Shutdown and save all data. Call on client shutdown. + */ + public static void shutdown() { + saveAllIfDirty(); + if (scheduler != null && !scheduler.isShutdown()) { + scheduler.shutdown(); + } + } + + private static void saveAllIfDirty() { + if (javaInstance != null) { + javaInstance.saveIfDirty(); + } + if (jsInstance != null) { + jsInstance.saveIfDirty(); + } + } + + // ==================== INSTANCE METHODS ==================== + + UsageTracker(String filename) { + File dir = getDir(); + this.file = new File(dir, filename); + } + + private File getDir() { + File dir = new File(CustomNpcs.Dir, "tracked_usages"); + if (!dir.exists()) { + dir.mkdir(); + } + return dir; + } + + /** + * Record that the user selected an autocomplete item. + * + * @param owner The owner context (full class name for members, null/empty for standalone) + * @param name The item name + * @param kind The item kind + */ + public void recordUsage(String owner, String name, AutocompleteItem.Kind kind) { + String key = buildKey(owner, name, kind); + usageCounts.merge(key, 1, Integer::sum); + dirty.set(true); + } + + /** + * Record usage directly from an AutocompleteItem. + * + * @param item The selected autocomplete item + * @param ownerFullName The full class name of the owner (for member access), or null + */ + public void recordUsage(AutocompleteItem item, String ownerFullName) { + String name = item.getSearchName() != null ? item.getSearchName() : item.getName(); + + // For methods, include parameter count to distinguish overloads + if (item.getKind() == AutocompleteItem.Kind.METHOD) { + int paramCount = item.getParameterCount(); + name = name + "(" + paramCount + ")"; + } + + recordUsage(ownerFullName, name, item.getKind()); + } + + /** + * Get the usage count for an item. + * + * @param owner The owner context + * @param name The item name + * @param kind The item kind + * @return The number of times this item was selected + */ + public int getUsageCount(String owner, String name, AutocompleteItem.Kind kind) { + String key = buildKey(owner, name, kind); + return usageCounts.getOrDefault(key, 0); + } + + /** + * Get usage count directly from an AutocompleteItem. + */ + public int getUsageCount(AutocompleteItem item, String ownerFullName) { + String name = item.getSearchName() != null ? item.getSearchName() : item.getName(); + + // For methods, include parameter count to distinguish overloads + if (item.getKind() == AutocompleteItem.Kind.METHOD) { + int paramCount = item.getParameterCount(); + name = name + "(" + paramCount + ")"; + } + + return getUsageCount(ownerFullName, name, item.getKind()); + } + + /** + * Calculate the score boost based on usage count. + * Uses a logarithmic scale to prevent very frequent items from dominating completely. + * + * @param usageCount The number of times the item was selected + * @return The score boost to add + */ + public static int calculateUsageBoost(int usageCount) { + if (usageCount <= 0) return 0; + + // Logarithmic scaling: log2(count + 1) * multiplier + // This gives diminishing returns for very high counts + int boost = (int) (Math.log(usageCount + 1) / Math.log(2) * USAGE_SCORE_MULTIPLIER); + return Math.min(boost, MAX_USAGE_BOOST); + } + + /** + * Build a unique key for an item. + */ + public static String buildKey(String owner, String name, AutocompleteItem.Kind kind) { + String ownerPart = owner != null ? owner : ""; + String kindPart = kind != null ? kind.name() : "UNKNOWN"; + return ownerPart + "|" + name + "|" + kindPart; + } + + // ==================== PERSISTENCE ==================== + + /** + * Load usage data from file. + */ + public void load() { + if (loaded.get()) return; + + if (!file.exists()) { + loaded.set(true); + return; + } + + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + Type type = new TypeToken>(){}.getType(); + Map data = GSON.fromJson(reader, type); + if (data != null) { + usageCounts.putAll(data); + } + loaded.set(true); + } catch (Exception e) { + System.err.println("[UsageTracker] Failed to load " + file.getName() + ": " + e.getMessage()); + loaded.set(true); // Mark as loaded even on failure to prevent retry loops + } + } + + /** + * Save usage data to file if there are pending changes. + */ + public void saveIfDirty() { + if (!dirty.compareAndSet(true, false)) { + return; // Not dirty, nothing to save + } + save(); + } + + /** + * Force save usage data to file. + */ + public void save() { + try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { + GSON.toJson(usageCounts, writer); + } catch (Exception e) { + System.err.println("[UsageTracker] Failed to save " + file.getName() + ": " + e.getMessage()); + dirty.set(true); // Mark dirty again so we retry later + } + } + + /** + * Clear all usage data (for testing/reset purposes). + */ + public void clear() { + usageCounts.clear(); + dirty.set(true); + } + + /** + * Get the number of tracked items. + */ + public int size() { + return usageCounts.size(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/AlphabeticalWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/AlphabeticalWeigher.java new file mode 100644 index 000000000..93252dc69 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/AlphabeticalWeigher.java @@ -0,0 +1,15 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +public class AlphabeticalWeigher extends CompletionWeigher { + + public AlphabeticalWeigher() { + super("alphabetical"); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + return item.getName().toLowerCase(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/CompletionWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/CompletionWeigher.java new file mode 100644 index 000000000..0505da0d1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/CompletionWeigher.java @@ -0,0 +1,40 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +/** + * A single scoring dimension for autocomplete ranking. + * + * Weighers are evaluated in chain order. For each pair of items being compared, + * the first weigher to return non-equal values determines the ordering. + * + * Contract: + * - weigh() MUST be a pure function (no side effects, no mutations) + * - weigh() MUST return consistent results for the same item+context + * - weigh() MAY return null to abstain (treated as equal for this weigher) + * - Lower Comparable values = higher priority (shown first) unless negated + * + * Modeled after IntelliJ's LookupElementWeigher (Apache 2.0). + */ +public abstract class CompletionWeigher { + + private final String id; + private final boolean negated; + + protected CompletionWeigher(String id, boolean negated) { + this.id = id; + this.negated = negated; + } + + protected CompletionWeigher(String id) { + this(id, false); + } + + public abstract Comparable weigh(AutocompleteItem item, ScoringContext context); + + public String getId() { return id; } + public boolean isNegated() { return negated; } + + @Override + public String toString() { return id; } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ContextFitWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ContextFitWeigher.java new file mode 100644 index 000000000..f2e1db62d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ContextFitWeigher.java @@ -0,0 +1,38 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +/** + * How well does this item fit the current access context? + * + * Combines what were previously applyStaticPenalty() and applyObjectMethodPenalty(). + * Uses ordered enum categories, eliminating all magic threshold numbers. + */ +public class ContextFitWeigher extends CompletionWeigher { + + public enum ContextFit { + /** Item naturally belongs in this context. */ + NATURAL, + /** Static member accessed through an instance — legal but bad style. */ + WRONG_STATIC_CONTEXT, + /** Inherited Object method (wait, notify, hashCode, getClass, etc.) */ + OBJECT_METHOD + } + + public ContextFitWeigher() { + super("contextFit"); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + if (item.isInheritedObjectMethod()) { + return ContextFit.OBJECT_METHOD; + } + + if (context.isMemberAccess && !context.isStaticContext && item.isStatic()) { + return ContextFit.WRONG_STATIC_CONTEXT; + } + + return ContextFit.NATURAL; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/DeprecatedWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/DeprecatedWeigher.java new file mode 100644 index 000000000..c8044226f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/DeprecatedWeigher.java @@ -0,0 +1,15 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +public class DeprecatedWeigher extends CompletionWeigher { + + public DeprecatedWeigher() { + super("deprecated"); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + return item.isDeprecated(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ImportStatusWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ImportStatusWeigher.java new file mode 100644 index 000000000..7008e6e4b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ImportStatusWeigher.java @@ -0,0 +1,27 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +/** + * Demote unimported classes below imported ones. + * + * Fixes the bug where the unimported class penalty (-500) was applied at + * creation time and overwritten by calculateMatchScore(). In the chain model, + * import status is a separate dimension that can never be overwritten. + */ +public class ImportStatusWeigher extends CompletionWeigher { + + public enum ImportStatus { + IMPORTED, + UNIMPORTED + } + + public ImportStatusWeigher() { + super("importStatus"); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + return item.requiresImport() ? ImportStatus.UNIMPORTED : ImportStatus.IMPORTED; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/InheritanceDepthWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/InheritanceDepthWeigher.java new file mode 100644 index 000000000..4c8ba8e58 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/InheritanceDepthWeigher.java @@ -0,0 +1,26 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +/** + * Prefer members defined closer in the inheritance tree. + * Child class members rank above parent class members. + * + * Only meaningful for JS/.d.ts types where inheritance depth is tracked. + * For items without inheritance tracking (depth < 0), this weigher abstains. + */ +public class InheritanceDepthWeigher extends CompletionWeigher { + + public InheritanceDepthWeigher() { + super("inheritanceDepth"); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + int depth = item.getInheritanceDepth(); + if (depth < 0) { + return null; + } + return depth; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/MatchQualityWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/MatchQualityWeigher.java new file mode 100644 index 000000000..a8f638729 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/MatchQualityWeigher.java @@ -0,0 +1,22 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +/** + * Text match quality against the user's prefix. + * PRIMARY sort dimension — how well the item name matches what was typed. + * + * Returns the existing calculateMatchScore() result, negated so that + * higher scores = higher priority. + */ +public class MatchQualityWeigher extends CompletionWeigher { + + public MatchQualityWeigher() { + super("matchQuality", true); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + return item.getMatchScore(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/MemberKindWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/MemberKindWeigher.java new file mode 100644 index 000000000..af2693751 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/MemberKindWeigher.java @@ -0,0 +1,56 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +public class MemberKindWeigher extends CompletionWeigher { + + public enum MemberKind { + ENUM_CONSTANT, + LOCAL_VARIABLE, + INSTANCE_FIELD, + INSTANCE_METHOD, + TYPE_CLASS, + TYPE_ENUM, + TYPE_INTERFACE, + STATIC_FIELD, + STATIC_METHOD, + KEYWORD, + SNIPPET + } + + public MemberKindWeigher() { + super("memberKind"); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + switch (item.getKind()) { + case ENUM_CONSTANT: return MemberKind.ENUM_CONSTANT; + case PARAMETER: return MemberKind.LOCAL_VARIABLE; + case VARIABLE: return MemberKind.LOCAL_VARIABLE; + case METHOD: + return item.isStatic() ? MemberKind.STATIC_METHOD : MemberKind.INSTANCE_METHOD; + case FIELD: + return item.isStatic() ? MemberKind.STATIC_FIELD : MemberKind.INSTANCE_FIELD; + case CLASS: return resolveTypeTier(item); + case ENUM: return MemberKind.TYPE_ENUM; + case KEYWORD: return MemberKind.KEYWORD; + case SNIPPET: return MemberKind.SNIPPET; + default: return MemberKind.INSTANCE_FIELD; + } + } + + private MemberKind resolveTypeTier(AutocompleteItem item) { + Object source = item.getSourceData(); + if (source instanceof TypeInfo) { + TypeInfo typeInfo = (TypeInfo) source; + switch (typeInfo.getKind()) { + case INTERFACE: return MemberKind.TYPE_INTERFACE; + case ENUM: return MemberKind.TYPE_ENUM; + default: return MemberKind.TYPE_CLASS; + } + } + return MemberKind.TYPE_CLASS; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ScoringContext.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ScoringContext.java new file mode 100644 index 000000000..6ee5501f5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/ScoringContext.java @@ -0,0 +1,27 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.UsageTracker; + +/** + * Immutable context for a single scoring pass. + * Created once when suggestions are requested, shared by all weighers. + */ +public class ScoringContext { + + public final String prefix; + public final boolean isMemberAccess; + public final boolean isStaticContext; + public final String ownerFullName; + public final UsageTracker usageTracker; + public final boolean requirePrefix; + + public ScoringContext(String prefix, boolean isMemberAccess, boolean isStaticContext, + String ownerFullName, UsageTracker usageTracker, boolean requirePrefix) { + this.prefix = prefix; + this.isMemberAccess = isMemberAccess; + this.isStaticContext = isStaticContext; + this.ownerFullName = ownerFullName; + this.usageTracker = usageTracker; + this.requirePrefix = requirePrefix; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/UsageFrequencyWeigher.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/UsageFrequencyWeigher.java new file mode 100644 index 000000000..fbb0a2308 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/UsageFrequencyWeigher.java @@ -0,0 +1,25 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; +import noppes.npcs.client.gui.util.script.autocomplete.UsageTracker; + +/** + * Boost items the user has selected before. + * Uses logarithmic scaling with a cap via UsageTracker.calculateUsageBoost(). + * Negated: higher usage count = higher priority. + */ +public class UsageFrequencyWeigher extends CompletionWeigher { + + public UsageFrequencyWeigher() { + super("usageFrequency", true); + } + + @Override + public Comparable weigh(AutocompleteItem item, ScoringContext context) { + if (context.usageTracker == null) { + return 0; + } + int usageCount = context.usageTracker.getUsageCount(item, context.ownerFullName); + return UsageTracker.calculateUsageBoost(usageCount); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/WeigherChain.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/WeigherChain.java new file mode 100644 index 000000000..3d2a6e878 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/weighter/WeigherChain.java @@ -0,0 +1,81 @@ +package noppes.npcs.client.gui.util.script.autocomplete.weighter; + +import noppes.npcs.client.gui.util.script.autocomplete.AutocompleteItem; + +import java.util.*; + +/** + * An ordered list of weighers that produces a Comparator for sorting autocomplete items. + * + * Items are compared dimension-by-dimension through the chain. + * The first weigher to produce a non-equal comparison determines the ordering. + * If all weighers return equal, items are considered equivalent (stable sort preserves + * insertion order). + * + * Simplified from IntelliJ's CompletionSorterImpl — uses Comparator instead of a + * classifier tree since we sort all items in a single batch. + */ +public class WeigherChain { + + private final List weighers; + + public WeigherChain(List weighers) { + this.weighers = Collections.unmodifiableList(new ArrayList<>(weighers)); + } + + /** + * Build a Comparator that evaluates items through the weigher chain. + * + * Weigher results are cached per item via IdentityHashMap to avoid + * recomputing weights during O(N log N) comparisons. + */ + public Comparator buildComparator(ScoringContext context) { + final Map[]> cache = new IdentityHashMap<>(); + final int chainLength = weighers.size(); + + return (a, b) -> { + Comparable[] weightsA = cache.computeIfAbsent(a, k -> computeWeights(k, context)); + Comparable[] weightsB = cache.computeIfAbsent(b, k -> computeWeights(k, context)); + + for (int i = 0; i < chainLength; i++) { + Comparable wA = weightsA[i]; + Comparable wB = weightsB[i]; + + if (wA == null && wB == null) continue; + if (wA == null) return 1; + if (wB == null) return -1; + + @SuppressWarnings("unchecked") + int cmp = ((Comparable) wA).compareTo(wB); + + if (cmp != 0) { + return weighers.get(i).isNegated() ? -cmp : cmp; + } + } + return 0; + }; + } + + private Comparable[] computeWeights(AutocompleteItem item, ScoringContext context) { + Comparable[] weights = new Comparable[weighers.size()]; + for (int i = 0; i < weighers.size(); i++) { + weights[i] = weighers.get(i).weigh(item, context); + } + return weights; + } + + /** + * Get all weigher results for an item (for debugging/testing). + */ + public Map> debugWeights(AutocompleteItem item, ScoringContext context) { + Map> result = new LinkedHashMap<>(); + for (CompletionWeigher weigher : weighers) { + result.put(weigher.getId(), weigher.weigh(item, context)); + } + return result; + } + + public List getWeighers() { + return weighers; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/CodeParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/CodeParser.java new file mode 100644 index 000000000..435c8f42e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/CodeParser.java @@ -0,0 +1,323 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +/** + * Utility class for parsing and analyzing code text. + * Provides methods for finding matching braces/parentheses, removing comments/strings, + * and locating keywords in code. + */ +public final class CodeParser { + + private CodeParser() {} // Utility class + + // ==================== Matching Delimiters ==================== + + /** + * Find the closing brace that matches the opening brace at the given position. + * @param text The text to search + * @param openBrace Position of the opening '{' + * @return Position of matching '}' or -1 if not found + */ + public static int findMatchingBrace(String text, int openBrace) { + if (openBrace < 0 || openBrace >= text.length() || text.charAt(openBrace) != '{') { + return -1; + } + int depth = 1; + for (int i = openBrace + 1; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '{') depth++; + else if (c == '}') { + depth--; + if (depth == 0) return i; + } + } + return -1; + } + + /** + * Find the closing parenthesis that matches the opening parenthesis at the given position. + * @param text The text to search + * @param openParen Position of the opening '(' + * @return Position of matching ')' or -1 if not found + */ + public static int findMatchingParen(String text, int openParen) { + if (openParen < 0 || openParen >= text.length() || text.charAt(openParen) != '(') { + return -1; + } + int depth = 1; + for (int i = openParen + 1; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '(') depth++; + else if (c == ')') { + depth--; + if (depth == 0) return i; + } + } + return -1; + } + + // ==================== Comment/String Removal ==================== + + /** + * Remove string literals and comments from code for structural analysis. + * This is used when analyzing control flow to avoid false positives from + * keywords inside strings or comments. + * @param code The source code + * @return Code with strings and comments removed + */ + public static String removeStringsAndComments(String code) { + StringBuilder result = new StringBuilder(); + boolean inString = false; + boolean inChar = false; + boolean inLineComment = false; + boolean inBlockComment = false; + + for (int i = 0; i < code.length(); i++) { + char c = code.charAt(i); + char next = (i + 1 < code.length()) ? code.charAt(i + 1) : 0; + + if (inLineComment) { + if (c == '\n') { + inLineComment = false; + result.append(c); + } + continue; + } + + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + i++; // skip '/' + } + continue; + } + + if (inString || inChar) { + if (c == '\\' && i + 1 < code.length()) { + i++; // skip escaped character + continue; + } + if ((inString && c == '"') || (inChar && c == '\'')) { + inString = false; + inChar = false; + } + continue; + } + + // Check for start of comments or strings + if (c == '/' && next == '/') { + inLineComment = true; + i++; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + i++; + continue; + } + if (c == '"') { + inString = true; + continue; + } + if (c == '\'') { + inChar = true; + continue; + } + + result.append(c); + } + + return result.toString(); + } + + /** + * Remove only comments from code, keeping strings intact and preserving positions. + * Comments are replaced with spaces to maintain character positions. + * @param code The source code + * @return Code with comments replaced by spaces + */ + public static String removeComments(String code) { + StringBuilder result = new StringBuilder(); + boolean inString = false; + boolean inChar = false; + boolean inLineComment = false; + boolean inBlockComment = false; + + for (int i = 0; i < code.length(); i++) { + char c = code.charAt(i); + char next = (i + 1 < code.length()) ? code.charAt(i + 1) : 0; + + if (inLineComment) { + if (c == '\n') { + inLineComment = false; + result.append(c); + } else { + result.append(' '); // Preserve position with spaces + } + continue; + } + + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + result.append(" "); // Preserve position + i++; + } else { + result.append(c == '\n' ? '\n' : ' '); // Preserve newlines + } + continue; + } + + if (inString) { + result.append(c); + if (c == '\\' && i + 1 < code.length()) { + result.append(code.charAt(++i)); + continue; + } + if (c == '"') inString = false; + continue; + } + + if (inChar) { + result.append(c); + if (c == '\\' && i + 1 < code.length()) { + result.append(code.charAt(++i)); + continue; + } + if (c == '\'') inChar = false; + continue; + } + + // Check for start of comments + if (c == '/' && next == '/') { + inLineComment = true; + result.append(" "); // Preserve position + i++; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + result.append(" "); // Preserve position + i++; + continue; + } + if (c == '"') { inString = true; } + if (c == '\'') { inChar = true; } + + result.append(c); + } + + return result.toString(); + } + + // ==================== Keyword Detection ==================== + + /** + * Check if a keyword exists at the given position in text. + * Verifies the keyword is not part of a larger identifier. + * @param text The text to check + * @param pos Position to check + * @param keyword The keyword to look for + * @return true if the keyword is at this position as a standalone word + */ + public static boolean isKeywordAt(String text, int pos, String keyword) { + if (pos + keyword.length() > text.length()) return false; + if (!text.substring(pos).startsWith(keyword)) return false; + + boolean validBefore = pos == 0 || !Character.isLetterOrDigit(text.charAt(pos - 1)); + boolean validAfter = pos + keyword.length() >= text.length() + || !Character.isLetterOrDigit(text.charAt(pos + keyword.length())); + + return validBefore && validAfter; + } + + /** + * Find the next "return" keyword that is not inside a string literal. + * @param text The text to search + * @param start Position to start searching from + * @return Position of "return" or -1 if not found + */ + public static int findReturnKeyword(String text, int start) { + boolean inString = false; + boolean inChar = false; + + for (int i = start; i < text.length() - 5; i++) { + char c = text.charAt(i); + + if (inString) { + if (c == '\\' && i + 1 < text.length()) { i++; continue; } + if (c == '"') inString = false; + continue; + } + if (inChar) { + if (c == '\\' && i + 1 < text.length()) { i++; continue; } + if (c == '\'') inChar = false; + continue; + } + + if (c == '"') { inString = true; continue; } + if (c == '\'') { inChar = true; continue; } + + // Check for "return" keyword + if (isKeywordAt(text, i, "return")) { + return i; + } + } + return -1; + } + + /** + * Find the semicolon that ends a return statement, handling nested structures. + * @param text The text to search + * @param start Position to start searching (after "return" keyword) + * @return Position of ';' or -1 if not found + */ + public static int findReturnSemicolon(String text, int start) { + int parenDepth = 0; + int braceDepth = 0; + boolean inString = false; + boolean inChar = false; + + for (int i = start; i < text.length(); i++) { + char c = text.charAt(i); + + if (inString) { + if (c == '\\' && i + 1 < text.length()) { i++; continue; } + if (c == '"') inString = false; + continue; + } + if (inChar) { + if (c == '\\' && i + 1 < text.length()) { i++; continue; } + if (c == '\'') inChar = false; + continue; + } + + if (c == '"') { inString = true; continue; } + if (c == '\'') { inChar = true; continue; } + if (c == '(') { parenDepth++; continue; } + if (c == ')') { parenDepth--; continue; } + if (c == '{') { braceDepth++; continue; } + if (c == '}') { braceDepth--; continue; } + + if (c == ';' && parenDepth == 0 && braceDepth == 0) { + return i; + } + } + return -1; + } + + // ==================== Whitespace Utilities ==================== + + /** + * Skip whitespace characters starting from the given position. + * @param text The text + * @param pos Starting position + * @return Position of first non-whitespace character + */ + public static int skipWhitespace(String text, int pos) { + while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) { + pos++; + } + return pos; + } +} + diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ControlFlowAnalyzer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ControlFlowAnalyzer.java new file mode 100644 index 000000000..6416805ba --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ControlFlowAnalyzer.java @@ -0,0 +1,215 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +/** + * Analyzes control flow in method bodies to determine if all paths return a value. + * Used for detecting "missing return statement" errors. + */ +public final class ControlFlowAnalyzer { + + private ControlFlowAnalyzer() {} // Utility class + + /** + * Check if the method body has a guaranteed return on all code paths. + */ + public static boolean hasGuaranteedReturn(String body) { + String cleanBody = CodeParser.removeStringsAndComments(body); + + return hasTopLevelReturn(cleanBody) + || hasCompleteIfElseReturn(cleanBody) + || hasTryFinallyReturn(cleanBody) + || hasCompleteSwitchReturn(cleanBody); + } + + /** + * Check for a bare return statement at the method's top level (brace depth 0). + */ + private static boolean hasTopLevelReturn(String body) { + int braceDepth = 0; + int parenDepth = 0; + + for (int i = 0; i < body.length(); i++) { + char c = body.charAt(i); + + if (c == '{') braceDepth++; + else if (c == '}') braceDepth--; + else if (c == '(') parenDepth++; + else if (c == ')') parenDepth--; + + if (braceDepth == 0 && parenDepth == 0 && isKeywordAt(body, i, "return")) { + return true; + } + } + return false; + } + + /** + * Check for complete if-else chains where all branches return. + */ + private static boolean hasCompleteIfElseReturn(String body) { + int braceDepth = 0; + + for (int i = 0; i < body.length(); i++) { + char c = body.charAt(i); + if (c == '{') { braceDepth++; continue; } + if (c == '}') { braceDepth--; continue; } + + if (braceDepth == 0 && isKeywordAt(body, i, "if")) { + if (checkIfElseChainReturns(body, i)) { + return true; + } + } + } + return false; + } + + /** + * Check if an if-else chain starting at the given position guarantees a return. + * Handles: if(true) { return; } - always returns (else unreachable) + * if(false) { } else { return; } - else always executes + */ + private static boolean checkIfElseChainReturns(String body, int ifStart) { + int pos = ifStart; + + while (pos < body.length()) { + if (!body.substring(pos).startsWith("if")) return false; + pos += 2; + + pos = skipWhitespace(body, pos); + if (pos >= body.length() || body.charAt(pos) != '(') return false; + + int condStart = pos; + int condEnd = CodeParser.findMatchingParen(body, pos); + if (condEnd < 0) return false; + + // Check for literal true/false conditions + String condition = body.substring(condStart + 1, condEnd).trim(); + boolean isAlwaysTrue = condition.equals("true"); + boolean isAlwaysFalse = condition.equals("false"); + + pos = skipWhitespace(body, condEnd + 1); + if (pos >= body.length() || body.charAt(pos) != '{') return false; + + int blockEnd = CodeParser.findMatchingBrace(body, pos); + if (blockEnd < 0) return false; + + String ifBlock = body.substring(pos + 1, blockEnd); + boolean ifBlockReturns = hasGuaranteedReturn(ifBlock); + + // if(true) with return means we always return (else is unreachable) + if (isAlwaysTrue && ifBlockReturns) { + return true; + } + + pos = skipWhitespace(body, blockEnd + 1); + + // Must have else clause for guaranteed return + if (!body.substring(pos).startsWith("else")) { + return false; + } + pos += 4; + pos = skipWhitespace(body, pos); + + // else if - continue the chain + if (isKeywordAt(body, pos, "if")) { + continue; + } + + // Plain else block - final branch + if (pos >= body.length() || body.charAt(pos) != '{') return false; + int elseBlockEnd = CodeParser.findMatchingBrace(body, pos); + if (elseBlockEnd < 0) return false; + + String elseBlock = body.substring(pos + 1, elseBlockEnd); + boolean elseBlockReturns = hasGuaranteedReturn(elseBlock); + + // For if-else to guarantee return: both branches must return + // Special case: if(false) means if-block never executes, so only else matters + if (isAlwaysFalse) { + return elseBlockReturns; + } + + // Normal case: both if and else must return + return ifBlockReturns && elseBlockReturns; + } + return false; + } + + /** + * Check for try-finally where finally block returns. + */ + private static boolean hasTryFinallyReturn(String body) { + for (int i = 0; i < body.length(); i++) { + if (!isKeywordAt(body, i, "try")) continue; + + int tryBlockStart = body.indexOf('{', i); + if (tryBlockStart < 0) continue; + + int tryBlockEnd = CodeParser.findMatchingBrace(body, tryBlockStart); + if (tryBlockEnd < 0) continue; + + // Skip catch blocks + int searchPos = skipCatchBlocks(body, tryBlockEnd + 1); + searchPos = skipWhitespace(body, searchPos); + + // Check for finally + if (body.substring(searchPos).startsWith("finally")) { + int finallyBlockStart = body.indexOf('{', searchPos); + if (finallyBlockStart >= 0) { + int finallyBlockEnd = CodeParser.findMatchingBrace(body, finallyBlockStart); + if (finallyBlockEnd >= 0) { + String finallyBlock = body.substring(finallyBlockStart + 1, finallyBlockEnd); + if (hasGuaranteedReturn(finallyBlock)) { + return true; + } + } + } + } + } + return false; + } + + private static int skipCatchBlocks(String body, int start) { + int pos = start; + while (true) { + pos = skipWhitespace(body, pos); + if (pos >= body.length() || !body.substring(pos).startsWith("catch")) break; + + int catchBlockStart = body.indexOf('{', pos); + if (catchBlockStart < 0) break; + + int catchBlockEnd = CodeParser.findMatchingBrace(body, catchBlockStart); + if (catchBlockEnd < 0) break; + + pos = catchBlockEnd + 1; + } + return pos; + } + + /** + * Check for switch with default where all cases return. + * Returns false for now - full implementation is complex. + */ + private static boolean hasCompleteSwitchReturn(String body) { + return false; + } + + // ==================== Utility Methods ==================== + + private static boolean isKeywordAt(String text, int pos, String keyword) { + if (pos + keyword.length() > text.length()) return false; + if (!text.substring(pos).startsWith(keyword)) return false; + + boolean validBefore = pos == 0 || !Character.isLetterOrDigit(text.charAt(pos - 1)); + boolean validAfter = pos + keyword.length() >= text.length() + || !Character.isLetterOrDigit(text.charAt(pos + keyword.length())); + + return validBefore && validAfter; + } + + private static int skipWhitespace(String text, int pos) { + while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) { + pos++; + } + return pos; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/DocumentError.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/DocumentError.java new file mode 100644 index 000000000..865e560b2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/DocumentError.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.gui.util.script.interpreter.token.Token; + +/** + * Centralized error representation for the script document. + * Captures all validation errors (method calls, assignments, method declarations, type declarations) + * into a single list for generic processing. + * + *

Each error tracks: + *

    + *
  • {@code token} - the associated token (may be null for span-based errors)
  • + *
  • {@code startPos} - global start offset of the error span
  • + *
  • {@code endPos} - global end offset of the error span
  • + *
  • {@code message} - human-readable error description
  • + *
+ */ +public class DocumentError { + + private final Token token; + private final int startPos; + private final int endPos; + private final String message; + + /** + * Create a new document error. + * + * @param token The associated token, or null if this error is span-based + * @param startPos Global start offset of the error span + * @param endPos Global end offset of the error span + * @param message Human-readable error description + */ + public DocumentError(Token token, int startPos, int endPos, String message) { + this.token = token; + this.startPos = startPos; + this.endPos = endPos; + this.message = message; + } + + public DocumentError(int startPos, int endPos, String message) { + this.token = null; + this.startPos = startPos; + this.endPos = endPos; + this.message = message; + } + + public Token getToken() { + return token; + } + + public int getStartPos() { + return startPos; + } + + public int getEndPos() { + return endPos; + } + + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "DocumentError{" + + "startPos=" + startPos + + ", endPos=" + endPos + + ", message='" + message + '\'' + + ", token=" + (token != null ? token.getText() : "null") + + '}'; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ErrorUnderlineRenderer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ErrorUnderlineRenderer.java new file mode 100644 index 000000000..bec08df8b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ErrorUnderlineRenderer.java @@ -0,0 +1,211 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.ClientProxy; +import org.lwjgl.opengl.GL11; + +/** + * Helper class for rendering error underlines in script editor lines. + * Renders underlines from the document's centralized error list ({@link DocumentError}). + * + *

Error collection happens during analysis in {@link ScriptDocument#formatCodeText()}. + * This renderer only draws; it does not detect or collect errors. + */ +public class ErrorUnderlineRenderer { + private static final int ERROR_COLOR = 0xFF5555; + + // Holds the calculation result for an underline + private static class UnderlinePosition { + final int x; + final int width; + + UnderlinePosition(int x, int width) { + this.x = x; + this.width = width; + } + + boolean isValid() { + return width > 0; + } + } + + /** + * Draw error underlines for all validation errors in the document that intersect the given line. + * Iterates over the document's centralized error list and draws underlines for each error + * whose span intersects this line. + * + * @param doc The script document containing all errors + * @param lineStartX X coordinate where the line starts rendering + * @param baselineY Y coordinate for the underline baseline + * @param lineText The text content of the line + * @param lineStart Global offset where this line starts + * @param lineEnd Global offset where this line ends + */ + public static void drawErrorUnderlines( + ScriptDocument doc, + int lineStartX, int baselineY, + String lineText, int lineStart, int lineEnd) { + drawErrorUnderlines(doc, null, lineStartX, baselineY, lineText, lineStart, lineEnd); + } + + /** + * Draw error underlines for all validation errors in the document that intersect the given line. + * When a ScriptLine is provided, uses style-aware width calculation so underlines align + * correctly under bold/italic tokens. + */ + public static void drawErrorUnderlines( + ScriptDocument doc, ScriptLine line, + int lineStartX, int baselineY, + String lineText, int lineStart, int lineEnd) { + + if (doc == null) + return; + + for (DocumentError error : doc.getErrors()) { + drawUnderlineForSpan(error.getStartPos(), error.getEndPos(), + lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR, line); + } + } + + /** + * Calculate underline position for a span of text within a line. + * Handles clipping to line boundaries and pixel width calculation. + * When a ScriptLine is provided, uses style-aware width calculation. + * + * @param spanStart Global offset where the span starts + * @param spanEnd Global offset where the span ends + * @param lineStartX X coordinate where the line starts rendering + * @param lineText The text content of the line + * @param lineStart Global offset where this line starts + * @param lineEnd Global offset where this line ends + * @param line Optional ScriptLine for style-aware width; null falls back to plain width + * @return UnderlinePosition with x and width, or null if span doesn't intersect line + */ + private static UnderlinePosition calculateUnderlinePosition( + int spanStart, int spanEnd, + int lineStartX, String lineText, int lineStart, int lineEnd, + ScriptLine line) { + + // Skip if span doesn't intersect this line + if (spanEnd < lineStart || spanStart > lineEnd) + return null; + + // Clip to line boundaries + int clipStart = Math.max(spanStart, lineStart); + int clipEnd = Math.min(spanEnd, lineEnd); + + if (clipStart >= clipEnd) + return null; + + // Convert to line-local coordinates + int lineLocalStart = clipStart - lineStart; + int lineLocalEnd = clipEnd - lineStart; + + // Bounds check + if (lineLocalStart < 0 || lineLocalStart >= lineText.length()) + return null; + + // Compute pixel position using style-aware width when available + int beforeWidth; + int spanWidth; + + if (line != null) { + beforeWidth = line.getRenderedWidth(0, lineLocalStart); + int clampedEnd = Math.min(lineLocalEnd, lineText.length()); + spanWidth = line.getRenderedWidth(lineLocalStart, clampedEnd); + } else { + String beforeSpan = lineText.substring(0, lineLocalStart); + beforeWidth = ClientProxy.Font.width(beforeSpan); + + if (lineLocalEnd > lineText.length()) { + spanWidth = ClientProxy.Font.width(lineText.substring(lineLocalStart)); + } else { + String spanTextOnLine = lineText.substring(lineLocalStart, lineLocalEnd); + spanWidth = ClientProxy.Font.width(spanTextOnLine); + } + } + + return new UnderlinePosition(lineStartX + beforeWidth, spanWidth); + } + + /** + * Draw an underline for a simple span if it intersects the line. + * + * @param spanStart Global offset where the span starts + * @param spanEnd Global offset where the span ends + * @param lineStartX X coordinate where the line starts rendering + * @param baselineY Y coordinate for the underline baseline + * @param lineText The text content of the line + * @param lineStart Global offset where this line starts + * @param lineEnd Global offset where this line ends + * @param color Underline color + */ + public static void drawUnderlineForSpan( + int spanStart, int spanEnd, + int lineStartX, int baselineY, + String lineText, int lineStart, int lineEnd, + int color) { + drawUnderlineForSpan(spanStart, spanEnd, lineStartX, baselineY, + lineText, lineStart, lineEnd, color, null); + } + + /** + * Draw an underline for a simple span if it intersects the line. + * When a ScriptLine is provided, uses style-aware width calculation. + */ + public static void drawUnderlineForSpan( + int spanStart, int spanEnd, + int lineStartX, int baselineY, + String lineText, int lineStart, int lineEnd, + int color, ScriptLine line) { + + UnderlinePosition pos = calculateUnderlinePosition( + spanStart, spanEnd, lineStartX, lineText, lineStart, lineEnd, line); + + if (pos != null && pos.isValid()) { + drawCurlyUnderline(pos.x, baselineY, pos.width, color); + } + } + + /** + * Draw a curly/wavy underline (like IDE error highlighting). + * @param x Start X position + * @param y Y position (bottom of text) + * @param width Width of the underline + * @param color Color in ARGB format (e.g., 0xFFFF5555 for red) + */ + public static void drawCurlyUnderline(int x, int y, int width, int color) { + if (width <= 0) + return; + + float a = ((color >> 24) & 0xFF) / 255f; + float r = ((color >> 16) & 0xFF) / 255f; + float g = ((color >> 8) & 0xFF) / 255f; + float b = (color & 0xFF) / 255f; + + // If alpha is 0, assume full opacity + if (a == 0) + a = 1.0f; + + GL11.glPushMatrix(); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(r, g, b, a); + GL11.glLineWidth(1.0f); + + GL11.glBegin(GL11.GL_LINE_STRIP); + // Wave parameters: 2 pixels amplitude, 4 pixels wavelength + int waveHeight = 1; + float waveLength = 4f; + for (float i = -0.5f; i <= width - 1; i += 0.125f) { + // Create a sine-like wave pattern + double phase = (double) i / waveLength * Math.PI * 2; + float yOffset = (float) (Math.sin(phase) * waveHeight) - 0.25f; + GL11.glVertex2f(x + i + 2f, y + yOffset); + } + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glPopMatrix(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/FieldChainMarker.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/FieldChainMarker.java new file mode 100644 index 000000000..5659c7f56 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/FieldChainMarker.java @@ -0,0 +1,518 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenErrorMessage; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Helper class for marking chained field accesses in script documents. + * Handles patterns like: identifier.field, this.field, super.field, method().field + */ +public class FieldChainMarker { + private final ScriptDocument document; + private final String text; + + public FieldChainMarker(ScriptDocument document, String text) { + this.document = document; + this.text = text; + } + + /** + * Mark all chained field accesses in the document. + * Uses two passes: one for standard chains, one for method/array result chains. + */ + public void markChainedFieldAccesses(List marks) { + // ==================== PASS 1: Standard identifier chains ==================== + // Pattern: identifier.identifier, this.identifier, super.identifier + Pattern chainPattern = Pattern.compile( + "\\b(this|super|[a-zA-Z_][a-zA-Z0-9_]*)\\s*\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)"); + Matcher m = chainPattern.matcher(text); + + while (m.find()) { + int chainStart = m.start(1); + + // Skip excluded ranges and imports + if (document.isExcluded(chainStart) || document.isInImportOrPackage(chainStart)) continue; + + // Skip if second segment is a method call - markMethodCalls handles it + if (document.isFollowedByParen(m.end(2))) continue; + + // Build the full chain + ChainData chain = buildChain(m); + if (chain == null) continue; + + // Resolve the starting type + ChainContext ctx = resolveChainStart(chain, chainStart); + + // Mark each segment + for (int i = ctx.startIndex; i < chain.segments.size(); i++) { + ctx.currentIndex = i; + int[] pos = chain.positions.get(i); + + if (document.isExcluded(pos[0])) continue; + + // Determine what type of marking this segment needs + MarkResult result = resolveSegmentMark(ctx, chainStart); + + // Apply the mark + if (result.mark != null) { + marks.add(result.mark); + } + + // Update context for next segment + ctx.currentType = result.nextType; + } + } + + // ==================== PASS 2: Method/array result chains ==================== + // Handle: getMinecraft().thePlayer, array[0].length + Pattern dotIdent = Pattern.compile("\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)"); + Matcher md = dotIdent.matcher(text); + + while (md.find()) { + int identStart = md.start(1); + int identEnd = md.end(1); + int dotPos = md.start(); + + // Skip excluded ranges and imports + if (document.isExcluded(identStart) || document.isInImportOrPackage(identStart)) continue; + + // Only handle when preceded by ')' or ']' (method call or array access result) + Character precedingChar = getNonWhitespaceBefore(dotPos); + if (precedingChar == null || (precedingChar != ')' && precedingChar != ']')) continue; + + // Get receiver type from the expression before the dot + int[] bounds = document.findReceiverBoundsBefore(dotPos); + if (bounds == null) continue; + + if (document.isExcluded(bounds[0]) || document.isInImportOrPackage(bounds[0])) continue; + + String receiverExpr = text.substring(bounds[0], bounds[1]).trim(); + if (receiverExpr.isEmpty()) continue; + + TypeInfo receiverType = document.resolveExpressionType(receiverExpr, bounds[0]); + + // Mark the first field and continue the chain + markReceiverChainSegments(marks, md.group(1), identStart, identEnd, receiverType); + } + } + + // ==================== CHAIN BUILDING HELPERS ==================== + + /** Data class for a parsed chain */ + private static class ChainData { + final List segments = new ArrayList<>(); + final List positions = new ArrayList<>(); + } + + /** Context for chain resolution */ + private static class ChainContext { + ChainData chain; + int currentIndex; + TypeInfo currentType; + ScriptTypeInfo enclosingType; // The enclosing script type for 'this' resolution + int startIndex; + boolean firstIsThis; + boolean firstIsSuper; + boolean firstIsPrecededByDot; + } + + /** Result of resolving a segment's mark */ + private static class MarkResult { + final ScriptLine.Mark mark; + final TypeInfo nextType; + + MarkResult(ScriptLine.Mark mark, TypeInfo nextType) { + this.mark = mark; + this.nextType = nextType; + } + } + + /** Build a complete chain from a regex match, continuing to read more segments */ + private ChainData buildChain(Matcher m) { + ChainData chain = new ChainData(); + + // Add first two segments from the match + chain.segments.add(m.group(1)); + chain.positions.add(new int[]{m.start(1), m.end(1)}); + chain.segments.add(m.group(2)); + chain.positions.add(new int[]{m.start(2), m.end(2)}); + + // Continue reading subsequent .identifier segments + int pos = m.end(2); + while (pos < text.length()) { + pos = document.skipWhitespace(pos); + if (pos >= text.length() || document.isExcluded(pos) || text.charAt(pos) != '.') break; + pos++; // Skip dot + + pos = document.skipWhitespace(pos); + if (pos >= text.length() || document.isExcluded(pos) || !Character.isJavaIdentifierStart(text.charAt(pos))) break; + + // Read identifier + int identStart = pos; + while (pos < text.length() && Character.isJavaIdentifierPart(text.charAt(pos))) pos++; + int identEnd = pos; + + // Stop if this is a method call + if (document.isFollowedByParen(identEnd)) break; + + chain.segments.add(text.substring(identStart, identEnd)); + chain.positions.add(new int[]{identStart, identEnd}); + } + + return chain; + } + + /** Resolve the starting context for a chain */ + private ChainContext resolveChainStart(ChainData chain, int chainStart) { + ChainContext ctx = new ChainContext(); + ctx.chain = chain; + ctx.currentIndex = 0; + String first = chain.segments.get(0); + + ctx.firstIsThis = first.equals("this"); + ctx.firstIsSuper = first.equals("super"); + ctx.firstIsPrecededByDot = document.isPrecededByDot(chainStart); + ctx.startIndex = ctx.firstIsPrecededByDot ? 0 : 1; + ctx.currentType = null; + ctx.enclosingType = document.findEnclosingScriptType(chainStart); + + if (ctx.firstIsThis) { + // 'this' - resolve to enclosing class/global fields + ctx.currentType = document.resolveThisType(chainStart); + if (ctx.currentType == null) { + ctx.currentType = ctx.enclosingType; + } + } else if (ctx.firstIsSuper) { + // 'super' - resolve to parent class + if (ctx.enclosingType != null && ctx.enclosingType.hasSuperClass()) { + ctx.currentType = ctx.enclosingType.getSuperClass(); + } + } else if (ctx.firstIsPrecededByDot) { + // Field access on a receiver (e.g., getMinecraft().thePlayer) + TypeInfo receiverType = document.resolveReceiverChain(chainStart); + if (receiverType != null && receiverType.hasField(first)) { + FieldInfo varInfo = receiverType.getFieldInfo(first); + ctx.currentType = (varInfo != null) ? varInfo.getTypeInfo() : null; + } + } else { + // Try as type first (static access), then as variable + TypeInfo typeCheck = document.resolveType(first); + if (typeCheck != null && typeCheck.isResolved()) { + ctx.currentType = typeCheck; + } else { + FieldInfo varInfo = document.resolveVariable(first, chainStart); + ctx.currentType = (varInfo != null) ? varInfo.getTypeInfo() : null; + } + } + + return ctx; + } + + /** Resolve what mark a segment should get */ + private MarkResult resolveSegmentMark(ChainContext ctx, int chainStart) { + int index = ctx.currentIndex; + String segment = ctx.chain.segments.get(index); + int[] pos = ctx.chain.positions.get(index); + + // Case 1: First segment preceded by dot (field on receiver) + if (index == 0 && ctx.firstIsPrecededByDot) { + return resolveReceiverFieldMark(ctx, chainStart); + } + + // Case 2: this.field + if (index == 1 && ctx.firstIsThis) { + return resolveThisFieldMark(ctx); + } + + // Case 3: super.field + if (index == 1 && ctx.firstIsSuper) { + return resolveSuperFieldMark(ctx); + } + + // Case 4: Resolved type with field + if (ctx.currentType != null && ctx.currentType.isResolved()) { + return resolveTypedFieldMark(ctx); + } + + // Case 5: Unresolved - mark as undefined + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR), + null + ); + } + + // ==================== SEGMENT RESOLUTION HELPERS ==================== + + /** Resolve mark for field access on a receiver (preceded by dot) */ + private MarkResult resolveReceiverFieldMark(ChainContext ctx, int chainStart) { + int index = ctx.currentIndex; + String segment = ctx.chain.segments.get(index); + int[] pos = ctx.chain.positions.get(index); + boolean isLast = (index == ctx.chain.segments.size() - 1); + boolean isStatic = isStaticContext(ctx); + + TypeInfo receiverType = document.resolveReceiverChain(chainStart); + + if (receiverType != null && receiverType.hasField(segment)) { + FieldInfo fieldInfo = receiverType.getFieldInfo(segment); + FieldAccessInfo accessInfo = document.createFieldAccessInfo(segment, pos[0], pos[1], + receiverType, fieldInfo, isLast, isStatic); + + return new MarkResult(new ScriptLine.Mark(pos[0], pos[1], getFieldTokenType(fieldInfo), accessInfo), + (fieldInfo != null) ? fieldInfo.getTypeInfo() : null + ); + } + + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR), + null + ); + } + + /** Resolve mark for this.field access */ + private MarkResult resolveThisFieldMark(ChainContext ctx) { + int index = ctx.currentIndex; + String segment = ctx.chain.segments.get(index); + int[] pos = ctx.chain.positions.get(index); + boolean isLast = (index == ctx.chain.segments.size() - 1); + + boolean found = false; + FieldInfo fieldInfo = null; + + TypeInfo thisType = ctx.currentType != null ? ctx.currentType : ctx.enclosingType; + + if (thisType != null && thisType.hasField(segment)) { + found = true; + fieldInfo = thisType.getFieldInfo(segment); + } else if (document.getGlobalFields().containsKey(segment)) { + found = true; + fieldInfo = document.getGlobalFields().get(segment); + } + + if (found) { + FieldAccessInfo accessInfo = document.createFieldAccessInfo(segment, pos[0], pos[1], thisType, + fieldInfo, isLast, false); + + return new MarkResult(new ScriptLine.Mark(pos[0], pos[1], getFieldTokenType(fieldInfo), accessInfo), + (fieldInfo != null) ? fieldInfo.getTypeInfo() : null + ); + } + + return new MarkResult(new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR), null + ); + } + + /** Resolve mark for super.field access */ + private MarkResult resolveSuperFieldMark(ChainContext ctx) { + int index = ctx.currentIndex; + String segment = ctx.chain.segments.get(index); + int[] pos = ctx.chain.positions.get(index); + boolean isLast = (index == ctx.chain.segments.size() - 1); + TypeInfo superType = ctx.currentType; + + if (superType == null) { + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR, + TokenErrorMessage.from("Cannot resolve field '" + segment + "'").clearOtherErrors()), + null + ); + } + + // Search through inheritance hierarchy + boolean found = false; + FieldInfo fieldInfo = null; + + if (superType instanceof ScriptTypeInfo) { + ScriptTypeInfo scriptSuper = (ScriptTypeInfo) superType; + found = scriptSuper.hasFieldInHierarchy(segment); + if (found) fieldInfo = scriptSuper.getFieldInfoInHierarchy(segment); + } else { + found = superType.hasField(segment); + if (found) fieldInfo = superType.getFieldInfo(segment); + } + + if (found) { + FieldAccessInfo accessInfo = document.createFieldAccessInfo(segment, pos[0], pos[1], + superType, fieldInfo, isLast, false); + return new MarkResult(new ScriptLine.Mark(pos[0], pos[1], getFieldTokenType(fieldInfo), accessInfo), + (fieldInfo != null) ? fieldInfo.getTypeInfo() : null + ); + } + + String errorMsg = "Field '" + segment + "' not found in parent class hierarchy starting from '" + + superType.getSimpleName() + "'"; + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR, + TokenErrorMessage.from(errorMsg).clearOtherErrors()), + null + ); + } + + /** Resolve mark for typed field access */ + private MarkResult resolveTypedFieldMark(ChainContext ctx) { + int index = ctx.currentIndex; + String segment = ctx.chain.segments.get(index); + int[] pos = ctx.chain.positions.get(index); + boolean isLast = (index == ctx.chain.segments.size() - 1); + boolean isStatic = isStaticContext(ctx); + TypeInfo currentType = ctx.currentType; + + if (!currentType.hasField(segment)) { + // Field not found — check if the segment names an inner class. + // This handles chains like Outer.Inner where Inner is a nested type, not a field. + TypeInfo rawType = currentType.getRawType(); + if (rawType instanceof ScriptTypeInfo) { + ScriptTypeInfo innerClass = ((ScriptTypeInfo) rawType).getInnerClass(segment); + if (innerClass != null) { + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], innerClass.getTokenType(), innerClass), + innerClass + ); + } + } + // Also check Java inner classes via reflection (e.g., Map.Entry) + if (currentType.getJavaClass() != null) { + try { + for (Class nested : currentType.getJavaClass().getDeclaredClasses()) { + if (java.lang.reflect.Modifier.isPublic(nested.getModifiers()) + && nested.getSimpleName().equals(segment)) { + TypeInfo nestedType = TypeInfo.fromClass(nested); + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], nestedType.getTokenType(), nestedType), + nestedType + ); + } + } + } catch (SecurityException ignored) { } + } + + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR), + null + ); + } + + FieldInfo fieldInfo = currentType.getFieldInfo(segment); + + // Check for static access error + if (isStatic && fieldInfo != null && !fieldInfo.isStatic()) { + TokenErrorMessage errorMsg = TokenErrorMessage + .from("Cannot access non-static field '" + segment + "' from static context '" + + currentType.getSimpleName() + "'") + .clearOtherErrors(); + return new MarkResult( + new ScriptLine.Mark(pos[0], pos[1], TokenType.UNDEFINED_VAR, errorMsg), + null + ); + } + + // Valid field access + FieldAccessInfo accessInfo = document.createFieldAccessInfo(segment, pos[0], pos[1], + currentType, fieldInfo, isLast, isStatic); + + return new MarkResult(new ScriptLine.Mark(pos[0], pos[1], getFieldTokenType(fieldInfo), accessInfo), + (fieldInfo != null) ? fieldInfo.getTypeInfo() : null + ); + } + + /** Mark segments following a method call or array access result */ + private void markReceiverChainSegments(List marks, String firstField, + int identStart, int identEnd, TypeInfo receiverType) { + // Mark the first field + FieldInfo fInfo = null; + TypeInfo currentType = null; + + if (receiverType != null && receiverType.hasField(firstField)) { + fInfo = receiverType.getFieldInfo(firstField); + boolean hasMore = document.isFollowedByDot(identEnd); + // For method/array result chains, the receiver is always an instance, not a type + boolean isStatic = false; + + FieldAccessInfo accessInfo = document.createFieldAccessInfo(firstField, identStart, identEnd, + receiverType, fInfo, !hasMore, isStatic); + + marks.add(new ScriptLine.Mark(identStart, identEnd, getFieldTokenType(fInfo), accessInfo)); + currentType = (fInfo != null) ? fInfo.getTypeInfo() : null; + } else { + marks.add(new ScriptLine.Mark(identStart, identEnd, TokenType.UNDEFINED_VAR)); + return; + } + + // Continue the chain + int pos = identEnd; + while (pos < text.length()) { + pos = document.skipWhitespace(pos); + if (pos >= text.length() || document.isExcluded(pos) || text.charAt(pos) != '.') break; + pos++; // Skip dot + + pos = document.skipWhitespace(pos); + if (pos >= text.length() || document.isExcluded(pos) || !Character.isJavaIdentifierStart(text.charAt(pos))) break; + + // Read identifier + int nStart = pos; + while (pos < text.length() && Character.isJavaIdentifierPart(text.charAt(pos))) pos++; + int nEnd = pos; + String seg = text.substring(nStart, nEnd); + + // Stop if method call + if (document.isFollowedByParen(nEnd)) break; + if (document.isExcluded(nStart)) break; + + boolean isLast = !document.isFollowedByDot(nEnd); + + if (currentType != null && currentType.isResolved() && currentType.hasField(seg)) { + FieldInfo segInfo = currentType.getFieldInfo(seg); + // In method/array result chains, segments are always instance access + boolean isStatic = false; + + FieldAccessInfo accessInfo = document.createFieldAccessInfo(seg, nStart, nEnd, + currentType, segInfo, isLast, isStatic); + + marks.add(new ScriptLine.Mark(nStart, nEnd, getFieldTokenType(segInfo), accessInfo)); + currentType = (segInfo != null) ? segInfo.getTypeInfo() : null; + } else { + marks.add(new ScriptLine.Mark(nStart, nEnd, TokenType.UNDEFINED_VAR)); + break; + } + } + } + + // ==================== UTILITY HELPERS ==================== + + private TokenType getFieldTokenType(FieldInfo fieldInfo) { + if (fieldInfo != null && fieldInfo.isEnumConstant()) + return TokenType.ENUM_CONSTANT; + + return TokenType.GLOBAL_FIELD; + } + + /** Get the non-whitespace character before a position */ + private Character getNonWhitespaceBefore(int pos) { + int before = pos - 1; + while (before >= 0 && Character.isWhitespace(text.charAt(before))) before--; + return (before >= 0) ? text.charAt(before) : null; + } + + /** Check if the receiver type is a class/type (static context) */ + private boolean isStaticContext(ChainContext ctx) { + // Static context if the previous segment name resolves to a type/class + if (ctx.currentIndex <= 0) + return false; + + String previousSegment = ctx.chain.segments.get(ctx.currentIndex - 1); + int prevPos = ctx.chain.positions.get(ctx.currentIndex - 1)[0]; + + // Use unified static access checker + return TypeResolver.isStaticAccessExpression(previousSegment, prevPos, document); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/InnerCallableScope.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/InnerCallableScope.java new file mode 100644 index 000000000..e0fed4951 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/InnerCallableScope.java @@ -0,0 +1,104 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; + +/** + * Represents an inner callable scope (lambda or JS function expression). + * These are NOT added to the methods list - they're resolution-only scopes. + */ +public class InnerCallableScope { + + public enum Kind { + JAVA_LAMBDA, + JS_FUNCTION_EXPR, + JS_ARROW_FUNC, + JS_SHORTHAND_METHOD + } + + private final Kind kind; + private final int headerStart; // Start of "(params) ->" or "function(params)" + private final int headerEnd; // End of header (position of "->" for lambda, ")" for JS func) + private final int bodyStart; // Start of body (expression start or '{') + private final int bodyEnd; // End of body (expression end or '}') + private final List parameters = new ArrayList<>(); + private final Map locals = new HashMap<>(); + private InnerCallableScope parentScope; // Enclosing inner scope (for nested lambdas) + private TypeInfo expectedType; // The expected functional interface type (set during resolution) + private TypeInfo containingObjectType; // For object-literal methods, the synthetic object-literal type + + public InnerCallableScope(Kind kind, int headerStart, int headerEnd, int bodyStart, int bodyEnd) { + this.kind = kind; + this.headerStart = headerStart; + this.headerEnd = headerEnd; + this.bodyStart = bodyStart; + this.bodyEnd = bodyEnd; + } + + // Getters + public Kind getKind() { return kind; } + public int getHeaderStart() { return headerStart; } + public int getHeaderEnd() { return headerEnd; } + public int getBodyStart() { return bodyStart; } + public int getBodyEnd() { return bodyEnd; } + public List getParameters() { return parameters; } + public Map getLocals() { return locals; } + public InnerCallableScope getParentScope() { return parentScope; } + public TypeInfo getExpectedType() { return expectedType; } + public TypeInfo getContainingObjectType() { return containingObjectType; } + + // Setters + public void setParentScope(InnerCallableScope parent) { this.parentScope = parent; } + public void setExpectedType(TypeInfo type) { this.expectedType = type; } + public void setContainingObjectType(TypeInfo type) { this.containingObjectType = type; } + + public void addParameter(FieldInfo param) { + parameters.add(param); + } + + public void addLocal(String name, FieldInfo local) { + locals.put(name, local); + } + + public FieldInfo getParameter(String name) { + for (FieldInfo param : parameters) { + if (param.getName().equals(name)) { + return param; + } + } + return null; + } + + public boolean hasParameter(String name) { + return getParameter(name) != null; + } + + /** + * Check if a position is inside this scope's body. + */ + public boolean containsPosition(int position) { + return position >= bodyStart && position < bodyEnd; + } + + /** + * Check if a position is inside this scope's header (parameter list). + */ + public boolean containsHeaderPosition(int position) { + return position >= headerStart && position < headerEnd; + } + + /** + * Get the full range (header + body). + */ + public int getFullStart() { + return headerStart; + } + + public int getFullEnd() { + return bodyEnd; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/LoopVariableParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/LoopVariableParser.java new file mode 100644 index 000000000..9b2b432b8 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/LoopVariableParser.java @@ -0,0 +1,224 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.gui.util.script.ScopeInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class LoopVariableParser { + + private static final Pattern ENHANCED_FOR = Pattern.compile( + "\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>,\\[\\] \\t\\n\\r]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*:\\s*([^)]+)\\)"); + private static final Pattern CLASSIC_FOR = Pattern.compile( + "\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>,\\[\\] \\t\\n\\r]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*="); + private static final Pattern FOR_IN = Pattern.compile( + "\\bfor\\s*\\(\\s*(?:var|let|const)\\s+(\\w+)\\s+in\\s+([^)]+)\\)"); + private static final Pattern FOR_OF = Pattern.compile( + "\\bfor\\s*\\(\\s*(?:var|let|const)\\s+(\\w+)\\s+of\\s+([^)]+)\\)"); + static final Pattern FOR_IN_OF_LOOKAHEAD = Pattern.compile("^\\s+(?:in|of)\\s"); + + private static final Set SKIP_TYPES = new HashSet<>(Arrays.asList( + "return", "if", "while", "for", "switch", "catch", "new", "throw")); + + private final ScriptDocument doc; + private final String text; + + LoopVariableParser(ScriptDocument doc, String text) { + this.doc = doc; + this.text = text; + } + + boolean isForInOrOf(String textAfterVarName) { + return FOR_IN_OF_LOOKAHEAD.matcher(textAfterVarName).find(); + } + + boolean isInsideForHeader(int bodyStart, int absPos) { + int enclosingParen = doc.findEnclosingParenStart(bodyStart, absPos); + return enclosingParen >= 0 && "for".equals(doc.readKeywordBefore(enclosingParen)); + } + + void parse(Map>> methodLocals) { + boolean js = doc.isJavaScript(); + + for (MethodInfo method : doc.getAllMethods()) { + int bodyStart = method.getBodyStart(); + int bodyEnd = method.getBodyEnd(); + if (bodyStart < 0 || bodyEnd <= bodyStart) continue; + String bodyText = text.substring(bodyStart, Math.min(bodyEnd, text.length())); + Map> locals = methodLocals.computeIfAbsent(method.getDeclarationOffset(), k -> new HashMap<>()); + scanRange(bodyText, bodyStart, bodyEnd, method, locals, js); + } + + for (InnerCallableScope scope : doc.getInnerScopes()) { + int bodyStart = scope.getBodyStart(); + int bodyEnd = scope.getBodyEnd(); + if (bodyStart < 0 || bodyEnd <= bodyStart) continue; + String bodyText = text.substring(bodyStart, Math.min(bodyEnd, text.length())); + MethodInfo ownerMethod = doc.findMethodAtPosition(bodyStart); + if (ownerMethod == null) continue; + Map> locals = methodLocals.computeIfAbsent(ownerMethod.getDeclarationOffset(), k -> new HashMap<>()); + scanRange(bodyText, bodyStart, bodyEnd, ownerMethod, locals, js); + } + + scanTopLevelLoops(); + } + + private void scanTopLevelLoops() { + boolean js = doc.isJavaScript(); + + if (!js) { + for (Matcher m = ENHANCED_FOR.matcher(text); m.find(); ) { + int absForPos = m.start(); + if (doc.isExcluded(absForPos) || isInsideAnyScope(absForPos)) continue; + String typeName = m.group(1).trim(); + String varName = m.group(2); + TypeInfo typeInfo = doc.resolveType(typeName); + ScopeInfo scope = computeForBodyScope(absForPos, 0, text.length()); + FieldInfo fi = FieldInfo.localField(varName, typeInfo, m.start(2), null, -1, -1, 0); + fi.setScopeInfo(scope); + doc.addTopLevelLocal(fi); + } + + for (Matcher m = CLASSIC_FOR.matcher(text); m.find(); ) { + int absForPos = m.start(); + if (doc.isExcluded(absForPos) || isInsideAnyScope(absForPos)) continue; + String typeName = m.group(1).trim(); + String varName = m.group(2); + if (SKIP_TYPES.contains(typeName)) continue; + TypeInfo typeInfo = doc.resolveType(typeName); + ScopeInfo scope = computeForBodyScope(absForPos, 0, text.length()); + FieldInfo fi = FieldInfo.localField(varName, typeInfo, m.start(2), null, -1, -1, 0); + fi.setScopeInfo(scope); + doc.addTopLevelLocal(fi); + } + } else { + for (Matcher m = FOR_IN.matcher(text); m.find(); ) { + int absForPos = m.start(); + if (doc.isExcluded(absForPos) || isInsideAnyScope(absForPos)) continue; + String varName = m.group(1); + ScopeInfo scope = computeForBodyScope(absForPos, 0, text.length()); + FieldInfo fi = FieldInfo.localField(varName, TypeInfo.fromPrimitive("int"), m.start(1), null, -1, -1, 0); + fi.setScopeInfo(scope); + doc.addTopLevelLocal(fi); + } + + for (Matcher m = FOR_OF.matcher(text); m.find(); ) { + int absForPos = m.start(); + if (doc.isExcluded(absForPos) || isInsideAnyScope(absForPos)) continue; + String varName = m.group(1); + String iterableExpr = m.group(2).trim(); + TypeInfo iterableType = doc.resolveExpressionType(iterableExpr, absForPos); + TypeInfo elementType = (iterableType != null) ? iterableType.getElementType() : null; + if (elementType == null) elementType = TypeInfo.ANY; + ScopeInfo scope = computeForBodyScope(absForPos, 0, text.length()); + FieldInfo fi = FieldInfo.localField(varName, elementType, m.start(1), null, -1, -1, 0); + fi.setScopeInfo(scope); + doc.addTopLevelLocal(fi); + } + } + } + + private boolean isInsideAnyScope(int pos) { + for (MethodInfo method : doc.getAllMethods()) { + if (method.containsPosition(pos)) return true; + } + for (InnerCallableScope scope : doc.getInnerScopes()) { + if (scope.containsPosition(pos)) return true; + } + return false; + } + + private void scanRange(String bodyText, int bodyStart, int bodyEnd, + MethodInfo method, Map> locals, boolean js) { + if (!js) { + Matcher m = ENHANCED_FOR.matcher(bodyText); + while (m.find()) { + int absForPos = bodyStart + m.start(); + if (doc.isExcluded(absForPos)) continue; + String typeName = m.group(1).trim(); + String varName = m.group(2); + int absVarPos = bodyStart + m.start(2); + TypeInfo typeInfo = doc.resolveType(typeName); + ScopeInfo scope = computeForBodyScope(absForPos, bodyStart, bodyEnd); + FieldInfo fi = FieldInfo.localField(varName, typeInfo, absVarPos, method, -1, -1, 0); + fi.setScopeInfo(scope); + locals.computeIfAbsent(varName, k -> new ArrayList<>()).add(fi); + } + + m = CLASSIC_FOR.matcher(bodyText); + while (m.find()) { + int absForPos = bodyStart + m.start(); + if (doc.isExcluded(absForPos)) continue; + String typeName = m.group(1).trim(); + String varName = m.group(2); + if (SKIP_TYPES.contains(typeName)) continue; + int absVarPos = bodyStart + m.start(2); + TypeInfo typeInfo = doc.resolveType(typeName); + ScopeInfo scope = computeForBodyScope(absForPos, bodyStart, bodyEnd); + FieldInfo fi = FieldInfo.localField(varName, typeInfo, absVarPos, method, -1, -1, 0); + fi.setScopeInfo(scope); + locals.computeIfAbsent(varName, k -> new ArrayList<>()).add(fi); + } + } else { + Matcher m = FOR_IN.matcher(bodyText); + while (m.find()) { + int absForPos = bodyStart + m.start(); + if (doc.isExcluded(absForPos)) continue; + String varName = m.group(1); + int absVarPos = bodyStart + m.start(1); + ScopeInfo scope = computeForBodyScope(absForPos, bodyStart, bodyEnd); + FieldInfo fi = FieldInfo.localField(varName, TypeInfo.fromPrimitive("int"), absVarPos, method, -1, -1, 0); + fi.setScopeInfo(scope); + locals.computeIfAbsent(varName, k -> new ArrayList<>()).add(fi); + } + + m = FOR_OF.matcher(bodyText); + while (m.find()) { + int absForPos = bodyStart + m.start(); + if (doc.isExcluded(absForPos)) continue; + String varName = m.group(1); + String iterableExpr = m.group(2).trim(); + int absVarPos = bodyStart + m.start(1); + TypeInfo iterableType = doc.resolveExpressionType(iterableExpr, absForPos); + TypeInfo elementType = (iterableType != null) ? iterableType.getElementType() : null; + if (elementType == null) elementType = TypeInfo.ANY; + ScopeInfo scope = computeForBodyScope(absForPos, bodyStart, bodyEnd); + FieldInfo fi = FieldInfo.localField(varName, elementType, absVarPos, method, -1, -1, 0); + fi.setScopeInfo(scope); + locals.computeIfAbsent(varName, k -> new ArrayList<>()).add(fi); + } + } + } + + private ScopeInfo computeForBodyScope(int forKeywordPos, int bodyStart, int bodyEnd) { + int max = Math.min(bodyEnd, text.length()); + int openParen = -1; + for (int i = forKeywordPos; i < max; i++) { + if (doc.isExcluded(i)) continue; + char c = text.charAt(i); + if (c == '(') { openParen = i; break; } + if (!Character.isWhitespace(c) && c != 'f' && c != 'o' && c != 'r') break; + } + if (openParen < 0) return new ScopeInfo(forKeywordPos, bodyEnd, false, "block"); + + int closeParen = doc.findMatchingParen(openParen, max); + if (closeParen < 0) return new ScopeInfo(forKeywordPos, bodyEnd, false, "block"); + + int after = doc.skipWhitespaceAndExcluded(closeParen + 1, max); + if (after < 0 || after >= max) return new ScopeInfo(forKeywordPos, bodyEnd, false, "block"); + + if (text.charAt(after) == '{') { + int closeBrace = doc.findMatchingBrace(after); + if (closeBrace > 0) return new ScopeInfo(forKeywordPos, closeBrace + 1, false, "block"); + return new ScopeInfo(forKeywordPos, bodyEnd, false, "block"); + } + + int stmtEnd = doc.findStatementEnd(after, max); + if (stmtEnd > after) return new ScopeInfo(forKeywordPos, stmtEnd, false, "block"); + return new ScopeInfo(forKeywordPos, bodyEnd, false, "block"); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/MultiDeclaratorParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/MultiDeclaratorParser.java new file mode 100644 index 000000000..7c5806a03 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/MultiDeclaratorParser.java @@ -0,0 +1,405 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +// ==================== MULTI-DECLARATOR HELPERS ==================== +// +// JavaScript and Java both allow declaring multiple variables in a single +// statement, separated by commas: +// +// JS: var a = 1, b = "x", c = player; +// Java: int x = 1, y, z = 3; +// +// The existing regex patterns only match the FIRST declarator because: +// - The JS pattern `(var|let|const)\s+(\w+)` requires a keyword prefix. +// - The Java FIELD_DECL_PATTERN requires a type name prefix. +// +// Continuation declarators after the first comma have no keyword/type prefix, +// so they must be scanned manually. The two helpers below handle this by +// scanning forward from the end of the first declarator for commas at +// nesting depth 0, then extracting the `name [= initializer]` pattern +// for each continuation declarator. + +/** + * Static helpers for parsing comma-separated multi-variable declarations. + * + *

Extracted from {@link ScriptDocument} to keep the main document class + * focused on orchestration while this class owns the scanning algorithms.

+ */ +public final class MultiDeclaratorParser { + + private MultiDeclaratorParser() {} + + // ======================== CALLBACKS ======================== + + /** Callback for {@link #scanJSContinuationDeclarators}. */ + @FunctionalInterface + public interface JSContinuationCallback { + void accept(String varName, int absNamePos, String initializer, int absInitStart, int absInitEnd); + } + + /** Callback for {@link #scanJavaContinuationDeclarators}. */ + @FunctionalInterface + public interface JavaContinuationCallback { + void accept(String varName, int absNamePos, int absInitStart, int absInitEnd); + } + + // ======================== JS SCANNING ======================== + + /** + * Scan forward from {@code scanStart} in {@code source} for comma-separated + * continuation declarators in a JS {@code var/let/const} statement. + * + *

Each continuation declarator follows the pattern: {@code name [= initializer]}. + * The initializer (if present) is terminated using comma-aware scanning via + * {@link ScriptDocument#findJsInitializerEnd(String, int, boolean)}, which stops at + * top-level commas so that each declarator's RHS is correctly bounded.

+ * + *

The callback receives (varName, absNamePos, initializer, absInitStart, absInitEnd) + * for each continuation declarator found.

+ * + * @param doc the owning ScriptDocument (provides {@code findJsInitializerEnd} + * and {@code skipSegmentWhitespace}) + * @param source the source text to scan within (e.g. method body or global text) + * @param scanStart the position in {@code source} to begin scanning (typically + * right after the first declarator's initializer end or name end) + * @param absBase the absolute offset of {@code source[0]} in the full document text + * (used to compute absolute positions for the callback) + * @param callback receives each continuation declarator + */ + public static void scanJSContinuationDeclarators( + ScriptDocument doc, String source, int scanStart, int absBase, + JSContinuationCallback callback) { + + int pos = scanStart; + while (pos < source.length()) { + // Skip whitespace + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) pos++; + if (pos >= source.length()) break; + + // Expect a comma separating the next declarator + if (source.charAt(pos) != ',') break; + pos++; // skip the comma + + // Skip whitespace after comma + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) pos++; + if (pos >= source.length()) break; + + // Read the variable name (must be an identifier) + int nameStart = pos; + while (pos < source.length() && Character.isJavaIdentifierPart(source.charAt(pos))) pos++; + if (pos == nameStart) break; // no identifier found; malformed + String varName = source.substring(nameStart, pos); + + // Skip whitespace after name + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) pos++; + + String initializer = null; + int initStart = -1; + int initEnd = -1; + + // Check for optional '=' initializer + if (pos < source.length() && source.charAt(pos) == '=') { + // Make sure it's not == + if (pos + 1 < source.length() && source.charAt(pos + 1) == '=') break; + pos++; // skip '=' + int rhsStart = doc.skipSegmentWhitespace(source, pos); + // Use comma-aware initializer termination so that the RHS stops at + // the next top-level comma (which starts the next declarator). + int rhsEnd = doc.findJsInitializerEnd(source, rhsStart, true); + if (rhsEnd > rhsStart) { + initializer = source.substring(rhsStart, rhsEnd).trim(); + if (initializer.isEmpty()) initializer = null; + } + initStart = rhsStart; + initEnd = rhsEnd; + pos = rhsEnd; + } + + int absNamePos = absBase + nameStart; + int absInitStart = initStart >= 0 ? absBase + initStart : -1; + int absInitEnd = initEnd >= 0 ? absBase + initEnd : -1; + + callback.accept(varName, absNamePos, initializer, absInitStart, absInitEnd); + } + } + + // ======================== JAVA SCANNING ======================== + + /** + * Scan forward from {@code scanStart} in {@code source} for comma-separated + * continuation declarators in a Java multi-variable declaration. + * + *

Java allows {@code int x = 1, y, z = 3;} where all declarators share + * the same declared type. The {@code FIELD_DECL_PATTERN} regex only matches + * the first declarator ({@code int x =}); subsequent names like {@code y} + * and {@code z} lack a type prefix. This method manually scans the remainder + * of the statement for those continuation names.

+ * + *

Each continuation declarator follows the pattern: {@code name [= initializer]}. + * The initializer is terminated at {@code ;} or {@code ,} at depth 0.

+ * + * @param source the source text to scan within + * @param scanStart the position in {@code source} to begin scanning (typically + * right after the semicolon/delimiter of the first declarator + * match, or right after the first declarator's initializer) + * @param absBase the absolute offset of {@code source[0]} in the full document text + * @param callback receives each continuation declarator + */ + public static void scanJavaContinuationDeclarators( + String source, int scanStart, int absBase, + JavaContinuationCallback callback) { + + int pos = scanStart; + while (pos < source.length()) { + // Skip whitespace + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) pos++; + if (pos >= source.length()) break; + + // Expect a comma separating the next declarator + if (source.charAt(pos) != ',') break; + pos++; // skip the comma + + // Skip whitespace after comma + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) pos++; + if (pos >= source.length()) break; + + // Read the variable name (must be an identifier) + int nameStart = pos; + while (pos < source.length() && Character.isJavaIdentifierPart(source.charAt(pos))) pos++; + if (pos == nameStart) break; // no identifier found; malformed + String varName = source.substring(nameStart, pos); + + // Skip whitespace after name + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) pos++; + + int initStart = -1; + int initEnd = -1; + + // Check for optional '=' initializer + if (pos < source.length() && source.charAt(pos) == '=') { + // Make sure it's not == + if (pos + 1 < source.length() && source.charAt(pos + 1) == '=') break; + + initStart = pos; // position of '=' + pos++; // skip '=' + int rhsStart = pos; + // Skip whitespace after '=' + while (rhsStart < source.length() && Character.isWhitespace(source.charAt(rhsStart))) rhsStart++; + + // Scan forward for ';' or ',' at depth 0 to terminate this declarator's initializer + int depth = 0; + int angleDepth = 0; + int scanPos = rhsStart; + while (scanPos < source.length()) { + char c = source.charAt(scanPos); + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') depth--; + else if (c == '<') angleDepth++; + else if (c == '>') angleDepth--; + else if ((c == ';' || c == ',') && depth == 0 && angleDepth == 0) { + initEnd = scanPos; + break; + } + scanPos++; + } + pos = (initEnd >= 0) ? initEnd : scanPos; + } else if (pos < source.length() && (source.charAt(pos) == ';' || source.charAt(pos) == ',')) { + // No initializer — name only (e.g., the `y` in `int x, y, z;`) + // Don't advance past ';' here; let the outer loop handle it. + // If it's a comma, we'll pick it up on the next iteration. + } else { + // Unexpected character; stop scanning + break; + } + + int absNamePos = absBase + nameStart; + int absInitStartAbs = initStart >= 0 ? absBase + initStart : -1; + int absInitEndAbs = initEnd >= 0 ? absBase + initEnd : -1; + + callback.accept(varName, absNamePos, absInitStartAbs, absInitEndAbs); + } + } + + // ======================== SCAN-START POSITION HELPERS ======================== + + /** + * Determine the scan position for continuation declarators after a JS + * declarator match. If the first declarator has an initializer, we scan + * from the initializer end; otherwise we scan from after the variable name. + * + * @param bodyText the body text being parsed + * @param matchEnd the end position of the regex match (end of var name or '=') + * @param hasEquals whether the first declarator has '=' + * @param initEnd the initializer end position (in bodyText coords), or -1 + * @return the position in bodyText to start scanning for continuation commas + */ + public static int jsDeclaratorScanStart(String bodyText, int matchEnd, boolean hasEquals, int initEnd) { + if (hasEquals && initEnd >= 0) { + return initEnd; + } + // No initializer: scan from after the variable name + return matchEnd; + } + + /** + * Determine the scan position for continuation declarators after a Java + * FIELD_DECL_PATTERN match. The pattern's group(3) matches either '=', ';', + * or ','. If it matched '=', the scan starts after the initializer expression; + * if ';', there are no continuations (semicolon ends the statement). + * + *

Note: when the regex greedily consumed commas into the type name + * (e.g. {@code "int x, y,"} as the type group), the caller must detect this + * via {@link #findFirstDepthZeroComma(String)} on the matched type string + * and use the returned comma position directly as the scan start, bypassing + * this method. See the call sites in {@link ScriptDocument} for details.

+ * + * @param source the source text + * @param delimiter the delimiter matched by group(3): "=", ";", or "," + * @param delimEnd the end position of the delimiter in source coords + * @param initEnd the initializer end position, or -1 if no initializer + * @return the position in source to start scanning for continuation commas, + * or -1 if the statement ended at a semicolon + */ + public static int javaDeclaratorScanStart(String source, String delimiter, int delimEnd, int initEnd) { + if (";".equals(delimiter)) { + return -1; // semicolon terminates the statement; no continuations possible + } + // delimiter is '=' or ',' — scan from after the initializer (which stops at ',' or ';') + if (initEnd >= 0) { + return initEnd; + } + // When delimiter is ',' with no initializer (e.g. the 'x' in "int x,y,z;"), + // m.end(3) lands AFTER the comma. The scanner expects to START at the comma + // so it can consume it as the continuation separator — so back up by one. + if (",".equals(delimiter)) { + return delimEnd - 1; + } + return delimEnd; + } + + // ======================== GREEDY-REGEX COMMA HELPERS ======================== + + /** + * Find the first comma at bracket-depth 0 in the given string. + * + *

The Java {@code FIELD_DECL_PATTERN} regex allows commas inside the + * type-name character class (to support generics like {@code Map}). + * This causes the regex to greedily consume multi-declarator commas into + * group(1). For example, {@code "int x, y, z;"} matches with + * group(1)={@code "int x, y,"} and group(2)={@code "z"}.

+ * + *

This helper scans for the first comma that is NOT inside angle brackets + * ({@code <>}), parentheses, square brackets, or braces, i.e. at depth 0. + * A depth-0 comma indicates a multi-declarator separator that was consumed + * by the greedy regex.

+ * + * @param s the string to search (typically the matched type group) + * @return the index of the first depth-0 comma, or -1 if none found + */ + public static int findFirstDepthZeroComma(String s) { + int depth = 0; + int angleDepth = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') depth--; + else if (c == '<') angleDepth++; + else if (c == '>') angleDepth--; + else if (c == ',' && depth == 0 && angleDepth == 0) return i; + } + return -1; + } + + /** + * Extract the real type name from a regex group(1) that greedily consumed + * extra variable names and commas. + * + *

When the regex matches {@code "int x, y, z;"} as group(1)={@code "int x, y,"}, + * the real type name is {@code "int"} — everything before the first identifier + * that precedes the first depth-0 comma.

+ * + *

For {@code "final int x, y,"}, returns {@code "final int"}. + * For {@code "Map x, y,"}, returns {@code "Map"}.

+ * + * @param typeGroup the full group(1) string from the regex match + * @param commaIndex the index of the first depth-0 comma in {@code typeGroup} + * (as returned by {@link #findFirstDepthZeroComma(String)}) + * @return the real type name (may include modifiers like "final") + */ + public static String extractRealTypeFromGreedyMatch(String typeGroup, int commaIndex) { + // The part before the first depth-0 comma contains "Type firstVar" + // (possibly with modifiers). We need to split off the last identifier + // token before the comma, as that's the first variable name, not the type. + String beforeComma = typeGroup.substring(0, commaIndex).trim(); + int lastSpace = beforeComma.lastIndexOf(' '); + int lastTab = beforeComma.lastIndexOf('\t'); + int lastWS = Math.max(lastSpace, lastTab); + if (lastWS < 0) { + // No whitespace found — the "type" is actually just a variable name + // This shouldn't happen for valid declarations but handle gracefully + return beforeComma; + } + return beforeComma.substring(0, lastWS).trim(); + } + + /** + * Extract the first variable name from a regex group(1) that greedily consumed + * extra variable names and commas. + * + *

When the regex matches {@code "int x, y, z;"} as group(1)={@code "int x, y,"}, + * the first variable name is {@code "x"} — the last identifier token before + * the first depth-0 comma.

+ * + * @param typeGroup the full group(1) string from the regex match + * @param commaIndex the index of the first depth-0 comma in {@code typeGroup} + * (as returned by {@link #findFirstDepthZeroComma(String)}) + * @return the first variable name + */ + public static String extractFirstVarFromGreedyMatch(String typeGroup, int commaIndex) { + String beforeComma = typeGroup.substring(0, commaIndex).trim(); + int lastSpace = beforeComma.lastIndexOf(' '); + int lastTab = beforeComma.lastIndexOf('\t'); + int lastWS = Math.max(lastSpace, lastTab); + if (lastWS < 0) { + return beforeComma; + } + return beforeComma.substring(lastWS + 1).trim(); + } + + /** + * Find the absolute position of the first variable name within a greedily-consumed + * type group. Searches for the first variable name (the last token before the + * first depth-0 comma) within the source text starting from the type group start. + * + * @param source the full source text + * @param typeGroupStart the absolute start of group(1) in the source + * @param typeGroup the group(1) string + * @param commaIndex the index of the first depth-0 comma in typeGroup + * @return the absolute position of the first variable name in source + */ + public static int findFirstVarPosition(String source, int typeGroupStart, String typeGroup, int commaIndex) { + String firstVar = extractFirstVarFromGreedyMatch(typeGroup, commaIndex); + // The first variable appears in typeGroup just before the comma. + // Search backwards from commaIndex to find it. + String beforeComma = typeGroup.substring(0, commaIndex).trim(); + int varStartInGroup = beforeComma.lastIndexOf(firstVar); + return typeGroupStart + varStartInGroup; + } + + // ======================== MISC HELPERS ======================== + + /** + * Check whether the statement starting at {@code stmtStart} begins with + * a JS declaration keyword ({@code var}, {@code let}, or {@code const}). + * Used by {@link ScriptDocument}'s {@code parseAssignments()} to decide + * whether the RHS of an {@code =} should stop at a top-level comma + * (multi-declarator context). + */ + public static boolean startsWithJSKeyword(String source, int stmtStart, int equalsPos) { + int i = stmtStart; + while (i < equalsPos && Character.isWhitespace(source.charAt(i))) i++; + String prefix = source.substring(i, Math.min(i + 6, equalsPos)).trim(); + return prefix.startsWith("var ") || prefix.startsWith("var\t") + || prefix.startsWith("let ") || prefix.startsWith("let\t") + || prefix.startsWith("const ") || prefix.startsWith("const\t"); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java new file mode 100644 index 000000000..9ddec2a92 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ObjectLiteralParser.java @@ -0,0 +1,1494 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.ArrayList; +import java.util.List; + +/** + * Helper class for JavaScript object literal (AKA dicts) analysis, parsing, type-shape inference, + * and dynamic property access handling. + * + *

Purpose

+ * Encapsulates the logic for: + *
    + *
  • Parsing object literal syntax ({@code { key: value, ... }}) into structured property lists.
  • + *
  • Inferring synthetic {@link TypeInfo} shapes from object literal contents for hover/autocomplete.
  • + *
  • Parsing dynamic property accesses ({@code obj.prop}, {@code obj["prop"]}) on the assignment LHS.
  • + *
  • Extending synthetic object shapes when new properties are assigned after initial declaration.
  • + *
  • Detecting synthetic object literal display names for UI rendering.
  • + *
+ * + *

V1 Scope

+ *
    + *
  • Only simple identifier keys and quoted-string keys are supported. Computed keys ({@code [expr]: val}) + * and spread ({@code ...obj}) are recognized but gracefully skipped.
  • + *
  • Nested object literals inside values degrade to {@link TypeInfo#ANY} rather than recursive inference.
  • + *
  • Value type inference delegates to the caller-supplied {@link ExpressionTypeResolverFn}; this class + * does not resolve types itself.
  • + *
+ * + *

Degradation Behavior

+ * When the parser encounters unsupported syntax (computed keys, spread, deeply nested literals), + * it sets {@link ObjectLiteralAnalysis#supportsInference} to {@code false} and returns partial + * property data. Callers (e.g. mark building) can still use the parsed properties for key highlighting + * even when full type inference is unavailable. + * + *

Architecture Note

+ * Methods that need access to ScriptDocument's type resolution ({@code resolveExpressionType}, + * {@code resolveVariable}) accept functional interfaces ({@link ExpressionTypeResolverFn}, + * {@link VariableResolverFn}) so that this class remains decoupled from ScriptDocument's internals. + * ScriptDocument retains ownership of {@code markObjectLiteralKeys} and + * {@code findMatchingBraceEndInDocument} which need direct access to document state (excluded ranges, text). + */ +public final class ObjectLiteralParser { + + private ObjectLiteralParser() { + // Static utility class — not instantiable + } + + // ────────────────────────────────────────────────────────────────────────── + // Functional interfaces for ScriptDocument callbacks + // ────────────────────────────────────────────────────────────────────────── + + /** + * Callback to resolve an expression's type given the expression text and its absolute position + * within the document. Delegates to {@code ScriptDocument.resolveExpressionType(expr, position)}. + */ + @FunctionalInterface + public interface ExpressionTypeResolverFn { + TypeInfo resolve(String expr, int position); + } + + /** Resolves a script-declared method by name. Used to copy parameter/return info into callable properties. */ + @FunctionalInterface + public interface MethodReferenceResolverFn { + MethodInfo resolve(String methodName, TypeInfo[] argTypes); + } + + /** + * Callback to resolve a variable by name at a given document position. + * Delegates to {@code ScriptDocument.resolveVariable(name, position)}. + */ + @FunctionalInterface + public interface VariableResolverFn { + FieldInfo resolve(String name, int position); + } + + // ────────────────────────────────────────────────────────────────────────── + // Data classes + // ────────────────────────────────────────────────────────────────────────── + + /** + * Result of analyzing an object literal expression. + * + *

Contains the parsed properties, whether full type inference is feasible, + * and (when inference succeeded) the synthetic {@link TypeInfo} representing the object's shape.

+ */ + public static final class ObjectLiteralAnalysis { + /** Parsed properties (key name, offsets, optional inferred value type). */ + public final List properties; + /** + * {@code true} when every property was fully parseable and the closing brace was found, + * meaning a synthetic type shape can be constructed. {@code false} when unsupported syntax + * was encountered or the literal is incomplete. + */ + public final boolean supportsInference; + /** + * The synthetic {@link TypeInfo} representing this object literal's shape, or {@code null} + * when inference was not requested or not supported. + */ + public final TypeInfo inferredType; + + ObjectLiteralAnalysis(List properties, boolean supportsInference, TypeInfo inferredType) { + this.properties = properties; + this.supportsInference = supportsInference; + this.inferredType = inferredType; + } + } + + /** + * A single property inside an object literal. + * + *

Tracks the key name, whether the key was written as a bare identifier or a quoted string, + * the absolute document offsets for both key and value spans, the inferred value type + * (when type inference was requested), and optional callable metadata when the value is a + * function expression, arrow function, or shorthand method.

+ */ + public static final class ObjectLiteralProperty { + /** The property key name (without quotes if originally quoted). */ + public final String keyName; + /** {@code true} if the key was a bare identifier; {@code false} if it was a quoted string. */ + public final boolean isIdentifierKey; + /** Absolute start offset of the key in the document. */ + public final int keyStartAbs; + /** Absolute end offset of the key in the document. */ + public final int keyEndAbs; + /** Absolute start offset of the value expression in the document. */ + public final int valueStartAbs; + /** Absolute end offset of the value expression in the document. */ + public final int valueEndAbs; + /** The inferred type of the value expression, or {@code null} if inference was not requested. */ + public final TypeInfo valueType; + /** Callable metadata if this property's value is a function expression, arrow, or shorthand method. */ + public final CallableInfo callableInfo; + + ObjectLiteralProperty(String keyName, boolean isIdentifierKey, int keyStartAbs, int keyEndAbs, + int valueStartAbs, int valueEndAbs, TypeInfo valueType, CallableInfo callableInfo) { + this.keyName = keyName; + this.isIdentifierKey = isIdentifierKey; + this.keyStartAbs = keyStartAbs; + this.keyEndAbs = keyEndAbs; + this.valueStartAbs = valueStartAbs; + this.valueEndAbs = valueEndAbs; + this.valueType = valueType; + this.callableInfo = callableInfo; + } + + public boolean isCallable() { + return callableInfo != null; + } + } + + /** + * Represents a dynamic property access on the LHS of an assignment. + * + *

Two forms are supported:

+ *
    + *
  • Dot access: {@code obj.prop} → {@code receiverExpr="obj", propertyName="prop", bracketAccess=false}
  • + *
  • Bracket access: {@code obj["prop"]} → {@code receiverExpr="obj", propertyName="prop", bracketAccess=true}
  • + *
+ */ + public static final class DynamicPropertyAccess { + /** The expression for the receiver object (everything before the dot or bracket). */ + public final String receiverExpr; + /** The property name being accessed. */ + public final String propertyName; + /** Absolute document offset where the receiver expression starts. */ + public final int receiverStart; + /** {@code true} if this is bracket notation ({@code obj["prop"]}); {@code false} for dot notation. */ + public final boolean bracketAccess; + + DynamicPropertyAccess(String receiverExpr, String propertyName, int receiverStart, boolean bracketAccess) { + this.receiverExpr = receiverExpr; + this.propertyName = propertyName; + this.receiverStart = receiverStart; + this.bracketAccess = bracketAccess; + } + } + + // ────────────────────────────────────────────────────────────────────────── + // Object literal analysis + // ────────────────────────────────────────────────────────────────────────── + + /** + * Analyze an object literal string and extract its properties. + * + *

The input is expected to start with {@code '{'} (after optional leading whitespace) and + * may or may not be a complete literal. Properties are parsed into {@link ObjectLiteralProperty} + * records. When {@code inferTypes} is {@code true} and inference is feasible, a synthetic + * {@link TypeInfo} shape is constructed with fields matching the parsed properties.

+ * + * @param objectLiteral the source text of the object literal (starting at or near '{') + * @param baseOffset the absolute document offset corresponding to the start of {@code objectLiteral} + * @param inferTypes if {@code true}, attempt to resolve value types and build a synthetic shape + * @param assumeComplete if {@code true}, treat the entire string as a complete literal (no brace matching needed) + * @param typeResolver callback for resolving value expression types (may be {@code null} if {@code inferTypes} is false) + * @param methodChecker callback for checking if an identifier is a known script method (for callable detection) + * @return the analysis result, or {@code null} if the input is not a valid object literal start + */ + public static ObjectLiteralAnalysis parse(String objectLiteral, int baseOffset, + boolean inferTypes, boolean assumeComplete, + ExpressionTypeResolverFn typeResolver, + MethodReferenceResolverFn methodResolver) { + if (objectLiteral == null) { + return null; + } + + // Trim leading and trailing whitespace. + int leading = 0; + while (leading < objectLiteral.length() && Character.isWhitespace(objectLiteral.charAt(leading))) { + leading++; + } + int trailing = objectLiteral.length(); + while (trailing > leading && Character.isWhitespace(objectLiteral.charAt(trailing - 1))) { + trailing--; + } + + String src = objectLiteral.substring(leading, trailing); + int absBase = baseOffset + leading; + + // Verify this starts with '{'. + if (src.isEmpty() || src.charAt(0) != '{') { + return null; + } + + // Find the matching '}' or use the entire string if assumeComplete is true. + int endExclusive; + if (assumeComplete) { + endExclusive = src.length(); + } else { + endExclusive = findMatchingObjectLiteralEnd(src); + if (endExclusive <= 0) { + return null; + } + } + + // Only attempt type inference if the literal is complete (closing brace found). + boolean supportsInference = (endExclusive == src.length()); + int bodyStart = 1; + int bodyEnd = endExclusive - 1; + + List props = new ArrayList<>(); + boolean sawUnsupported = false; + + // Parse each property in the object literal body. + int i = bodyStart; + while (i < bodyEnd) { + i = skipSeparatorsAndComments(src, i, bodyEnd); + if (i >= bodyEnd) { + break; + } + + int keyStart = i; + String keyName = null; + boolean isIdentifierKey = false; + + char kc = src.charAt(i); + // Parse key: quoted string or bare identifier or async method shorthand + if (kc == '"' || kc == '\'') { + // Quoted key — extract and validate + int keyEnd = scanStringLiteralEnd(src, i); + if (keyEnd < 0 || keyEnd > bodyEnd) { + sawUnsupported = true; + break; + } + keyName = src.substring(i + 1, keyEnd - 1); + isIdentifierKey = false; + if (!isSimpleIdentifier(keyName)) { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, keyEnd, bodyEnd); + continue; + } + i = keyEnd; + } else if (Character.isJavaIdentifierStart(kc)) { + // Bare identifier key + i++; + while (i < bodyEnd && Character.isJavaIdentifierPart(src.charAt(i))) { + i++; + } + keyName = src.substring(keyStart, i); + isIdentifierKey = true; + + // Handle 'async methodName()' shorthand syntax + if ("async".equals(keyName)) { + int afterAsync = i; + while (afterAsync < bodyEnd && Character.isWhitespace(src.charAt(afterAsync))) { + afterAsync++; + } + if (afterAsync < bodyEnd && Character.isJavaIdentifierStart(src.charAt(afterAsync))) { + int realKeyStart = afterAsync; + afterAsync++; + while (afterAsync < bodyEnd && Character.isJavaIdentifierPart(src.charAt(afterAsync))) { + afterAsync++; + } + keyStart = realKeyStart; + keyName = src.substring(realKeyStart, afterAsync); + i = afterAsync; + } + } + } else if (kc == '[') { + // Computed key — unsupported for inference, skip to next property + sawUnsupported = true; + i = scanToNextTopLevelComma(src, i, bodyEnd); + continue; + } else if (kc == '.' && i + 2 < bodyEnd && src.charAt(i + 1) == '.' && src.charAt(i + 2) == '.') { + // Spread syntax — unsupported, skip + sawUnsupported = true; + i = scanToNextTopLevelComma(src, i, bodyEnd); + continue; + } else { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, i, bodyEnd); + continue; + } + + int keyEnd = i; + while (i < bodyEnd && Character.isWhitespace(src.charAt(i))) { + i++; + } + + // Check for shorthand method syntax: key() { ... } + if (i < bodyEnd && src.charAt(i) == '(' && isIdentifierKey) { + int parenOpen = i; + int parenClose = findMatchingParen(src, parenOpen); + if (parenClose < 0 || parenClose >= bodyEnd) { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, i, bodyEnd); + continue; + } + + // Extract parameter names and infer return type from the method body. + List params = extractParameterNames(src.substring(parenOpen + 1, parenClose)); + int afterParen = parenClose + 1; + while (afterParen < bodyEnd && Character.isWhitespace(src.charAt(afterParen))) { + afterParen++; + } + // Expect a '{' after the parameter list + if (afterParen >= bodyEnd || src.charAt(afterParen) != '{') { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, afterParen, bodyEnd); + continue; + } + + int braceEnd = findMatchingObjectLiteralEnd(src.substring(afterParen)); + if (braceEnd <= 0) { + sawUnsupported = true; + break; + } + int methodBodyEnd = afterParen + braceEnd; + String bodyText = src.substring(afterParen, methodBodyEnd); + TypeInfo returnType = inferReturnTypeFromBlockBody(bodyText, absBase + afterParen, typeResolver); + + CallableInfo callableInfo = new CallableInfo(params, returnType, + absBase + afterParen, absBase + methodBodyEnd, true); + int keyStartAbs = absBase + keyStart; + int keyEndAbs = absBase + keyEnd; + int valueStartAbs = absBase + parenOpen; + int valueEndAbs = absBase + methodBodyEnd; + + props.add(new ObjectLiteralProperty(keyName, true, keyStartAbs, keyEndAbs, + valueStartAbs, valueEndAbs, returnType, callableInfo)); + i = methodBodyEnd; + while (i < bodyEnd && Character.isWhitespace(src.charAt(i))) { + i++; + } + if (i < bodyEnd && src.charAt(i) == ',') { + i++; + } + continue; + } + + // Regular property: key: value + if (i >= bodyEnd || src.charAt(i) != ':') { + sawUnsupported = true; + i = scanToNextTopLevelComma(src, i, bodyEnd); + continue; + } + i++; + + while (i < bodyEnd && Character.isWhitespace(src.charAt(i))) { + i++; + } + int valueStart = i; + int valueEnd = scanTopLevelValueEnd(src, valueStart, bodyEnd); + if (valueEnd < valueStart) { + sawUnsupported = true; + break; + } + + // Try to detect callable or infer value type + TypeInfo valueType = null; + CallableInfo callableInfo = null; + if (inferTypes && typeResolver != null) { + String valueExpr = src.substring(valueStart, valueEnd).trim(); + callableInfo = detectCallableExpression(valueExpr, absBase + valueStart, methodResolver, typeResolver); + if (callableInfo != null) { + valueType = callableInfo.returnType; + } else { + valueType = inferValueType(valueExpr, absBase + valueStart, typeResolver); + } + } + + int keyStartAbs = absBase + keyStart; + int keyEndAbs = absBase + keyEnd; + int valueStartAbs = absBase + valueStart; + int valueEndAbs = absBase + valueEnd; + + if (keyName != null) { + props.add(new ObjectLiteralProperty(keyName, isIdentifierKey, keyStartAbs, keyEndAbs, + valueStartAbs, valueEndAbs, valueType, callableInfo)); + } + + i = valueEnd; + i = skipSeparatorsAndComments(src, i, bodyEnd); + } + + if (sawUnsupported) { + supportsInference = false; + } + + TypeInfo inferredType = null; + if (inferTypes && supportsInference) { + inferredType = TypeInfo.objectLiteral(props); + } + + return new ObjectLiteralAnalysis(props, supportsInference, inferredType); + } + + // ────────────────────────────────────────────────────────────────────────── + // Synthetic object literal display name detection + // ────────────────────────────────────────────────────────────────────────── + + /** + * Determine whether a {@link JSTypeInfo} represents a synthetic object literal type, + * and if so return its display name ({@code "Object"}). + * + *

Synthetic object literal types are created by {@link #parse} with + * names of the form {@code __ObjectLiteral$} under the {@code __synthetic__} namespace. + * This method recognizes that naming convention and maps it to a human-readable display name.

+ * + * @param jsType the JS type info to inspect (may be {@code null}) + * @return {@code "Object"} if this is a synthetic object literal type, {@code null} otherwise + */ + public static String getSyntheticObjectLiteralDisplayName(JSTypeInfo jsType) { + if (jsType == null) { + return null; + } + String namespace = jsType.getNamespace(); + String simple = jsType.getSimpleName(); + if ("__synthetic__".equals(namespace) && simple != null && simple.startsWith("__ObjectLiteral$")) { + return "Object"; + } + return null; + } + + // ────────────────────────────────────────────────────────────────────────── + // Dynamic property access parsing + // ────────────────────────────────────────────────────────────────────────── + + /** + * Parse a left-hand-side expression to detect dynamic property access patterns. + * + *

Recognizes two forms:

+ *
    + *
  • Dot access: {@code obj.prop} — the last dot-separated segment is treated as the property name.
  • + *
  • Bracket access: {@code obj["prop"]} or {@code obj['prop']} — the quoted string inside brackets + * is treated as the property name.
  • + *
+ * + *

Only simple identifier property names are accepted. Complex expressions (e.g., {@code obj[expr]} + * where {@code expr} is not a string literal) return {@code null}.

+ * + * @param lhs the left-hand-side expression text + * @param lhsStart the absolute document offset of the LHS start + * @return a {@link DynamicPropertyAccess} if a valid pattern was detected, {@code null} otherwise + */ + public static DynamicPropertyAccess parseDynamicPropertyAccess(String lhs, int lhsStart) { + if (lhs == null || lhs.isEmpty()) { + return null; + } + + int dotIndex = lhs.lastIndexOf('.'); + int bracketIndex = lhs.lastIndexOf('['); + + if (dotIndex >= 0 && dotIndex > bracketIndex) { + String receiverExpr = lhs.substring(0, dotIndex).trim(); + String propertyName = lhs.substring(dotIndex + 1).trim(); + if (!receiverExpr.isEmpty() && isSimpleIdentifier(propertyName)) { + return new DynamicPropertyAccess(receiverExpr, propertyName, lhsStart, false); + } + return null; + } + + if (bracketIndex >= 0 && lhs.endsWith("]")) { + String receiverExpr = lhs.substring(0, bracketIndex).trim(); + String keyExpr = lhs.substring(bracketIndex + 1, lhs.length() - 1).trim(); + String propertyName = extractQuotedPropertyName(keyExpr); + if (!receiverExpr.isEmpty() && propertyName != null && isSimpleIdentifier(propertyName)) { + return new DynamicPropertyAccess(receiverExpr, propertyName, lhsStart, true); + } + } + + return null; + } + + /** + * Resolve the receiver type for a dynamic property access by first trying expression type resolution + * and then falling back to variable resolution. + * + * @param access the dynamic property access to resolve + * @param typeResolver callback for expression type resolution + * @param variableResolver callback for variable resolution + * @return the resolved receiver {@link TypeInfo}, or {@code null} if resolution failed + */ + public static TypeInfo resolveDynamicPropertyReceiverType(DynamicPropertyAccess access, + ExpressionTypeResolverFn typeResolver, + VariableResolverFn variableResolver) { + if (access == null) { + return null; + } + + TypeInfo receiverType = typeResolver.resolve(access.receiverExpr, access.receiverStart); + if (receiverType != null && receiverType.isResolved()) { + return receiverType; + } + + FieldInfo receiverField = variableResolver.resolve(access.receiverExpr, access.receiverStart); + if (receiverField != null) { + return receiverField.getTypeInfo(); + } + + return null; + } + + /** + * Extract a property name from a quoted string expression. + * + *

Handles both single and double quotes, plus basic backslash escapes. + * Returns {@code null} if the expression is not a properly quoted string.

+ * + * @param expr the expression to extract from (e.g., {@code "prop"} or {@code 'prop'}) + * @return the unquoted, unescaped property name, or {@code null} if extraction failed + */ + public static String extractQuotedPropertyName(String expr) { + if (expr == null || expr.length() < 2) { + return null; + } + char quote = expr.charAt(0); + if ((quote != '"' && quote != '\'') || expr.charAt(expr.length() - 1) != quote) { + return null; + } + + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < expr.length() - 1; i++) { + char c = expr.charAt(i); + if (c == '\\') { + if (i + 1 >= expr.length() - 1) { + return null; + } + char escaped = expr.charAt(++i); + sb.append(escaped); + continue; + } + sb.append(c); + } + return sb.toString(); + } + + /** + * Extend a synthetic object literal shape with a new property (or update an existing one). + * + *

This is called when an assignment like {@code obj.newProp = value} is encountered and + * {@code obj} was previously inferred as a synthetic object literal type. The new property + * is added to the underlying {@link JSTypeInfo} so subsequent hover/autocomplete sees it.

+ * + *

Only operates on types that are recognized as synthetic object literals + * (see {@link #getSyntheticObjectLiteralDisplayName}). Returns {@code false} and does nothing + * if the receiver type is not a synthetic object literal.

+ * + * @param receiverType the type of the receiver object + * @param propertyName the name of the property to add/update + * @param propertyType the inferred type of the property value (defaults to {@link TypeInfo#ANY} if null/unresolved) + * @return {@code true} if the shape was extended/updated, {@code false} if the receiver is not a synthetic object literal + */ + public static boolean extendSyntheticObjectShape(TypeInfo receiverType, String propertyName, TypeInfo propertyType) { + if (receiverType == null || propertyName == null || propertyName.isEmpty()) { + return false; + } + if (!receiverType.isSyntheticObjectLiteralType()) { + return false; + } + TypeInfo safeType = (propertyType != null && propertyType.isResolved()) ? propertyType : TypeInfo.ANY; + receiverType.removeSyntheticField(propertyName); + receiverType.addSyntheticField(propertyName, safeType); + return true; + } + + /** Holds the resolved receiver type, property name, and field for a dynamic property access result. */ + public static final class DynamicFieldResult { + public final TypeInfo receiverType; + public final String propertyName; + public final FieldInfo field; + + DynamicFieldResult(TypeInfo receiverType, String propertyName, FieldInfo field) { + this.receiverType = receiverType; + this.propertyName = propertyName; + this.field = field; + } + } + + /** Resolve an existing field on a dynamic property access receiver without modifying the type shape. */ + public static DynamicFieldResult resolveExistingField(DynamicPropertyAccess access, + ExpressionTypeResolverFn typeResolver, VariableResolverFn varResolver) { + TypeInfo receiver = resolveDynamicPropertyReceiverType(access, typeResolver, varResolver); + FieldInfo field = (receiver != null && receiver.isResolved()) ? receiver.getFieldInfo(access.propertyName) : null; + return new DynamicFieldResult(receiver, access.propertyName, field); + } + + /** Extend a synthetic object's shape with a new property, then return the resolved field. Overload without RHS text. */ + public static DynamicFieldResult extendAndGetField(DynamicPropertyAccess access, + TypeInfo existingReceiver, TypeInfo sourceType, + ExpressionTypeResolverFn typeResolver, VariableResolverFn varResolver) { + return extendAndGetField(access, existingReceiver, sourceType, null, typeResolver, varResolver); + } + + /** + * Extend a synthetic object's shape with a new property, then return the resolved field. + * When {@code rhsText} is a function expression, a synthetic method is registered instead of a plain field. + */ + public static DynamicFieldResult extendAndGetField(DynamicPropertyAccess access, + TypeInfo existingReceiver, TypeInfo sourceType, String rhsText, + ExpressionTypeResolverFn typeResolver, VariableResolverFn varResolver) { + // Prefer the already-resolved receiver to avoid a redundant re-resolution. + TypeInfo receiver = (existingReceiver != null && existingReceiver.isResolved()) + ? existingReceiver + : resolveDynamicPropertyReceiverType(access, typeResolver, varResolver); + if (receiver == null || !receiver.isSyntheticObjectLiteralType()) return null; + + // If the RHS looks like a callable (function/arrow/ref), register it as a method; otherwise as a field. + CallableInfo callable = (rhsText != null) ? detectCallableExpression(rhsText.trim(), -1, null, typeResolver) : null; + if (callable != null) { + extendSyntheticObjectWithMethod(receiver, access.propertyName, callable); + } else { + if (!extendSyntheticObjectShape(receiver, access.propertyName, sourceType)) return null; + } + return new DynamicFieldResult(receiver, access.propertyName, receiver.getFieldInfo(access.propertyName)); + } + + /** + * Metadata for a callable property value (function expression, arrow function, or shorthand method). + * + *

Captures the parameter names and the inferred return type so that the property can be + * registered as a synthetic method on the object literal's type.

+ */ + public static final class CallableInfo { + private static final TypeInfo THIS_RETURN_SENTINEL = TypeInfo.unresolved("", ""); + public final List parameterNames; + public final TypeInfo returnType; + public final int bodyStartAbs; + public final int bodyEndAbs; + public final boolean blockBody; + + CallableInfo(List parameterNames, TypeInfo returnType, int bodyStartAbs, int bodyEndAbs, boolean blockBody) { + this.parameterNames = parameterNames != null ? parameterNames : new ArrayList<>(); + this.returnType = returnType; + this.bodyStartAbs = bodyStartAbs; + this.bodyEndAbs = bodyEndAbs; + this.blockBody = blockBody; + } + + public boolean returnsThis() { + return returnType == THIS_RETURN_SENTINEL; + } + + static TypeInfo thisReturnSentinel() { + return THIS_RETURN_SENTINEL; + } + } + + // ────────────────────────────────────────────────────────────────────────── + // Callable expression detection + // ────────────────────────────────────────────────────────────────────────── + + /** + * Detect whether a value expression is callable (function expression, arrow function, or bare script method reference). + * Returns a {@link CallableInfo} with parameter names and inferred return type, or {@code null} if not callable. + */ + static CallableInfo detectCallableExpression(String expr, int exprStartAbs, + MethodReferenceResolverFn methodResolver, + ExpressionTypeResolverFn typeResolver) { + if (expr == null || expr.isEmpty()) return null; + + // Inline function expression: function(...) { ... } + if (expr.startsWith("function")) { + return parseFunctionExpressionCallable(expr, exprStartAbs, typeResolver); + } + + // Arrow function: (...) => ... or x => ... + if (expr.contains("=>")) { + return parseArrowFunctionCallable(expr, exprStartAbs, typeResolver); + } + + // Bare identifier that resolves to a known script method (e.g. onTick: handleTick) + if (isSimpleIdentifier(expr.trim()) && methodResolver != null) { + MethodInfo method = methodResolver.resolve(expr.trim(), new TypeInfo[0]); + if (method != null) { + TypeInfo returnType = method.getReturnType() != null ? method.getReturnType() : TypeInfo.ANY; + List paramNames = new ArrayList<>(); + for (FieldInfo param : method.getParameters()) paramNames.add(param.getName()); + return new CallableInfo(paramNames, returnType, exprStartAbs, exprStartAbs + expr.trim().length(), false); + } + } + + return null; + } + + /** Parse a {@code function(...) { ... }} expression into a CallableInfo, extracting params and inferring return type. */ + private static CallableInfo parseFunctionExpressionCallable(String expr, int exprStartAbs, + ExpressionTypeResolverFn typeResolver) { + int parenOpen = expr.indexOf('('); + if (parenOpen < 0) return null; + int parenClose = findMatchingParen(expr, parenOpen); + if (parenClose < 0) return null; + + List params = extractParameterNames(expr.substring(parenOpen + 1, parenClose)); + TypeInfo returnType = inferReturnTypeFromBody(expr, parenClose + 1, exprStartAbs, typeResolver); + String rest = expr.substring(parenClose + 1).trim(); + int bodyOffset = expr.indexOf(rest, parenClose + 1); + return new CallableInfo(params, returnType, + exprStartAbs >= 0 ? exprStartAbs + Math.max(bodyOffset, 0) : -1, + exprStartAbs >= 0 ? exprStartAbs + expr.length() : -1, + rest.startsWith("{")); + } + + /** + * Parse an arrow function — handles both parenthesized params {@code (a, b) => ...} + * and single bare param {@code x => ...}. + */ + private static CallableInfo parseArrowFunctionCallable(String expr, int exprStartAbs, + ExpressionTypeResolverFn typeResolver) { + int arrowIdx = findArrowOperator(expr); + if (arrowIdx < 0) return null; + + String paramPart = expr.substring(0, arrowIdx).trim(); + List params; + if (paramPart.startsWith("(") && paramPart.endsWith(")")) { + // Parenthesized parameter list + params = extractParameterNames(paramPart.substring(1, paramPart.length() - 1)); + } else { + // Single bare parameter (no parens) + params = new ArrayList<>(); + if (isSimpleIdentifier(paramPart)) { + params.add(paramPart); + } + } + + String bodyPart = expr.substring(arrowIdx + 2).trim(); + int bodyOffset = expr.indexOf(bodyPart, arrowIdx + 2); + int bodyStartAbs = exprStartAbs >= 0 ? exprStartAbs + Math.max(bodyOffset, 0) : -1; + // Route both block and expression bodies through the shared inference path + TypeInfo returnType = inferReturnTypeFromBody(bodyPart, 0, bodyStartAbs, typeResolver); + return new CallableInfo(params, returnType, + bodyStartAbs, + bodyStartAbs >= 0 ? bodyStartAbs + bodyPart.length() : -1, + bodyPart.startsWith("{")); + } + + /** + * Find the {@code =>} operator in an arrow function expression, skipping strings and nested parentheses + * to avoid false positives from comparison operators inside nested expressions. + */ + private static int findArrowOperator(String expr) { + boolean inString = false; + char stringChar = 0; + int parenDepth = 0; + + for (int i = 0; i < expr.length() - 1; i++) { + char c = expr.charAt(i); + if (inString) { + if (c == '\\') { i++; continue; } + if (c == stringChar) inString = false; + continue; + } + if (c == '"' || c == '\'') { inString = true; stringChar = c; continue; } + if (c == '(') parenDepth++; + else if (c == ')') parenDepth = Math.max(0, parenDepth - 1); + + if (c == '=' && expr.charAt(i + 1) == '>' && parenDepth == 0) { + return i; + } + } + return -1; + } + + /** Split a comma-separated parameter list into individual names, stripping any leading type annotation. */ + private static List extractParameterNames(String paramList) { + List params = new ArrayList<>(); + if (paramList == null || paramList.trim().isEmpty()) return params; + + for (String part : paramList.split(",")) { + String name = part.trim(); + int spaceIdx = name.indexOf(' '); + if (spaceIdx > 0) name = name.substring(0, spaceIdx); + if (isSimpleIdentifier(name)) { + params.add(name); + } + } + return params; + } + + /** Find the closing {@code )} matching the opening {@code (} at {@code openPos}, respecting strings and nesting. */ + private static int findMatchingParen(String src, int openPos) { + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = openPos; i < src.length(); i++) { + char c = src.charAt(i); + if (inString) { + if (c == '\\') { i++; continue; } + if (c == stringChar) inString = false; + continue; + } + if (c == '"' || c == '\'') { inString = true; stringChar = c; continue; } + if (c == '(') depth++; + else if (c == ')') { depth--; if (depth == 0) return i; } + } + return -1; + } + + /** Infer the return type from the portion of a function expression after the parameter list. */ + private static TypeInfo inferReturnTypeFromBody(String expr, int afterParams, + int exprStartAbs, ExpressionTypeResolverFn typeResolver) { + String rest = expr.substring(afterParams).trim(); + int restOffset = expr.indexOf(rest, afterParams); + int restStartAbs = exprStartAbs >= 0 ? exprStartAbs + restOffset : -1; + if (rest.startsWith("{")) { + return inferReturnTypeFromBlockBody(rest, restStartAbs, typeResolver); + } + return inferReturnTypeFromExpressionBody(rest, restStartAbs, typeResolver); + } + + /** + * Infer a return type from a block body {@code { ... }} by scanning {@code return} statements + * and resolving each expression via the type resolver. Falls back to {@code ANY} if nothing resolves. + */ + private static TypeInfo inferReturnTypeFromBlockBody(String body, int bodyStartAbs, + ExpressionTypeResolverFn typeResolver) { + if (body == null || !body.startsWith("{")) return TypeInfo.ANY; + + int endBrace = findMatchingObjectLiteralEnd(body); + if (endBrace <= 0) return TypeInfo.ANY; + + String inner = body.substring(1, endBrace - 1); + int innerStartAbs = bodyStartAbs >= 0 ? bodyStartAbs + 1 : -1; + + // Scan for 'return ' statements and resolve each one. + int i = 0; + while (i < inner.length()) { + int returnIdx = inner.indexOf("return", i); + if (returnIdx < 0) break; + + // Ensure 'return' is a keyword boundary, not part of a longer identifier. + if (returnIdx > 0 && Character.isJavaIdentifierPart(inner.charAt(returnIdx - 1))) { + i = returnIdx + 6; + continue; + } + int afterReturn = returnIdx + 6; + if (afterReturn >= inner.length()) break; + char afterChar = inner.charAt(afterReturn); + if (!Character.isWhitespace(afterChar) && afterChar != ';') { + i = afterReturn; + continue; + } + + while (afterReturn < inner.length() && Character.isWhitespace(inner.charAt(afterReturn))) { + afterReturn++; + } + + // Scan to end of the return expression (stop at ';' or newline at depth 0). + int exprEnd = afterReturn; + int depth = 0; + while (exprEnd < inner.length()) { + char c = inner.charAt(exprEnd); + if (c == '{' || c == '(' || c == '[') depth++; + else if (c == '}' || c == ')' || c == ']') { if (depth == 0) break; depth--; } + else if ((c == ';' || c == '\n' || c == '\r') && depth == 0) break; + exprEnd++; + } + + String returnExpr = inner.substring(afterReturn, exprEnd).trim(); + if (returnExpr.isEmpty()) { i = exprEnd + 1; continue; } + + if ("this".equals(returnExpr)) return CallableInfo.thisReturnSentinel(); + + // Try full type resolution, then fall back to literal matching. + if (typeResolver != null && innerStartAbs >= 0) { + TypeInfo resolved = typeResolver.resolve(returnExpr, innerStartAbs + afterReturn); + if (resolved != null && resolved.isResolved()) return resolved; + } + TypeInfo literal = resolveLiteralType(returnExpr); + if (literal != TypeInfo.ANY) return literal; + + i = exprEnd + 1; + } + + return TypeInfo.ANY; + } + + /** + * Infer a return type from a concise arrow-function body (expression, not block). + * Delegates to the type resolver first, then falls back to literal pattern matching. + */ + private static TypeInfo inferReturnTypeFromExpressionBody(String bodyExpr, int bodyStartAbs, + ExpressionTypeResolverFn typeResolver) { + if (bodyExpr == null || bodyExpr.isEmpty()) return TypeInfo.ANY; + bodyExpr = bodyExpr.trim(); + + if ("this".equals(bodyExpr)) return CallableInfo.thisReturnSentinel(); + + // Full resolution via ScriptDocument — covers variables, method calls, chains, etc. + if (typeResolver != null && bodyStartAbs >= 0) { + TypeInfo resolved = typeResolver.resolve(bodyExpr, bodyStartAbs); + if (resolved != null && resolved.isResolved()) return resolved; + } + + return resolveLiteralType(bodyExpr); + } + + /** Match simple literal expressions to their TypeInfo without needing a resolver. */ + private static TypeInfo resolveLiteralType(String expr) { + if (expr.startsWith("{") && expr.endsWith("}")) return TypeInfo.ANY; + if (expr.startsWith("\"") && expr.endsWith("\"")) return TypeInfo.string(); + if (expr.startsWith("'") && expr.endsWith("'")) return TypeInfo.fromPrimitive("char"); + if (expr.equals("true") || expr.equals("false")) return TypeInfo.fromPrimitive("boolean"); + if (expr.matches("[-+]?\\d*\\.?\\d+[fFdD]?")) return TypeInfo.NUMBER; + if (expr.contains("+") || expr.contains("-") || expr.contains("*") || expr.contains("/") || expr.contains("%")) return TypeInfo.NUMBER; + return TypeInfo.ANY; + } + + /** + * Register a callable property as both a synthetic field (for field-access resolution) + * and a synthetic method (for call-site resolution) on the receiver's type shape. + */ + private static void extendSyntheticObjectWithMethod(TypeInfo receiver, String name, CallableInfo callable) { + // Build typed parameter list — all params default to ANY since we only have names, not types. + List params = new ArrayList<>(); + for (String paramName : callable.parameterNames) { + params.add(FieldInfo.external(paramName, TypeInfo.ANY, null, java.lang.reflect.Modifier.PUBLIC)); + } + // Use 'receiver' as the return type sentinel when the method returns 'this'. + TypeInfo returnType = callable.returnsThis() ? receiver : (callable.returnType != null ? callable.returnType : TypeInfo.ANY); + receiver.removeSyntheticField(name); + receiver.addSyntheticField(name, TypeInfo.ANY); + receiver.removeSyntheticMethod(name); + receiver.addSyntheticMethod(name, returnType, params); + } + + /** + * Walk backward from the start of an inner callable scope to find the enclosing object literal and + * attach its inferred {@link TypeInfo} as the scope's containing object type (enabling {@code this.} resolution). + * Handles three cases: {@code key: function(...)} (colon), {@code obj = { ... }} (equals), and shorthand methods. + */ + static void attachObjectLiteralContext(InnerCallableScope scope, ScriptDocument doc) { + // Only applicable for JS; skip if already has a containing object type. + if (!doc.isJavaScript() || scope == null || scope.getContainingObjectType() != null) { + return; + } + String text = doc.getText(); + int headerStart = scope.getHeaderStart(); + if (headerStart < 0 || headerStart >= text.length()) { + return; + } + + // Walk backward from the scope header to find a ':' or '=' that indicates object literal context. + int searchPos = headerStart - 1; + while (searchPos >= 0 && Character.isWhitespace(text.charAt(searchPos))) { + searchPos--; + } + if (searchPos < 0) { + return; + } + + // Find the opening '{' of the enclosing object literal by walking backward, respecting nesting and strings. + int braceStart = -1; + if (text.charAt(searchPos) == ':') { + // Case 1: key: function(...) — find the containing {...} + searchPos--; + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = searchPos; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + } else if (text.charAt(searchPos) == '=') { + // Case 2: variable = {...} — find the containing {...} + searchPos--; + while (searchPos >= 0 && Character.isWhitespace(text.charAt(searchPos))) { + searchPos--; + } + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = searchPos; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + } else if (scope.getKind() == InnerCallableScope.Kind.JS_SHORTHAND_METHOD) { + // Case 3: Shorthand method inside {...} — find the containing {...} + int depth = 0; + boolean inString = false; + char stringChar = 0; + for (int i = searchPos; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + } + + if (braceStart < 0) { + return; + } + + ObjectLiteralAnalysis analysis = doc.getObjectLiteral(braceStart); + if (analysis != null && analysis.inferredType != null) { + scope.setContainingObjectType(analysis.inferredType); + } + } + + + /** + * Infer the TypeInfo for a single value expression inside an object literal. + * Nested object literals are recursively parsed; arrays and other complex expressions fall back to {@code ANY}. + */ + private static TypeInfo inferValueType(String valueExpr, int valueStartAbs, ExpressionTypeResolverFn typeResolver) { + if (valueExpr == null || valueExpr.isEmpty()) { + return TypeInfo.ANY; + } + + char first = valueExpr.charAt(0); + if (first == '{') { + ObjectLiteralAnalysis nested = parse(valueExpr, valueStartAbs, true, false, typeResolver,null); + if (nested != null && nested.supportsInference && nested.inferredType != null) { + return nested.inferredType; + } + return TypeInfo.ANY; + } + + TypeInfo inferred = typeResolver.resolve(valueExpr, valueStartAbs); + return (inferred != null) ? inferred : TypeInfo.ANY; + } + + // ────────────────────────────────────────────────────────────────────────── + // Scanning / parsing utilities (package-private static, used by analyzer) + // ────────────────────────────────────────────────────────────────────────── + + /** + * Scan to the end of a string literal starting at {@code start}. + * + *

Handles backslash escapes. The returned index points one past the closing quote character.

+ * + * @param src the source text + * @param start index of the opening quote character + * @return index one past the closing quote, or {@code -1} if the string is unterminated + */ + static int scanStringLiteralEnd(String src, int start) { + if (start < 0 || start >= src.length()) { + return -1; + } + char quote = src.charAt(start); + int i = start + 1; + while (i < src.length()) { + char c = src.charAt(i); + if (c == '\\') { + i += (i + 1 < src.length()) ? 2 : 1; + continue; + } + if (c == quote) { + return i + 1; + } + i++; + } + return -1; + } + + /** + * Check whether a string is a valid simple identifier (Java identifier rules). + * + * @param s the string to check + * @return {@code true} if {@code s} is non-empty and consists of valid Java identifier characters + */ + static boolean isSimpleIdentifier(String s) { + if (s == null || s.isEmpty()) { + return false; + } + if (!Character.isJavaIdentifierStart(s.charAt(0))) { + return false; + } + for (int i = 1; i < s.length(); i++) { + if (!Character.isJavaIdentifierPart(s.charAt(i))) { + return false; + } + } + return true; + } + + /** + * Scan forward to find the end of a top-level value expression within an object literal. + * + *

Respects nested braces, brackets, parentheses, string literals, and comments. + * Stops at a top-level comma or the {@code endLimit}.

+ * + * @param src the source text + * @param start where to start scanning + * @param endLimit the exclusive boundary (typically the position of the closing brace) + * @return the index where the value expression ends (at a comma or {@code endLimit}) + */ + static int scanTopLevelValueEnd(String src, int start, int endLimit) { + int parenDepth = 0; + int bracketDepth = 0; + int braceDepth = 0; + + boolean inString = false; + char stringChar = 0; + boolean inLineComment = false; + boolean inBlockComment = false; + + int i = start; + while (i < endLimit) { + char c = src.charAt(i); + char next = (i + 1 < endLimit) ? src.charAt(i + 1) : 0; + + if (inLineComment) { + if (c == '\n' || c == '\r') { + inLineComment = false; + } + i++; + continue; + } + + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + i += 2; + continue; + } + i++; + continue; + } + + if (inString) { + if (c == '\\') { + i += (i + 1 < endLimit) ? 2 : 1; + continue; + } + if (c == stringChar) { + inString = false; + } + i++; + continue; + } + + if (c == '/' && next == '/') { + inLineComment = true; + i += 2; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + i += 2; + continue; + } + + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + i++; + continue; + } + + if (c == '(') parenDepth++; + else if (c == ')') parenDepth = Math.max(0, parenDepth - 1); + else if (c == '[') bracketDepth++; + else if (c == ']') bracketDepth = Math.max(0, bracketDepth - 1); + else if (c == '{') braceDepth++; + else if (c == '}') braceDepth = Math.max(0, braceDepth - 1); + + if (c == ',' && parenDepth == 0 && bracketDepth == 0 && braceDepth == 0) { + return i; + } + + i++; + } + + return endLimit; + } + + /** Advance past whitespace, commas, and line/block comments between object literal properties. */ + private static int skipSeparatorsAndComments(String src, int start, int endLimit) { + int i = start; + while (i < endLimit) { + char c = src.charAt(i); + char next = (i + 1 < endLimit) ? src.charAt(i + 1) : 0; + if (Character.isWhitespace(c) || c == ',') { + i++; + continue; + } + if (c == '/' && next == '/') { + i += 2; + while (i < endLimit) { + char line = src.charAt(i); + if (line == '\n' || line == '\r') { + break; + } + i++; + } + continue; + } + if (c == '/' && next == '*') { + i += 2; + while (i + 1 < endLimit) { + if (src.charAt(i) == '*' && src.charAt(i + 1) == '/') { + i += 2; + break; + } + i++; + } + continue; + } + break; + } + return i; + } + + /** + * Determine whether the document position is inside an object literal by counting unmatched braces + * and verifying that the nearest enclosing {@code {} is preceded by {@code =}, {@code :}, {@code (}, etc. + */ + static boolean isInsideObjectLiteral(int position, ScriptDocument doc) { + // First pass: count unmatched braces forward to position to check if we're in a brace context. + int braceDepth = 0; + boolean inString = false; + char stringChar = 0; + String text = doc.getText(); + for (int i = 0; i < position && i < text.length(); i++) { + if (doc.isExcluded(i)) { + continue; + } + char c = text.charAt(i); + if (inString) { + if (c == '\\') { i++; continue; } + if (c == stringChar) inString = false; + continue; + } + if (c == '"' || c == '\'') { inString = true; stringChar = c; continue; } + if (c == '{') braceDepth++; + else if (c == '}') braceDepth = Math.max(0, braceDepth - 1); + } + // Not inside any braces at all. + if (braceDepth <= 0) return false; + + // Second pass: walk backward to find the matching '{' for our position. + int braceStart = -1; + int depth = 0; + inString = false; + stringChar = 0; + for (int i = position - 1; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i)) { + continue; + } + if (inString) { + if (c == stringChar && (i == 0 || text.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '}') { + depth++; + } else if (c == '{') { + if (depth == 0) { + braceStart = i; + break; + } + depth--; + } + } + if (braceStart < 0) { + return false; + } + + // Third pass: check if the '{' is preceded by a literal indicator (=, :, (, [, comma, or nested {). + for (int i = braceStart - 1; i >= 0; i--) { + char c = text.charAt(i); + if (doc.isExcluded(i) || Character.isWhitespace(c)) { + continue; + } + return c == '=' || c == ':' || c == '(' || c == '[' || c == ',' || c == '{'; + } + return true; + } + + /** + * Scan forward to find the next top-level comma (skipping nested structures and strings). + * + *

Used to skip over unsupported property entries (computed keys, spread, etc.) + * and advance to the next property in the object literal.

+ * + * @param src the source text + * @param start where to start scanning + * @param endLimit the exclusive boundary + * @return the index just past the comma, or {@code endLimit} if no comma is found + */ + static int scanToNextTopLevelComma(String src, int start, int endLimit) { + int i = start; + int depth = 0; + boolean inString = false; + char stringChar = 0; + while (i < endLimit) { + char c = src.charAt(i); + if (inString) { + if (c == '\\') { + i += (i + 1 < endLimit) ? 2 : 1; + continue; + } + if (c == stringChar) { + inString = false; + } + i++; + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + i++; + continue; + } + if (c == '{' || c == '[' || c == '(') depth++; + else if (c == '}' || c == ']' || c == ')') depth = Math.max(0, depth - 1); + if (c == ',' && depth == 0) { + return i + 1; + } + i++; + } + return endLimit; + } + + /** + * Find the matching closing brace for an object literal within a standalone string. + * + *

Unlike {@code ScriptDocument.findMatchingBraceEndInDocument} which operates on the full + * document text with excluded-range awareness, this method works on an isolated string snippet + * and handles comments/strings inline.

+ * + * @param src the source text starting with '{' (or containing it) + * @return the index one past the matching '}', or {@code -1} if not found + */ + static int findMatchingObjectLiteralEnd(String src) { + int depth = 0; + boolean inString = false; + char stringChar = 0; + boolean inLineComment = false; + boolean inBlockComment = false; + + for (int i = 0; i < src.length(); i++) { + char c = src.charAt(i); + char next = (i + 1 < src.length()) ? src.charAt(i + 1) : 0; + + if (inLineComment) { + if (c == '\n' || c == '\r') { + inLineComment = false; + } + continue; + } + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + i++; + } + continue; + } + if (inString) { + if (c == '\\') { + i += (i + 1 < src.length()) ? 1 : 0; + continue; + } + if (c == stringChar) { + inString = false; + } + continue; + } + + if (c == '/' && next == '/') { + inLineComment = true; + i++; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + i++; + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + + if (c == '{') { + depth++; + } else if (c == '}') { + depth--; + if (depth == 0) { + return i + 1; + } + } + } + + return -1; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java new file mode 100644 index 000000000..e9d6d7cf2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java @@ -0,0 +1,11051 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.script.interpreter.expression.CastExpressionResolver; +import noppes.npcs.client.gui.util.script.interpreter.expression.ExpressionNode; +import noppes.npcs.client.gui.util.script.interpreter.expression.ExpressionTypeResolver; +import noppes.npcs.client.gui.util.script.interpreter.field.AssignmentInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSScriptAnalyzer; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSMethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParamTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParser; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodSignature; +import noppes.npcs.client.gui.util.script.interpreter.token.Token; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenErrorMessage; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.*; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticField; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticMethod; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticType; +import noppes.npcs.client.gui.util.script.ScopeInfo; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.controllers.data.DataScript; +import noppes.npcs.controllers.ScriptHookController; + +import java.util.*; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * The main document container that manages script text, lines, and tokens. + * This is the clean reimplementation of JavaTextContainer. + * + * Architecture: + * - ScriptDocument holds the complete source text and global state + * - ScriptLine holds individual lines with their tokens + * - Token holds individual syntax elements with type-specific metadata + * - TypeResolver handles all class/type resolution + * + * Single-pass tokenization: + * 1. Parse excluded regions (comments, strings) + * 2. Parse imports and resolve types + * 3. Parse structure (methods, classes, fields) + * 4. Tokenize with all context available + */ +public class ScriptDocument { + + public static ScriptDocument INSTANCE = null; // For easy access in expressions + // ==================== PATTERNS ==================== + + private static final Pattern WORD_PATTERN = Pattern.compile("[\\p{L}\\p{N}_-]+|\\n|$"); + + // Literals + private static final Pattern STRING_PATTERN = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1"); + private static final Pattern COMMENT_PATTERN = Pattern.compile("/\\*[\\s\\S]*?(?:\\*/|$)|//.*|#.*"); + private static final Pattern NUMBER_PATTERN = Pattern.compile( + "\\b-?(?:0[xX][\\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?(?:[fFbBdDlLsS])?|NaN|null|Infinity|true|false)\\b"); + + // Keywords + private static final Pattern MODIFIER_PATTERN = Pattern.compile( + "\\b(public|protected|private|static|final|abstract|synchronized|native|default)\\b"); + private static final Pattern KEYWORD_PATTERN = Pattern.compile( + "\\b(null|boolean|int|float|double|long|char|byte|short|void|if|else|switch|case|for|while|do|try|catch|finally|return|throw|var|let|const|function|continue|break|this|super|new|typeof|instanceof|import)\\b"); + + private static final Pattern KEYWORD_JS_PATTERN = Pattern.compile( + "\\b(function|var|let|const|if|else|for|while|do|switch|case|break|continue|return|" + + "try|catch|finally|throw|delete|new|typeof|instanceof|in|of|this|null|undefined|true|false|" + + "class|extends|import|export|default|async|await|yield)\\b"); + + // Declarations - Updated to capture method parameters + private static final Pattern IMPORT_PATTERN = Pattern.compile( + "(?m)\\bimport\\s+(?:static\\s+)?([A-Za-z_][A-Za-z0-9_]*(?:\\s*\\.\\s*[A-Za-z_][A-Za-z0-9_]*)*)(?:\\s*\\.\\s*\\*?)?\\s*(?:;|$)"); + private static final Pattern CLASS_DECL_PATTERN = Pattern.compile( + "\\b(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)"); + private static final Pattern METHOD_DECL_PATTERN = Pattern.compile( + "\\b([A-Za-z_][a-zA-Z0-9_.<>,[ \\t]\\[\\]]*)[ \\t]+([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\("); + private static final Pattern METHOD_CALL_PATTERN = Pattern.compile( + "([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\("); + // Also matches ',' as a delimiter so that "int x, y, z;" is recognized + // (the first declarator "int x," is captured; continuations are scanned manually). + private static final Pattern FIELD_DECL_PATTERN = Pattern.compile( + "\\b([A-Za-z_][a-zA-Z0-9_.<>,[ \\t]\\[\\]]*)[ \\t]+([a-zA-Z_][a-zA-Z0-9_]*)[ \\t]*(=|;|,)"); + private static final Pattern NEW_TYPE_PATTERN = Pattern.compile("\\bnew\\s+([A-Za-z_][a-zA-Z0-9_]*)\\s*(?:<([^>]*)>)?"); + + // Cast expression pattern: captures type name inside cast parentheses + // Matches: (Type), (Type[]), (pkg.Type), (Type) + private static final Pattern CAST_TYPE_PATTERN = Pattern.compile( + "\\(\\s*([A-Za-z_][a-zA-Z0-9_]*(?:\\s*\\.\\s*[A-Za-z_][a-zA-Z0-9_]*)*)\\s*(?:<[^>]*>)?\\s*(\\[\\s*\\])*\\s*\\)\\s*(?=[a-zA-Z_\"'(\\d!~+-])"); + + // Function parameters (for JS-style scripts) + private static final Pattern FUNC_PARAMS_PATTERN = Pattern.compile( + "\\bfunction\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s*\\(([^)]*)\\)"); + + // ==================== STATE ==================== + + private String text = ""; + private final List lines = new ArrayList<>(); + + private final List imports = new ArrayList<>(); + private final Set wildcardPackages = new HashSet<>(); + private Map importsBySimpleName = new HashMap<>(); + + // Script-defined types (classes, interfaces, enums defined in the script) + // PRIMARY: simple name → ScriptTypeInfo (backward-compatible, top-level only) + private final Map scriptTypes = new HashMap<>(); + // SECONDARY: dollar-separated full name → ScriptTypeInfo (all types including nested) + // Enables O(1) lookup by qualified name for any nesting depth (e.g., "Outer$Middle$Inner") + private final Map scriptTypesByFullName = new HashMap<>(); + // TERTIARY: dot-separated display name → ScriptTypeInfo (for resolveType("Outer.Inner")) + // Populated alongside scriptTypesByFullName during parsing; matches user-written syntax + private final Map scriptTypesByDotName = new HashMap<>(); + + private final List methods = new ArrayList<>(); + private final Map globalFields = new HashMap<>(); + // Local variables per method (methodStartOffset -> {varName -> FieldInfo}) + private final Map>> methodLocals = new HashMap<>(); + // Top-level variables (outside methods) - for JavaScript, these can be treated as globals, but we keep them separate for clarity + // Mainly top level loops like for (var x : collection) { } where x is a local variable but not inside a method + private final Map> topLevelLocals = new HashMap<>(); + + // Inner callable scopes (lambdas, JS function expressions) - NOT in methods list + private final List innerScopes = new ArrayList<>(); + + // Method calls - stores all parsed method call information + private final List methodCalls = new ArrayList<>(); + // Field accesses - stores all parsed field access information + private final List fieldAccesses = new ArrayList<>(); + // Assignments to external fields (fields from reflection, not script-defined) + private final List externalFieldAssignments = new ArrayList<>(); + + // Declaration errors (duplicate declarations, etc.) + private final List declarationErrors = new ArrayList<>(); + + // Centralized error list - populated by ErrorUnderlineRenderer during rendering + private final List errors = new ArrayList<>(); + + // Excluded regions (strings/comments) - positions where other patterns shouldn't match + private final List excludedRanges = new ArrayList<>(); + + // SAM context tracking for named function references + // Maps method name -> first SAM signature applied (for conflict detection) + private final Map scriptMethodSamContexts = new HashMap<>(); + + // Cached object literal analyses, keyed by brace-start offset in text. + // Populated once in parseObjectLiterals() and consumed by markObjectLiteralKeys, + // resolveExpressionType, and attachObjectLiteralContext. + private final Map objectLiterals = new HashMap<>(); + + // Cached lambda metadata, keyed by lambda header-start offset in text. + // Populated in inferLambdaParameterTypes() (method calls, constructors, field assignments). + // Consumed by resolveExpressionType() to avoid re-inferring lambda context. + private final Map lambdaCache = new HashMap<>(); + + // Thread-local to communicate SAM conflict errors from resolveIdentifier back to parseMethodArguments + // Set when injectSamParameterTypes detects a conflict, cleared after argument is created + private static final ThreadLocal CURRENT_SAM_CONFLICT_ERROR = new ThreadLocal<>(); + + // Type resolver + private final TypeResolver typeResolver; + + // JSDoc parser for extracting type information from JSDoc comments + private final JSDocParser jsDocParser = new JSDocParser(this); + + // Script language: "ECMAScript", "Groovy", etc. + private String language = "ECMAScript"; + + // Script context: NPC, PLAYER, BLOCK, ITEM, etc. + // Determines which hooks and event types are available + private ScriptContext scriptContext = ScriptContext.GLOBAL; + + // Editor-injected globals (name -> type name) provided by the handler + private Map editorGlobals = Collections.emptyMap(); + + // Implicit imports from JaninoScript default imports and hook parameter types + // These are types that should be resolved even without explicit import statements + private final Set implicitImports = new HashSet<>(); + + // Layout properties + public int lineHeight = 13; + public int totalHeight; + public int visibleLines = 1; + public int linesCount; + + // ==================== CONSTRUCTOR ==================== + + public ScriptDocument(String text) { + this.typeResolver = TypeResolver.getInstance(); + setText(text); + } + + public ScriptDocument(String text, TypeResolver resolver) { + this.typeResolver = resolver != null ? resolver : TypeResolver.getInstance(); + setText(text); + } + + public ScriptDocument(String text, String language) { + this.typeResolver = TypeResolver.getInstance(); + this.language = language != null ? language : "ECMAScript"; + setText(text); + } + + /** + * Set the scripting language. + */ + public void setLanguage(String language) { + this.language = language != null ? language : "ECMAScript"; + } + + /** + * Get the scripting language. + */ + public String getLanguage() { + return language; + } + + /** + * Check if this is a JavaScript/ECMAScript document. + */ + public boolean isJavaScript() { + return "ECMAScript".equalsIgnoreCase(language); + } + + /** + * Set the script context (NPC, PLAYER, BLOCK, ITEM, etc.). + * This determines which hooks and event types are available for autocomplete. + * + * @param context The script context + */ + public void setScriptContext(ScriptContext context) { + this.scriptContext = context != null ? context : ScriptContext.GLOBAL; + } + + /** + * Get the current script context. + * + * @return The script context (NPC, PLAYER, BLOCK, ITEM, etc.) + */ + public ScriptContext getScriptContext() { + return scriptContext; + } + + /** + * Set editor-injected globals (name -> type name). + * i.e. DataScript global definitions {@link DataScript#getEditorGlobals(String)} + * This is provided by the script handler at editor init time. + */ + public void setEditorGlobals(Map globals) { + if (globals == null || globals.isEmpty()) { + this.editorGlobals = Collections.emptyMap(); + return; + } + this.editorGlobals = new LinkedHashMap<>(globals); + } + + /** + * Get editor-injected globals (name -> type name). + */ + public Map getEditorGlobals() { + return Collections.unmodifiableMap(editorGlobals); + } + + /** + * Add implicit imports that should be resolved without explicit import statements. + * Used for JaninoScript default imports and hook parameter types. + * + * Patterns can be: + * - Wildcard: "noppes.npcs.api.*" (imports all classes from package) + * - Specific class: "noppes.npcs.api.event.INpcEvent$InitEvent" (nested class) + * - Regular class: "noppes.npcs.api.entity.IEntity" + * + * @param patterns Array of import patterns to add (packages with .* or fully qualified class names) + */ + public void addImplicitImports(String... patterns) { + if (patterns != null) { + for (String pattern : patterns) { + if (pattern != null && !pattern.isEmpty()) { + this.implicitImports.add(pattern); + } + } + } + } + + // ==================== TEXT MANAGEMENT ==================== + + public void setText(String text) { + this.text = text != null ? text.replaceAll("\\r?\\n|\\r", "\n") : ""; + } + + public String getText() { + return text; + } + + // ==================== INITIALIZATION ==================== + + /** + * Initialize the document with layout constraints. + * Builds lines based on width wrapping. + */ + public void init(int width, int height) { + lines.clear(); + lineHeight = ClientProxy.Font.height(); + if (lineHeight == 0) + lineHeight = 12; + + String[] sourceLines = text.split("\n", -1); + int totalChars = 0; + int lineIndex = 0; + + for (String sourceLine : sourceLines) { + StringBuilder currentLine = new StringBuilder(); + Matcher m = WORD_PATTERN.matcher(sourceLine); + int i = 0; + + while (m.find()) { + String word = sourceLine.substring(i, m.start()); + if (ClientProxy.Font.width(currentLine + word) > width - 10) { + // Wrap line + int lineStart = totalChars; + int lineEnd = totalChars + currentLine.length(); + lines.add(new ScriptLine(currentLine.toString(), lineStart, lineEnd, lineIndex++)); + totalChars = lineEnd; + currentLine = new StringBuilder(); + } + currentLine.append(word); + i = m.start(); + } + + // Add final line segment (including newline character in range) + int lineStart = totalChars; + int lineEnd = totalChars + currentLine.length() + 1; + lines.add(new ScriptLine(currentLine.toString(), lineStart, lineEnd, lineIndex++)); + totalChars = lineEnd; + } + + // Set up line navigation + for (int li = 0; li < lines.size(); li++) { + ScriptLine line = lines.get(li); + line.setParent(this); + if (li > 0) { + line.setPrev(lines.get(li - 1)); + lines.get(li - 1).setNext(line); + } + } + + linesCount = lines.size(); + totalHeight = linesCount * lineHeight; + visibleLines = Math.max(height / lineHeight - 1, 1); + INSTANCE = this; + } + + // ==================== TOKENIZATION ==================== + + /** + * Main tokenization entry point. + * Performs complete analysis and builds tokens for all lines. + * Uses the SAME unified pipeline for both Java and JavaScript. + * + * All data structures (methods, globalFields, methodLocals, methodCalls, + * fieldAccesses, etc.) are shared between languages. + */ + public void formatCodeText() { + // Clear previous state (same for both languages) + errors.clear(); + imports.clear(); + methods.clear(); + globalFields.clear(); + wildcardPackages.clear(); + excludedRanges.clear(); + methodLocals.clear(); + topLevelLocals.clear(); + scriptTypes.clear(); + scriptTypesByFullName.clear(); + scriptTypesByDotName.clear(); + innerScopes.clear(); + methodCalls.clear(); + externalFieldAssignments.clear(); + declarationErrors.clear(); + scriptMethodSamContexts.clear(); + objectLiterals.clear(); + lambdaCache.clear(); + + // Unified pipeline for both languages + List marks = formatUnified(); + + // Phase 5: Resolve conflicts and sort + marks = resolveConflicts(marks); + + // Phase 6: Build tokens for each line + for (ScriptLine line : lines) { + line.buildTokensFromMarks(marks, text, this); + } + + // Phase 6.5: Now that tokens are built, remove implicit imports that aren't actually used + removeUnusedImplicitImports(); + + // Phase 7: Compute indent guides + computeIndentGuides(marks); + + // Phase 8: Populate centralized error list from all error sources + populateErrors(); + } + + // Store the last JS analyzer for autocomplete (deprecated - use methods/globalFields/methodLocals instead) + @Deprecated + private JSScriptAnalyzer currentJSAnalyzer; + + /** + * @deprecated Use the unified pipeline. Access methods/globalFields/methodLocals directly. + */ + @Deprecated + public JSScriptAnalyzer getJSAnalyzer() { + return currentJSAnalyzer; + } + + /** + * Unified format method - single pipeline for both Java and JavaScript. + * ALL methods called here handle BOTH languages using the SAME data structures. + */ + private List formatUnified() { + TypeChecker.enterTypeCheckingContext(isJavaScript()); + + // Phase 1: Find excluded regions (strings/comments) - same for both + findExcludedRanges(); + + // Phase 2: Parse imports (Java only, JS skips this) + parseImports(); + + // Phase 3: Parse structure (methods, fields, locals) - language aware + parseStructure(); + + // Phase 4: Build marks - language aware + return buildMarks(); + } + + /** + * @deprecated Use formatUnified() instead. Kept for compatibility. + */ + @Deprecated + private List formatJavaScript() { + // Delegate to unified pipeline + currentJSAnalyzer = new JSScriptAnalyzer(this); + return currentJSAnalyzer.analyze(); + } + + /** + * @deprecated Use formatUnified() instead. Kept for compatibility. + */ + @Deprecated + private List formatJava() { + return formatUnified(); + } + + // ==================== PHASE 1: EXCLUDED RANGES ==================== + + private void findExcludedRanges() { + // Find strings + Matcher m = STRING_PATTERN.matcher(text); + while (m.find()) { + excludedRanges.add(new int[]{m.start(), m.end()}); + } + + // Find comments + m = COMMENT_PATTERN.matcher(text); + while (m.find()) { + excludedRanges.add(new int[]{m.start(), m.end()}); + } + + // Sort and merge overlapping ranges + excludedRanges.sort(Comparator.comparingInt(a -> a[0])); + mergeOverlappingRanges(); + } + + private void mergeOverlappingRanges() { + if (excludedRanges.size() < 2) + return; + + List merged = new ArrayList<>(); + int[] current = excludedRanges.get(0); + + for (int i = 1; i < excludedRanges.size(); i++) { + int[] next = excludedRanges.get(i); + if (next[0] <= current[1]) { + current[1] = Math.max(current[1], next[1]); + } else { + merged.add(current); + current = next; + } + } + merged.add(current); + + excludedRanges.clear(); + excludedRanges.addAll(merged); + } + + + public boolean isExcluded(int position) { + for (int[] range : excludedRanges) { + if (position >= range[0] && position < range[1]) { + return true; + } + } + return false; + } + + /** + * Like isExcluded but uses inclusive end bound (position <= range end). + * Used by auto-pair logic where the cursor sits right at a string boundary. + */ + public boolean isExcludedInclusive(int position) { + for (int[] range : excludedRanges) { + if (position >= range[0] && position <= range[1]) { + return true; + } + } + return false; + } + + /** + * Check if any position in [start, end) falls inside an excluded range. + * Uses range-overlap logic (O(excludedRanges.size())) instead of per-character checks. + * Two ranges [a,b) and [c,d) overlap iff a < d && c < b. + */ + public boolean hasExcludedRange(int start, int end) { + for (int[] range : excludedRanges) { + if (start < range[1] && range[0] < end) { + return true; + } + } + return false; + } + + /** + * Check if a position falls inside one of the type's inner class bodies. + * Used to prevent field/constructor declarations inside inner classes + * from being misattributed to the outer class during member parsing. + */ + private boolean isInsideNestedType(int position, ScriptTypeInfo type) { + for (ScriptTypeInfo inner : type.getInnerClasses()) { + if (inner.containsPosition(position)) { + return true; + } + } + return false; + } + + /** + * Get the list of excluded ranges (comments, strings, etc.). + * Used by AutocompleteManager to skip over excluded regions. + * @return List of [start, end) ranges to exclude + */ + public List getExcludedRanges() { + return excludedRanges; + } + + /** + * Check if a position is within a comment range (not string). + * Used to skip comment text when scanning for identifiers. + */ + private boolean isInCommentRange(int position) { + // Check if position is in a comment by checking against COMMENT_PATTERN + Matcher m = COMMENT_PATTERN.matcher(text); + while (m.find()) { + if (position >= m.start() && position < m.end()) { + return true; + } + } + return false; + } + + // ==================== PHASE 2: IMPORTS ==================== + + private void parseImports() { + // JavaScript doesn't use Java-style imports + if (isJavaScript()) { + return; + } + + Matcher m = IMPORT_PATTERN.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) + continue; + + String fullPath = m.group(1).replaceAll("\\s+", "").trim(); + String matchText = m.group(0); + boolean isWildcard = matchText.contains("*"); + boolean isStatic = matchText.contains("static"); + + // Skip if path ends with dot (incomplete import) + if (fullPath.endsWith(".")) { + // continue; + } + + int lastDot = fullPath.lastIndexOf('.'); + String simpleName = isWildcard ? null : (lastDot >= 0 ? fullPath.substring(lastDot + 1) : fullPath); + + ImportData importData = new ImportData( + fullPath, simpleName, isWildcard, isStatic, + m.start(), m.end(), m.start(1), m.end(1) + ); + imports.add(importData); + + if (isWildcard) { + wildcardPackages.add(fullPath); + } + } + + // Add ALL implicit imports initially so tokens can be built with proper type resolution + addAllImplicitImportsToList(); + + // Resolve all imports (including all implicit ones) + importsBySimpleName = typeResolver.resolveImports(imports); + } + + /** + * Add ALL implicit imports to the imports list initially. + * This allows tokens to be built with proper type resolution. + * After tokenization, we'll remove the unused ones. + */ + private void addAllImplicitImportsToList() { + for (String pattern : implicitImports) { + if (pattern == null || pattern.isEmpty()) continue; + + boolean isWildcard = pattern.endsWith(".*"); + String fullPath; + String simpleName; + + if (isWildcard) { + fullPath = pattern.substring(0, pattern.length() - 2); // Remove ".*" + simpleName = null; + wildcardPackages.add(fullPath); + } else { + fullPath = pattern.replace('$', '.'); + int lastDot = fullPath.lastIndexOf('.'); + simpleName = lastDot >= 0 ? fullPath.substring(lastDot + 1) : fullPath; + } + + ImportData importData = new ImportData( + fullPath, simpleName, isWildcard, false, + -1, -1, -1, -1 + ); + + if (!imports.contains(importData)) { + imports.add(importData); + } + } + } + + /** + * Remove implicit imports that aren't actually used in the text. + * This keeps autocomplete clean by not showing types from hooks that aren't present. + * Called after tokenization is complete. + */ + private void removeUnusedImplicitImports() { + // Collect imports to remove (can't remove during iteration) + List toRemove = new ArrayList<>(); + + for (ImportData imp : imports) { + // Only check implicit imports (those with offset -1) + if (imp.getStartOffset() != -1) continue; + + // Skip wildcard imports - keep them all + if (imp.isWildcard()) continue; + + // Check if this specific class import is actually used + String simpleName = imp.getSimpleName(); + String fullPath = imp.getFullPath(); + + if (!isTypeReferenced(simpleName, fullPath)) { + toRemove.add(imp); + } + } + + // Remove unused implicit imports + imports.removeAll(toRemove); + + // Re-resolve imports after removing unused ones + importsBySimpleName = typeResolver.resolveImports(imports); + } + + /** + * Check if a type is referenced anywhere in the script tokens. + * Looks for the simple name or any part of the fully qualified name. + */ + private boolean isTypeReferenced(String simpleName, String fullPath) { + if (simpleName == null || simpleName.isEmpty()) return false; + + // Check all lines and their tokens + for (ScriptLine line : lines) { + for (Token token : line.getTokens()) { + String tokenText = token.getText(); + + // Check if token matches the simple name + if (tokenText.equals(simpleName)) { + return true; + } + + // Check if token contains nested class reference (e.g., "InitEvent" in "INpcEvent.InitEvent") + if (fullPath.contains("$") && tokenText.equals(simpleName)) { + return true; + } + + // Check for partial matches in qualified references + if (fullPath.contains(".") && tokenText.contains(".")) { + // e.g., "INpcEvent.InitEvent" matches "noppes.npcs.api.event.INpcEvent$InitEvent" + String[] pathParts = fullPath.replace('$', '.').split("\\."); + String[] tokenParts = tokenText.split("\\."); + + // Check if the last parts match (e.g., "InitEvent") + if (pathParts.length > 0 && tokenParts.length > 0) { + String lastPathPart = pathParts[pathParts.length - 1]; + String lastTokenPart = tokenParts[tokenParts.length - 1]; + if (lastTokenPart.equals(lastPathPart)) { + return true; + } + } + } + } + } + + return false; + } + + + // ==================== PHASE 3: STRUCTURE ==================== + + /** + * Parse the script structure - methods, fields, variables. + * Uses the SAME logic and data structures for both Java and JavaScript. + */ + private void parseStructure() { + // Clear import references before re-parsing + for (ImportData imp : imports) { + imp.clearReferences(); + } + + // Parse script-defined types (classes, interfaces, enums) - Java only + if (!isJavaScript()) { + parseScriptTypes(); + } + + // Parse methods/functions - UNIFIED for both languages + parseMethodDeclarations(); + + // Parse inner callable scopes (lambdas, JS function expressions) + parseInnerCallableScopes(); + + // Parse local variables inside methods/functions - UNIFIED for both languages + parseLocalVariables(); + + // Parse global fields (outside methods) - UNIFIED for both languages + parseGlobalFields(); + + // Must run before parseAssignments: sets inferredType on lambda params so that + // body variable resolution (e.g. "act" in "int x = act.getData()") works correctly. + inferLambdaParameterTypes(); + + // Parse and validate assignments (reassignments) - UNIFIED for both languages + parseAssignments(); + + // Cache object literals after globals/locals are available for accurate value-type inference + parseObjectLiterals(); + + // Detect method overrides and interface implementations for script types - Java only + if (!isJavaScript()) { + detectMethodInheritance(); + } + } + + static class LambdaCacheEntry { + final InnerCallableScope scope; + final TypeInfo expectedType; + + LambdaCacheEntry(InnerCallableScope scope, TypeInfo expectedType) { + this.scope = scope; + this.expectedType = expectedType; + } + } + + /** + * Intermediate record for type declarations discovered in Pass 1 of parseScriptTypes(). + * Holds raw data before hierarchy relationships are established in Pass 2. + */ + private static class RawTypeDeclaration { + final String name; + final TypeInfo.Kind kind; + final int declOffset; + final int bodyStart; + final int bodyEnd; + final int modifiers; + final String typeParamsClause; + final int typeParamsClauseOffset; // Global offset of first char inside <...> + final String extendsClause; + final String implementsClause; + final JSDocInfo jsDoc; + + RawTypeDeclaration(String name, TypeInfo.Kind kind, int declOffset, int bodyStart, int bodyEnd, + int modifiers, String typeParamsClause, int typeParamsClauseOffset, + String extendsClause, String implementsClause, JSDocInfo jsDoc) { + this.name = name; + this.kind = kind; + this.declOffset = declOffset; + this.bodyStart = bodyStart; + this.bodyEnd = bodyEnd; + this.modifiers = modifiers; + this.typeParamsClause = typeParamsClause; + this.typeParamsClauseOffset = typeParamsClauseOffset; + this.extendsClause = extendsClause; + this.implementsClause = implementsClause; + this.jsDoc = jsDoc; + } + } + + /** + * Parse class, interface, and enum declarations using a two-pass strategy. + * + * Pass 1: Regex scan discovers all type declarations with their body spans. + * Pass 2: Sort by bodyStart, then use a stack to determine parent-child nesting. + * The stack invariant is: top = innermost enclosing type for the current position. + * This correctly handles arbitrary nesting depth in O(n) time. + */ + private void parseScriptTypes() { + // ========== PASS 1: Discover all type declarations (flat list) ========== + // Regex only anchors on keyword + name — generic clauses are extracted manually + // below to correctly handle nested angle brackets like >. + Pattern typeDecl = Pattern.compile( + "(?:(?:public|private|protected|static|final|abstract)\\s+)*(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)"); + + List rawDeclarations = new ArrayList<>(); + Matcher m = typeDecl.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) + continue; + + String kindStr = m.group(1); + String typeName = m.group(2); + + // Manually extract type params, extends, implements using depth-aware scanning + int scanPos = m.end(); + while (scanPos < text.length() && Character.isWhitespace(text.charAt(scanPos))) + scanPos++; + + // Extract type params clause <...> if present (depth-aware) + String typeParamsClause = null; + int typeParamsClauseOffset = -1; + if (scanPos < text.length() && text.charAt(scanPos) == '<') { + int depth = 1, i = scanPos + 1; + while (i < text.length() && depth > 0) { + char c = text.charAt(i++); + if (c == '<') depth++; + else if (c == '>') depth--; + } + if (depth == 0) { + typeParamsClauseOffset = scanPos + 1; + typeParamsClause = text.substring(scanPos + 1, i - 1); + scanPos = i; + while (scanPos < text.length() && Character.isWhitespace(text.charAt(scanPos))) + scanPos++; + } + } + + // Find the opening brace, scanning depth-aware for angle brackets + int bracePos = scanPos; + int angleDepth = 0; + while (bracePos < text.length()) { + char c = text.charAt(bracePos); + if (c == '<') angleDepth++; + else if (c == '>') angleDepth--; + else if (c == '{' && angleDepth == 0) break; + bracePos++; + } + if (bracePos >= text.length()) continue; + + String betweenParamsAndBrace = text.substring(scanPos, bracePos).trim(); + + // Parse extends/implements from the text between type params and opening brace + String extendsClause = null; + String implementsClause = null; + + int extIdx = indexOfAtDepthZero(betweenParamsAndBrace, "extends"); + int implIdx = indexOfAtDepthZero(betweenParamsAndBrace, "implements"); + + if (extIdx >= 0) { + int extEnd = implIdx >= 0 ? implIdx : betweenParamsAndBrace.length(); + extendsClause = betweenParamsAndBrace.substring(extIdx + 7, extEnd).trim(); + } + if (implIdx >= 0) { + implementsClause = betweenParamsAndBrace.substring(implIdx + 10).trim(); + } + + int bodyStart = bracePos; + int bodyEnd = findMatchingBrace(bodyStart); + if (bodyEnd < 0) bodyEnd = text.length(); + + TypeInfo.Kind kind; + switch (kindStr) { + case "interface": kind = TypeInfo.Kind.INTERFACE; break; + case "enum": kind = TypeInfo.Kind.ENUM; break; + default: kind = TypeInfo.Kind.CLASS; break; + } + + String fullMatch = text.substring(m.start(), bodyStart + 1); + int modifiers = parseModifiers(fullMatch); + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, m.start()); + + rawDeclarations.add(new RawTypeDeclaration( + typeName, kind, m.start(), bodyStart, bodyEnd, + modifiers, typeParamsClause, typeParamsClauseOffset, extendsClause, implementsClause, jsDoc)); + } + + // ========== PASS 2a: Pre-register all type names (enables forward references) ========== + // Sort by bodyStart ascending so outer types are processed before inner types + rawDeclarations.sort(Comparator.comparingInt(r -> r.bodyStart)); + + // Pre-registration pass: create ScriptTypeInfo objects and register them in all + // lookup maps BEFORE resolving extends/implements clauses. This allows classes to + // reference script-defined types declared later in the file (forward references). + List registeredTypes = new ArrayList<>(rawDeclarations.size()); + { + Deque preRegStack = new ArrayDeque<>(); + for (RawTypeDeclaration raw : rawDeclarations) { + while (!preRegStack.isEmpty() && preRegStack.peek().getBodyEnd() <= raw.bodyStart) { + preRegStack.pop(); + } + + ScriptTypeInfo scriptType; + if (preRegStack.isEmpty()) { + scriptType = ScriptTypeInfo.create( + raw.name, raw.kind, raw.declOffset, raw.bodyStart, raw.bodyEnd, raw.modifiers); + scriptTypes.put(raw.name, scriptType); + } else { + ScriptTypeInfo parent = preRegStack.peek(); + scriptType = ScriptTypeInfo.createInner( + raw.name, raw.kind, parent, raw.declOffset, raw.bodyStart, raw.bodyEnd, raw.modifiers); + } + + if (raw.jsDoc != null) { + scriptType.setJSDocInfo(raw.jsDoc); + } + + // Parse generic type parameters early so they are available during hierarchy resolution + if (raw.typeParamsClause != null && !raw.typeParamsClause.trim().isEmpty()) { + parseTypeParamsClause(raw.typeParamsClause, scriptType, raw.bodyStart + 1, raw.typeParamsClauseOffset); + } + + scriptTypesByFullName.put(scriptType.getFullName(), scriptType); + scriptTypesByDotName.put(scriptType.getDotSeparatedName(), scriptType); + + preRegStack.push(scriptType); + registeredTypes.add(scriptType); + } + } + + // ========== PASS 2b: Resolve hierarchy and parse members ========== + // All script-defined type names are now in the lookup maps, so resolveType() + // can find forward-declared types during extends/implements resolution. + for (int i = 0; i < rawDeclarations.size(); i++) { + RawTypeDeclaration raw = rawDeclarations.get(i); + ScriptTypeInfo scriptType = registeredTypes.get(i); + + // Resolve extends clause (parent class inheritance) + // Use bodyStart+1 so findEnclosingScriptType returns this type, + // making its declared type params (T, E, etc.) resolvable. + if (raw.extendsClause != null && !raw.extendsClause.trim().isEmpty()) { + String parentName = raw.extendsClause.trim(); + // Strip generic args (e.g., "NumberBox" -> "NumberBox") for type resolution + int genIdx = parentName.indexOf('<'); + String parentGenericArgs = null; + if (genIdx >= 0) { + parentGenericArgs = parentName.substring(genIdx); + parentName = parentName.substring(0, genIdx); + } + TypeInfo parentType = resolveType(parentName, raw.bodyStart + 1); + if (parentType == null) { + parentType = TypeInfo.unresolved(parentName, parentName); + } + // Parameterize the parent type with generic args (e.g., NumberBox -> NumberBox parameterized with T) + if (parentGenericArgs != null && parentType.isResolved()) { + // Strip surrounding < > from parentGenericArgs + String argsContent = parentGenericArgs.substring(1, parentGenericArgs.length() - 1).trim(); + if (!argsContent.isEmpty()) { + parentType = parameterizeWithClause(parentType, argsContent, raw.bodyStart + 1); + } + } + scriptType.setSuperClass(parentType, parentName); + } + + // Resolve implements clause (interfaces) + if (raw.implementsClause != null && !raw.implementsClause.trim().isEmpty()) { + List interfaceNames = splitAtDepthZero(raw.implementsClause, ','); + for (String ifaceName : interfaceNames) { + String trimmedName = ifaceName.trim(); + if (trimmedName.isEmpty()) + continue; + // Strip generic args (e.g., "Comparable" -> "Comparable") + int genIdx = trimmedName.indexOf('<'); + String ifaceGenericArgs = null; + if (genIdx >= 0) { + ifaceGenericArgs = trimmedName.substring(genIdx); + trimmedName = trimmedName.substring(0, genIdx); + } + TypeInfo ifaceType = resolveType(trimmedName, raw.bodyStart + 1); + if (ifaceType == null) { + ifaceType = TypeInfo.unresolved(trimmedName, trimmedName); + } + if (ifaceGenericArgs != null && ifaceType.isResolved()) { + String argsContent = ifaceGenericArgs.substring(1, ifaceGenericArgs.length() - 1).trim(); + if (!argsContent.isEmpty()) { + ifaceType = parameterizeWithClause(ifaceType, argsContent, raw.bodyStart + 1); + } + } + scriptType.addImplementedInterface(ifaceType, trimmedName); + } + } + + // Parse fields and methods inside this type + parseScriptTypeMembers(scriptType); + } + } + + /** + * Parse a generic type parameters clause like "E", "K, V", or "T extends Entity" + * into TypeParamInfo objects and add them to the script type. + * Validates that in multi-bound declarations (e.g., {@code T extends Number & Comparable}), + * all bounds after the first must be interfaces (Java 8+ rule). + */ + private void parseTypeParamsClause(String clause, ScriptTypeInfo scriptType, int declOffset, int clauseStartOffset) { + List params = splitAtDepthZero(clause, ','); + int paramTextPos = 0; + for (String param : params) { + String trimmed = param.trim(); + int leadingSpaces = param.indexOf(trimmed.isEmpty() ? param : trimmed); + if (trimmed.isEmpty()) { + paramTextPos += param.length() + 1; + continue; + } + + int extendsIdx = indexOfAtDepthZero(trimmed, "extends"); + String paramName = extendsIdx >= 0 ? trimmed.substring(0, extendsIdx).trim() : trimmed; + + int endIdx = 0; + while (endIdx < paramName.length() && + (Character.isJavaIdentifierPart(paramName.charAt(endIdx)) || paramName.charAt(endIdx) == '.')) { + endIdx++; + } + paramName = paramName.substring(0, endIdx); + + String boundName = null; + List additionalBoundNames = new ArrayList<>(); + if (extendsIdx >= 0) { + String afterExtends = trimmed.substring(extendsIdx + 7).trim(); + List bounds = splitAtDepthZero(afterExtends, '&'); + + // Track position within trimmed to find each bound's absolute location + int searchFrom = extendsIdx + 7; + + for (int bi = 0; bi < bounds.size(); bi++) { + String bound = bounds.get(bi).trim(); + if (bound.isEmpty()) continue; + int boundEndIdx = 0; + while (boundEndIdx < bound.length() && + (Character.isJavaIdentifierPart(bound.charAt(boundEndIdx)) || bound.charAt(boundEndIdx) == '.')) { + boundEndIdx++; + } + if (boundEndIdx > 0) { + String name = bound.substring(0, boundEndIdx); + + // Find the position of this bound name within trimmed + int nameIdxInTrimmed = trimmed.indexOf(name, searchFrom); + searchFrom = nameIdxInTrimmed + name.length(); + + if (bi == 0) { + boundName = name; + } else { + additionalBoundNames.add(name); + + // Validate: secondary bounds must be interfaces + if (clauseStartOffset >= 0 && nameIdxInTrimmed >= 0) { + TypeInfo addBoundCheck = resolveType(name, declOffset); + if (addBoundCheck != null && addBoundCheck.isResolved() && !isInterfaceType(addBoundCheck)) { + int errorStart = clauseStartOffset + paramTextPos + leadingSpaces + nameIdxInTrimmed; + int errorEnd = errorStart + name.length(); + addError(null, errorStart, errorEnd, "Interface expected here"); + } + } + } + } + } + } + + TypeParamInfo typeParam = new TypeParamInfo(paramName, boundName, null); + if (boundName != null) { + TypeInfo boundTypeInfo = resolveType(boundName, declOffset); + if (boundTypeInfo != null && boundTypeInfo.isResolved()) { + typeParam.setBoundTypeInfo(boundTypeInfo); + } + } + for (String addBound : additionalBoundNames) { + typeParam.addAdditionalBound(addBound); + TypeInfo addBoundType = resolveType(addBound, declOffset); + if (addBoundType != null && addBoundType.isResolved()) { + typeParam.addAdditionalBoundType(addBoundType); + } + } + scriptType.addDeclaredTypeParam(typeParam); + paramTextPos += param.length() + 1; + } + + } + + private boolean isInterfaceType(TypeInfo typeInfo) { + if (typeInfo.isInterface()) return true; + Class javaClass = typeInfo.getJavaClass(); + if (javaClass != null) return javaClass.isInterface(); + return false; + } + + /** + * Split a string by a delimiter character, but only at angle-bracket depth 0. + * This ensures commas inside nested generics like {@code Map} are not treated as separators. + */ + private static List splitAtDepthZero(String s, char delimiter) { + List result = new ArrayList<>(); + int depth = 0; + int start = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '<') depth++; + else if (c == '>') depth--; + else if (c == delimiter && depth == 0) { + result.add(s.substring(start, i)); + start = i + 1; + } + } + result.add(s.substring(start)); + return result; + } + + /** + * Replace newline characters ({@code \n}, {@code \r}) with spaces when they + * occur inside angle brackets (generic type arguments). This lets patterns + * like FIELD_DECL_PATTERN and METHOD_DECL_PATTERN match multi-line generics + * (e.g. {@code HashMap}) without allowing a match to + * span across {@code //} comment lines. + * + *

The returned string has the same length as the input (characters + * are replaced, never inserted or removed), so all positional indices remain + * valid for the original text. + */ + private static String normalizeGenericNewlines(String src) { + StringBuilder sb = new StringBuilder(src.length()); + int depth = 0; + for (int i = 0; i < src.length(); i++) { + char c = src.charAt(i); + if (c == '<') + depth++; + else if (c == '>') { + if (depth > 0) + depth--; + } + if ((c == '\n' || c == '\r') && depth > 0) + sb.append(' '); + else + sb.append(c); + } + return sb.toString(); + } + + /** + * Find the index of a keyword in a string, but only at angle-bracket depth 0. + * The keyword must be preceded and followed by non-identifier characters (word boundary). + * Returns -1 if not found at depth 0. + */ + private static int indexOfAtDepthZero(String s, String keyword) { + int depth = 0; + int keyLen = keyword.length(); + for (int i = 0; i <= s.length() - keyLen; i++) { + char c = s.charAt(i); + if (c == '<') { depth++; continue; } + if (c == '>') { depth--; continue; } + if (depth == 0 && s.regionMatches(i, keyword, 0, keyLen)) { + // Check word boundaries + boolean startOk = (i == 0 || !Character.isJavaIdentifierPart(s.charAt(i - 1))); + boolean endOk = (i + keyLen >= s.length() || !Character.isJavaIdentifierPart(s.charAt(i + keyLen))); + if (startOk && endOk) { + return i; + } + } + } + return -1; + } + + private TypeInfo parameterizeWithClause(TypeInfo baseType, String typeArgsClause, int position) { + return parameterizeWithClause(baseType, typeArgsClause, position, -1); + } + + private TypeInfo parameterizeWithClause(TypeInfo baseType, String typeArgsClause, int position, int clauseTextOffset) { + List argSegments = splitAtDepthZero(typeArgsClause, ','); + List typeArgs = new ArrayList<>(); + for (String argName : argSegments) { + String trimmed = argName.trim(); + if (trimmed.isEmpty()) continue; + // Strip nested generic args for resolution (e.g., "Map" -> "Map") + int ltIdx = trimmed.indexOf('<'); + String baseName = ltIdx >= 0 ? trimmed.substring(0, ltIdx).trim() : trimmed; + TypeInfo argType = resolveType(baseName, position); + if (argType == null) { + argType = TypeInfo.unresolved(baseName, baseName); + } + if (ltIdx >= 0 && argType.isResolved() && trimmed.endsWith(">")) { + String nestedArgs = trimmed.substring(ltIdx + 1, trimmed.length() - 1).trim(); + if (!nestedArgs.isEmpty()) { + argType = parameterizeWithClause(argType, nestedArgs, position); + } + } + typeArgs.add(argType); + } + if (!typeArgs.isEmpty()) { + if (clauseTextOffset >= 0) { + validateTypeArgBounds(baseType, typeArgs, argSegments, clauseTextOffset); + } + return baseType.parameterize(typeArgs); + } + return baseType; + } + + private void validateTypeArgBounds(TypeInfo baseType, List typeArgs, + List argSegments, int clauseTextOffset) { + List typeParams = baseType.getTypeParams(); + if (typeParams == null || typeParams.isEmpty()) return; + + int count = Math.min(typeArgs.size(), typeParams.size()); + int charPos = 0; + int segIdx = 0; + for (int i = 0; i < count; i++) { + TypeInfo argType = typeArgs.get(i); + TypeParamInfo param = typeParams.get(i); + + String segment = segIdx < argSegments.size() ? argSegments.get(segIdx) : ""; + String trimmedSeg = segment.trim(); + int leading = 0; + while (leading < segment.length() && Character.isWhitespace(segment.charAt(leading))) leading++; + + if (argType != null && argType.isResolved() && !trimmedSeg.isEmpty()) { + TypeInfo primaryBound = param.getBoundTypeInfo(); + if (primaryBound != null && primaryBound.isResolved()) { + if (!TypeChecker.isTypeCompatible(primaryBound, argType)) { + int errorStart = clauseTextOffset + charPos + leading; + int errorEnd = errorStart + trimmedSeg.length(); + addError(null, errorStart, errorEnd, + "Type argument " + argType.getSimpleName() + " is not within bounds of type parameter " + + param.getName() + " (expected extends " + primaryBound.getSimpleName() + ")"); + } + } + + for (TypeInfo addBound : param.getAdditionalBoundTypes()) { + if (addBound == null || !addBound.isResolved()) continue; + if (!TypeChecker.isTypeCompatible(addBound, argType)) { + int errorStart = clauseTextOffset + charPos + leading; + int errorEnd = errorStart + trimmedSeg.length(); + addError(null, errorStart, errorEnd, + "Type argument " + argType.getSimpleName() + " does not implement required interface " + + addBound.getSimpleName()); + break; + } + } + } + + charPos += segment.length() + 1; + segIdx++; + } + } + + private void markTypeParamDeclarations(List marks, int afterNameEnd, ScriptTypeInfo typeInfo) { + int ltPos = text.indexOf('<', afterNameEnd); + if (ltPos < 0 || ltPos > afterNameEnd + 5) return; + + // Depth-aware matching to find the closing '>' (handles >) + int depth = 1, i = ltPos + 1; + while (i < text.length() && depth > 0) { + char c = text.charAt(i++); + if (c == '<') depth++; + else if (c == '>') depth--; + } + if (depth != 0) return; + int gtPos = i - 1; + + String clause = text.substring(ltPos + 1, gtPos); + + // Split type params by commas at depth 0 to handle bounds with nested generics + List paramSegments = splitAtDepthZero(clause, ','); + int segmentOffset = ltPos + 1; + + int paramIndex = 0; + List declaredParams = typeInfo.getDeclaredTypeParams(); + + for (String segment : paramSegments) { + if (paramIndex >= declaredParams.size()) break; + TypeParamInfo param = declaredParams.get(paramIndex++); + + int paramIdx = segment.indexOf(param.getName()); + if (paramIdx < 0) continue; + + int paramStart = segmentOffset + paramIdx; + int paramEnd = paramStart + param.getName().length(); + marks.add(new ScriptLine.Mark(paramStart, paramEnd, TokenType.GENERIC_TYPE_PARAM, param)); + + int extendsIdx = indexOfAtDepthZero(segment, "extends"); + if (extendsIdx >= 0) { + int extendsStart = segmentOffset + extendsIdx; + marks.add(new ScriptLine.Mark(extendsStart, extendsStart + 7, TokenType.KEYWORD)); + + TypeInfo boundType = param.getBoundTypeInfo(); + if (boundType != null) { + String afterExtends = segment.substring(extendsIdx + 7).trim(); + if (!afterExtends.isEmpty()) { + // Split on & at depth 0 to handle multiple bounds + List boundSegments = splitAtDepthZero(afterExtends, '&'); + int boundScanPos = extendsStart + 7; + while (boundScanPos < gtPos && Character.isWhitespace(text.charAt(boundScanPos))) boundScanPos++; + + for (int bi = 0; bi < boundSegments.size(); bi++) { + String boundSeg = boundSegments.get(bi).trim(); + if (boundSeg.isEmpty()) continue; + + // Mark the '&' separator (for bounds after the first) + if (bi > 0) { + int ampSearch = boundScanPos - 1; + while (ampSearch >= 0 && text.charAt(ampSearch) != '&') ampSearch--; + if (ampSearch >= 0) { + marks.add(new ScriptLine.Mark(ampSearch, ampSearch + 1, TokenType.DEFAULT)); + } + } + + // Extract base type name (without generic args) for marking + int nameEnd = 0; + while (nameEnd < boundSeg.length() && + (Character.isJavaIdentifierPart(boundSeg.charAt(nameEnd)) || boundSeg.charAt(nameEnd) == '.')) { + nameEnd++; + } + if (nameEnd > 0) { + String bName = boundSeg.substring(0, nameEnd); + TypeInfo bType; + if (bi == 0) { + bType = boundType; + } else { + List addBounds = param.getAdditionalBoundTypes(); + bType = (bi - 1 < addBounds.size()) ? addBounds.get(bi - 1) : null; + } + if (bType != null) { + marks.add(new ScriptLine.Mark(boundScanPos, boundScanPos + bName.length(), TokenType.getByType(bType), bType)); + } + + if (nameEnd < boundSeg.length() && boundSeg.charAt(nameEnd) == '<') { + int nestedStart = boundScanPos + nameEnd; + markNestedTypeParamUsages(marks, nestedStart, gtPos, declaredParams); + } + } + + // Advance past this bound segment + the '&' separator + boundScanPos += boundSeg.length(); + // Skip whitespace and '&' to reach the next bound + while (boundScanPos < gtPos && (Character.isWhitespace(text.charAt(boundScanPos)) || text.charAt(boundScanPos) == '&')) { + boundScanPos++; + } + } + } + } + } + + segmentOffset += segment.length() + 1; // +1 for the comma + } + } + + private void markNestedTypeParamUsages(List marks, int start, int limit, List typeParams) { + Map paramMap = new HashMap<>(); + for (TypeParamInfo tp : typeParams) paramMap.put(tp.getName(), tp); + + Pattern ident = Pattern.compile("\\b([A-Za-z_][a-zA-Z0-9_]*)\\b"); + String region = text.substring(start, Math.min(limit, text.length())); + Matcher m = ident.matcher(region); + while (m.find()) { + TypeParamInfo tp = paramMap.get(m.group(1)); + if (tp != null) { + int absStart = start + m.start(1); + marks.add(new ScriptLine.Mark(absStart, absStart + m.group(1).length(), TokenType.GENERIC_TYPE_PARAM, tp)); + } + } + } + /** + * Parse fields and methods inside a script-defined type. + */ + private void parseScriptTypeMembers(ScriptTypeInfo scriptType) { + int bodyStart = scriptType.getBodyStart(); + int bodyEnd = scriptType.getBodyEnd(); + + if (bodyStart < 0 || bodyEnd <= bodyStart) return; + + String bodyText = text.substring(bodyStart + 1, Math.min(bodyEnd, text.length())); + + // Parse constructors (ClassName(params) { ... }) + // Constructor pattern: ClassName matches the script type name, no return type + String typeName = scriptType.getSimpleName(); + Pattern constructorPattern = Pattern.compile( + "\\b" + Pattern.quote(typeName) + "\\s*\\(([^)]*)\\)\\s*\\{"); + Matcher cm = constructorPattern.matcher(bodyText); + while (cm.find()) { + int absPos = bodyStart + 1 + cm.start(); + if (isExcluded(absPos)) continue; + // Skip constructors found inside a nested type's body — they belong to the inner class + if (isInsideNestedType(absPos, scriptType)) continue; + + String paramList = cm.group(1); + + int constructorBodyStart = bodyStart + 1 + cm.end() - 1; + int constructorBodyEnd = findMatchingBrace(constructorBodyStart); + if (constructorBodyEnd < 0) constructorBodyEnd = bodyEnd; + + // Extract documentation before this constructor + String documentation = extractDocumentationBefore(absPos); + + // Extract modifiers by scanning backwards + int modifiers = extractModifiersBackwards(cm.start() - 1, bodyText); + + // Parse parameters with their actual positions + List params = parseParametersWithPositions(paramList, bodyStart + 1 + cm.start(1)); + + // Calculate the three offsets for constructor + // For constructors, type offset and name offset are the same (start of constructor name) + int nameOffset = bodyStart + 1 + cm.start(); + int typeOffset = nameOffset; // No separate type for constructors + int fullDeclOffset = findFullDeclarationStart(cm.start(), bodyText); + if (fullDeclOffset >= 0) { + fullDeclOffset += bodyStart + 1; + } else { + fullDeclOffset = nameOffset; + } + + // Constructors don't have a return type, but we'll use the containing type as a marker + MethodInfo constructorInfo = MethodInfo.declaration( + typeName, + scriptType, + // Return type is the type itself + scriptType, + params, + fullDeclOffset, + typeOffset, + nameOffset, + constructorBodyStart, + constructorBodyEnd, + modifiers, + documentation); + scriptType.addConstructor(constructorInfo); + } + + // Parse enum constants (for enum types only) + if (scriptType.getKind() == TypeInfo.Kind.ENUM) { + List constants = EnumConstantInfo.parseEnumConstants( + scriptType, + bodyText, + bodyStart + 1, + KEYWORD_PATTERN + ); + + for (EnumConstantInfo constant : constants) { + scriptType.addEnumConstant(constant); + if (constant.getConstructorCall() != null) { + + } + // methodCalls.add(constant.getConstructorCall()); + + } + } + } + + /** + * Check if a position is inside a nested method body within a class. + * This prevents field declarations inside methods from being treated as class fields. + */ + private boolean isInsideNestedMethod(int position, int classBodyStart, int classBodyEnd) { + String bodyText = text.substring(classBodyStart + 1, Math.min(classBodyEnd, text.length())); + int relativePos = position - classBodyStart - 1; + + Pattern methodPattern = Pattern.compile( + "\\b[A-Za-z_][a-zA-Z0-9_<>\\[\\]]*\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s*\\([^)]*\\)\\s*\\{"); + Matcher m = methodPattern.matcher(bodyText); + + while (m.find()) { + int methodBodyStart = m.end() - 1; + int absMethodBodyStart = classBodyStart + 1 + methodBodyStart; + int absMethodBodyEnd = findMatchingBrace(absMethodBodyStart); + + if (absMethodBodyEnd > 0 && position > absMethodBodyStart && position < absMethodBodyEnd) { + return true; + } + } + return false; + } + + /** + * Parse method/function declarations - UNIFIED for both Java and JavaScript. + * Stores results in the shared 'methods' list. + * + * For Java: Parses "ReturnType methodName(params) { ... }" + * For JavaScript: Parses "function funcName(params) { ... }" with hook type inference + */ + private void parseMethodDeclarations() { + if (isJavaScript()) { + // JavaScript: function funcName(params) { ... } + Pattern funcPattern = Pattern.compile("function\\s+(\\w+)\\s*\\(([^)]*)\\)\\s*\\{"); + Matcher m = funcPattern.matcher(text); + + while (m.find()) { + if (isExcluded(m.start())) continue; + + String funcName = m.group(1); + String paramList = m.group(2); + + int nameStart = m.start(1); + int bodyStart = text.indexOf('{', m.end() - 1); + int bodyEnd = findMatchingBrace(bodyStart); + if (bodyEnd < 0) bodyEnd = text.length(); + + // Extract documentation before this method + String documentation = extractDocumentationBefore(m.start()); + + // Check for JSDoc before the function declaration + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, m.start()); + + // For JS hooks, infer parameter types from registry + // Use the script context's namespaces (e.g., ["IPlayerEvent", "IAnimationEvent"]) for lookup + List params = new ArrayList<>(); + TypeInfo returnType = TypeInfo.fromPrimitive("void"); + List namespaces = scriptContext != null ? scriptContext.getNamespaces() : Collections.singletonList("Global"); + + boolean runtimeHook = false; + if (ScriptHookController.Instance != null && scriptContext != null) { + String hookContext = scriptContext.hookContext; + if (hookContext != null && !hookContext.isEmpty()) { + runtimeHook = ScriptHookController.Instance.hasHook(hookContext, funcName); + } + } + + if (runtimeHook) { + if (typeResolver.isJSHook(namespaces, funcName)) { + List sigs = typeResolver.getJSHookSignatures(namespaces, funcName); + if (!sigs.isEmpty()) { + JSTypeRegistry.HookSignature sig = sigs.get(0); + documentation = sig.doc; + + if (paramList != null && !paramList.trim().isEmpty()) { + String[] paramNames = paramList.split(","); + if (paramNames.length > 0) { + String paramName = paramNames[0].trim(); + TypeInfo paramType = typeResolver.resolveJSType(sig.paramType); + int paramStart = m.start(2) + paramList.indexOf(paramName); + params.add(FieldInfo.parameter(paramName, paramType, paramStart, null)); + } + } + } + } else { + if (paramList != null && !paramList.trim().isEmpty()) { + String[] paramNames = paramList.split(","); + if (paramNames.length > 0) { + String paramName = paramNames[0].trim(); + int paramStart = m.start(2) + paramList.indexOf(paramName); + params.add(FieldInfo.parameter(paramName, TypeInfo.ANY, paramStart, null)); + } + } + } + } else { + // Non-hook function - use JSDoc param types if available, else 'any' type + if (paramList != null && !paramList.trim().isEmpty()) { + int paramOffset = m.start(2); + for (String p : paramList.split(",")) { + String pn = p.trim(); + if (!pn.isEmpty()) { + int paramStart = paramOffset + paramList.indexOf(pn); + + // Check if JSDoc has a @param tag for this parameter + TypeInfo paramType = TypeInfo.ANY; + if (jsDoc != null) { + JSDocParamTag paramTag = jsDoc.getParamTag(pn); + if (paramTag != null && paramTag.getTypeInfo() != null) { + paramType = paramTag.getTypeInfo(); + } + } + + params.add(FieldInfo.parameter(pn, paramType, paramStart, null)); + } + } + } + + // Use JSDoc @return type if available + if (jsDoc != null && jsDoc.hasReturnTag() && jsDoc.getReturnType() != null) { + returnType = jsDoc.getReturnType(); + } + } + + // Create MethodInfo and add to shared methods list + MethodInfo methodInfo = MethodInfo.declaration( + funcName, null, returnType, params, + m.start(), nameStart, nameStart, + bodyStart, bodyEnd, 0, documentation + ); + + if(jsDoc!=null) + methodInfo.setJSDocInfo(jsDoc); + + methods.add(methodInfo); + } + } else { + // Java: ReturnType methodName(params) { ... } or { ; } + Pattern methodWithBody = Pattern.compile( + "\\b([a-zA-Z_][a-zA-Z0-9_.<>,[ \\t]\\[\\]]*)[ \\t]+([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(([^)]*)\\)\\s*(\\{|;)"); + + Matcher m = methodWithBody.matcher(normalizeGenericNewlines(text)); + while (m.find()) { + String methodName = m.group(2); + + if (isExcluded(m.start()) || isKeyword(methodName)) + continue; + + if (isExcluded(m.start(2))) + continue; + + if (hasExcludedRange(m.start(1), m.end(1))) + continue; + + String returnType = m.group(1); + + if (returnType.equals("class") || returnType.equals("interface") || returnType.equals("enum") || returnType.equals("new") + || TypeResolver.isModifier(returnType)) { + continue; + } + + String paramList = m.group(3); + String delimiter = m.group(4); + boolean hasBody = delimiter.equals("{"); + + int bodyStart = !hasBody ? m.end() : text.indexOf('{', m.end() - 1); + int bodyEnd = !hasBody ? m.end() : findMatchingBrace(bodyStart); + if (bodyEnd < 0) + bodyEnd = text.length(); + + // Extract documentation before this method + String documentation = extractDocumentationBefore(m.start()); + + // Extract modifiers by scanning backwards from match start + int modifiers = extractModifiersBackwards(m.start() - 1, text); + + // Calculate offset positions + int typeOffset = m.start(1); + int nameOffset = m.start(2); + int fullDeclOffset = findFullDeclarationStart(m.start(1), text); + + // Use findEnclosingScriptType (recursive descent) so methods declared + // inside inner classes are attributed to the innermost containing type. + ScriptTypeInfo scriptType = findEnclosingScriptType(bodyStart); + + // Parse parameters with their actual positions + List params = parseParametersWithPositions(paramList, m.start(3)); + + MethodInfo methodInfo = MethodInfo.declaration( + methodName, + scriptType, + resolveType(returnType, m.start(1)), + params, + fullDeclOffset, + typeOffset, + nameOffset, + bodyStart, + bodyEnd, + modifiers, + documentation + ); + + if (scriptType != null) { + scriptType.addMethod(methodInfo); + } else + methods.add(methodInfo); + + // Validate the method (return statements, parameters) with type resolution + String methodBodyText = bodyEnd > bodyStart + 1 ? text.substring(bodyStart + 1, bodyEnd) : ""; + methodInfo.validate(methodBodyText, hasBody, (expr, pos) -> resolveExpressionType(expr, pos)); + } + + + } + // Check for duplicate method declarations + checkDuplicateMethods(); + } + + /** + * Find the start of a full method declaration, including any modifiers before the type. + */ + private int findFullDeclarationStart(int typeStart, String sourceText) { + int pos = typeStart - 1; + + // Skip whitespace before type + while (pos >= 0 && Character.isWhitespace(sourceText.charAt(pos))) { + pos--; + } + + // Check for modifiers + int earliestPos = typeStart; + while (pos >= 0) { + // Skip whitespace + while (pos >= 0 && Character.isWhitespace(sourceText.charAt(pos))) { + pos--; + } + if (pos < 0) break; + + // Read word backwards + int wordEnd = pos + 1; + while (pos >= 0 && Character.isJavaIdentifierPart(sourceText.charAt(pos))) { + pos--; + } + int wordStart = pos + 1; + + if (wordStart < wordEnd) { + String word = sourceText.substring(wordStart, wordEnd); + if (TypeResolver.isModifier(word)) { + earliestPos = wordStart; + } else { + break; + } + } else { + break; + } + } + + return earliestPos; + } + + /** + * Check for duplicate method declarations with same signature in same scope. + */ + private void checkDuplicateMethods() { + // Group methods by their containing type (script class/interface or document root) + // Methods are only duplicates if they're in the SAME containing type + Map> methodsByType = new HashMap<>(); + + for (MethodInfo method : getAllMethods()) { + TypeInfo containingType = method.getContainingType(); + methodsByType.computeIfAbsent(containingType, k -> new ArrayList<>()).add(method); + } + + // Check each type for duplicate method signatures + for (List typeMethods : methodsByType.values()) { + Map> signatureMap = new HashMap<>(); + + for (MethodInfo method : typeMethods) { + MethodSignature signature = method.getSignature(); + signatureMap.computeIfAbsent(signature, k -> new ArrayList<>()).add(method); + } + + // Mark all methods with duplicate signatures within the same type + for (Map.Entry> entry : signatureMap.entrySet()) { + List duplicates = entry.getValue(); + if (duplicates.size() > 1) { + for (MethodInfo duplicate : duplicates) { + duplicate.setError( + MethodInfo.ErrorType.DUPLICATE_METHOD, + duplicate.getSignature() + " is already defined in this scope" + ); + } + } + } + } + } + + /** + * Calculate the scope depth of a position (0 = top level, 1 = in class, etc.). + */ + private int calculateScopeDepth(int position) { + int depth = 0; + int braceDepth = 0; + boolean inString = false; + boolean inComment = false; + boolean inLineComment = false; + + for (int i = 0; i < position && i < text.length(); i++) { + char c = text.charAt(i); + char next = (i + 1 < text.length()) ? text.charAt(i + 1) : 0; + + // Handle strings + if (c == '"' && !inComment && !inLineComment) { + inString = !inString; + continue; + } + if (inString) continue; + + // Handle comments + if (!inComment && !inLineComment && c == '/' && next == '/') { + inLineComment = true; + i++; + continue; + } + if (!inComment && !inLineComment && c == '/' && next == '*') { + inComment = true; + i++; + continue; + } + if (inComment && c == '*' && next == '/') { + inComment = false; + i++; + continue; + } + if (inLineComment && c == '\n') { + inLineComment = false; + continue; + } + if (inComment || inLineComment) continue; + + // Track braces + if (c == '{') { + braceDepth++; + depth = Math.max(depth, braceDepth); + } else if (c == '}') { + braceDepth--; + } + } + + return depth; + } + + private List parseParametersWithPositions(String paramList, int paramListStart) { + List params = new ArrayList<>(); + if (paramList == null || paramList.trim().isEmpty()) { + return params; + } + + // Collapse all whitespace runs to single spaces, tracking original positions via posMap. + // posMap[normalizedIndex] = originalIndex, enabling correct absolute offsets after matching. + StringBuilder normalized = new StringBuilder(paramList.length()); + int[] posMap = new int[paramList.length() + 1]; + boolean lastWasSpace = false; + for (int i = 0; i < paramList.length(); i++) { + char c = paramList.charAt(i); + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { + if (!lastWasSpace) { + posMap[normalized.length()] = i; + normalized.append(' '); + lastWasSpace = true; + } + } else { + posMap[normalized.length()] = i; + normalized.append(c); + lastWasSpace = false; + } + } + posMap[normalized.length()] = paramList.length(); + String normalizedStr = normalized.toString(); + + // Split by top-level commas (not inside < > brackets), then parse each parameter individually + List paramRanges = new ArrayList<>(); + int depth = 0; + int start = 0; + for (int i = 0; i < normalizedStr.length(); i++) { + char c = normalizedStr.charAt(i); + if (c == '<') depth++; + else if (c == '>') depth--; + else if (c == ',' && depth == 0) { + paramRanges.add(new int[]{start, i}); + start = i + 1; + } + } + paramRanges.add(new int[]{start, normalizedStr.length()}); + + // Matches: type (with optional generics, arrays, dots) + optional varargs + whitespace + paramName + Pattern paramPattern = Pattern.compile( + "\\s*([a-zA-Z_][a-zA-Z0-9_.<>,? \\[\\]]*)(?:\\.{3})?\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*"); + + for (int[] range : paramRanges) { + String segment = normalizedStr.substring(range[0], range[1]); + if (segment.trim().isEmpty()) continue; + + Matcher m = paramPattern.matcher(segment); + if (!m.matches()) continue; + + String rawType = m.group(1).replaceAll("\\s+", ""); + String paramName = m.group(2); + String between = segment.substring(m.end(1), m.start(2)); + boolean isVarArg = between.contains("..."); + + TypeInfo typeInfo = resolveType(rawType, paramListStart); + + // m.start(2) is relative to segment; add range[0] to get position in normalizedStr, then posMap to original + int normalizedNamePos = range[0] + m.start(2); + int paramNameStart = paramListStart + posMap[normalizedNamePos]; + FieldInfo fieldInfo = FieldInfo.parameter(paramName, typeInfo, paramNameStart, null); + fieldInfo.setVarArg(isVarArg); + params.add(fieldInfo); + } + return params; + } + + private ScopeInfo computeBlockScope(int bodyStart, int bodyEnd, int declarationOffset) { + int end = Math.min(bodyEnd, text.length()); + int pos = Math.min(Math.max(declarationOffset, bodyStart), end); + + Deque stack = new ArrayDeque<>(); + for (int i = bodyStart; i < pos && i < text.length(); i++) { + if (isExcluded(i)) { + continue; + } + char c = text.charAt(i); + if (c == '{') { + stack.push(i); + } else if (c == '}') { + if (!stack.isEmpty()) { + stack.pop(); + } + } + } + + if (stack.isEmpty()) { + ScopeInfo parenScope = computeParenStatementScope(bodyStart, bodyEnd, pos); + if (parenScope != null) { + return parenScope; + } + return new ScopeInfo(bodyStart, bodyEnd, false, "method"); + } + + int openBrace = stack.peek(); + int closeBrace = findMatchingBrace(openBrace); + if (closeBrace < 0 || closeBrace > bodyEnd) { + return new ScopeInfo(bodyStart, bodyEnd, false, "method"); + } + return new ScopeInfo(openBrace + 1, closeBrace, false, "block"); + } + + private ScopeInfo computeParenStatementScope(int bodyStart, int bodyEnd, int position) { + int openParen = findEnclosingParenStart(bodyStart, position); + if (openParen < 0) { + return null; + } + + int closeParen = findMatchingParen(openParen, bodyEnd); + if (closeParen < 0 || position > closeParen) { + return null; + } + + String keyword = readKeywordBefore(openParen); + if (!"for".equals(keyword) && !"catch".equals(keyword)) { + return null; + } + + int after = skipWhitespaceAndExcluded(closeParen + 1, bodyEnd); + if (after < 0 || after >= bodyEnd) { + return null; + } + + if (text.charAt(after) == '{') { + int closeBrace = findMatchingBrace(after); + if (closeBrace > 0) { + return new ScopeInfo(openParen, closeBrace, false, "block"); + } + return null; + } + + int stmtEnd = findStatementEnd(after, bodyEnd); + if (stmtEnd > after) { + return new ScopeInfo(openParen, stmtEnd, false, "block"); + } + return null; + } + + int skipWhitespaceAndExcluded(int pos, int limit) { + int i = Math.max(pos, 0); + int max = Math.min(limit, text.length()); + while (i < max) { + if (isExcluded(i)) { + i++; + continue; + } + if (!Character.isWhitespace(text.charAt(i))) { + return i; + } + i++; + } + return -1; + } + + int findStatementEnd(int start, int limit) { + int max = Math.min(limit, text.length()); + int parenDepth = 0; + int bracketDepth = 0; + for (int i = start; i < max; i++) { + if (isExcluded(i)) { + continue; + } + char c = text.charAt(i); + if (c == '(') parenDepth++; + else if (c == ')') parenDepth = Math.max(0, parenDepth - 1); + else if (c == '[') bracketDepth++; + else if (c == ']') bracketDepth = Math.max(0, bracketDepth - 1); + else if (c == '{') { + int closeBrace = findMatchingBrace(i); + return closeBrace > 0 ? closeBrace : -1; + } else if (c == ';' && parenDepth == 0 && bracketDepth == 0) { + return i + 1; + } + } + return -1; + } + + int findEnclosingParenStart(int min, int position) { + int depth = 0; + for (int i = Math.min(position - 1, text.length() - 1); i >= min; i--) { + if (isExcluded(i)) { + continue; + } + char c = text.charAt(i); + if (c == ')') { + depth++; + } else if (c == '(') { + if (depth == 0) { + return i; + } + depth--; + } + } + return -1; + } + + int findMatchingParen(int openParenIndex, int limit) { + if (openParenIndex < 0 || openParenIndex >= text.length()) { + return -1; + } + int max = Math.min(limit, text.length()); + int depth = 0; + for (int i = openParenIndex; i < max; i++) { + if (isExcluded(i)) { + continue; + } + char c = text.charAt(i); + if (c == '(') depth++; + else if (c == ')') { + depth--; + if (depth == 0) { + return i; + } + } + } + return -1; + } + + String readKeywordBefore(int position) { + int i = position - 1; + while (i >= 0) { + if (isExcluded(i)) { + i--; + continue; + } + if (!Character.isWhitespace(text.charAt(i))) { + break; + } + i--; + } + if (i < 0) { + return ""; + } + int end = i + 1; + while (i >= 0 && Character.isJavaIdentifierPart(text.charAt(i))) { + i--; + } + int start = i + 1; + if (start >= end) { + return ""; + } + return text.substring(start, end); + } + + private FieldInfo pickVisibleLocal(List candidates, int position) { + if (candidates == null || candidates.isEmpty()) { + return null; + } + FieldInfo best = null; + for (FieldInfo f : candidates) { + if (f == null) { + continue; + } + if (!f.isVisibleAt(position)) { + continue; + } + if (best == null || f.getDeclarationOffset() > best.getDeclarationOffset()) { + best = f; + } + } + return best; + } + + private FieldInfo pickVisibleTopLevelLocal(String name, int position) { + return pickVisibleLocal(topLevelLocals.get(name), position); + } + + void addTopLevelLocal(FieldInfo fieldInfo) { + if (fieldInfo == null) { + return; + } + topLevelLocals.computeIfAbsent(fieldInfo.getName(), k -> new ArrayList<>()).add(fieldInfo); + } + + private Collection getVisibleTopLevelLocals(int position) { + List visible = new ArrayList<>(); + for (List candidates : topLevelLocals.values()) { + FieldInfo best = pickVisibleLocal(candidates, position); + if (best != null) { + visible.add(best); + } + } + return visible; + } + + Collection getTopLevelLocalCandidates() { + List all = new ArrayList<>(); + for (List fields : topLevelLocals.values()) { + all.addAll(fields); + } + return all; + } + + /** + * Parse local variables inside methods/functions - UNIFIED for both Java and JavaScript. + * Stores results in the shared 'methodLocals' map (methodOffset -> varName -> FieldInfo). + * + * For Java: Parses "Type varName = expr;" or "Type varName;" + * For JavaScript: Parses "var/let/const varName = expr;" with type inference + */ + private void parseLocalVariables() { + List allMethodsAndConstructors = getAllMethods(); + allMethodsAndConstructors.addAll(getAllConstructors()); + for (MethodInfo method : allMethodsAndConstructors) { + Map> locals = new HashMap<>(); + methodLocals.put(method.getDeclarationOffset(), locals); + + int bodyStart = method.getBodyStart(); + int bodyEnd = method.getBodyEnd(); + if (bodyStart < 0 || bodyEnd <= bodyStart) continue; + + String bodyText = text.substring(bodyStart, Math.min(bodyEnd, text.length())); + + if (isJavaScript()) { + // JavaScript: var/let/const varName = expr; + Pattern varPattern = Pattern.compile("(var|let|const)\\s+(\\w+)(?:\\s*(=))?"); + Matcher m = varPattern.matcher(bodyText); + + while (m.find()) { + int absPos = bodyStart + m.start(2); + if (isExcluded(absPos)) continue; + + int afterVar = m.end(2); + if (afterVar < bodyText.length()) { + String rest = bodyText.substring(afterVar); + if (rest.length() > 0 && java.util.regex.Pattern.compile("^\\s+(?:in|of)\\s").matcher(rest).find()) continue; + } + + boolean insideInner = false; + for (InnerCallableScope scope : innerScopes) { + if (scope.containsPosition(absPos)) { + insideInner = true; + break; + } + } + if (insideInner) continue; + + String kind = m.group(1); + String varName = m.group(2); + String initializer = null; + int initializerStart = -1; + int initializerEnd = -1; + if (m.group(3) != null) { + initializerStart = skipSegmentWhitespace(bodyText, m.end(3)); + initializerEnd = findJsInitializerEnd(bodyText, initializerStart, true); + if (initializerEnd > initializerStart) { + initializer = bodyText.substring(initializerStart, initializerEnd).trim(); + if (initializer.isEmpty()) { + initializer = null; + } + } + } + + // Check for JSDoc type annotation before the declaration + int absStart = bodyStart + m.start(); + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, absStart); + + TypeInfo typeInfo = null; + + // Priority 1: JSDoc @type takes precedence + if (jsDoc != null && jsDoc.hasTypeTag()) { + typeInfo = jsDoc.getDeclaredType(); + } + + // Priority 2: Infer type from initializer if no JSDoc type + if (typeInfo == null && initializer != null && !initializer.isEmpty()) { + TypeInfo inferred = resolveExpressionType(initializer, bodyStart + initializerStart); + if (!TypeInfo.NULL.equals(inferred)) { + typeInfo = inferred; + } + } + + // Priority 3: Use "any" type for uninitialized variables + if (typeInfo == null) { + typeInfo = TypeInfo.ANY; + } + + int initStart = -1, initEnd = -1; + if (m.group(3) != null) { + initStart = bodyStart + m.start(3); + initEnd = (initializerEnd >= 0) ? bodyStart + initializerEnd : bodyStart + m.end(3); + } + + FieldInfo fieldInfo = FieldInfo.localField(varName, typeInfo, absPos, method, initStart, initEnd, 0); + ScopeInfo scopeInfo; + if ("var".equals(kind)) { + scopeInfo = new ScopeInfo(bodyStart, bodyEnd, false, "method"); + } else { + scopeInfo = computeBlockScope(bodyStart, bodyEnd, absPos); + } + fieldInfo.setScopeInfo(scopeInfo); + + if(jsDoc != null) + fieldInfo.setJSDocInfo(jsDoc); + // Check for duplicate + List existing = locals.get(varName); + if (existing != null && !existing.isEmpty()) { + boolean dup = false; + if ("let".equals(kind) || "const".equals(kind)) { + for (FieldInfo prev : existing) { + ScopeInfo prevScope = prev.getScopeInfo(); + if (prevScope != null && prevScope.startOffset == scopeInfo.startOffset && prevScope.endOffset == scopeInfo.endOffset) { + dup = true; + break; + } + } + } + if (dup || globalFields.containsKey(varName)) { + AssignmentInfo dupError = AssignmentInfo.duplicateDeclaration( + varName, absPos, absPos + varName.length(), + "Variable '" + varName + "' is already defined in the scope"); + dupError.setScopeInfo(scopeInfo); + declarationErrors.add(dupError); + continue; + } + if ("var".equals(kind)) { + continue; + } + } else if (globalFields.containsKey(varName)) { + AssignmentInfo dupError = AssignmentInfo.duplicateDeclaration( + varName, absPos, absPos + varName.length(), + "Variable '" + varName + "' is already defined in the scope"); + dupError.setScopeInfo(scopeInfo); + declarationErrors.add(dupError); + continue; + } + + locals.computeIfAbsent(varName, k -> new ArrayList<>()).add(fieldInfo); + + // --- Multi-declarator continuation for JS --- + // For "var a=1, b='x', c=player;" the regex only matched 'a'. + // Scan forward from the end of this declarator for comma-separated + // continuation names (b, c, ...) that share the same var/let/const keyword. + final String fKind = kind; + final MethodInfo fMethod = method; + final int fBodyStart = bodyStart; + final int fBodyEnd = bodyEnd; + final Map> fLocals = locals; + int contScanStart = MultiDeclaratorParser.jsDeclaratorScanStart(bodyText, m.end(2), m.group(3) != null, initializerEnd); + MultiDeclaratorParser.scanJSContinuationDeclarators(this, bodyText, contScanStart, bodyStart, + (cVarName, cAbsNamePos, cInit, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + boolean cInsideInner = false; + for (InnerCallableScope sc : innerScopes) { + if (sc.containsPosition(cAbsNamePos)) { cInsideInner = true; break; } + } + if (cInsideInner) return; + + TypeInfo cType = null; + if (cInit != null && !cInit.isEmpty()) { + TypeInfo inferred = resolveExpressionType(cInit, cAbsInitStart); + if (!TypeInfo.NULL.equals(inferred)) cType = inferred; + } + if (cType == null) cType = TypeInfo.ANY; + + FieldInfo cField = FieldInfo.localField(cVarName, cType, cAbsNamePos, fMethod, + cAbsInitStart, cAbsInitEnd, 0); + ScopeInfo cScope; + if ("var".equals(fKind)) { + cScope = new ScopeInfo(fBodyStart, fBodyEnd, false, "method"); + } else { + cScope = computeBlockScope(fBodyStart, fBodyEnd, cAbsNamePos); + } + cField.setScopeInfo(cScope); + + if (fLocals.containsKey(cVarName) || globalFields.containsKey(cVarName)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + cVarName, cAbsNamePos, cAbsNamePos + cVarName.length(), + "Variable '" + cVarName + "' is already defined in the scope"); + dupErr.setScopeInfo(cScope); + declarationErrors.add(dupErr); + return; + } + fLocals.computeIfAbsent(cVarName, k -> new ArrayList<>()).add(cField); + }); + } + } else { + // Java: Type varName = expr; or Type varName; + Matcher m = FIELD_DECL_PATTERN.matcher(normalizeGenericNewlines(bodyText)); + while (m.find()) { + String typeName = m.group(1); + String varName = m.group(2); + String delimiter = m.group(3); + + int absPos = bodyStart + m.start(2); + if (isExcluded(absPos)) continue; + + // FIELD_DECL_PATTERN's type group allows newlines, so a match can + // start inside a line comment (e.g., "// Integer\nString str =") + // where group(2) lands on the next line outside the comment. + int absTypeStart = bodyStart + m.start(1); + if (isExcluded(absTypeStart)) continue; + if (hasExcludedRange(absTypeStart, bodyStart + m.end(1))) + continue; + + // --- FIX: Detect greedy regex consuming commas into the type name --- + // FIELD_DECL_PATTERN allows commas in its type character class (for generics). + // This causes "int x, y, z = 10;" to match as type="int x, y," name="z" delim="=". + // When a depth-0 comma exists in typeName, the regex swallowed extra declarators. + // We extract the real type and first variable, then let the continuation scanner + // handle ALL variables (including the regex-matched one). + int commaInType = MultiDeclaratorParser.findFirstDepthZeroComma(typeName); + if (commaInType >= 0) { + String realTypeName = MultiDeclaratorParser.extractRealTypeFromGreedyMatch(typeName, commaInType); + String firstVar = MultiDeclaratorParser.extractFirstVarFromGreedyMatch(typeName, commaInType); + int firstVarAbsPos = MultiDeclaratorParser.findFirstVarPosition( + bodyText, m.start(1), typeName, commaInType) + bodyStart; + + // Skip control flow keywords on the real type + if (realTypeName.equals("return") || realTypeName.equals("if") || realTypeName.equals("while") || + realTypeName.equals("for") || realTypeName.equals("switch") || realTypeName.equals("catch") || + realTypeName.equals("new") || realTypeName.equals("throw")) { + continue; + } + + int enclosingParen1 = findEnclosingParenStart(bodyStart, firstVarAbsPos); + if (enclosingParen1 >= 0) continue; + + int greedyModifiers = parseModifiers(realTypeName); + TypeInfo greedyTypeInfo = resolveType(realTypeName, firstVarAbsPos); + + // Register the first variable (extracted from the greedy type group) + FieldInfo firstField = FieldInfo.localField(firstVar, greedyTypeInfo, firstVarAbsPos, + method, -1, -1, greedyModifiers); + ScopeInfo firstScope = computeBlockScope(bodyStart, bodyEnd, firstVarAbsPos); + firstField.setScopeInfo(firstScope); + + List existingFirst = locals.get(firstVar); + if (existingFirst != null) { + boolean dup = false; + for (FieldInfo prev : existingFirst) { + ScopeInfo prevScope = prev.getScopeInfo(); + if (prevScope != null && prevScope.containsPosition(firstVarAbsPos)) { + dup = true; + break; + } + } + if (dup || globalFields.containsKey(firstVar)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + firstVar, firstVarAbsPos, firstVarAbsPos + firstVar.length(), + "Variable '" + firstVar + "' is already defined in the scope"); + dupErr.setScopeInfo(firstScope); + declarationErrors.add(dupErr); + } else { + locals.computeIfAbsent(firstVar, k -> new ArrayList<>()).add(firstField); + } + } else if (globalFields.containsKey(firstVar)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + firstVar, firstVarAbsPos, firstVarAbsPos + firstVar.length(), + "Variable '" + firstVar + "' is already defined in the scope"); + dupErr.setScopeInfo(firstScope); + declarationErrors.add(dupErr); + } else { + locals.computeIfAbsent(firstVar, k -> new ArrayList<>()).add(firstField); + } + + // Scan continuations from the first depth-0 comma in the type group. + // This will pick up all remaining variables (y, z, etc.) including the + // regex-matched varName which was the last one consumed by the greedy match. + final TypeInfo greedySharedType = greedyTypeInfo; + final int greedySharedMod = greedyModifiers; + final MethodInfo fMethod3 = method; + final Map> fLocals3 = locals; + int greedyScanStart = m.start(1) + commaInType; + MultiDeclaratorParser.scanJavaContinuationDeclarators(bodyText, greedyScanStart, bodyStart, + (cVarName, cAbsNamePos, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + if (findEnclosingParenStart(bodyStart, cAbsNamePos) >= 0) return; + FieldInfo cField = FieldInfo.localField(cVarName, greedySharedType, cAbsNamePos, + fMethod3, cAbsInitStart, cAbsInitEnd, greedySharedMod); + ScopeInfo cScope = computeBlockScope(bodyStart, bodyEnd, cAbsNamePos); + cField.setScopeInfo(cScope); + + if (fLocals3.containsKey(cVarName) || globalFields.containsKey(cVarName)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + cVarName, cAbsNamePos, cAbsNamePos + cVarName.length(), + "Variable '" + cVarName + "' is already defined in the scope"); + dupErr.setScopeInfo(cScope); + declarationErrors.add(dupErr); + return; + } + fLocals3.computeIfAbsent(cVarName, k -> new ArrayList<>()).add(cField); + }); + continue; + } + + // Skip control flow keywords + if (typeName.equals("return") || typeName.equals("if") || typeName.equals("while") || + typeName.equals("for") || typeName.equals("switch") || typeName.equals("catch") || + typeName.equals("new") || typeName.equals("throw")) { + continue; + } + + int enclosingParen = findEnclosingParenStart(bodyStart, absPos); + if (enclosingParen >= 0 && "for".equals(readKeywordBefore(enclosingParen))) continue; + + int modifiers = parseModifiers(typeName); + + TypeInfo typeInfo; + if ((typeName.equals("var") || typeName.equals("let") || typeName.equals("const")) + && delimiter.equals("=")) { + int rhsStart = bodyStart + m.end(); + typeInfo = inferTypeFromExpression(rhsStart); + } else { + // Use position-aware resolution so inner class type names resolve in scope + typeInfo = resolveType(typeName, bodyStart + m.start(2)); + } + + int initStart = -1, initEnd = -1; + if ("=".equals(delimiter)) { + initStart = bodyStart + m.start(3); + int searchPos = bodyStart + m.end(3); + int depth = 0; + int angleDepth = 0; + while (searchPos < text.length()) { + char c = text.charAt(searchPos); + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') depth--; + else if (c == '<') angleDepth++; + else if (c == '>') angleDepth--; + else if ((c == ';' || c == ',') && depth == 0 && angleDepth == 0) { + initEnd = searchPos; + break; + } + searchPos++; + } + } + + int declPos = bodyStart + m.start(2); + FieldInfo fieldInfo = FieldInfo.localField(varName, typeInfo, declPos, method, initStart, initEnd, modifiers); + ScopeInfo scopeInfo = computeBlockScope(bodyStart, bodyEnd, declPos); + fieldInfo.setScopeInfo(scopeInfo); + + List existing = locals.get(varName); + if (existing != null) { + boolean dup = false; + for (FieldInfo prev : existing) { + ScopeInfo prevScope = prev.getScopeInfo(); + if (prevScope != null && prevScope.containsPosition(declPos)) { + dup = true; + break; + } + } + if (dup || globalFields.containsKey(varName)) { + AssignmentInfo dupError = AssignmentInfo.duplicateDeclaration( + varName, declPos, declPos + varName.length(), + "Variable '" + varName + "' is already defined in the scope"); + dupError.setScopeInfo(scopeInfo); + declarationErrors.add(dupError); + continue; + } + } else if (globalFields.containsKey(varName)) { + AssignmentInfo dupError = AssignmentInfo.duplicateDeclaration( + varName, declPos, declPos + varName.length(), + "Variable '" + varName + "' is already defined in the scope"); + dupError.setScopeInfo(scopeInfo); + declarationErrors.add(dupError); + continue; + } + + locals.computeIfAbsent(varName, k -> new ArrayList<>()).add(fieldInfo); + + // --- Multi-declarator continuation for Java --- + // For "int x = 1, y, z = 3;" FIELD_DECL_PATTERN matched "int x =" (or "int x,"). + // Scan forward for comma-separated continuation declarators (y, z) + // that share the same declared type from the first match. + final TypeInfo sharedType = typeInfo; + final int sharedModifiers = modifiers; + final MethodInfo fMethod2 = method; + final Map> fLocals2 = locals; + int javaScanStart = MultiDeclaratorParser.javaDeclaratorScanStart(bodyText, delimiter, m.end(3), + initEnd >= 0 ? initEnd - bodyStart : -1); + if (javaScanStart >= 0) { + MultiDeclaratorParser.scanJavaContinuationDeclarators(bodyText, javaScanStart, bodyStart, + (cVarName, cAbsNamePos, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + FieldInfo cField = FieldInfo.localField(cVarName, sharedType, cAbsNamePos, + fMethod2, cAbsInitStart, cAbsInitEnd, sharedModifiers); + ScopeInfo cScope = computeBlockScope(bodyStart, bodyEnd, cAbsNamePos); + cField.setScopeInfo(cScope); + + if (fLocals2.containsKey(cVarName) || globalFields.containsKey(cVarName)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + cVarName, cAbsNamePos, cAbsNamePos + cVarName.length(), + "Variable '" + cVarName + "' is already defined in the scope"); + dupErr.setScopeInfo(cScope); + declarationErrors.add(dupErr); + return; + } + fLocals2.computeIfAbsent(cVarName, k -> new ArrayList<>()).add(cField); + }); + } + } + } + } + + // Also parse locals inside inner callable scopes + for (InnerCallableScope scope : innerScopes) { + parseLocalVariablesInScope(scope); + } + + new LoopVariableParser(this, text).parse(methodLocals); + } + + private void parseLocalVariablesInScope(InnerCallableScope scope) { + int start = scope.getBodyStart(); + int end = scope.getBodyEnd(); + + if (start < 0 || end <= start) return; + + if (isJavaScript()) { + parseJSLocalsInRange(start, end, scope); + } else { + parseJavaLocalsInRange(start, end, scope); + } + } + + /** + * Parse Java local variable declarations in the range [start, end). + * Pattern: Type varName = ... or var varName = ... + */ + private void parseJavaLocalsInRange(int start, int end, InnerCallableScope scope) { + String rangeText = text.substring(start, Math.min(end, text.length())); + + Matcher m = FIELD_DECL_PATTERN.matcher(normalizeGenericNewlines(rangeText)); + while (m.find()) { + int declPos = start + m.start(); + if (declPos < start || declPos >= end) continue; + if (isExcluded(declPos)) continue; + if (hasExcludedRange(start + m.start(1), start + m.end(1))) + continue; + + String typeNameRaw = m.group(1); + String varName = m.group(2); + String delimiter = m.group(3); + + // --- FIX: Detect greedy regex consuming commas into the type name --- + // Same issue as the other call sites: FIELD_DECL_PATTERN greedily consumes + // multi-declarator commas into group(1). Handle by extracting the real type + // and first variable, then scanning continuations from the first comma. + int commaInType = MultiDeclaratorParser.findFirstDepthZeroComma(typeNameRaw); + if (commaInType >= 0) { + String realTypeNameRaw = MultiDeclaratorParser.extractRealTypeFromGreedyMatch(typeNameRaw, commaInType); + String firstVar = MultiDeclaratorParser.extractFirstVarFromGreedyMatch(typeNameRaw, commaInType); + int firstVarAbsPos = MultiDeclaratorParser.findFirstVarPosition( + rangeText, m.start(1), typeNameRaw, commaInType) + start; + + // Skip control flow keywords on the real type + if (realTypeNameRaw.equals("return") || realTypeNameRaw.equals("if") || realTypeNameRaw.equals("while") || + realTypeNameRaw.equals("for") || realTypeNameRaw.equals("switch") || realTypeNameRaw.equals("catch") || + realTypeNameRaw.equals("new") || realTypeNameRaw.equals("throw")) { + continue; + } + + String greedyTypeName = stripModifiers(realTypeNameRaw); + int greedyModifiers = parseModifiers(realTypeNameRaw); + TypeInfo greedyVarType = resolveType(greedyTypeName, firstVarAbsPos); + + // Register the first variable + FieldInfo firstField = FieldInfo.localField(firstVar, greedyVarType, firstVarAbsPos, + null, -1, -1, greedyModifiers); + scope.addLocal(firstVar, firstField); + + // Scan continuations from the first depth-0 comma + final TypeInfo greedySharedType = greedyVarType; + final int greedySharedMod = greedyModifiers; + final InnerCallableScope fScope3 = scope; + int greedyScanStart = m.start(1) + commaInType; + MultiDeclaratorParser.scanJavaContinuationDeclarators(rangeText, greedyScanStart, start, + (cVarName, cAbsNamePos, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + FieldInfo cField = FieldInfo.localField(cVarName, greedySharedType, cAbsNamePos, + null, cAbsInitStart, cAbsInitEnd, greedySharedMod); + fScope3.addLocal(cVarName, cField); + }); + continue; + } + + // Skip control flow keywords + if (typeNameRaw.equals("return") || typeNameRaw.equals("if") || typeNameRaw.equals("while") || + typeNameRaw.equals("for") || typeNameRaw.equals("switch") || typeNameRaw.equals("catch") || + typeNameRaw.equals("new") || typeNameRaw.equals("throw")) { + continue; + } + + String typeName = stripModifiers(typeNameRaw); + int modifiers = parseModifiers(typeNameRaw); + + TypeInfo varType = null; + if (!typeName.equals("var") && !typeName.equals("let") && !typeName.equals("const")) { + varType = resolveType(typeName); + } else if (delimiter.equals("=")) { + // Infer type from initializer + int rhsStart = start + m.end(); + varType = inferTypeFromExpression(rhsStart); + } + + int initStart = -1, initEnd = -1; + if ("=".equals(delimiter)) { + initStart = start + m.start(3); + int searchPos = start + m.end(3); + int depth = 0; + int angleDepth = 0; + while (searchPos < end) { + char c = text.charAt(searchPos); + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') depth--; + else if (c == '<') angleDepth++; + else if (c == '>') angleDepth--; + else if ((c == ';' || c == ',') && depth == 0 && angleDepth == 0) { + initEnd = searchPos; + break; + } + searchPos++; + } + } + + int absPos = start + m.start(2); + FieldInfo localVar = FieldInfo.localField(varName, varType, absPos, null, initStart, initEnd, modifiers); + scope.addLocal(varName, localVar); + + // Multi-declarator continuation for Java: "int x, y = 2, z;" + final TypeInfo sharedType = varType; + final int sharedModifiers = modifiers; + final InnerCallableScope fScope2 = scope; + int javaScanStart = MultiDeclaratorParser.javaDeclaratorScanStart(rangeText, delimiter, m.end(3), + initEnd >= 0 ? initEnd - start : -1); + if (javaScanStart >= 0) { + MultiDeclaratorParser.scanJavaContinuationDeclarators(rangeText, javaScanStart, start, + (cVarName, cAbsNamePos, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + FieldInfo cField = FieldInfo.localField(cVarName, sharedType, cAbsNamePos, + null, cAbsInitStart, cAbsInitEnd, sharedModifiers); + fScope2.addLocal(cVarName, cField); + }); + } + } + } + + /** + * Parse JS local variable declarations in the range [start, end). + * Pattern: var/let/const varName = ... + */ + private void parseJSLocalsInRange(int start, int end, InnerCallableScope scope) { + String rangeText = text.substring(start, Math.min(end, text.length())); + + Pattern varPattern = Pattern.compile("(?:var|let|const)\\s+(\\w+)(?:\\s*(=))?"); + Matcher m = varPattern.matcher(rangeText); + + while (m.find()) { + int declPos = start + m.start(); + if (declPos < start || declPos >= end) continue; + if (isExcluded(declPos)) continue; + + int afterVar = m.end(1); + if (afterVar < rangeText.length()) { + String rest = rangeText.substring(afterVar); + if (rest.length() > 0 && java.util.regex.Pattern.compile("^\\s+(?:in|of)\\s").matcher(rest).find()) continue; + } + + String varName = m.group(1); + String initializer = null; + int initializerStart = -1; + int initializerEnd = -1; + if (m.group(2) != null) { + initializerStart = skipSegmentWhitespace(rangeText, m.end(2)); + // Use comma-aware termination so multi-declarator RHS is bounded correctly + initializerEnd = findJsInitializerEnd(rangeText, initializerStart, true); + if (initializerEnd > initializerStart) { + initializer = rangeText.substring(initializerStart, initializerEnd).trim(); + if (initializer.isEmpty()) { + initializer = null; + } + } + } + + // Check for JSDoc type annotation + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, declPos); + + TypeInfo varType = null; + + // Priority 1: JSDoc @type + if (jsDoc != null && jsDoc.hasTypeTag()) { + varType = jsDoc.getDeclaredType(); + } + + // Priority 2: Infer from initializer + if (varType == null && initializer != null && !initializer.isEmpty()) { + TypeInfo inferred = resolveExpressionType(initializer, start + initializerStart); + if (!TypeInfo.NULL.equals(inferred)) { + varType = inferred; + } + } + + // Priority 3: Use "any" type + if (varType == null) { + varType = TypeInfo.ANY; + } + + int initStart = -1, initEnd = -1; + if (m.group(2) != null) { + initStart = start + m.start(2); + initEnd = (initializerEnd >= 0) ? start + initializerEnd : start + m.end(2); + } + + int absPos = start + m.start(1); + FieldInfo localVar = FieldInfo.localField(varName, varType, absPos, null, initStart, initEnd, 0); + + if (jsDoc != null) { + localVar.setJSDocInfo(jsDoc); + } + + scope.addLocal(varName, localVar); + + // Multi-declarator continuation: scan for "var a=1, b, c=3" + final InnerCallableScope fScope = scope; + int contScanStart = MultiDeclaratorParser.jsDeclaratorScanStart(rangeText, m.end(1), m.group(2) != null, initializerEnd); + MultiDeclaratorParser.scanJSContinuationDeclarators(this, rangeText, contScanStart, start, + (cVarName, cAbsNamePos, cInit, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + TypeInfo cType = null; + if (cInit != null && !cInit.isEmpty()) { + TypeInfo inferred = resolveExpressionType(cInit, cAbsInitStart); + if (!TypeInfo.NULL.equals(inferred)) cType = inferred; + } + if (cType == null) cType = TypeInfo.ANY; + FieldInfo cField = FieldInfo.localField(cVarName, cType, cAbsNamePos, null, + cAbsInitStart, cAbsInitEnd, 0); + fScope.addLocal(cVarName, cField); + }); + } + } + + int skipSegmentWhitespace(String source, int pos) { + while (pos < source.length() && Character.isWhitespace(source.charAt(pos))) { + pos++; + } + return pos; + } + + /** + * Scans forward from {@code rhsStart} to find where a JavaScript initializer expression ends. + * + * Unlike Java, JS has no mandatory semicolons, so this method implements a conservative + * ASI (Automatic Semicolon Insertion) heuristic: + *

    + *
  • A {@code ;} at depth 0 always terminates the expression.
  • + *
  • A newline while inside open parens, brackets, or braces does NOT terminate — + * the expression continues on the next line (e.g. multi-line object literals, + * chained calls).
  • + *
  • A newline at depth 0 terminates only if {@link #shouldContinueJsInitializer} + * says the line break is NOT a continuation. Continuation is inferred from + * the current line ending with an operator/open-bracket, or the next line + * starting with {@code .}, {@code ?.}, or {@code [}.
  • + *
+ * + * String literals (single/double-quoted) and both comment forms ({@code //} and + * {@code /* ... *\/}) are skipped so their contents never affect depth tracking. + * + * @param source the full source text to scan + * @param rhsStart the index to begin scanning (typically the character after {@code =}) + * @return the index of the terminating character (a {@code ;} or newline), or + * {@code source.length()} if the source ends before a terminator is found. + * Returns {@code rhsStart} unchanged if {@code rhsStart} is out of bounds. + */ + int findJsInitializerEnd(String source, int rhsStart) { + return findJsInitializerEnd(source, rhsStart, false); + } + + int findJsInitializerEnd(String source, int rhsStart, boolean stopAtTopLevelComma) { + if (rhsStart < 0 || rhsStart >= source.length()) { + return rhsStart; + } + + int pos = rhsStart; + int lineExprStart = rhsStart; + + int parenDepth = 0; + int bracketDepth = 0; + int braceDepth = 0; + + boolean inString = false; + char stringChar = 0; + boolean inLineComment = false; + boolean inBlockComment = false; + + while (pos < source.length()) { + char c = source.charAt(pos); + char next = (pos + 1 < source.length()) ? source.charAt(pos + 1) : 0; + + if (inLineComment) { + if (c == '\n' || c == '\r') { + inLineComment = false; + } else { + pos++; + continue; + } + } + + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + pos += 2; + continue; + } + pos++; + continue; + } + + if (inString) { + if (c == '\\') { + pos += (pos + 1 < source.length()) ? 2 : 1; + continue; + } + if (c == stringChar) { + inString = false; + } + pos++; + continue; + } + + if (c == '/' && next == '/') { + inLineComment = true; + pos += 2; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + pos += 2; + continue; + } + + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + pos++; + continue; + } + + if (c == '(') { + parenDepth++; + } else if (c == ')') { + parenDepth = Math.max(0, parenDepth - 1); + } else if (c == '[') { + bracketDepth++; + } else if (c == ']') { + bracketDepth = Math.max(0, bracketDepth - 1); + } else if (c == '{') { + braceDepth++; + } else if (c == '}') { + braceDepth = Math.max(0, braceDepth - 1); + } + + if (c == ';' && parenDepth == 0 && bracketDepth == 0 && braceDepth == 0) { + return pos; + } + + if (stopAtTopLevelComma && c == ',' && parenDepth == 0 && bracketDepth == 0 && braceDepth == 0) { + return pos; + } + + if (c == '\n' || c == '\r') { + int lineBreakPos = pos; + int nextPos = pos + 1; + if (c == '\r' && nextPos < source.length() && source.charAt(nextPos) == '\n') { + nextPos++; + } + + if (parenDepth != 0 || bracketDepth != 0 || braceDepth != 0) { + pos = nextPos; + lineExprStart = nextPos; + continue; + } + + int currentLineEnd = lineBreakPos; + while (currentLineEnd > lineExprStart && Character.isWhitespace(source.charAt(currentLineEnd - 1))) { + currentLineEnd--; + } + String currentLineExpr = source.substring(lineExprStart, currentLineEnd); + + int nextExprStart = nextPos; + while (nextExprStart < source.length()) { + char n = source.charAt(nextExprStart); + if (n == ' ' || n == '\t') { + nextExprStart++; + continue; + } + if (n == ';') { + return nextExprStart; + } + if (n == '\n' || n == '\r') { + nextExprStart++; + if (n == '\r' && nextExprStart < source.length() && source.charAt(nextExprStart) == '\n') { + nextExprStart++; + } + continue; + } + break; + } + + if (nextExprStart >= source.length()) { + return source.length(); + } + + int nextLineEnd = nextExprStart; + while (nextLineEnd < source.length()) { + char n = source.charAt(nextLineEnd); + if (n == '\n' || n == '\r' || n == ';') { + break; + } + nextLineEnd++; + } + String nextLineExpr = source.substring(nextExprStart, nextLineEnd).trim(); + + if (!shouldContinueJsInitializer(currentLineExpr, nextLineExpr)) { + return lineBreakPos; + } + + pos = nextExprStart; + lineExprStart = nextExprStart; + continue; + } + pos++; + } + return source.length(); + } + + private boolean shouldContinueJsInitializer(String currentLineExpr, String nextLineExpr) { + if (nextLineExpr.isEmpty()) { + return false; + } + + if (nextLineExpr.startsWith(".") || nextLineExpr.startsWith("?.") || nextLineExpr.startsWith("[")) { + return true; + } + + String current = currentLineExpr.trim(); + if (current.isEmpty()) { + return false; + } + + char tail = current.charAt(current.length() - 1); + return tail == '+' || tail == '-' || tail == '*' || tail == '/' || tail == '%' || + tail == '&' || tail == '|' || tail == '^' || tail == '!' || tail == '=' || + tail == '<' || tail == '>' || tail == '?' || tail == ':' || tail == ',' || + tail == '.' || tail == '(' || tail == '[' || tail == '{'; + } + + /** + * Infer the type of an expression starting at the given position. + * Handles patterns like: + * - "new TypeName()" - returns TypeName + * - "receiver.fieldOrMethod" - resolves chain and returns result type + * - "variable" - looks up variable type + * - Literals like numbers, strings, booleans + */ + private TypeInfo inferTypeFromExpression(int position) { + // Skip whitespace + while (position < text.length() && Character.isWhitespace(text.charAt(position))) + position++; + + if (position >= text.length()) + return null; + + // Check for 'new' keyword + if (text.startsWith("new ", position)) { + position += 4; + while (position < text.length() && Character.isWhitespace(text.charAt(position))) + position++; + + // Read the type name + int typeStart = position; + while (position < text.length() && Character.isJavaIdentifierPart(text.charAt(position))) + position++; + + if (position > typeStart) { + String typeName = text.substring(typeStart, position); + return resolveType(typeName, typeStart); + } + return null; + } + + // Check for string literal + if (position < text.length() && (text.charAt(position) == '"' || text.charAt(position) == '\'')) { + return resolveType("String"); + } + + // Check for numeric literal + if (position < text.length() && Character.isDigit(text.charAt(position))) { + // Check for float/double (has decimal point or f/d suffix) + int numEnd = position; + boolean hasDecimal = false; + while (numEnd < text.length() && (Character.isDigit(text.charAt(numEnd)) || + text.charAt(numEnd) == '.' || text.charAt(numEnd) == 'f' || + text.charAt(numEnd) == 'd' || text.charAt(numEnd) == 'F' || + text.charAt(numEnd) == 'D' || text.charAt(numEnd) == 'L' || + text.charAt(numEnd) == 'l')) { + if (text.charAt(numEnd) == '.') hasDecimal = true; + numEnd++; + } + String num = text.substring(position, numEnd).toLowerCase(); + if (num.endsWith("f")) return resolveType("float"); + if (num.endsWith("d") || hasDecimal) return resolveType("double"); + if (num.endsWith("l")) return resolveType("long"); + return resolveType("int"); + } + + // Check for boolean literals + if (text.startsWith("true", position) || text.startsWith("false", position)) { + return resolveType("boolean"); + } + + // Check for null + if (text.startsWith("null", position)) { + return null; // Can't infer type from null + } + + // Must be an identifier or chain - read the first identifier + if (Character.isJavaIdentifierStart(text.charAt(position))) { + int identStart = position; + while (position < text.length() && Character.isJavaIdentifierPart(text.charAt(position))) + position++; + String ident = text.substring(identStart, position); + + // Skip whitespace + while (position < text.length() && Character.isWhitespace(text.charAt(position))) + position++; + + // Check if this is the start of a chain (followed by .) + if (position < text.length() && text.charAt(position) == '.') { + // This is a chain like "event.player" or "Minecraft.getMinecraft()" + // We need to resolve the entire chain to get the final type + return inferChainType(ident, identStart, position); + } + + // Check if this is a method call (followed by ()) + if (position < text.length() && text.charAt(position) == '(') { + // Method call - check if it's a script method + if (isScriptMethod(ident)) { + MethodInfo methodInfo = getScriptMethodInfo(ident); + return (methodInfo != null) ? methodInfo.getReturnType() : null; + } + return null; + } + + // Just a variable - resolve its type + FieldInfo varInfo = resolveVariable(ident, identStart); + return (varInfo != null) ? varInfo.getTypeInfo() : null; + } + + return null; + } + + /** + * Infer the type from a chain expression starting with the given identifier. + */ + private TypeInfo inferChainType(String firstIdent, int identStart, int dotPosition) { + TypeInfo currentType = null; + + // Resolve the first segment + if ("this".equals(firstIdent)) { + currentType = resolveThisType(identStart); + } + + TypeInfo typeCheck = resolveType(firstIdent, identStart); + if (currentType == null && typeCheck != null && typeCheck.isResolved()) { + // Static access like Event.player or scriptType.field + currentType = typeCheck; + } else if (currentType == null) { + // Variable access + FieldInfo varInfo = resolveVariable(firstIdent, identStart); + currentType = (varInfo != null) ? varInfo.getTypeInfo() : null; + } + + if (currentType == null || !currentType.isResolved()) + return null; + + // Now resolve the rest of the chain + int pos = dotPosition; + while (pos < text.length() && text.charAt(pos) == '.') { + pos++; // Skip the dot + + // Skip whitespace + while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) + pos++; + + if (pos >= text.length() || !Character.isJavaIdentifierStart(text.charAt(pos))) + break; + + // Read the next identifier + int segStart = pos; + while (pos < text.length() && Character.isJavaIdentifierPart(text.charAt(pos))) + pos++; + String segment = text.substring(segStart, pos); + + // Skip whitespace + while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) + pos++; + + // Check if this is a method call + if (pos < text.length() && text.charAt(pos) == '(') { + // Method call + if (currentType.hasMethod(segment)) { + // Parse argument types + int closeParen = findMatchingParen(pos); + if (closeParen < 0) return null; + String argsText = text.substring(pos + 1, closeParen).trim(); + TypeInfo[] argTypes = parseArgumentTypes(argsText, pos + 1); + + // Check if this is a synthetic type with dynamic return type resolver (like Java.type()) + SyntheticType syntheticType = null; + if (isJavaScript() && typeResolver.isSyntheticType(firstIdent)) { + syntheticType = typeResolver.getSyntheticType(firstIdent); + } + + if (syntheticType != null && syntheticType.hasMethod(segment)) { + SyntheticMethod synMethod = syntheticType.getMethod(segment); + if (synMethod != null) { + // Try dynamic resolution first + String[] strArgs = TypeResolver.parseStringArguments(argsText); + TypeInfo dynamicType = synMethod.resolveReturnType(strArgs); + if (dynamicType != null) { + currentType = dynamicType; + } else { + // Fall back to static return type + currentType = synMethod.getReturnTypeInfo(); + } + } + } else { + MethodInfo methodInfo = currentType.getBestMethodOverload(segment, argTypes); + currentType = (methodInfo != null) ? methodInfo.getReturnType() : null; + } + + // Skip to after the closing paren + pos = closeParen + 1; + } else { + return null; + } + } else { + // Field access + if (currentType.hasField(segment)) { + FieldInfo fieldInfo = currentType.getFieldInfo(segment); + currentType = (fieldInfo != null) ? fieldInfo.getTypeInfo() : null; + } else { + return null; + } + } + + if (currentType == null || !currentType.isResolved()) + return null; + + // Skip whitespace for next iteration + while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) + pos++; + } + + return currentType; + } + + /** + * Parse inner callable scopes (lambdas and JS function expressions). + * These are NOT added to the methods list - they're resolution-only scopes. + */ + private void parseInnerCallableScopes() { + // For Java: detect (params) -> expr and (params) -> { ... } and param -> expr + // For JS: detect function(params) { ... } that are expressions (not declarations) + + if (isJavaScript()) { + parseJSFunctionExpressions(); + parseJSArrowFunctions(); + parseJSShorthandMethods(); + } else { + parseJavaLambdas(); + } + + // Sort by header start and set up parent relationships + innerScopes.sort((a, b) -> Integer.compare(a.getHeaderStart(), b.getHeaderStart())); + setupScopeParents(); + } + + private void parseJavaLambdas() { + // Pattern: (params) -> or identifier -> + // Look for -> that's not inside strings/comments + String arrowPattern = "->"; + int pos = 0; + while ((pos = text.indexOf(arrowPattern, pos)) >= 0) { + if (isExcluded(pos)) { + pos += 2; + continue; + } + + // Found a potential lambda arrow + int arrowPos = pos; + + // Look backwards to find the parameter list + int headerStart = findLambdaHeaderStart(arrowPos); + if (headerStart < 0) { + pos += 2; + continue; + } + + // Look forward to find the body end + int bodyStart = arrowPos + 2; + // Skip whitespace after -> + while (bodyStart < text.length() && Character.isWhitespace(text.charAt(bodyStart))) { + bodyStart++; + } + + if (bodyStart >= text.length()) { + pos += 2; + continue; + } + + int bodyEnd; + if (text.charAt(bodyStart) == '{') { + // Block lambda + bodyEnd = findMatchingBrace(bodyStart); + if (bodyEnd < 0) bodyEnd = text.length(); + else bodyEnd++; // Include the closing brace + } else { + // Expression lambda - find end of expression + bodyEnd = findLambdaExpressionEnd(bodyStart); + } + + InnerCallableScope scope = new InnerCallableScope( + InnerCallableScope.Kind.JAVA_LAMBDA, + headerStart, + arrowPos + 2, + bodyStart, + bodyEnd + ); + + // Parse parameters (will be typed later during resolution) + parseLambdaParameters(scope, headerStart, arrowPos); + + innerScopes.add(scope); + pos = bodyEnd; + } + } + + private int findLambdaHeaderStart(int arrowPos) { + // Work backwards from arrow to find start of parameter list + int pos = arrowPos - 1; + + // Skip whitespace + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + + if (pos < 0) return -1; + + if (text.charAt(pos) == ')') { + // Parenthesized params: find matching ( + int depth = 1; + pos--; + while (pos >= 0 && depth > 0) { + if (isExcluded(pos)) { + pos--; + continue; + } + char c = text.charAt(pos); + if (c == ')') depth++; + else if (c == '(') depth--; + pos--; + } + return pos + 1; // Position of '(' + } else if (Character.isJavaIdentifierPart(text.charAt(pos))) { + // Single identifier param (no parens): identifier -> + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) { + pos--; + } + return pos + 1; + } + + return -1; + } + + private int findLambdaExpressionEnd(int start) { + // Find end of expression lambda body + // Ends at: ; , ) ] } (at depth 0) or end of text + int depth = 0; + int angleDepth = 0; + int pos = start; + boolean inString = false; + char stringChar = 0; + + while (pos < text.length()) { + char c = text.charAt(pos); + + // Handle strings + if (!inString && (c == '"' || c == '\'')) { + inString = true; + stringChar = c; + pos++; + continue; + } + if (inString) { + if (c == stringChar && (pos == 0 || text.charAt(pos - 1) != '\\')) { + inString = false; + } + pos++; + continue; + } + + // Track nesting + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') { + if (depth == 0) return pos; + depth--; + } + else if (c == '<') angleDepth++; + else if (c == '>') angleDepth = Math.max(0, angleDepth - 1); + else if ((c == ';' || c == ',') && depth == 0 && angleDepth == 0) { + return pos; + } + + pos++; + } + + return pos; + } + + private void parseLambdaParameters(InnerCallableScope scope, int headerStart, int arrowPos) { + String headerText = text.substring(headerStart, arrowPos).trim(); + + if (headerText.startsWith("(") && headerText.endsWith(")")) { + // Parenthesized: (a, b) or (Type a, Type b) + String paramsText = headerText.substring(1, headerText.length() - 1).trim(); + if (!paramsText.isEmpty()) { + String[] params = paramsText.split(","); + int offset = headerStart + 1; // After '(' + for (String param : params) { + param = param.trim(); + if (param.isEmpty()) continue; + + // Find position in original text + // Search within a reasonable window to avoid matching shadowed names from outer scopes + int paramOffset = text.indexOf(param, offset); + if (paramOffset < 0) paramOffset = offset; + // Validate that we found it within expected range (before next comma or closing paren) + int nextComma = text.indexOf(',', offset); + int nextClose = text.indexOf(')', offset); + int endBound = Math.min( + nextComma >= 0 ? nextComma : Integer.MAX_VALUE, + nextClose >= 0 ? nextClose : Integer.MAX_VALUE + ); + if (paramOffset >= endBound) { + // Found match is outside the parameter list, use direct offset calculation instead + paramOffset = offset; + } + + String[] parts = param.split("\\s+"); + String paramName; + TypeInfo paramType = null; + + if (parts.length >= 2) { + // Typed: Type name + paramName = parts[parts.length - 1]; + String typeName = parts[parts.length - 2]; + boolean isVarArg = typeName.endsWith("..."); + if (isVarArg) typeName = typeName.substring(0, typeName.length() - 3); + paramType = resolveType(typeName); + // For typed params, the name is after the type, so calculate position more carefully + int nameOffset = paramOffset + (param.lastIndexOf(paramName)); + if (nameOffset < paramOffset || nameOffset >= endBound) + nameOffset = paramOffset + param.length() - paramName.length(); + FieldInfo paramInfo = FieldInfo.parameter(paramName, paramType, nameOffset, null); + paramInfo.setVarArg(isVarArg); + scope.addParameter(paramInfo); + } else { + // Untyped: just name (type will be inferred from expected FI) + paramName = parts[0]; + // For untyped params, the entire param string is the name, so use paramOffset directly + int nameOffset = paramOffset; + FieldInfo paramInfo = FieldInfo.parameter(paramName, paramType, nameOffset, null); + scope.addParameter(paramInfo); + } + + offset = Math.max(paramOffset + param.length(), offset + 1); + } + } + } else { + // Single identifier: x -> + String paramName = headerText; + int nameOffset = text.indexOf(paramName, headerStart); + // Validate found position is before the arrow (not a shadowed name after) + if (nameOffset < 0 || nameOffset >= arrowPos) { + nameOffset = headerStart; + } + + FieldInfo paramInfo = FieldInfo.parameter(paramName, null, nameOffset, null); + scope.addParameter(paramInfo); + } + } + + private void parseJSFunctionExpressions() { + // Pattern: function(params) { ... } or function name(params) { ... } + // But NOT function declarations at top level (those are already in methods) + Pattern funcExprPattern = Pattern.compile("function\\s*(?:\\w+)?\\s*\\(([^)]*)\\)\\s*\\{"); + Matcher m = funcExprPattern.matcher(text); + + while (m.find()) { + int start = m.start(); + if (isExcluded(start)) continue; + + // Check if this is a function expression (not a declaration) + // A function declaration is at statement level; expression is inside parens, after =, etc. + if (isFunctionDeclaration(start)) continue; + + int headerStart = start; + int headerEnd = m.end() - 1; // Position of '{' + int bodyStart = m.end() - 1; + int bodyEnd = findMatchingBrace(bodyStart); + if (bodyEnd < 0) bodyEnd = text.length(); + else bodyEnd++; // Include closing brace + + InnerCallableScope scope = new InnerCallableScope( + InnerCallableScope.Kind.JS_FUNCTION_EXPR, + headerStart, + headerEnd, + bodyStart, + bodyEnd + ); + + // Parse parameters + String paramsText = m.group(1).trim(); + if (!paramsText.isEmpty()) { + String[] params = paramsText.split(","); + int offset = m.start(1); + for (String param : params) { + param = param.trim(); + if (param.isEmpty()) continue; + + int nameOffset = text.indexOf(param, offset); + if (nameOffset < 0) nameOffset = offset; + + // JS params don't have types by default; will infer from expected FI + FieldInfo paramInfo = FieldInfo.parameter(param, TypeInfo.ANY, nameOffset, null); + scope.addParameter(paramInfo); + + offset = nameOffset + param.length(); + } + } + + innerScopes.add(scope); + } + } + + private void parseJSArrowFunctions() { + String arrowToken = "=>"; + int pos = 0; + while ((pos = text.indexOf(arrowToken, pos)) >= 0) { + if (isExcluded(pos)) { + pos += 2; + continue; + } + + int arrowPos = pos; + int headerStart = findArrowFunctionHeaderStart(arrowPos); + if (headerStart < 0) { + pos += 2; + continue; + } + + int bodyStart = arrowPos + 2; + while (bodyStart < text.length() && Character.isWhitespace(text.charAt(bodyStart))) { + bodyStart++; + } + + if (bodyStart >= text.length()) { + pos += 2; + continue; + } + + int bodyEnd; + if (text.charAt(bodyStart) == '{') { + bodyEnd = findMatchingBrace(bodyStart); + if (bodyEnd < 0) bodyEnd = text.length(); + else bodyEnd++; + } else { + bodyEnd = findLambdaExpressionEnd(bodyStart); + } + + InnerCallableScope scope = new InnerCallableScope( + InnerCallableScope.Kind.JS_ARROW_FUNC, + headerStart, + arrowPos + 2, + bodyStart, + bodyEnd + ); + + parseArrowFunctionParameters(scope, headerStart, arrowPos); + innerScopes.add(scope); + pos = bodyEnd; + } + } + + private int findArrowFunctionHeaderStart(int arrowPos) { + int pos = arrowPos - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + if (pos < 0) return -1; + + if (text.charAt(pos) == ')') { + int depth = 1; + pos--; + while (pos >= 0 && depth > 0) { + if (isExcluded(pos)) { pos--; continue; } + char c = text.charAt(pos); + if (c == ')') depth++; + else if (c == '(') depth--; + pos--; + } + return pos + 1; + } else if (Character.isJavaIdentifierPart(text.charAt(pos))) { + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) { + pos--; + } + return pos + 1; + } + return -1; + } + + private void parseArrowFunctionParameters(InnerCallableScope scope, int headerStart, int arrowPos) { + String headerText = text.substring(headerStart, arrowPos).trim(); + + if (headerText.startsWith("(") && headerText.endsWith(")")) { + String paramsText = headerText.substring(1, headerText.length() - 1).trim(); + if (!paramsText.isEmpty()) { + String[] params = paramsText.split(","); + int offset = headerStart + 1; + for (String param : params) { + param = param.trim(); + if (param.isEmpty()) continue; + + int nameOffset = text.indexOf(param, offset); + if (nameOffset < 0) nameOffset = offset; + + FieldInfo paramInfo = FieldInfo.parameter(param, TypeInfo.ANY, nameOffset, null); + scope.addParameter(paramInfo); + offset = nameOffset + param.length(); + } + } + } else { + if (ObjectLiteralParser.isSimpleIdentifier(headerText)) { + int nameOffset = text.indexOf(headerText, headerStart); + if (nameOffset < 0) nameOffset = headerStart; + FieldInfo paramInfo = FieldInfo.parameter(headerText, TypeInfo.ANY, nameOffset, null); + scope.addParameter(paramInfo); + } + } + } + + private void parseJSShorthandMethods() { + Pattern shorthandPattern = Pattern.compile("(\\w+)\\s*\\(([^)]*)\\)\\s*\\{"); + Matcher m = shorthandPattern.matcher(text); + + while (m.find()) { + int start = m.start(); + if (isExcluded(start)) continue; + + if (!ObjectLiteralParser.isInsideObjectLiteral(start,this)) continue; + + String methodName = m.group(1); + if (TypeChecker.isJavaScriptKeyword(methodName)) continue; + + int headerStart = m.start(1); + int bodyStart = m.end() - 1; + int bodyEnd = findMatchingBrace(bodyStart); + if (bodyEnd < 0) bodyEnd = text.length(); + else bodyEnd++; + + InnerCallableScope scope = new InnerCallableScope( + InnerCallableScope.Kind.JS_SHORTHAND_METHOD, + headerStart, + bodyStart, + bodyStart, + bodyEnd + ); + + String paramsText = m.group(2).trim(); + if (!paramsText.isEmpty()) { + String[] params = paramsText.split(","); + int offset = m.start(2); + for (String param : params) { + param = param.trim(); + if (param.isEmpty()) continue; + + int nameOffset = text.indexOf(param, offset); + if (nameOffset < 0) nameOffset = offset; + + FieldInfo paramInfo = FieldInfo.parameter(param, TypeInfo.ANY, nameOffset, null); + scope.addParameter(paramInfo); + offset = nameOffset + param.length(); + } + } + + innerScopes.add(scope); + } + } + + private boolean isFunctionDeclaration(int funcStart) { + // A function declaration is a statement, check context: + // - If preceded by = or ( or , or : or [ it's an expression + // - If at line start (possibly with whitespace) or after { or ; it's a declaration + + int pos = funcStart - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos)) && text.charAt(pos) != '\n') { + pos--; + } + + if (pos < 0) return true; // Start of file = declaration + + char prev = text.charAt(pos); + // These characters indicate it's an expression, not a declaration + if (prev == '=' || prev == '(' || prev == ',' || prev == ':' || prev == '[' || prev == '?') { + return false; + } + // After newline + whitespace could be declaration + if (prev == '\n' || prev == '{' || prev == ';' || prev == '}') { + return true; + } + + return true; // Default to declaration to avoid false positives in inner scopes + } + + private void setupScopeParents() { + // For each scope, find its immediate parent (smallest enclosing scope) + for (int i = 0; i < innerScopes.size(); i++) { + InnerCallableScope scope = innerScopes.get(i); + InnerCallableScope parent = null; + + for (int j = 0; j < innerScopes.size(); j++) { + if (i == j) continue; + InnerCallableScope candidate = innerScopes.get(j); + + // Check if candidate contains scope + if (candidate.getBodyStart() < scope.getHeaderStart() && + candidate.getBodyEnd() > scope.getFullEnd()) { + // candidate contains scope + if (parent == null || + (candidate.getBodyStart() > parent.getBodyStart())) { + // candidate is smaller (more immediate) than current parent + parent = candidate; + } + } + } + + scope.setParentScope(parent); + } + } + + /** + * Parse global fields/variables (outside methods) - UNIFIED for both Java and JavaScript. + * Stores results in the shared 'globalFields' map. + * + * For Java: Parses "[modifiers] Type fieldName [= expr];" + * For JavaScript: Parses "var/let/const varName [= expr];" outside of functions + */ + private void parseGlobalFields() { + if (isJavaScript()) { + // JavaScript: var/let/const varName = expr; (outside functions) + Pattern varPattern = Pattern.compile("(?:var|let|const)\\s+(\\w+)(?:\\s*(=))?"); + Matcher m = varPattern.matcher(text); + + while (m.find()) { + int position = m.start(1); + if (isExcluded(position)) continue; + + // Check if inside a function - if so, skip (handled by parseLocalVariables) + boolean insideMethod = false; + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(position)) { + insideMethod = true; + break; + } + } + if (!insideMethod) { + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(position)) { + insideMethod = true; + break; + } + } + } + if (insideMethod) continue; + + boolean insideInner = false; + for (InnerCallableScope scope : innerScopes) { + if (scope.containsPosition(position)) { + insideInner = true; + break; + } + } + if (insideInner) continue; + + int afterVar = m.end(1); + if (afterVar < text.length() && LoopVariableParser.FOR_IN_OF_LOOKAHEAD.matcher(text.substring(afterVar)).find()) continue; + + String varName = m.group(1); + String initializer = null; + int initializerStart = -1; + int initializerEnd = -1; + if (m.group(2) != null) { + initializerStart = skipSegmentWhitespace(text, m.end(2)); + // Use comma-aware termination for multi-declarator support + initializerEnd = findJsInitializerEnd(text, initializerStart, true); + if (initializerEnd > initializerStart) { + initializer = text.substring(initializerStart, initializerEnd).trim(); + if (initializer.isEmpty()) { + initializer = null; + } + } + } + + // First, check for JSDoc type annotation + String documentation = extractDocumentationBefore(m.start()); + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, m.start()); + + TypeInfo typeInfo = null; + + // Priority 1: JSDoc @type takes precedence + if (jsDoc != null && jsDoc.hasTypeTag()) { + typeInfo = jsDoc.getDeclaredType(); + } + + // Priority 2: Infer from initializer if no JSDoc type + if (typeInfo == null && initializer != null && !initializer.isEmpty()) { + TypeInfo inferred = resolveExpressionType(initializer, initializerStart); + if (!TypeInfo.NULL.equals(inferred)) { + typeInfo = inferred; + } + } + + // Priority 3: Use "any" type for uninitialized variables + if (typeInfo == null) { + typeInfo = TypeInfo.ANY; + } + + int initStart = -1, initEnd = -1; + if (m.group(2) != null) { + initStart = m.start(2); + initEnd = (initializerEnd >= 0) ? initializerEnd : m.end(2); + } + + FieldInfo fieldInfo = FieldInfo.globalField(varName, typeInfo, position, documentation, initStart, initEnd, 0); + + if(jsDoc != null) + fieldInfo.setJSDocInfo(jsDoc); + + if (globalFields.containsKey(varName)) { + AssignmentInfo dupError = AssignmentInfo.duplicateDeclaration( + varName, position, position + varName.length(), + "Variable '" + varName + "' is already defined in the scope"); + declarationErrors.add(dupError); + } else { + globalFields.put(varName, fieldInfo); + } + + // Multi-declarator continuation for global JS: "var a=1, b='x', c;" + int contScanStart = MultiDeclaratorParser.jsDeclaratorScanStart(text, m.end(1), m.group(2) != null, initializerEnd); + MultiDeclaratorParser.scanJSContinuationDeclarators(this, text, contScanStart, 0, + (cVarName, cAbsNamePos, cInit, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + boolean cInsideMethod = false; + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(cAbsNamePos)) { cInsideMethod = true; break; } + } + if (!cInsideMethod) { + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(cAbsNamePos)) { cInsideMethod = true; break; } + } + } + if (cInsideMethod) return; + boolean cInsideInner = false; + for (InnerCallableScope sc : innerScopes) { + if (sc.containsPosition(cAbsNamePos)) { cInsideInner = true; break; } + } + if (cInsideInner) return; + + TypeInfo cType = null; + if (cInit != null && !cInit.isEmpty()) { + TypeInfo inferred = resolveExpressionType(cInit, cAbsInitStart); + if (!TypeInfo.NULL.equals(inferred)) cType = inferred; + } + if (cType == null) cType = TypeInfo.ANY; + + FieldInfo cField = FieldInfo.globalField(cVarName, cType, cAbsNamePos, null, + cAbsInitStart, cAbsInitEnd, 0); + if (globalFields.containsKey(cVarName)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + cVarName, cAbsNamePos, cAbsNamePos + cVarName.length(), + "Variable '" + cVarName + "' is already defined in the scope"); + declarationErrors.add(dupErr); + } else { + globalFields.put(cVarName, cField); + } + }); + } + } else { + // Java: [modifiers] Type fieldName [= expr]; + Matcher m = FIELD_DECL_PATTERN.matcher(normalizeGenericNewlines(text)); + while (m.find()) { + String typeNameRaw = m.group(1); + String fieldName = m.group(2); + String delimiter = m.group(3); + int position = m.start(2); + + if (isExcluded(position)) + continue; + + // Guard against cross-line matches that start inside a comment + if (isExcluded(m.start(1))) + continue; + + if (hasExcludedRange(m.start(1), m.end(1))) + continue; + + // --- FIX: Detect greedy regex consuming commas into the type name --- + // Same issue as parseLocalVariables: FIELD_DECL_PATTERN greedily consumes + // multi-declarator commas into group(1). When a depth-0 comma exists in + // typeNameRaw, extract the real type and first variable, then let the + // continuation scanner handle ALL variables. + int commaInType = MultiDeclaratorParser.findFirstDepthZeroComma(typeNameRaw); + if (commaInType >= 0) { + String realTypeNameRaw = MultiDeclaratorParser.extractRealTypeFromGreedyMatch(typeNameRaw, commaInType); + String firstVar = MultiDeclaratorParser.extractFirstVarFromGreedyMatch(typeNameRaw, commaInType); + int firstVarAbsPos = MultiDeclaratorParser.findFirstVarPosition( + text, m.start(1), typeNameRaw, commaInType); + + if (isExcluded(firstVarAbsPos)) continue; + + int enclosingParen1 = findEnclosingParenStart(0, firstVarAbsPos); + if (enclosingParen1 >= 0 && "for".equals(readKeywordBefore(enclosingParen1))) continue; + + int greedyModifiers = parseModifiers(realTypeNameRaw); + String greedyTypeName = stripModifiers(realTypeNameRaw); + + // Use findEnclosingScriptType (recursive descent) so inner class fields + // are attributed to the innermost containing type, not just the first + // HashMap match (which could be the outer class). + ScriptTypeInfo greedyContainingType = findEnclosingScriptType(firstVarAbsPos); + + boolean greedyInsideMethod = false; + if (greedyContainingType != null && isInsideNestedMethod(firstVarAbsPos, + greedyContainingType.getBodyStart(), greedyContainingType.getBodyEnd())) + greedyInsideMethod = true; + else { + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(firstVarAbsPos)) { greedyInsideMethod = true; break; } + } + if (!greedyInsideMethod) { + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(firstVarAbsPos)) { greedyInsideMethod = true; break; } + } + } + } + if (greedyInsideMethod) continue; + + String greedyDocumentation = extractDocumentationBefore(m.start()); + TypeInfo greedyTypeInfo = resolveType(greedyTypeName, firstVarAbsPos); + + // Register the first variable (no initializer since the regex consumed it into the type group) + FieldInfo firstField = FieldInfo.globalField(firstVar, greedyTypeInfo, firstVarAbsPos, + greedyDocumentation, -1, -1, greedyModifiers); + if (greedyContainingType != null) { + greedyContainingType.addField(firstField); + } else if (globalFields.containsKey(firstVar)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + firstVar, firstVarAbsPos, firstVarAbsPos + firstVar.length(), + "Variable '" + firstVar + "' is already defined in the scope"); + declarationErrors.add(dupErr); + } else { + globalFields.put(firstVar, firstField); + } + + // Scan continuations from the first depth-0 comma in the type group + final TypeInfo greedySharedType = greedyTypeInfo; + final int greedySharedMod = greedyModifiers; + final ScriptTypeInfo fGreedyContType = greedyContainingType; + int greedyScanStart = m.start(1) + commaInType; + MultiDeclaratorParser.scanJavaContinuationDeclarators(text, greedyScanStart, 0, + (cVarName, cAbsNamePos, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + boolean cInsideMethod = false; + if (fGreedyContType != null && isInsideNestedMethod(cAbsNamePos, + fGreedyContType.getBodyStart(), fGreedyContType.getBodyEnd())) + cInsideMethod = true; + else { + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(cAbsNamePos)) { cInsideMethod = true; break; } + } + if (!cInsideMethod) { + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(cAbsNamePos)) { cInsideMethod = true; break; } + } + } + } + if (cInsideMethod) return; + + FieldInfo cField = FieldInfo.globalField(cVarName, greedySharedType, cAbsNamePos, + null, cAbsInitStart, cAbsInitEnd, greedySharedMod); + if (fGreedyContType != null) { + fGreedyContType.addField(cField); + } else if (globalFields.containsKey(cVarName)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + cVarName, cAbsNamePos, cAbsNamePos + cVarName.length(), + "Variable '" + cVarName + "' is already defined in the scope"); + declarationErrors.add(dupErr); + } else { + globalFields.put(cVarName, cField); + } + }); + continue; + } + + int enclosingParen = findEnclosingParenStart(0, position); + if (enclosingParen >= 0 && "for".equals(readKeywordBefore(enclosingParen))) + continue; + + int modifiers = parseModifiers(typeNameRaw); + String typeName = stripModifiers(typeNameRaw); + + // Use findEnclosingScriptType (recursive descent) so inner class fields + // are attributed to the innermost containing type, not just the first + // HashMap match (which could be the outer class). + ScriptTypeInfo containingScriptType = findEnclosingScriptType(position); + + // Check if inside a method - if so, it's a local, not global + boolean insideMethod = false; + if (containingScriptType != null && isInsideNestedMethod(position, containingScriptType.getBodyStart(), + containingScriptType.getBodyEnd())) + insideMethod = true; + else { + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(position)) { + insideMethod = true; + break; + } + } + if (!insideMethod) { + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(position)) { + insideMethod = true; + break; + } + } + } + } + + if (insideMethod) + continue; + + String documentation = extractDocumentationBefore(m.start()); + + int initStart = -1; + int initEnd = -1; + if ("=".equals(delimiter)) { + initStart = m.start(3); + int searchPos = m.end(3); + int depth = 0; + // Stop at ',' or ';' at depth 0 so that multi-declarator + // statements like "int x = 1, y, z = 3;" correctly bound + // the initializer of x to just "1" (not "1, y, z = 3"). + while (searchPos < text.length()) { + char c = text.charAt(searchPos); + if (c == '(' || c == '[' || c == '{') depth++; + else if (c == ')' || c == ']' || c == '}') depth--; + else if ((c == ';' || c == ',') && depth == 0) { + initEnd = searchPos; + break; + } + searchPos++; + } + } + + // Use position-aware resolution so inner class type names resolve correctly + TypeInfo typeInfo = resolveType(typeName, position); + FieldInfo fieldInfo = FieldInfo.globalField(fieldName, typeInfo, position, documentation, initStart, initEnd, modifiers); + + if (containingScriptType != null) { + containingScriptType.addField(fieldInfo); + } else if (globalFields.containsKey(fieldName)) { + AssignmentInfo dupError = AssignmentInfo.duplicateDeclaration( + fieldName, position, position + fieldName.length(), + "Variable '" + fieldName + "' is already defined in the scope"); + declarationErrors.add(dupError); + } else { + globalFields.put(fieldName, fieldInfo); + } + + // --- Multi-declarator continuation for global Java fields --- + // For "int x = 1, y, z = 3;" FIELD_DECL_PATTERN matched "int x =" + // (or "int x,"). Scan forward for comma-separated continuation + // declarators (y, z) that share the same declared type. + final TypeInfo sharedType = typeInfo; + final int sharedModifiers = modifiers; + final ScriptTypeInfo fContainingType = containingScriptType; + int javaScanStart = MultiDeclaratorParser.javaDeclaratorScanStart(text, delimiter, m.end(3), + initEnd >= 0 ? initEnd : -1); + if (javaScanStart >= 0) { + MultiDeclaratorParser.scanJavaContinuationDeclarators(text, javaScanStart, 0, + (cVarName, cAbsNamePos, cAbsInitStart, cAbsInitEnd) -> { + if (isExcluded(cAbsNamePos)) return; + // Check if inside a method — if so, skip (it's a local, not global) + boolean cInsideMethod = false; + if (fContainingType != null && isInsideNestedMethod(cAbsNamePos, + fContainingType.getBodyStart(), fContainingType.getBodyEnd())) + cInsideMethod = true; + else { + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(cAbsNamePos)) { cInsideMethod = true; break; } + } + if (!cInsideMethod) { + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(cAbsNamePos)) { cInsideMethod = true; break; } + } + } + } + if (cInsideMethod) return; + + FieldInfo cField = FieldInfo.globalField(cVarName, sharedType, cAbsNamePos, + null, cAbsInitStart, cAbsInitEnd, sharedModifiers); + if (fContainingType != null) { + fContainingType.addField(cField); + } else if (globalFields.containsKey(cVarName)) { + AssignmentInfo dupErr = AssignmentInfo.duplicateDeclaration( + cVarName, cAbsNamePos, cAbsNamePos + cVarName.length(), + "Variable '" + cVarName + "' is already defined in the scope"); + declarationErrors.add(dupErr); + } else { + globalFields.put(cVarName, cField); + } + }); + } + } + } + } + + /** + * Strip Java modifiers from a type name string. + * e.g., "public static String" -> "String" + */ + private String stripModifiers(String typeName) { + if (typeName == null) return null; + + String[] parts = typeName.trim().split("\\s+"); + // Filter out known modifiers + StringBuilder result = new StringBuilder(); + for (String part : parts) { + if (!TypeResolver.isModifier(part)) { + if (result.length() > 0) result.append(" "); + result.append(part); + } + } + return result.toString(); + } + + /** + * Parse modifiers from a declaration string and return the corresponding Modifier flags. + * e.g., "public static final" -> Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL + */ + private int parseModifiers(String declaration) { + if (declaration == null) return 0; + + int modifiers = 0; + String[] parts = declaration.trim().split("\\s+"); + for (String part : parts) { + if (part.equals("public")) modifiers |= java.lang.reflect.Modifier.PUBLIC; + else if (part.equals("private")) modifiers |= java.lang.reflect.Modifier.PRIVATE; + else if (part.equals("protected")) modifiers |= java.lang.reflect.Modifier.PROTECTED; + else if (part.equals("static")) modifiers |= java.lang.reflect.Modifier.STATIC; + else if (part.equals("final")) modifiers |= java.lang.reflect.Modifier.FINAL; + else if (part.equals("abstract")) modifiers |= java.lang.reflect.Modifier.ABSTRACT; + else if (part.equals("synchronized")) modifiers |= java.lang.reflect.Modifier.SYNCHRONIZED; + else if (part.equals("volatile")) modifiers |= java.lang.reflect.Modifier.VOLATILE; + else if (part.equals("transient")) modifiers |= java.lang.reflect.Modifier.TRANSIENT; + else if (part.equals("native")) modifiers |= java.lang.reflect.Modifier.NATIVE; + else if (part.equals("strictfp")) modifiers |= java.lang.reflect.Modifier.STRICT; + } + return modifiers; + } + + /** + * Scan backwards from scanStart position in the given text to extract modifier keywords. + * Returns the parsed modifier flags. + * + * @param scanStart The position to start scanning backwards from (exclusive) + * @param sourceText The text to scan in + * @return The combined modifier flags + */ + private int extractModifiersBackwards(int scanStart, String sourceText) { + // Skip whitespace + while (scanStart >= 0 && Character.isWhitespace(sourceText.charAt(scanStart))) { + scanStart--; + } + + // Scan backwards collecting modifier words + StringBuilder modifiersText = new StringBuilder(); + while (scanStart >= 0) { + // Skip whitespace + while (scanStart >= 0 && Character.isWhitespace(sourceText.charAt(scanStart))) { + scanStart--; + } + if (scanStart < 0) break; + + // Read a word backwards + int wordEnd = scanStart + 1; + while (scanStart >= 0 && Character.isJavaIdentifierPart(sourceText.charAt(scanStart))) { + scanStart--; + } + int wordStart = scanStart + 1; + if (wordStart < wordEnd) { + String word = sourceText.substring(wordStart, wordEnd); + // Check if it's a modifier + if (TypeResolver.isModifier(word)) { + if (modifiersText.length() > 0) { + modifiersText.insert(0, " "); + } + modifiersText.insert(0, word); + } else { + // Hit a non-modifier word, stop scanning + break; + } + } else { + break; + } + } + + // Parse the collected modifiers + return parseModifiers(modifiersText.toString()); + } + + /** + * Extract documentation comment immediately preceding a position. + * Supports both single-line (//) and multi-line (/* *\/) comment styles. + * Returns null if no documentation is found. + * + * @param position The position of the declaration (e.g., start of method/field) + * @return The documentation text, or null if none found + */ + private String extractDocumentationBefore(int position) { + if (position <= 0) return null; + + // First, skip backwards to get off the current declaration line + // (declarations might have modifiers like 'public' before the matched position) + int searchStart = position - 1; + + // Skip backwards to the previous newline + while (searchStart >= 0 && text.charAt(searchStart) != '\n') { + searchStart--; + } + + if (searchStart < 0) return null; + + // Now we're at a newline before the declaration line + // Skip backwards through any additional whitespace + searchStart--; + while (searchStart >= 0 && Character.isWhitespace(text.charAt(searchStart))) { + searchStart--; + } + + if (searchStart < 0) return null; + + // Now searchStart should be at the last non-whitespace character before the declaration line + + // Check if we're at the end of a comment + // Case 1: Multi-line comment ending with */ + if (searchStart > 0 && text.charAt(searchStart) == '/' && text.charAt(searchStart - 1) == '*') { + // Find the start of this comment + int commentEnd = searchStart + 1; + int commentStart = text.lastIndexOf("/*", searchStart - 1); + if (commentStart >= 0) { + String comment = text.substring(commentStart, commentEnd); + return cleanDocumentation(comment); + } + } + + // Case 2: Single-line comments (may be multiple consecutive lines) + StringBuilder doc = new StringBuilder(); + int currentPos = searchStart; + + // Walk backward through consecutive comment lines + while (currentPos >= 0) { + // Find start of current line + int lineStart = currentPos; + while (lineStart > 0 && text.charAt(lineStart - 1) != '\n') { + lineStart--; + } + + // Find end of current line + int lineEnd = currentPos; + while (lineEnd < text.length() && text.charAt(lineEnd) != '\n') { + lineEnd++; + } + + // Extract the line and trim + String line = text.substring(lineStart, lineEnd).trim(); + + // Check if this line is a comment + if (line.startsWith("//") || line.startsWith("#")) { + // Prepend to doc (we're going backwards) + String commentText = line.substring(2).trim(); + if (doc.length() > 0) { + doc.insert(0, "\n"); + } + doc.insert(0, commentText); + + // Move to previous line + if (lineStart > 0) { + currentPos = lineStart - 1; + // Skip to previous line (skip the newline) + while (currentPos >= 0 && text.charAt(currentPos) == '\n') { + currentPos--; + } + } else { + break; + } + } else { + // Not a comment line, stop + break; + } + } + + if (doc.length() > 0) { + return doc.toString(); + } + + return null; + } + + /** + * Clean up documentation comment text by removing comment markers and extra formatting. + */ + private String cleanDocumentation(String comment) { + if (comment == null || comment.isEmpty()) return null; + + // Remove /* and */ markers + comment = comment.replaceAll("^/\\*+\\s*", "").replaceAll("\\s*\\*+/$", ""); + + // Split into lines and clean each one + String[] lines = comment.split("\n"); + StringBuilder cleaned = new StringBuilder(); + + for (String line : lines) { + // Remove leading asterisks and whitespace + line = line.trim().replaceAll("^\\*+\\s*", ""); + if (cleaned.length() > 0 && !line.isEmpty()) { + cleaned.append("\n"); + } + if (!line.isEmpty()) { + cleaned.append(line); + } + } + + String result = cleaned.toString().trim(); + return result.isEmpty() ? null : result; + } + + public TypeInfo resolveType(String typeName) { + /** + * Resolve a JS type name to unified TypeInfo. + * Handles JS primitives, .d.ts defined types, and falls back to Java types. + */ + if (isJavaScript()) + return typeResolver.resolveJSType(typeName); + + return resolveTypeAndTrackUsage(typeName); + } + + /** + * Recursively resolve any unresolved type names inside a TypeInfo using position-aware resolution. + * + * This handles a different concern than {@link GenericContext#substitute(TypeInfo)} — + * it does not replace type variables with concrete bindings. Instead, it re-resolves + * unresolved simple names (e.g., inner class names like "Node" or script-declared type + * parameters like "T") that appear as type arguments in parameterized types. + * + * For example, if a type resolves to {@code List} but "Node" is still unresolved, + * this will attempt to resolve "Node" using the position-aware + * {@link #resolveType(String, int)} which can find inner classes and type parameters + * visible at the given position. + * + * @param type the type whose unresolved components should be re-resolved + * @param position the script text offset for scope-aware resolution + * @return the type with all resolvable components resolved, or the original if nothing changed + */ + private TypeInfo substituteTypeParams(TypeInfo type, int position) { + if (type == null) + return null; + + if (!type.isResolved() && type.getSimpleName() != null + && !type.getSimpleName().contains(".")) { + TypeInfo sub = resolveType(type.getSimpleName(), position); + return (sub != null && sub.isResolved()) ? sub : type; + } + + if (type.isParameterized()) { + List args = type.getAppliedTypeArgs(); + if (args != null && !args.isEmpty()) { + List substituted = new ArrayList<>(args.size()); + boolean anyChanged = false; + for (TypeInfo arg : args) { + TypeInfo sub = substituteTypeParams(arg, position); + if (sub != arg) + anyChanged = true; + substituted.add(sub); + } + if (anyChanged) { + TypeInfo raw = type.getRawType(); + return raw != null ? raw.parameterize(substituted) : type.parameterize(substituted); + } + } + } + + return type; + } + + /** + * Position-aware type resolution overload. + * Resolves a type name with positional context so that an unqualified inner class name + * (e.g., just "Inner") resolves correctly when the cursor/position is inside the body + * of an enclosing type that declares that inner class. + * + * Resolution order: + * 1. Standard resolveType(typeName) — handles simple names, dot-names, imports, primitives + * 2. If unresolved and the name is a simple identifier (no dots), check the enclosing + * type at 'position' for an inner class with that name. + * This walks the nesting hierarchy upward so "Inner" resolves even from deeply nested code. + * + * @param typeName The type name to resolve (simple or dot-separated) + * @param position The absolute offset in the script text for scope context + * @return The resolved TypeInfo, or an unresolved TypeInfo if not found + */ + public TypeInfo resolveType(String typeName, int position) { + // First: delegate to the standard (positionless) resolver + TypeInfo resolved = resolveType(typeName); + + // If already resolved, no need for positional fallback + if (resolved != null && resolved.isResolved()) { + return substituteTypeParams(resolved, position); + } + + if (typeName != null && !typeName.contains(".")) { + TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(typeName); + String baseTypeName = arraySplit.base; + int arrayDims = arraySplit.dimensions; + + ScriptTypeInfo enclosing = findEnclosingScriptType(position); + while (enclosing != null) { + // Check if the name is a declared type parameter on this class (e.g., E in class Box) + TypeParamInfo typeParam = enclosing.getDeclaredTypeParam(baseTypeName); + if (typeParam != null) { + TypeInfo result = TypeInfo.typeParameter(baseTypeName, typeParam); + for (int i = 0; i < arrayDims; i++) result = TypeInfo.arrayOf(result); + return result; + } + + // Check inner classes + ScriptTypeInfo inner = enclosing.getInnerClass(typeName); + if (inner != null) { + return inner; + } + // Move up to the parent type — inner classes of outer types are also in scope + enclosing = enclosing.getOuterClass(); + } + } + + // Return whatever resolveType() returned (possibly unresolved) + return resolved; + } + + /** + * Resolve a type and track the import usage for unused import detection. + * Checks script-defined types first, then falls back to imported types. + * Used for Java/Groovy scripts. + */ + private TypeInfo resolveTypeAndTrackUsage(String typeName) { + if (typeName == null || typeName.isEmpty()) + return TypeInfo.unresolved(typeName, typeName); + + final String normalized = typeName.trim(); + final String normalizedFinal = stripLeadingModifiers(normalized); + + // Split array suffixes first + TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalizedFinal); + String baseExpr = arraySplit.base; + int arrayDims = arraySplit.dimensions; + + // Base type resolver with import tracking + Function resolveBase = baseName -> { + TypeInfo resolved; + + // Primitives + if (TypeResolver.isPrimitiveType(baseName)) { + resolved = TypeInfo.fromPrimitive(baseName); + } + // Common java.lang.String + else if ("String".equals(baseName)) { + resolved = typeResolver.resolveFullName("java.lang.String"); + } + // Script-defined types (simple names only) + else if (!baseName.contains(".") && scriptTypes.containsKey(baseName)) { + resolved = scriptTypes.get(baseName); + } + // Script-defined inner types (dot-separated, e.g., "Outer.Inner") + // Checked before Java full-name resolution so script types shadow Java types + else if (baseName.contains(".") && scriptTypesByDotName.containsKey(baseName)) { + resolved = scriptTypesByDotName.get(baseName); + } + // Fully-qualified Java types + else if (baseName.contains(".")) { + resolved = typeResolver.resolveFullName(baseName); + // Fallback: "SimpleName.InnerClass" where SimpleName is a known import + // e.g., "Map.Entry" when java.util.Map is imported → java.util.Map$Entry + if (resolved == null || !resolved.isResolved()) { + int firstDot = baseName.indexOf('.'); + String outerSimple = baseName.substring(0, firstDot); + String innerPath = baseName.substring(firstDot + 1); + TypeInfo outerType = typeResolver.resolveSimpleName(outerSimple, importsBySimpleName, wildcardPackages); + if (outerType != null && outerType.isResolved() && outerType.getJavaClass() != null) { + Class currentClass = outerType.getJavaClass(); + for (String part : innerPath.split("\\.")) { + Class found = null; + for (Class inner : currentClass.getClasses()) { + if (inner.getSimpleName().equals(part)) { + found = inner; + break; + } + } + currentClass = found; + if (currentClass == null) break; + } + if (currentClass != null) { + resolved = TypeInfo.fromClass(currentClass); + // Track import usage for the outer class + ImportData usedImport = importsBySimpleName.get(outerSimple); + if (usedImport != null) { + usedImport.incrementUsage(); + } else if (wildcardPackages != null) { + String resultPkg = outerType.getPackageName(); + for (ImportData imp : imports) { + if (imp.isWildcard() && resultPkg != null && resultPkg.equals(imp.getFullPath())) { + imp.incrementUsage(); + break; + } + } + } + } + } + } + } + // Imported/simple + else { + resolved = typeResolver.resolveSimpleName(baseName, importsBySimpleName, wildcardPackages); + + // Track import usage + if (resolved != null && resolved.isResolved()) { + ImportData usedImport = importsBySimpleName.get(baseName); + if (usedImport != null) { + usedImport.incrementUsage(); + } else if (wildcardPackages != null) { + String resultPkg = resolved.getPackageName(); + for (ImportData imp : imports) { + if (imp.isWildcard() && resultPkg != null && resultPkg.equals(imp.getFullPath())) { + imp.incrementUsage(); + break; + } + } + } + } + } + + return resolved != null ? resolved : TypeInfo.unresolved(baseName, normalizedFinal); + }; + + TypeInfo resolved; + + // Fast path: no generics - skip expensive parsing + if (!baseExpr.contains("<")) { + resolved = resolveBase.apply(baseExpr); + } else { + // Slow path: parse and resolve generics + GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(baseExpr); + if (parsed != null) { + // Normalize whitespace around dots in base name + String baseName = parsed.baseName.replaceAll("\\s*\\.\\s*", ".").trim(); + resolved = resolveBase.apply(baseName); + + // Apply generic arguments + if (parsed.hasTypeArgs() && resolved != null && resolved.isResolved()) { + List resolvedArgs = new ArrayList<>(); + for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) { + if (argParsed == null) { + resolvedArgs.add(TypeInfo.fromClass(Object.class)); + } else { + TypeInfo argType = resolveTypeAndTrackUsage(argParsed.rawString); + resolvedArgs.add(argType != null ? argType : TypeInfo.unresolved(argParsed.baseName, + argParsed.baseName)); + } + } + if (!resolvedArgs.isEmpty()) { + resolved = resolved.parameterize(resolvedArgs); + } + } + } else + // Fallback: treat as simple type + resolved = resolveBase.apply(baseExpr); + } + + // Apply array dimensions + for (int i = 0; i < arrayDims; i++) { + resolved = TypeInfo.arrayOf(resolved); + } + + return resolved; + } + + /** + * Strip only LEADING Java modifiers from a type expression. + * This avoids breaking generic argument lists which may contain whitespace. + */ + private String stripLeadingModifiers(String typeExpr) { + if (typeExpr == null) { + return null; + } + int i = 0; + int len = typeExpr.length(); + while (i < len) { + while (i < len && Character.isWhitespace(typeExpr.charAt(i))) i++; + int start = i; + while (i < len && Character.isJavaIdentifierPart(typeExpr.charAt(i))) i++; + if (start == i) { + break; + } + String word = typeExpr.substring(start, i); + if (TypeResolver.isModifier(word)) { + // Continue stripping modifiers + continue; + } + // Not a modifier; rewind to the start of this token + return typeExpr.substring(start).trim(); + } + return typeExpr.trim(); + } + + // ==================== PHASE 4: BUILD MARKS ==================== + + /** + * Build syntax highlighting marks - UNIFIED for both Java and JavaScript. + * Uses the SAME mark methods for both languages since they share data structures. + */ + private List buildMarks() { + List marks = new ArrayList<>(); + + // Strings first to protect their content + addPatternMarks(marks, STRING_PATTERN, TokenType.STRING); + + // JSDoc comments with fragmented marking (avoids conflicts with @tags and {Type}) + markJSDocElements(marks); + + // Regular comments (non-JSDoc) + markNonJSDocComments(marks); + + // Keywords - same for both languages (KEYWORD_PATTERN includes JS keywords like function, var, let, const) + addPatternMarks(marks, KEYWORD_PATTERN, TokenType.KEYWORD); + if(isJavaScript()) + addPatternMarks(marks, KEYWORD_JS_PATTERN, TokenType.KEYWORD); + + // Numbers - same for both languages + addPatternMarks(marks, NUMBER_PATTERN, TokenType.LITERAL); + + if (isJavaScript()) { + markObjectLiteralKeys(marks); + } + + // Import statements - Java only + if (!isJavaScript()) { + markImports(marks); + } + + // Class/interface/enum declarations - Java only + if (!isJavaScript()) { + markClassDeclarations(marks); + markEnumConstants(marks); + } + + // Modifiers - Java only + if (!isJavaScript()) { + addPatternMarks(marks, MODIFIER_PATTERN, TokenType.KEYWORD); + } + + // Type declarations and usages - Java only (JS doesn't have explicit types) + if (!isJavaScript()) { + markTypeDeclarations(marks); + } + + // Methods/functions - UNIFIED (uses shared 'methods' list) + markMethodDeclarations(marks); + + // Method calls - UNIFIED (stores in shared 'methodCalls' list) + markMethodCalls(marks); + + // Variables and fields - UNIFIED (uses shared globalFields, methodLocals) + markVariables(marks); + + // Chained field accesses - UNIFIED (uses resolveVariable which handles both) + markChainedFieldAccesses(marks); + markImportedClassUsages(marks); + + // Java-specific final passes + if (!isJavaScript()) { + markCastTypes(marks); + markUnusedImports(marks); + // Mark method reference expressions (target::methodName) + markMethodReferences(marks); + } + + // Mark lambda and method reference operators (-> and ::) + markLambdaOperators(marks); + + // Mark lambda/function parameters with type info + markInnerScopeParameters(marks); + + // Validate lambda return types + validateLambdaReturnTypes(marks); + + // Final pass: Mark any remaining unmarked identifiers as undefined + markUndefinedIdentifiers(marks); + + return marks; + } + + private void markObjectLiteralKeys(List marks) { + for (ObjectLiteralParser.ObjectLiteralAnalysis analysis : objectLiterals.values()) { + for (ObjectLiteralParser.ObjectLiteralProperty p : analysis.properties) { + if (p.isIdentifierKey) { + marks.add(new ScriptLine.Mark(p.keyStartAbs, p.keyEndAbs, TokenType.LOCAL_FIELD)); + } + } + } + } + + /** + * Two-phase object literal parsing. + * + *

Phase 1 (structure-only): parse every object literal with a no-op type + * resolver. This produces {@link ObjectLiteralParser.ObjectLiteralAnalysis} entries + * whose property names are correct but whose value types are all {@code ANY}. + * The synthetic {@link TypeInfo} shapes built from those names are then attached to + * the corresponding {@link InnerCallableScope}s via + * {@link ObjectLiteralParser#attachObjectLiteralContext}, so that + * {@code resolveThisType()} can return the containing object literal type for + * {@code this.property} chains.

+ * + *

Phase 2 (full resolution): re-parse with the real + * {@code this::resolveExpressionType} callback. Because scopes now have their + * {@code containingObjectType} wired, expressions like {@code return this.faah.length} + * inside method bodies resolve correctly instead of falling back to {@code ANY}.

+ */ + private void parseObjectLiterals() { + if (!isJavaScript()) return; + + List braceRanges = findObjectLiteralBraces(); + if (braceRanges.isEmpty()) + return; + + // Phase 1: structure-only — property names extracted, value types = ANY + ObjectLiteralParser.ExpressionTypeResolverFn nullResolver = (expr, pos) -> null; + for (int[] range : braceRanges) { + String objectLiteral = text.substring(range[0], range[1]); + ObjectLiteralParser.ObjectLiteralAnalysis analysis = + ObjectLiteralParser.parse(objectLiteral, range[0], true, true, nullResolver, + this::getScriptMethodInfo); + if (analysis != null) + objectLiterals.put(range[0], analysis); + } + + for (InnerCallableScope scope : innerScopes) + ObjectLiteralParser.attachObjectLiteralContext(scope, this); + + // Phase 2: full resolution — accurate value / return types via resolveExpressionType + for (int[] range : braceRanges) { + String objectLiteral = text.substring(range[0], range[1]); + ObjectLiteralParser.ObjectLiteralAnalysis analysis = + ObjectLiteralParser.parse(objectLiteral, range[0], true, true, this::resolveExpressionType, + this::getScriptMethodInfo); + if (analysis != null) + objectLiterals.put(range[0], analysis); + } + + // Re-attach with fully-resolved types (reset so the guard allows re-attachment) + for (InnerCallableScope scope : innerScopes) { + scope.setContainingObjectType(null); + ObjectLiteralParser.attachObjectLiteralContext(scope, this); + } + } + + /** + * Scan the document for opening braces that are likely object-literal starts and + * return their {@code [start, end)} ranges. Shared by both parsing phases to avoid + * duplicate scanning. + */ + private List findObjectLiteralBraces() { + List ranges = new ArrayList<>(); + int i = 0; + while (i < text.length()) { + int brace = text.indexOf('{', i); + if (brace < 0) break; + if (isExcluded(brace) || !isLikelyObjectLiteralStart(brace)) { + i = brace + 1; + continue; + } + int end = findMatchingBraceEndInDocument(brace); + if (end <= brace) { + i = brace + 1; + continue; + } + ranges.add(new int[]{brace, end}); + i = brace + 1; + } + return ranges; + } + + private boolean isLikelyObjectLiteralStart(int bracePos) { + int prev = bracePos - 1; + while (prev >= 0 && Character.isWhitespace(text.charAt(prev))) { + prev--; + } + if (prev < 0) { + return false; + } + + char pc = text.charAt(prev); + if (pc == '=' || pc == '(' || pc == '[' || pc == ',' || pc == ':' || pc == '?' || pc == '!' || + pc == '+' || pc == '-' || pc == '*' || pc == '/' || pc == '%' || pc == '&' || pc == '|' || + pc == '^') { + return true; + } + + if (Character.isJavaIdentifierPart(pc)) { + int end = prev + 1; + int start = prev; + while (start >= 0 && Character.isJavaIdentifierPart(text.charAt(start))) { + start--; + } + start++; + String word = text.substring(start, end); + return "return".equals(word); + } + + return false; + } + + private int findMatchingBraceEndInDocument(int braceStart) { + int depth = 0; + for (int pos = braceStart; pos < text.length(); pos++) { + if (isExcluded(pos)) { + continue; + } + char c = text.charAt(pos); + if (c == '{') { + depth++; + } else if (c == '}') { + depth--; + if (depth == 0) { + return pos + 1; + } + } + } + return -1; + } + + + + + + + /** + * Mark lambda arrow (->) and method reference (::) operators. + */ + private void markLambdaOperators(List marks) { + // Mark -> operators (lambda arrows) + for (int i = 0; i < text.length() - 1; i++) { + if (text.charAt(i) == '-' && text.charAt(i + 1) == '>') { + if (!isExcluded(i)) { + marks.add(new ScriptLine.Mark(i, i + 2, TokenType.KEYWORD)); + } + } + } + + // Mark :: operators (method references) + for (int i = 0; i < text.length() - 1; i++) { + if (text.charAt(i) == ':' && text.charAt(i + 1) == ':') { + if (!isExcluded(i)) { + marks.add(new ScriptLine.Mark(i, i + 2, TokenType.DEFAULT)); + } + } + } + } + + /** + * Pattern for method reference: target::methodName + * target can be: identifier, qualified name (a.b.c), or 'this'/'super' + */ + private static final java.util.regex.Pattern METHOD_REF_PATTERN = + java.util.regex.Pattern.compile("([a-zA-Z_$][a-zA-Z0-9_$]*(?:\\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)\\s*::\\s*([a-zA-Z_$][a-zA-Z0-9_$]*|new)"); + + /** + * Mark method reference expressions with appropriate token types. + * Target gets its resolved type's token, method name gets METHOD_CALL if valid. + * Validates that the method exists on the target type. + */ + private void markMethodReferences(List marks) { + java.util.regex.Matcher m = METHOD_REF_PATTERN.matcher(text); + while (m.find()) { + int targetStart = m.start(1); + int targetEnd = m.end(1); + int methodStart = m.start(2); + int methodEnd = m.end(2); + + // Skip if in excluded region (string/comment) + if (isExcluded(targetStart) || isExcluded(methodStart)) { + continue; + } + + String target = m.group(1); + String methodName = m.group(2); + + // Check if there are parentheses after the method name (invalid for method references) + if (methodEnd < text.length() && text.charAt(methodEnd) == '(') { + // Mark the :: as error + int doubleColonPos = targetEnd; + while (doubleColonPos < methodStart && text.charAt(doubleColonPos) != ':') { + doubleColonPos++; + } + if (doubleColonPos < methodStart) { + marks.add(new ScriptLine.Mark(doubleColonPos, doubleColonPos + 2, TokenType.UNDEFINED_VAR, + TokenErrorMessage.from("Method references cannot have parentheses. Use '" + target + "::" + methodName + "' instead of '" + target + "::" + methodName + "()'"))); + } + // Also mark the method name as error + marks.add(new ScriptLine.Mark(methodStart, methodEnd, TokenType.UNDEFINED_VAR, + TokenErrorMessage.from("Method references cannot have parentheses"))); + // Mark opening paren as error too + marks.add(new ScriptLine.Mark(methodEnd, methodEnd + 1, TokenType.UNDEFINED_VAR, + TokenErrorMessage.from("Remove parentheses from method reference"))); + continue; // Skip normal processing for this invalid reference + } + + // Mark the target based on what it resolves to + markMethodRefTarget(marks, target, targetStart, targetEnd); + + // Resolve the target type to validate method existence + TypeInfo targetType = resolveMethodRefTargetType(target, targetStart); + + if (targetType != null && targetType.isResolved()) { + // Handle constructor references (::new) + if ("new".equals(methodName)) { + if (targetType.hasConstructors()) { + MethodInfo ctorInfo = targetType.findConstructor(0); + if (ctorInfo == null) { + List ctors = targetType.getConstructors(); + if (!ctors.isEmpty()) { + ctorInfo = ctors.get(0); + } + } + marks.add(new ScriptLine.Mark(methodStart, methodEnd, TokenType.METHOD_CALL, ctorInfo)); + } else { + // No constructors found + marks.add(new ScriptLine.Mark(methodStart, methodEnd, TokenType.UNDEFINED_VAR, + TokenErrorMessage.from("No constructor found for '" + targetType.getSimpleName() + "'"))); + } + } else if (targetType.hasMethod(methodName)) { + // Method exists - get the MethodInfo for metadata + MethodInfo methodInfo = targetType.getMethodInfo(methodName); + if (methodInfo == null) { + // Try getting from overloads if single getMethodInfo fails + List overloads = targetType.getAllMethodOverloads(methodName); + if (!overloads.isEmpty()) { + methodInfo = overloads.get(0); + } + } + marks.add(new ScriptLine.Mark(methodStart, methodEnd, TokenType.METHOD_CALL, methodInfo)); + } else { + // Method does not exist on target type + marks.add(new ScriptLine.Mark(methodStart, methodEnd, TokenType.UNDEFINED_VAR, + TokenErrorMessage.from("Method '" + methodName + "' not found in '" + targetType.getSimpleName() + "'"))); + } + } else { + // Could not resolve target type - mark method as potentially valid (no error) + // This allows for cases where the target type cannot be resolved but might be valid at runtime + marks.add(new ScriptLine.Mark(methodStart, methodEnd, TokenType.UNDEFINED_VAR)); + } + } + } + + /** + * Resolve the target type for a method reference expression. + * @param target The target expression (e.g., "this", "String", "java.util.Arrays") + * @param position The position in the text for scope resolution + * @return The resolved TypeInfo, or null if it cannot be resolved + */ + private TypeInfo resolveMethodRefTargetType(String target, int position) { + // Handle keywords + if ("this".equals(target)) { + // Resolve 'this' to the enclosing type + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null) { + return enclosingType; + } + // For hook methods, resolve to the implied 'this' type + MethodInfo containingMethod = findContainingMethod(position); + if (containingMethod != null && containingMethod.getContainingType() != null) { + return containingMethod.getContainingType(); + } + return null; + } + + if ("super".equals(target)) { + // Resolve 'super' to the parent type of the enclosing class + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null && enclosingType.hasSuperClass()) { + return enclosingType.getSuperClass(); + } + return null; + } + + // Handle qualified names (a.b.ClassName) + if (target.contains(".")) { + TypeInfo typeInfo = resolveType(target, position); + if (typeInfo != null && typeInfo.isResolved()) { + return typeInfo; + } + // Could not resolve as type - leave unresolved + return null; + } + + // Simple identifier - try as variable first (instance reference like myList::add) + FieldInfo varInfo = resolveVariable(target, position); + if (varInfo != null && varInfo.getTypeInfo() != null) { + return varInfo.getTypeInfo(); + } + + // Try as type name (class reference like String::valueOf) + TypeInfo typeInfo = resolveType(target, position); + if (typeInfo != null && typeInfo.isResolved()) { + return typeInfo; + } + + return null; + } + + /** + * Mark the target of a method reference with the appropriate token type. + */ + private void markMethodRefTarget(List marks, String target, int start, int end) { + // Handle keywords + if ("this".equals(target)) { + marks.add(new ScriptLine.Mark(start, end, TokenType.KEYWORD)); + return; + } + if ("super".equals(target)) { + marks.add(new ScriptLine.Mark(start, end, TokenType.KEYWORD)); + return; + } + + // Handle qualified names (a.b.ClassName) - mark the whole thing + if (target.contains(".")) { + // Try to resolve as a type + TypeInfo typeInfo = resolveType(target); + if (typeInfo != null && typeInfo.isResolved()) { + addTypeMark(marks, start, end, TokenType.IMPORTED_CLASS, typeInfo); + return; + } + // Otherwise mark the parts separately + markQualifiedTargetParts(marks, target, start); + return; + } + + // Simple identifier - determine its token type + // Check for local variable + FieldInfo varInfo = resolveVariable(target, start); + if (varInfo != null) { + TokenType tokenType = varInfo.isParameter() ? TokenType.PARAMETER + : varInfo.isGlobal() ? TokenType.GLOBAL_FIELD + : TokenType.LOCAL_FIELD; + marks.add(new ScriptLine.Mark(start, end, tokenType, varInfo)); + return; + } + + // Check for type name (imported class) + TypeInfo typeInfo = resolveType(target); + if (typeInfo != null && typeInfo.isResolved()) { + addTypeMark(marks, start, end, TokenType.IMPORTED_CLASS, typeInfo); + return; + } + + // Unknown - leave as default + } + + /** + * Mark parts of a qualified name like java.util.Arrays::asList + */ + private void markQualifiedTargetParts(List marks, String qualifiedName, int baseStart) { + String[] parts = qualifiedName.split("\\."); + int offset = baseStart; + for (int i = 0; i < parts.length; i++) { + String part = parts[i]; + int partEnd = offset + part.length(); + + if (i == parts.length - 1) { + // Last part is typically the class name + marks.add(new ScriptLine.Mark(offset, partEnd, TokenType.IMPORTED_CLASS)); + } else { + // Package parts + marks.add(new ScriptLine.Mark(offset, partEnd, TokenType.TYPE_DECL)); + } + + offset = partEnd + 1; // +1 for the dot + } + } + + /** + * Mark parameters in all inner callable scopes (lambdas and JS function expressions). + */ + private void markInnerScopeParameters(List marks) { + for (InnerCallableScope scope : innerScopes) { + for (FieldInfo param : scope.getParameters()) { + int start = param.getDeclarationOffset(); + int end = start + param.getName().length(); + + // Use FieldInfo as metadata - hover system will extract tooltip + marks.add(new ScriptLine.Mark(start, end, TokenType.PARAMETER, param)); + } + } + } + + /** + * Validate lambda return types against expected SAM return type. + */ + private void validateLambdaReturnTypes(List marks) { + for (InnerCallableScope scope : innerScopes) { + if (scope.getKind() == InnerCallableScope.Kind.JAVA_LAMBDA || + scope.getKind() == InnerCallableScope.Kind.JS_FUNCTION_EXPR || + scope.getKind() == InnerCallableScope.Kind.JS_ARROW_FUNC || + scope.getKind() == InnerCallableScope.Kind.JS_SHORTHAND_METHOD) { + validateLambdaReturnType(scope, marks); + } + } + } + + /** + * Validate that a lambda's body return type matches the expected SAM return type. + */ + private void validateLambdaReturnType(InnerCallableScope lambda, List marks) { + TypeInfo expectedType = lambda.getExpectedType(); + if (expectedType == null || !expectedType.isFunctionalInterface()) { + return; // No expected type to validate against + } + + MethodInfo sam = expectedType.getSingleAbstractMethod(); + if (sam == null) { + return; + } + + TypeInfo expectedReturnType = sam.getReturnType(); + + int bodyStart = lambda.getBodyStart(); + int bodyEnd = lambda.getBodyEnd(); + if (bodyStart < 0 || bodyEnd <= bodyStart || bodyEnd > text.length()) { + return; + } + + String bodyText = text.substring(bodyStart, bodyEnd).trim(); + + if (bodyText.startsWith("{")) { + // Block lambda - validate return statements + validateBlockLambdaReturns(lambda, bodyStart, bodyEnd, expectedReturnType, marks); + } else { + // Expression lambda - validate expression type + try { + TypeInfo bodyType = resolveExpressionType(bodyText, bodyStart); + + if (bodyType != null && expectedReturnType != null) { + // Check compatibility + if (!isCompatibleType(bodyType, expectedReturnType)) { + // Mark error at body start + String error = "Incompatible return type: expected " + + expectedReturnType.getSimpleName() + + " but was " + bodyType.getSimpleName(); + marks.add(new ScriptLine.Mark(bodyStart, bodyEnd, TokenType.UNDEFINED_VAR, TokenErrorMessage.from(error))); + } + } + } catch (Exception e) { + // Fail soft - don't crash on malformed expressions + } + } + } + + /** + * Validate return statements in a block lambda (one with { }). + * Checks that all return statements return compatible types with the expected SAM return type. + */ + private void validateBlockLambdaReturns(InnerCallableScope lambda, int blockStart, int blockEnd, + TypeInfo expectedReturnType, List marks) { + // Find all return statements in the block + String blockText = text.substring(blockStart, blockEnd); + Pattern returnPattern = Pattern.compile("\\breturn\\b(\\s*;|\\s+[^;]+;)"); + Matcher m = returnPattern.matcher(blockText); + + while (m.find()) { + int returnStart = blockStart + m.start(); + int returnEnd = blockStart + m.end(); + + if (isExcluded(returnStart)) { + continue; + } + + // Get the return expression (if any) + String returnStmt = m.group(1).trim(); + + if (returnStmt.equals(";")) { + // return; - void return + if (expectedReturnType != null && !expectedReturnType.getSimpleName().equals("void")) { + String error = "Cannot return void from lambda expecting " + expectedReturnType.getSimpleName(); + marks.add(new ScriptLine.Mark(returnStart, returnEnd, TokenType.UNDEFINED_VAR, TokenErrorMessage.from(error))); + } + } else { + // return ; - typed return + String expr = returnStmt.substring(0, returnStmt.length() - 1).trim(); + + if (expectedReturnType != null && expectedReturnType.getSimpleName().equals("void")) { + String error = "Cannot return a value from void lambda"; + marks.add(new ScriptLine.Mark(returnStart, returnEnd, TokenType.UNDEFINED_VAR, TokenErrorMessage.from(error))); + } else { + try { + // Validate return expression type + int exprStart = returnStart + m.group(0).indexOf(expr); + TypeInfo returnType = resolveExpressionType(expr, exprStart); + + if (returnType != null && expectedReturnType != null) { + if (!isCompatibleType(returnType, expectedReturnType)) { + String error = "Incompatible return type: expected " + + expectedReturnType.getSimpleName() + + " but returned " + returnType.getSimpleName(); + int exprEnd = exprStart + expr.length(); + marks.add(new ScriptLine.Mark(exprStart, exprEnd, TokenType.UNDEFINED_VAR, TokenErrorMessage.from(error))); + } + } + } catch (Exception e) { + // Fail soft on malformed expressions + } + } + } + } + + // Check for missing returns in non-void lambdas + // This is a warning rather than an error - Java allows it if the lambda throws or has infinite loop + // We skip this validation to avoid false positives + } + + /** + * Check if an actual type is compatible with an expected type. + * Includes boxing, subtype checking, and special cases like void. + */ + private boolean isCompatibleType(TypeInfo actual, TypeInfo expected) { + if (actual == null || expected == null) return false; + if (actual.equals(expected)) return true; + if (actual.getSimpleName().equals(expected.getSimpleName())) return true; + + // void is compatible with anything (statement lambda) + if (expected.getSimpleName().equals("void")) return true; + + // Object is compatible with anything + if (expected.getSimpleName().equals("Object") || expected.getFullName().equals("java.lang.Object")) return true; + + // Check primitive boxing + if (isBoxingCompatible(actual.getSimpleName(), expected.getSimpleName())) return true; + + // Use TypeChecker for more complex compatibility + return TypeChecker.isTypeCompatible(expected, actual); + } + + /** + * Check if types are compatible via boxing/unboxing. + */ + private boolean isBoxingCompatible(String actualName, String expectedName) { + if (actualName.equals("int") && expectedName.equals("Integer")) return true; + if (actualName.equals("Integer") && expectedName.equals("int")) return true; + if (actualName.equals("boolean") && expectedName.equals("Boolean")) return true; + if (actualName.equals("Boolean") && expectedName.equals("boolean")) return true; + if (actualName.equals("long") && expectedName.equals("Long")) return true; + if (actualName.equals("Long") && expectedName.equals("long")) return true; + if (actualName.equals("double") && expectedName.equals("Double")) return true; + if (actualName.equals("Double") && expectedName.equals("double")) return true; + if (actualName.equals("float") && expectedName.equals("Float")) return true; + if (actualName.equals("Float") && expectedName.equals("float")) return true; + if (actualName.equals("byte") && expectedName.equals("Byte")) return true; + if (actualName.equals("Byte") && expectedName.equals("byte")) return true; + if (actualName.equals("short") && expectedName.equals("Short")) return true; + if (actualName.equals("Short") && expectedName.equals("short")) return true; + if (actualName.equals("char") && expectedName.equals("Character")) return true; + if (actualName.equals("Character") && expectedName.equals("char")) return true; + return false; + } + + /** + * Find and mark unused imports as UNUSED_IMPORT type. + * This must be called after all other mark building is complete. + */ + private void markUnusedImports(List marks) { + for (ImportData imp : imports) { + if (!imp.isUsed() && imp.isResolved() && !imp.isWildcard()) { + // This import is not used - find and update its marks + // Mark the entire import line as unused (gray color) + marks.add(new ScriptLine.Mark(imp.getStartOffset(), imp.getEndOffset(), + TokenType.UNUSED_IMPORT, imp)); + } + } + } + + /** + * Final pass: Mark any remaining unmarked identifiers as UNDEFINED_VAR. + * This should be called last, after all other marking passes are complete. + * Only marks identifiers that haven't been marked by any other pass. + */ + private void markUndefinedIdentifiers(List marks) { + // Build a set of all marked positions for fast lookup + // Use a boolean array for O(1) lookup + boolean[] markedPositions = new boolean[text.length()]; + for (ScriptLine.Mark mark : marks) { + for (int i = mark.start; i < mark.end && i < markedPositions.length; i++) { + markedPositions[i] = true; + } + } + + // Keywords that should not be marked as undefined + Set knownKeywords = new HashSet<>(Arrays.asList( + "boolean", "int", "float", "double", "long", "char", "byte", "short", "void", + "null", "true", "false", "if", "else", "switch", "case", "for", "while", "do", + "try", "catch", "finally", "return", "throw", "var", "let", "const", "function", + "continue", "break", "this", "new", "typeof", "instanceof", "class", "interface", + "extends", "implements", "import", "package", "public", "private", "protected", + "static", "final", "abstract", "synchronized", "native", "default", "enum", + "throws", "super", "assert", "volatile", "transient" + )); + + if (isJavaScript()) { + knownKeywords.add("delete"); + knownKeywords.add("undefined"); + } + + // Find all identifiers + Pattern identifier = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b"); + Matcher m = identifier.matcher(text); + + while (m.find()) { + int start = m.start(1); + int end = m.end(1); + String name = m.group(1); + + // Skip if already marked + if (start < markedPositions.length && markedPositions[start]) { + continue; + } + + // Skip if in excluded region (string/comment) + if (isExcluded(start)) { + continue; + } + + // Skip keywords + if (knownKeywords.contains(name)) { + continue; + } + + // Mark as undefined + marks.add(new ScriptLine.Mark(start, end, TokenType.UNDEFINED_VAR, null)); + } + } + + private void addPatternMarks(List marks, Pattern pattern, TokenType type) { + addPatternMarks(marks, pattern, type, 0); + } + + private void addPatternMarks(List marks, Pattern pattern, TokenType type, int group) { + Matcher m = pattern.matcher(text); + while (m.find()) { + marks.add(new ScriptLine.Mark(m.start(group), m.end(group), type)); + } + } + + private void markImports(List marks) { + for (ImportData imp : imports) { + // Skip implicit imports (from JaninoScript defaults, not in source text) + // These have offset -1 and don't need to be visually marked + if (imp.getStartOffset() < 0) + continue; + + // Mark 'import' keyword + marks.add(new ScriptLine.Mark(imp.getStartOffset(), imp.getStartOffset() + 6, TokenType.KEYWORD, imp)); + + // Parse path tokens + int pathStart = imp.getPathStartOffset(); + int pathEnd = imp.getPathEndOffset(); + String pathText = text.substring(pathStart, Math.min(pathEnd, text.length())); + + // Skip if path ends with dot (incomplete) + if (pathText.trim().endsWith(".")) { + continue; + } + + // Tokenize the path + List tokens = new ArrayList<>(); + List tokenStarts = new ArrayList<>(); + List tokenEnds = new ArrayList<>(); + Pattern idPattern = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*"); + Matcher idm = idPattern.matcher(pathText); + while (idm.find()) { + tokens.add(idm.group()); + tokenStarts.add(pathStart + idm.start()); + tokenEnds.add(pathStart + idm.end()); + } + + if (tokens.isEmpty()) continue; + + if (imp.isWildcard()) { + // Wildcard import: mark all tokens as package (blue) if valid + boolean pkgValid = typeResolver.isValidPackage(imp.getFullPath()); + + // Also check if it might be a class wildcard (OuterClass.*) + TypeInfo outerType = typeResolver.resolveFullName(imp.getFullPath()); + + if (pkgValid || outerType != null) { + // Mark package portion in blue + int pkgTokenCount = outerType != null ? tokens.size() - 1 : tokens.size(); + for (int i = 0; i < Math.min(pkgTokenCount, tokens.size()); i++) { + marks.add(new ScriptLine.Mark(tokenStarts.get(i), tokenEnds.get(i), TokenType.TYPE_DECL, imp)); + } + // If it's a class wildcard, mark the class with its type + if (outerType != null && tokens.size() > 0) { + int lastIdx = tokens.size() - 1; + marks.add(new ScriptLine.Mark(tokenStarts.get(lastIdx), tokenEnds.get(lastIdx), + outerType.getTokenType(), imp)); + } + } else { + // Unknown package/class - mark as undefined + marks.add(new ScriptLine.Mark(pathStart, pathEnd, TokenType.UNDEFINED_VAR, imp)); + } + } else { + // Non-wildcard import: package is blue, class name(s) get type colors + TypeInfo resolvedType = imp.getResolvedType(); + + if (resolvedType != null && resolvedType.isResolved()) { + // Count package segments + String fullPath = imp.getFullPath(); + String resolvedName = resolvedType.getFullName(); + String pkgName = resolvedType.getPackageName(); + + int pkgSegments = pkgName != null && !pkgName.isEmpty() + ? pkgName.split("\\.").length : 0; + + // Mark package tokens in blue + for (int i = 0; i < Math.min(pkgSegments, tokens.size()); i++) { + marks.add(new ScriptLine.Mark(tokenStarts.get(i), tokenEnds.get(i), TokenType.TYPE_DECL, imp)); + } + + // Mark class tokens with appropriate type colors + // For inner classes, each segment might have a different type + for (int i = pkgSegments; i < tokens.size(); i++) { + String segmentName = tokens.get(i); + // Try to resolve this specific class/inner class + StringBuilder classPath = new StringBuilder(); + if (pkgName != null && !pkgName.isEmpty()) { + classPath.append(pkgName).append("."); + } + for (int j = pkgSegments; j <= i; j++) { + if (j > pkgSegments) classPath.append("$"); + classPath.append(tokens.get(j)); + } + + TypeInfo segmentType = typeResolver.resolveFullName(classPath.toString()); + TokenType tokenType = segmentType != null + ? segmentType.getTokenType() + : resolvedType.getTokenType(); + + marks.add(new ScriptLine.Mark(tokenStarts.get(i), tokenEnds.get(i), tokenType, imp)); + } + } else { + // Try to figure out which parts are valid vs invalid + // First, try to find valid package segments + int lastValidPkg = -1; + StringBuilder pkgBuilder = new StringBuilder(); + + for (int i = 0; i < tokens.size(); i++) { + if (i > 0) pkgBuilder.append("."); + pkgBuilder.append(tokens.get(i)); + + // Check if this is a valid package + if (typeResolver.isValidPackage(pkgBuilder.toString())) { + lastValidPkg = i; + } + } + + // Now try to resolve outer classes that might exist after the package + // For import like kamkeel.api.IOverlay.idk where IOverlay exists but idk doesn't + int lastValidClass = -1; + TypeInfo lastValidType = null; + StringBuilder classPath = new StringBuilder(); + + if (lastValidPkg >= 0) { + classPath.append(pkgBuilder.substring(0, + pkgBuilder.toString().indexOf(tokens.get(lastValidPkg)) + tokens.get(lastValidPkg) + .length())); + } + + for (int i = lastValidPkg + 1; i < tokens.size(); i++) { + if (classPath.length() > 0) + classPath.append(i == lastValidPkg + 1 ? "." : "$"); + classPath.append(tokens.get(i)); + + TypeInfo segmentType = typeResolver.resolveFullName(classPath.toString()); + if (segmentType != null && segmentType.isResolved()) { + lastValidClass = i; + lastValidType = segmentType; + } else { + break; // Stop at first unresolved segment + } + } + + // Mark valid package portion in blue + for (int i = 0; i <= lastValidPkg; i++) { + marks.add(new ScriptLine.Mark(tokenStarts.get(i), tokenEnds.get(i), TokenType.TYPE_DECL, imp)); + } + + // Mark valid class segments with their type colors + StringBuilder resolvedPath = new StringBuilder(); + if (lastValidPkg >= 0) { + for (int i = 0; i <= lastValidPkg; i++) { + if (i > 0) + resolvedPath.append("."); + resolvedPath.append(tokens.get(i)); + } + } + + for (int i = lastValidPkg + 1; i <= lastValidClass; i++) { + if (resolvedPath.length() > 0) + resolvedPath.append(i == lastValidPkg + 1 ? "." : "$"); + resolvedPath.append(tokens.get(i)); + + TypeInfo segmentType = typeResolver.resolveFullName(resolvedPath.toString()); + TokenType tokenType = (segmentType != null) ? segmentType.getTokenType() : TokenType.IMPORTED_CLASS; + marks.add(new ScriptLine.Mark(tokenStarts.get(i), tokenEnds.get(i), tokenType, imp)); + } + + // Mark remaining unresolved segments as undefined (red) + int firstUnresolved = Math.max(lastValidPkg + 1, lastValidClass + 1); + for (int i = firstUnresolved; i < tokens.size(); i++) { + marks.add(new ScriptLine.Mark(tokenStarts.get(i), tokenEnds.get(i), TokenType.UNDEFINED_VAR, + imp)); + } + + // If nothing was valid at all, mark everything as undefined + if (lastValidPkg < 0 && lastValidClass < 0) { + marks.add(new ScriptLine.Mark(pathStart, pathEnd, TokenType.UNDEFINED_VAR, imp)); + } + } + } + } + } + + private void markClassDeclarations(List marks) { + Pattern classKeyword = Pattern.compile( + "\\b(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)"); + + Matcher m = classKeyword.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) + continue; + + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.KEYWORD)); + + String kind = m.group(1); + TokenType nameType; + if ("interface".equals(kind)) { + nameType = TokenType.INTERFACE_DECL; + } else if ("enum".equals(kind)) { + nameType = TokenType.ENUM_DECL; + } else { + nameType = TokenType.CLASS_DECL; + } + String typeName = m.group(2); + ScriptTypeInfo typeInfo = scriptTypes.get(typeName); + if (typeInfo == null) { + for (ScriptTypeInfo candidate : scriptTypesByFullName.values()) { + if (candidate.getSimpleName().equals(typeName) + && m.start(2) >= candidate.getDeclarationOffset() + && m.start(2) < candidate.getBodyEnd()) { + typeInfo = candidate; + break; + } + } + } + marks.add(new ScriptLine.Mark(m.start(2), m.end(2), nameType, typeInfo)); + + // Skip past type params clause <...> using depth-aware scan + int scanPos = m.end(2); + while (scanPos < text.length() && Character.isWhitespace(text.charAt(scanPos))) + scanPos++; + + if (typeInfo != null && typeInfo.hasDeclaredTypeParams()) { + markTypeParamDeclarations(marks, m.end(2), typeInfo); + } + + if (scanPos < text.length() && text.charAt(scanPos) == '<') { + int depth = 1, i = scanPos + 1; + while (i < text.length() && depth > 0) { + char c = text.charAt(i++); + if (c == '<') depth++; + else if (c == '>') depth--; + } + if (depth == 0) scanPos = i; + } + + // Skip optional () (for enum constructors etc.) + while (scanPos < text.length() && Character.isWhitespace(text.charAt(scanPos))) + scanPos++; + if (scanPos + 1 < text.length() && text.charAt(scanPos) == '(' && text.charAt(scanPos + 1) == ')') { + scanPos += 2; + } + + // Find opening brace, scanning for extends/implements keywords + int bracePos = scanPos; + while (bracePos < text.length() && text.charAt(bracePos) != '{') { + bracePos++; + } + if (bracePos >= text.length()) continue; + + String betweenParamsAndBrace = text.substring(scanPos, bracePos); + + // Find extends keyword at depth 0 + int extIdx = indexOfAtDepthZero(betweenParamsAndBrace, "extends"); + if (extIdx >= 0) { + int extendsAbsStart = scanPos + extIdx; + marks.add(new ScriptLine.Mark(extendsAbsStart, extendsAbsStart + 7, TokenType.KEYWORD)); + + // Extract parent name after 'extends ' + String afterExtends = betweenParamsAndBrace.substring(extIdx + 7).trim(); + // Stop at 'implements' keyword or end + int implIdx = indexOfAtDepthZero(afterExtends, "implements"); + String parentSection = implIdx >= 0 ? afterExtends.substring(0, implIdx).trim() : afterExtends.trim(); + + // Extract just the base name (without generics) for markExtendsClause + int nameEnd = 0; + while (nameEnd < parentSection.length() && + (Character.isJavaIdentifierPart(parentSection.charAt(nameEnd)) || parentSection.charAt(nameEnd) == '.')) { + nameEnd++; + } + if (nameEnd > 0) { + String parentName = parentSection.substring(0, nameEnd); + int parentAbsStart = extendsAbsStart + 7; + while (parentAbsStart < bracePos && Character.isWhitespace(text.charAt(parentAbsStart))) + parentAbsStart++; + markExtendsClause(marks, parentAbsStart, parentName); + + // Mark generic args on the parent (e.g., in extends Parent) + if (nameEnd < parentSection.length() && parentSection.charAt(nameEnd) == '<') { + int genStart = parentAbsStart + nameEnd; + markGenericArgsInExtendsClause(marks, genStart, typeInfo); + } + } + } + + // Find implements keyword at depth 0 + int implIdx = indexOfAtDepthZero(betweenParamsAndBrace, "implements"); + if (implIdx >= 0) { + int implAbsStart = scanPos + implIdx; + marks.add(new ScriptLine.Mark(implAbsStart, implAbsStart + 10, TokenType.KEYWORD)); + + String afterImpl = betweenParamsAndBrace.substring(implIdx + 10).trim(); + int implListStart = implAbsStart + 10; + while (implListStart < bracePos && Character.isWhitespace(text.charAt(implListStart))) + implListStart++; + markImplementsClause(marks, implListStart, afterImpl); + } + } + } + + private void markGenericArgsInExtendsClause(List marks, int ltPos, ScriptTypeInfo childType) { + if (ltPos >= text.length() || text.charAt(ltPos) != '<') return; + int depth = 1, i = ltPos + 1; + while (i < text.length() && depth > 0) { + char c = text.charAt(i++); + if (c == '<') depth++; + else if (c == '>') depth--; + } + if (depth != 0) return; + int gtPos = i - 1; + + if (childType != null && childType.hasDeclaredTypeParams()) { + List typeParams = childType.getDeclaredTypeParams(); + markNestedTypeParamUsages(marks, ltPos + 1, gtPos, typeParams); + } + } + + /** + * Mark enum constants with ENUM_CONSTANT token type. + * Adds marks for all enum constants in script-defined enums. + */ + private void markEnumConstants(List marks) { + // Iterate all types (including inner) so enum constants in nested enums are marked + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + if (!scriptType.isEnum()) + continue; + + // Mark each enum constant + for (EnumConstantInfo constant : scriptType.getEnumConstants().values()) { + FieldInfo fieldInfo = constant.getFieldInfo(); + int start = fieldInfo.getDeclarationOffset(); + int end = start + fieldInfo.getName().length(); + + // Always use ENUM_CONSTANT token type (blue + bold + italic) + // Errors are shown via underline, not by changing the token type + marks.add(new ScriptLine.Mark(start, end, TokenType.ENUM_CONSTANT, fieldInfo)); + } + } + } + + /** + * Mark the extends clause with proper coloring. + * The parent class is colored based on its resolved type. + */ + private void markExtendsClause(List marks, int clauseStart, String parentName) { + String trimmedName = parentName.trim(); + if (trimmedName.isEmpty()) + return; + + + // Resolve the parent type with position context for inner class names + TypeInfo parentType = resolveType(trimmedName, clauseStart); + TokenType tokenType; + + if (parentType != null && parentType.isResolved()) { + // Use the type's specific token type (CLASS, INTERFACE, ENUM) + tokenType = parentType.getTokenType(); + } else { + // Unresolved - mark as undefined + tokenType = TokenType.UNDEFINED_VAR; + if (parentType == null) { + parentType = TypeInfo.unresolved(trimmedName, trimmedName); + } + } + + // Find actual position in text (might have leading whitespace in the group) + int actualStart = clauseStart; + String fullClause = parentName; + while (actualStart < clauseStart + fullClause.length() && + Character.isWhitespace(text.charAt(actualStart))) { + actualStart++; + } + + marks.add(new ScriptLine.Mark(actualStart, actualStart + trimmedName.length(), tokenType, parentType)); + } + + /** + * Mark the implements clause with proper coloring. + * Each interface is colored based on its resolved type. + */ + private void markImplementsClause(List marks, int clauseStart, String implementsList) { + String[] interfaces = implementsList.split(","); + int currentPos = clauseStart; + + for (String ifaceName : interfaces) { + String trimmedName = ifaceName.trim(); + if (trimmedName.isEmpty()) { + currentPos += ifaceName.length() + 1; // +1 for comma + continue; + } + + // Find the actual start position of this interface name in the text + int leadingSpaces = 0; + while (leadingSpaces < ifaceName.length() && Character.isWhitespace(ifaceName.charAt(leadingSpaces))) { + leadingSpaces++; + } + int actualStart = currentPos + leadingSpaces; + + // Resolve the interface type with position context for inner class names + TypeInfo ifaceType = resolveType(trimmedName, actualStart); + TokenType tokenType; + + if (ifaceType != null && ifaceType.isResolved()) { + tokenType = ifaceType.getTokenType(); + } else { + tokenType = TokenType.UNDEFINED_VAR; + if (ifaceType == null) { + ifaceType = TypeInfo.unresolved(trimmedName, trimmedName); + } + } + + marks.add(new ScriptLine.Mark(actualStart, actualStart + trimmedName.length(), tokenType, ifaceType)); + + // Move past this interface name and the comma + currentPos += ifaceName.length() + 1; + } + } + + private void markTypeDeclarations(List marks) { + // First, mark variables that hold Java.type() results + if (isJavaScript()) { + markJavaTypeVariables(marks); + } + + // Pattern for type optionally followed by generics - we'll manually parse generics + Pattern typeStart = Pattern.compile( + "(?:(?:public|private|protected|static|final|transient|volatile)\\s+)*" + + "([a-zA-Z][a-zA-Z0-9_]*)\\s*"); + + Matcher m = typeStart.matcher(text); + int searchFrom = 0; + + while (m.find(searchFrom)) { + int typeNameStart = m.start(1); + int typeNameEnd = m.end(1); + + if (isExcluded(typeNameStart) || isInImportOrPackage(typeNameStart)) { + searchFrom = m.end(); + continue; + } + + String typeName = m.group(1); + int posAfterType = m.end(1); + + // Skip whitespace after type name + while (posAfterType < text.length() && Character.isWhitespace(text.charAt(posAfterType))) { + posAfterType++; + } + + // Check for generic parameters + String genericContent = null; + int genericStart = -1; + int genericEnd = -1; + + if (posAfterType < text.length() && text.charAt(posAfterType) == '<') { + genericStart = posAfterType; + int depth = 1; + int i = posAfterType + 1; + while (i < text.length() && depth > 0) { + char c = text.charAt(i); + if (c == '<') + depth++; + else if (c == '>') + depth--; + i++; + } + if (depth == 0) { + genericEnd = i; + genericContent = text.substring(genericStart + 1, genericEnd - 1); + posAfterType = genericEnd; + } + } + + // Skip whitespace after generics + while (posAfterType < text.length() && Character.isWhitespace(text.charAt(posAfterType))) { + posAfterType++; + } + + int varScanPos = posAfterType; + while (text.startsWith("[]", varScanPos)) { + marks.add(new ScriptLine.Mark(varScanPos, varScanPos + 2, TokenType.DEFAULT, null)); + varScanPos += 2; + while (varScanPos < text.length() && Character.isWhitespace(text.charAt(varScanPos))) varScanPos++; + } + + // Check if this looks like a type declaration: + boolean hasGeneric = genericContent != null && !genericContent.isEmpty(); + boolean followedByVarName = false; + boolean atEndOfLine = varScanPos >= text.length() || text.charAt(varScanPos) == '\n'; + + if (!atEndOfLine && varScanPos < text.length()) { + char nextChar = text.charAt(varScanPos); + followedByVarName = Character.isLetter(nextChar) || nextChar == '_'; + } + + // Accept as type if: has generics OR followed by variable name + if (hasGeneric || followedByVarName) { + // Resolve with position context so type params (T, E, etc.) resolve via enclosing class + TypeInfo info = resolveType(typeName, typeNameStart); + TokenType tokenType = (info != null && info.isResolved()) ? info.getTokenType() : TokenType.UNDEFINED_VAR; + marks.add(new ScriptLine.Mark(typeNameStart, typeNameEnd, tokenType, info)); + + // Handle generic content recursively + if (hasGeneric && genericStart >= 0) { + int contentStart = genericStart + 1; + markGenericTypesRecursive(genericContent, contentStart, marks, typeNameStart); + } + } + + searchFrom = m.end(); + } + } + + + + /** + * Mark variables that hold Java.type() class references. + * Example: var File = Java.type("java.io.File"); + */ + private void markJavaTypeVariables(List marks) { + // Pattern: var/let/const varName = Java.type("className") + Pattern javaTypePattern = Pattern.compile( + "\\b(var|let|const)\\s+(\\w+)\\s*=\\s*Java\\.type\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)"); + + Matcher m = javaTypePattern.matcher(text); + + while (m.find()) { + if (isExcluded(m.start())) continue; + + String varName = m.group(2); + String className = m.group(3); + int varStart = m.start(2); + int varEnd = m.end(2); + + // Resolve the class name + TypeInfo classType = typeResolver.resolveFullName(className); + if (classType != null && classType.isResolved()) { + // Create ClassTypeInfo to represent that this variable holds a Class reference + ClassTypeInfo classRef = new ClassTypeInfo(classType); + + // Mark the variable with the ClassTypeInfo for hover info + marks.add(new ScriptLine.Mark(varStart, varEnd, TokenType.LOCAL_FIELD, classRef)); + } + } + } + + /** + * Recursively parse and mark generic type parameters. + * Handles arbitrarily nested generics like Map>>. + */ + private void markGenericTypesRecursive(String content, int baseOffset, List marks) { + markGenericTypesRecursive(content, baseOffset, marks, -1); + } + + private static final Set GENERIC_KEYWORDS = new HashSet<>(Arrays.asList("extends", "super")); + + private void markGenericTypesRecursive(String content, int baseOffset, List marks, int positionContext) { + if (content == null || content.isEmpty()) + return; + + int i = 0; + while (i < content.length()) { + char c = content.charAt(i); + + // Skip whitespace and punctuation + if (!Character.isJavaIdentifierStart(c)) { + i++; + continue; + } + + // Found start of identifier + int start = i; + while (i < content.length() && Character.isJavaIdentifierPart(content.charAt(i))) { + i++; + } + String typeName = content.substring(start, i); + + // Skip keywords that appear in generic bounds (extends, super) + if (GENERIC_KEYWORDS.contains(typeName)) { + continue; + } + + int absStart = baseOffset + start; + int absEnd = baseOffset + i; + + TypeInfo typeCheck = positionContext >= 0 + ? resolveType(typeName, positionContext) + : resolveType(typeName); + if (typeCheck != null && typeCheck.isResolved()) { + if (!isExcluded(absStart)) { + TokenType tokenType = typeCheck.getTokenType(); + marks.add(new ScriptLine.Mark(absStart, absEnd, tokenType, typeCheck)); + } + } + + // Skip whitespace + while (i < content.length() && Character.isWhitespace(content.charAt(i))) { + i++; + } + + // Check for nested generic + if (i < content.length() && content.charAt(i) == '<') { + int nestedStart = i + 1; + int depth = 1; + i++; + + // Find matching > + while (i < content.length() && depth > 0) { + if (content.charAt(i) == '<') + depth++; + else if (content.charAt(i) == '>') + depth--; + i++; + } + + // Recursively parse nested content + if (nestedStart < i - 1) { + String nestedContent = content.substring(nestedStart, i - 1); + markGenericTypesRecursive(nestedContent, baseOffset + nestedStart, marks, positionContext); + } + } + } + } + + /** + * Mark JSDoc elements within comments for syntax highlighting. + * Adds marks for @tags (like @param, @return, @type) and {Type} references. + */ + private void markJSDocElements(List marks) { + // Find all JSDoc comments (/** ... */) + Pattern jsDocPattern = Pattern.compile("/\\*\\*([\\s\\S]*?)\\*/"); + Matcher jsDocMatcher = jsDocPattern.matcher(text); + + while (jsDocMatcher.find()) { + int commentStart = jsDocMatcher.start(); + int commentEnd = jsDocMatcher.end(); + + // Skip if this JSDoc is inside a string + boolean insideString = false; + for (ScriptLine.Mark mark : marks) { + if (mark.type == TokenType.STRING && + commentStart >= mark.start && commentEnd <= mark.end) { + insideString = true; + break; + } + } + if (insideString) { + continue; + } + + String commentContent = jsDocMatcher.group(0); + + // Find the method that this JSDoc belongs to, for parameter validation + MethodInfo associatedMethod = findMethodAfterPosition(commentEnd); + Set methodParamNames = new HashSet<>(); + if (associatedMethod != null) { + for (FieldInfo param : associatedMethod.getParameters()) { + methodParamNames.add(param.getName()); + } + } + + // Collect all special element positions (@tags and {Type}s) that should NOT be gray + java.util.List specialRanges = new java.util.ArrayList<>(); + + // Find @tags and process @param and @type specially + Pattern tagPattern = Pattern.compile("@(\\w+)"); + Matcher tagMatcher = tagPattern.matcher(commentContent); + while (tagMatcher.find()) { + int tagStart = commentStart + tagMatcher.start(); + int tagEnd = commentStart + tagMatcher.end(); + specialRanges.add(new int[]{tagStart, tagEnd}); + + String tagName = tagMatcher.group(1); + + // For @type tag, resolve the type and attach it for hover + TypeInfo tagTypeInfo = null; + if ("type".equals(tagName)) { + // Look for {Type} after @type + int afterTag = tagMatcher.end(); + String afterTagText = commentContent.substring(afterTag); + Pattern typeRefPattern = Pattern.compile("^\\s*\\{([^}]+)\\}"); + Matcher typeRefMatcher = typeRefPattern.matcher(afterTagText); + if (typeRefMatcher.find()) { + String typeName = typeRefMatcher.group(1).trim(); + tagTypeInfo = resolveType(typeName); + } + } + + // Mark the @tag itself (with TypeInfo for @type) + marks.add(new ScriptLine.Mark(tagStart, tagEnd, TokenType.JSDOC_TAG, tagTypeInfo)); + + // If this is @param, look for parameter name after the type + if ("param".equals(tagName)) { + // Look for: @param {Type} paramName or @param paramName + int afterTag = tagMatcher.end(); + String afterTagText = commentContent.substring(afterTag); + + // Pattern to match optional {Type} followed by parameter name + Pattern paramNamePattern = Pattern.compile("^\\s*(?:\\{[^}]*\\}\\s*)?([a-zA-Z_][a-zA-Z0-9_]*)"); + Matcher paramNameMatcher = paramNamePattern.matcher(afterTagText); + if (paramNameMatcher.find()) { + String paramName = paramNameMatcher.group(1); + int paramNameStart = commentStart + afterTag + paramNameMatcher.start(1); + int paramNameEnd = commentStart + afterTag + paramNameMatcher.end(1); + + // Check if this parameter exists in the method + boolean paramExists = methodParamNames.contains(paramName); + TokenType paramTokenType = paramExists ? TokenType.PARAMETER : TokenType.UNDEFINED_VAR; + + // Add to special ranges to exclude from comment marking + specialRanges.add(new int[]{paramNameStart, paramNameEnd}); + // Mark the parameter name + marks.add(new ScriptLine.Mark(paramNameStart, paramNameEnd, paramTokenType, null)); + } + } + } + + // Find {Type} references + Pattern typePattern = Pattern.compile("\\{([^}]+)\\}"); + Matcher typeMatcher = typePattern.matcher(commentContent); + while (typeMatcher.find()) { + int braceStart = commentStart + typeMatcher.start(); + int braceEnd = commentStart + typeMatcher.end(); + specialRanges.add(new int[]{braceStart, braceEnd}); + + // Mark braces + marks.add(new ScriptLine.Mark(braceStart, braceStart + 1, TokenType.JSDOC_TYPE, null)); // { + marks.add(new ScriptLine.Mark(braceEnd - 1, braceEnd, TokenType.JSDOC_TYPE, null)); // } + + // Mark the type name inside braces + String typeName = typeMatcher.group(1).trim(); + int typeStart = commentStart + typeMatcher.start(1); + int typeEnd = commentStart + typeMatcher.end(1); + + // Try to resolve the type for hover info + TypeInfo resolvedType = resolveType(typeName); + addTypeMark(marks, typeStart, typeEnd, + resolvedType != null ? resolvedType.getTokenType() : TokenType.UNDEFINED_VAR, + resolvedType); + } + + // Sort special ranges by start position + specialRanges.sort((a, b) -> Integer.compare(a[0], b[0])); + + // Mark the comment in FRAGMENTS between special elements + int lastPos = commentStart; + for (int[] range : specialRanges) { + // Mark from lastPos to start of special element + if (lastPos < range[0]) { + marks.add(new ScriptLine.Mark(lastPos, range[0], TokenType.COMMENT, null)); + } + lastPos = range[1]; // Move past the special element + } + // Mark from last special element to end of comment + if (lastPos < commentEnd) { + marks.add(new ScriptLine.Mark(lastPos, commentEnd, TokenType.COMMENT, null)); + } + } + } + + /** + * Find the method declaration that immediately follows the given position. + * Used to associate JSDoc comments with their methods for parameter validation. + */ + private MethodInfo findMethodAfterPosition(int position) { + // Skip whitespace after position + int searchStart = position; + while (searchStart < text.length() && Character.isWhitespace(text.charAt(searchStart))) { + searchStart++; + } + + // Find the method with the smallest offset that is >= searchStart + MethodInfo closestMethod = null; + int closestDistance = Integer.MAX_VALUE; + + for (MethodInfo method : methods) { + if (!method.isDeclaration()) + continue; + int methodStart = method.getFullDeclarationOffset(); + if (methodStart < 0) + methodStart = method.getNameOffset(); + if (methodStart < 0) + continue; + + // Check if this method starts at or after our search position + // but within a reasonable distance (e.g., 200 chars to account for modifiers) + if (methodStart >= position && methodStart < position + 200) { + int distance = methodStart - position; + if (distance < closestDistance) { + closestDistance = distance; + closestMethod = method; + } + } + } + + // Also check methods inside script types (including inner classes) + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + for (MethodInfo method : scriptType.getAllMethodsFlat()) { + if (!method.isDeclaration()) + continue; + int methodStart = method.getFullDeclarationOffset(); + if (methodStart < 0) + methodStart = method.getNameOffset(); + if (methodStart < 0) + continue; + + if (methodStart >= position && methodStart < position + 200) { + int distance = methodStart - position; + if (distance < closestDistance) { + closestDistance = distance; + closestMethod = method; + } + } + } + } + + return closestMethod; + } + + /** + * Mark all comments EXCEPT JSDoc comments (slash-star-star style). + * JSDoc comments are handled separately in markJSDocElements. + */ + private void markNonJSDocComments(List marks) { + // Match: /* ... */ (but not /**), // ..., # ... + Matcher m = COMMENT_PATTERN.matcher(text); + while (m.find()) { + int start = m.start(); + int end = m.end(); + String comment = m.group(); + + // Skip JSDoc comments (/** style) - they're handled separately + if (comment.startsWith("/**")) { + continue; + } + + marks.add(new ScriptLine.Mark(start, end, TokenType.COMMENT, null)); + } + } + + private void addTypeMark(List marks, int start, int end, TokenType type, Object metadata) { + int bracketStart = text.indexOf('[', start); + int coreEnd = (bracketStart >= start && bracketStart < end) ? bracketStart : end; + if (coreEnd < end) marks.add(new ScriptLine.Mark(coreEnd, end, TokenType.DEFAULT, null)); + marks.add(new ScriptLine.Mark(start, coreEnd, type, metadata)); + } + + private void markMethodDeclarations(List marks) { + Matcher m = METHOD_DECL_PATTERN.matcher(normalizeGenericNewlines(text)); + while (m.find()) { + if (isExcluded(m.start())) + continue; + + if (isExcluded(m.start(2))) + continue; + + if (hasExcludedRange(m.start(1), m.end(1))) + continue; + + // Skip class/interface/enum declarations - these look like method declarations + // but "class Foo(" is not a method, it's a class declaration3 + String returnType = m.group(1); + if (returnType.equals("class") || returnType.equals("interface") || returnType.equals("enum") ||returnType.equals("new")) { + continue; + } + + // Find the corresponding MethodInfo created in parseMethodDeclarations + int methodDeclStart = m.start(); + int methodNameStart = m.start(2); + MethodInfo methodInfo = null; + for (MethodInfo method : getAllMethods()) { + boolean matchesDeclStart = method.getTypeOffset() == methodDeclStart + || method.getFullDeclarationOffset() == methodDeclStart; + boolean matchesNameStart = method.getNameOffset() == methodNameStart; + + if (matchesDeclStart || matchesNameStart) { + methodInfo = method; + break; + } + } + + // Return type + TokenType returnToken = TokenType.UNDEFINED_VAR; + if (methodInfo != null) + returnToken = methodInfo.getReturnType().getTokenType(); + + int returnStart = m.start(1); + int returnEnd = m.end(1); + addTypeMark(marks, returnStart, returnEnd, + returnToken, methodInfo != null ? methodInfo.getReturnType() : null); + // Method name with MethodInfo metadata + marks.add(new ScriptLine.Mark(m.start(2), m.end(2), TokenType.METHOD_DECL, methodInfo)); + } + } + + private void markMethodCalls(List marks) { + Matcher m = METHOD_CALL_PATTERN.matcher(text); + while (m.find()) { + int nameStart = m.start(1); + int nameEnd = m.end(1); + String methodName = m.group(1); + + if (isExcluded(nameStart) || isKeyword(methodName)) + continue; + + // Skip if in import/package statement + if (isInImportOrPackage(nameStart)) + continue; + + boolean skip = false; + for (MethodInfo decl : methods) + if (decl.getNameOffset() == nameStart) + // This is a method declaration, not a call + skip = true; + + if (skip) + continue; + + // Find the opening parenthesis by scanning forward from the method name end + // The regex includes \( but we scan manually to be safe + int openParen = nameEnd; + while (openParen < text.length() && Character.isWhitespace(text.charAt(openParen))) { + openParen++; + } + + if (openParen >= text.length() || text.charAt(openParen) != '(') { + // Not actually a method call + continue; + } + + // Find the matching closing parenthesis + int closeParen = findMatchingParen(openParen); + if (closeParen < 0) { + // Malformed - no closing paren + continue; + } + + // Handle super() constructor calls + if (methodName.equals("super")) { + handleSuperConstructorCall(marks, nameStart, nameEnd, openParen, closeParen); + continue; + } + + // Parse the arguments (first pass - without expected types for overload resolution) + List arguments = parseMethodArguments(openParen + 1, closeParen, null, null); + + // Check if this is a static access (Class.method() style) + boolean isStaticAccess = isStaticAccessCall(nameStart); + + // Resolve receiver using existing chain-based resolver and detect static access + TypeInfo receiverType = resolveReceiverChain(nameStart); + MethodInfo resolvedMethod = null; + + if (receiverType != null) { + // Check for synthetic types first (JavaScript only) + SyntheticType syntheticType = null; + if (isJavaScript()) { + syntheticType = typeResolver.getSyntheticType(receiverType.getSimpleName()); + } + + if (syntheticType != null && syntheticType.hasMethod(methodName)) { + // Synthetic type method call (e.g., Java.type()) + resolvedMethod = syntheticType.getMethodInfo(methodName); + + // Check for dynamic return type resolution (like Java.type("className")) + SyntheticMethod synMethod = syntheticType.getMethod(methodName); + TypeInfo dynamicReturnType = null; + if (synMethod != null) { + String argsText = text.substring(openParen + 1, closeParen); + String[] strArgs = TypeResolver.parseStringArguments(argsText); + dynamicReturnType = synMethod.resolveReturnType(strArgs); + } + + MethodCallInfo callInfo = new MethodCallInfo(methodName, nameStart, nameEnd, openParen, + closeParen, arguments, receiverType, resolvedMethod, false); + + // Set the actual resolved return type for downstream type resolution + if (dynamicReturnType != null) { + callInfo.setResolvedReturnType(dynamicReturnType); + } + + callInfo.validate(); + methodCalls.add(callInfo); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL, callInfo)); + continue; + } + // Regular type - check for method existence using hierarchy search if it's a ScriptTypeInfo + boolean hasMethod = false; + TypeInfo rawReceiver = receiverType.getRawType(); + if (rawReceiver instanceof ScriptTypeInfo) { + hasMethod = ((ScriptTypeInfo) rawReceiver).hasMethodInHierarchy(methodName); + } else { + hasMethod = receiverType.hasMethod(methodName); + } + + if (hasMethod) { + + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType).toArray(TypeInfo[]::new); + + // Get best method overload based on argument types + resolvedMethod = receiverType.getBestMethodOverload(methodName, argTypes); + + if (isStaticAccess && resolvedMethod != null && !resolvedMethod.isStatic()) { + TokenErrorMessage errorMsg = TokenErrorMessage + .from("Cannot call non-static method '" + methodName + "' from static context '" + receiverType.getSimpleName() + "'") + .clearOtherErrors(); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.UNDEFINED_VAR, errorMsg)); + } else { + // Second pass: Re-resolve arguments with expected parameter types if method was found + if (resolvedMethod != null && resolvedMethod.getParameters().size() == arguments.size()) + arguments = parseMethodArguments(openParen + 1, closeParen, resolvedMethod, receiverType); + + + MethodCallInfo callInfo = new MethodCallInfo(methodName, nameStart, nameEnd, openParen, + closeParen, arguments, receiverType, resolvedMethod, isStaticAccess); + // Set expected type for validation if this is the final expression + if (!isFollowedByDot(closeParen)) { + TypeInfo expectedType = findExpectedTypeAtPosition(nameStart); + if (expectedType != null) { + callInfo.setExpectedType(expectedType); + } + } + + callInfo.validate(); + methodCalls.add(callInfo); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL, callInfo)); + } + } else { + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.UNDEFINED_VAR)); + } + } else { + boolean hasDot = isPrecededByDot(nameStart); + if (hasDot) { + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.UNDEFINED_VAR)); + } else { + if (isScriptMethod(methodName)) { + // Extract argument types from parsed arguments + + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType).toArray(TypeInfo[]::new); + resolvedMethod = getScriptMethodInfo(methodName, argTypes); + + // Second pass: Re-resolve arguments with expected parameter types if method was found + if (resolvedMethod != null && resolvedMethod.getParameters().size() == arguments.size()) { + arguments = parseMethodArguments(openParen + 1, closeParen, resolvedMethod, null); + } + + // Check if this is a method from a script type + // Instance methods from script types cannot be called without a receiver + if (resolvedMethod != null && isMethodFromScriptType(resolvedMethod) && !resolvedMethod.isStatic()) { + // Instance method called without receiver - mark as undefined + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.UNDEFINED_VAR)); + } else { + MethodCallInfo callInfo = new MethodCallInfo( + methodName, nameStart, nameEnd, openParen, closeParen, + arguments, null, resolvedMethod + ); + + // Only set expected type if this is the final expression (not followed by .field or .method) + if (!isFollowedByDot(closeParen)) { + TypeInfo expectedType = findExpectedTypeAtPosition(nameStart); + if (expectedType != null) { + callInfo.setExpectedType(expectedType); + } + } + + callInfo.validate(); + methodCalls.add(callInfo); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL, callInfo)); + } + } else if (isGlobalEngineFunction(methodName)) { + JSMethodInfo jsGlobalMethod = JSTypeRegistry.getInstance().getGlobalEngineFunction(methodName); + MethodInfo resolvedGlobal = MethodInfo.fromJSMethod(jsGlobalMethod, null); + + List globalArguments = arguments; + if (resolvedGlobal.getParameters().size() == arguments.size()) { + globalArguments = parseMethodArguments(openParen + 1, closeParen, resolvedGlobal, null); + } + + MethodCallInfo callInfo = new MethodCallInfo( + methodName, nameStart, nameEnd, openParen, closeParen, + globalArguments, null, resolvedGlobal + ); + if (!isFollowedByDot(closeParen)) { + TypeInfo expectedType = findExpectedTypeAtPosition(nameStart); + if (expectedType != null) callInfo.setExpectedType(expectedType); + } + callInfo.validate(); + methodCalls.add(callInfo); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL, callInfo)); + } else { + // Not a top-level script method or engine function — check if the call site is inside + // a ScriptTypeInfo whose method table contains this name (implicit 'this' call). + // e.g. getYaw() called without 'this.' or 'abilityLine.' inside AbilityLine resolves via AbilityLine's method hierarchy. + ScriptTypeInfo callerType = findEnclosingScriptType(nameStart); + + if (callerType != null && callerType.hasMethodInHierarchy(methodName)) { + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType).toArray(TypeInfo[]::new); + MethodInfo implicitMethod = callerType.getBestMethodOverload(methodName, argTypes); + if (implicitMethod != null && implicitMethod.getParameters().size() == arguments.size()) { + arguments = parseMethodArguments(openParen + 1, closeParen, implicitMethod, callerType); + } + MethodCallInfo callInfo = new MethodCallInfo( + methodName, nameStart, nameEnd, openParen, closeParen, + arguments, callerType, implicitMethod + ); + if (!isFollowedByDot(closeParen)) { + TypeInfo expectedType = findExpectedTypeAtPosition(nameStart); + if (expectedType != null) callInfo.setExpectedType(expectedType); + } + callInfo.validate(); + methodCalls.add(callInfo); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL, callInfo)); + } else { + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.UNDEFINED_VAR)); + } + } + } + } + } + } + + public boolean isKeyword(String word){ + Set keywords = new HashSet<>(Arrays.asList(TypeChecker.getJavaKeywords())); + if (isJavaScript()) + keywords.addAll(Arrays.asList(TypeChecker.getJavaScriptKeywords())); + return keywords.contains(word); + } + /** + * Check if a method call is a static access (Class.method() style). + * Returns true if the immediate receiver before the dot is a class name (uppercase). + */ + /** + * Check if a method call at the given position is static access. + * Walks backward from the method name to analyze the receiver. + */ + private boolean isStaticAccessCall(int methodNameStart) { + // Walk backward to find the dot + int pos = methodNameStart - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) + pos--; + + if (pos < 0 || isExcluded(pos) || text.charAt(pos) != '.') + return false; + + // Skip the dot and any whitespace + pos--; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) + pos--; + + if (pos < 0 || isExcluded(pos)) + return false; + + // Check what's before the dot - could be: + // 1. An identifier ending (field or class name) + // 2. A closing paren (method call result) + // 3. A closing bracket (array access) + + char c = text.charAt(pos); + if (c == ')' || c == ']') { + // Method call or array - would need complex expression resolution + // For now, conservatively treat as instance access + return false; + } + + if (!Character.isJavaIdentifierPart(c)) + return false; + + // Read the identifier backward + int identEnd = pos + 1; + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) + pos--; + int identStart = pos + 1; + + String ident = text.substring(identStart, identEnd); + + // Skip whitespace before the identifier + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) + pos--; + + // If preceded by a dot, this is part of a chain - treat as instance for now + if (pos >= 0 && !isExcluded(pos) && text.charAt(pos) == '.') { + return false; + } + + // Direct identifier - check if it resolves to a type (static) or variable (instance) + if (ident.isEmpty()) return false; + + // Use unified static access checker + return TypeResolver.isStaticAccessExpression(ident, identStart, this); + } + + /** + * Find the MethodCallInfo that contains the given position as an argument. + * Returns null if the position is not inside any method call's argument list. + */ + private MethodCallInfo findMethodCallContainingPosition(int position) { + for (MethodCallInfo call : methodCalls) { + // Check if position is within the argument list (between open and close parens) + if (position >= call.getOpenParenOffset() && position <= call.getCloseParenOffset()) { + // Check if it's within any of the arguments + for (MethodCallInfo.Argument arg : call.getArguments()) { + if (position >= arg.getStartOffset() && position <= arg.getEndOffset()) { + return call; + } + } + } + } + return null; + } + + /** + * Find the matching closing parenthesis for an opening parenthesis. + * Handles nested parentheses, strings, and comments. + */ + private int findMatchingParen(int openPos) { + if (openPos < 0 || openPos >= text.length() || text.charAt(openPos) != '(') { + return -1; + } + + int depth = 1; + boolean inString = false; + boolean inChar = false; + char stringChar = 0; + + for (int i = openPos + 1; i < text.length(); i++) { + char c = text.charAt(i); + char prev = (i > 0) ? text.charAt(i - 1) : 0; + + // Handle string literals + if (!inChar && (c == '"' || c == '\'') && prev != '\\') { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + continue; + } + + if (inString) continue; + + // Skip excluded regions (comments) + if (isExcluded(i)) continue; + + if (c == '(') { + depth++; + } else if (c == ')') { + depth--; + if (depth == 0) { + return i; + } + } + } + + return -1; // No matching paren found + } + + /** + * Parse method arguments from the text between opening and closing parentheses. + * Handles nested expressions, strings, and complex argument types. + */ + /** + * Parse method call arguments. + * + * @param start Start position of arguments (after opening paren) + * @param end End position of arguments (at closing paren) + * @param methodInfo Optional MethodInfo to provide expected parameter types for validation + * @param receiverType Optional receiver/containing type for substituting generic type parameters in argument types + * @return List of parsed arguments with resolved types + */ + public List parseMethodArguments(int start, int end, MethodInfo methodInfo, TypeInfo receiverType) { + List args = new ArrayList<>(); + + if (start >= end) + return args; // No arguments + + end = Math.min(end, text.length()); + + + int depth = 0; + int argStart = start; + boolean inString = false; + char stringChar = 0; + + for (int i = start; i <= end; i++) { + if (i == end || (depth == 0 && !inString && text.charAt(i) == ',')) { + // End of an argument + String argText = text.substring(argStart, i).trim(); + if (!argText.isEmpty()) { + // Find the actual start/end positions (excluding leading/trailing whitespace) + int actualStart = argStart; + while (actualStart < i && Character.isWhitespace(text.charAt(actualStart))) { + actualStart++; + } + int actualEnd = i; + while (actualEnd > actualStart && Character.isWhitespace(text.charAt(actualEnd - 1))) { + actualEnd--; + } + + // Try to resolve the argument type + // First check if this looks like a parameter declaration (Type varName) + // Get expected parameter type if available + TypeInfo expectedParamType = null; + if (methodInfo != null && args.size() < methodInfo.getParameters().size()) { + FieldInfo parameter = methodInfo.getParameters().get(args.size()); + expectedParamType = parameter.getTypeInfo(); + } + + TypeInfo argType = resolveArgumentType(argText, actualStart, expectedParamType); + + // Substitute type parameters using receiver's generic context + if (receiverType != null && argType != null && GenericContext.hasGenerics(receiverType)) { + GenericContext ctx = GenericContext.forReceiver(receiverType); + TypeInfo substituted = ctx.substitute(argType); + if (substituted != null && substituted.isResolved()) { + argType = substituted; + } + } + + String samConflictError = CURRENT_SAM_CONFLICT_ERROR.get(); + if (samConflictError != null) { + CURRENT_SAM_CONFLICT_ERROR.remove(); + args.add(new MethodCallInfo.Argument( + argText, actualStart, actualEnd, argType, false, samConflictError + )); + } else { + args.add(new MethodCallInfo.Argument( + argText, actualStart, actualEnd, argType, true, null + )); + } + } + argStart = i + 1; + continue; + } + + char c = text.charAt(i); + char prev = (i > start) ? text.charAt(i - 1) : 0; + + // Handle string literals + if (!inString && (c == '"' || c == '\'') && prev != '\\') { + inString = true; + stringChar = c; + } else if (inString && c == stringChar && prev != '\\') { + inString = false; + } + + if (!inString) { + if (c == '(' || c == '[' || c == '{' || c == '<') { + depth++; + } else if (c == ')' || c == ']' || c == '}') { + depth--; + } else if (c == '>' && prev != '-') { + // Skip '>' when preceded by '-' (lambda arrow '->'), otherwise treat as closing bracket + depth--; + } + } + } + + return args; + } + + /** + * Resolve the type of a method call argument. + * Handles both parameter declarations (Type varName) and expressions (variable.field()). + * + * @param argText The argument text + * @param position The position in the document + * @param expectedType Optional expected parameter type for validation + * @return The resolved type of the argument + */ + private TypeInfo resolveArgumentType(String argText, int position, TypeInfo expectedType) { + argText = argText.trim(); + + // Check if this looks like a parameter declaration: "Type varName" + // Pattern: identifier followed by whitespace and another identifier + if (argText.matches("^[A-Za-z_][a-zA-Z0-9_<>\\[\\],\\s\\n\\r]*\\s+[a-zA-Z_][a-zA-Z0-9_]*$")) { + // Split into tokens + String[] parts = argText.split("\\s+"); + if (parts.length >= 2) { + // Last part is the variable name, everything before is the type + // Join all but last as the type name + StringBuilder typeBuilder = new StringBuilder(); + for (int i = 0; i < parts.length - 1; i++) { + if (i > 0) typeBuilder.append(" "); + typeBuilder.append(parts[i]); + } + String typeName = typeBuilder.toString(); + return resolveType(typeName); + } + } + + // Otherwise, treat it as an expression with expected type context + if (expectedType != null) { + ExpressionTypeResolver.CURRENT_EXPECTED_TYPE = expectedType; + try { + return resolveExpressionType(argText, position); + } finally { + ExpressionTypeResolver.CURRENT_EXPECTED_TYPE = null; + } + } + + // No expected type - resolve normally + return resolveExpressionType(argText, position); + } + + /** + * Check if a numeric literal has excessive precision for its type. + * Counts significant digits (excluding leading zeros, decimal point, and suffix). + * + * @param numLiteral The numeric literal string (e.g., "1.23456789f", "0.00123456789") + * @param maxDigits Maximum significant digits allowed (7 for float, 15 for double) + * @return true if the literal has more significant digits than allowed + */ + private boolean hasExcessivePrecision(String numLiteral, int maxDigits) { + String cleaned = numLiteral.trim(); + + // Remove leading sign + if (cleaned.startsWith("-") || cleaned.startsWith("+")) { + cleaned = cleaned.substring(1); + } + + // Remove suffix (f, F, d, D, l, L) + if (cleaned.endsWith("f") || cleaned.endsWith("F") || + cleaned.endsWith("d") || cleaned.endsWith("D") || + cleaned.endsWith("l") || cleaned.endsWith("L")) { + cleaned = cleaned.substring(0, cleaned.length() - 1); + } + + // Remove decimal point for counting + cleaned = cleaned.replace(".", ""); + + // Remove leading zeros (they're not significant in the mantissa) + while (cleaned.startsWith("0") && cleaned.length() > 1) { + cleaned = cleaned.substring(1); + } + + // If it's just "0", that's fine + if (cleaned.equals("0") || cleaned.isEmpty()) { + return false; + } + + // Count significant digits + int significantDigits = cleaned.length(); + + return significantDigits > maxDigits; + } + + private TypeInfo narrowIntLiteral(String literalText) { + if (isJavaScript()) + return TypeInfo.NUMBER; + + TypeInfo expectedType = ExpressionTypeResolver.CURRENT_EXPECTED_TYPE; + if (expectedType != null) { + TypeInfo narrowed = TypeChecker.narrowLiteralToExpectedType(literalText, expectedType); + if (narrowed != null) { + return narrowed; + } + } + return TypeInfo.fromPrimitive("int"); + } + + /** + * Comprehensive expression type resolver that handles: + * - Literals (strings, numbers, booleans, null) + * - Variables (local, parameter, global) + * - Simple identifiers + * - Chained field accesses (a.b.c) + * - Chained method calls (a().b().c()) + * - Mixed chains (a.b().c.d()) + * - Static access (Class.field, Class.method()) + * - New expressions (new Type()) + * - All Java operators (arithmetic, logical, bitwise, etc.) + * + * This is THE method that should be used for all type resolution needs. + */ + public TypeInfo resolveExpressionType(String expr, int position) { + expr = expr.trim(); + expr = stripLineComments(expr); + + if (expr.endsWith(".")) + expr = expr.substring(0, expr.length() - 1).trim(); + + if (expr.isEmpty()) + return null; + + if (isJavaScript() && expr.charAt(0) == '{') { + ObjectLiteralParser.ObjectLiteralAnalysis analysis = objectLiterals.get(position); + if (analysis == null) + analysis = ObjectLiteralParser.parse(expr, position, true, false, this::resolveExpressionType, this::getScriptMethodInfo); + + if (analysis == null) { + return TypeInfo.ANY; + } + if (!analysis.supportsInference || analysis.inferredType == null) { + return TypeInfo.ANY; + } + return analysis.inferredType; + } + + LambdaCacheEntry cachedLambda = lambdaCache.get(position); + if (cachedLambda != null && cachedLambda.expectedType != null) { + return cachedLambda.expectedType; + } + + // Check if expression contains operators - if so, use the full expression resolver + // Handle cast expressions: (Type)expr, ((Type)expr).method(), etc + // Also route JS function expressions and arrow lambdas through the parser + if (containsOperators(expr) || expr.contains("::") || expr.contains("->") || expr.contains("=>") || expr.startsWith("(") || looksLikeFunctionOrLambda(expr)) { + return resolveExpressionWithParserAPI(expr, position); + } + + // JS array literals: [], [a, b], ["hi", "bye"] + if (isJavaScript() && expr.startsWith("[") && expr.endsWith("]")) { + String inner = expr.substring(1, expr.length() - 1).trim(); + return TypeInfo.arrayOf(unifyJsArrayElementType(inner, position + 1)); + } + + // Invalid expressions starting with brackets + if (expr.startsWith("[") || expr.startsWith("]")) { + return null; // Invalid syntax + } + + // String literals + if (expr.startsWith("\"") && expr.endsWith("\"")) { + return TypeInfo.string(); + } + + // Character literals + if (expr.startsWith("'") && expr.endsWith("'")) { + return TypeInfo.fromPrimitive("char"); + } + + // Boolean literals + if (expr.equals("true") || expr.equals("false")) { + return TypeInfo.fromPrimitive("boolean"); + } + + // Null literal + if (expr.equals("null")) { + return TypeInfo.NULL; // null is compatible with any reference type + } + + // Numeric literals with precision checking + // Float: can be 10f, 10.5f, 10.f, .5f + if (expr.matches("-?\\d*\\.?\\d+[fF]")) { + if (isJavaScript()) + return TypeInfo.NUMBER; + + // Check if it has too many decimal places for float (>7 significant digits) + // If so, treat it as double (causing type mismatch) + if (hasExcessivePrecision(expr, 7)) { + return TypeInfo.fromPrimitive("double"); + } + return TypeInfo.fromPrimitive("float"); + } + // Double: can be 10d, 10.5d, 10.5, .5, 10., but NOT plain integers + if (expr.matches("-?\\d*\\.\\d+[dD]?") || expr.matches("-?\\d+\\.[dD]?") || expr.matches("-?\\d+[dD]")) { + if (isJavaScript()) + return TypeInfo.NUMBER; + + // Check if it has too many decimal places for double (>15 significant digits) + // Return null to indicate the literal is invalid/unrepresentable + if (hasExcessivePrecision(expr, 15)) { + return null; // Exceeds double precision + } + return TypeInfo.fromPrimitive("double"); + } + // Long: 10L or 10l + if (expr.matches("-?\\d+[lL]")) { + if (isJavaScript()) + return TypeInfo.NUMBER; + + return TypeInfo.fromPrimitive("long"); + } + // Hex integer literals: 0x7F, -0x80, 0X1A + if (expr.matches("[-+]?0[xX][0-9a-fA-F][0-9a-fA-F_]*")) { + return narrowIntLiteral(expr); + } + // Binary integer literals: 0b1010, -0b1100, 0B1111 + if (expr.matches("[-+]?0[bB][01][01_]*")) { + return narrowIntLiteral(expr); + } + // Int: plain integers without suffix + if (expr.matches("[-+]?\\d[\\d_]*")) { + return narrowIntLiteral(expr); + } + + // "this" keyword + if (expr.equals("this")) { + return resolveThisType(position); + } + + if (expr.startsWith("new ")) { + Matcher newMatcher = NEW_TYPE_PATTERN.matcher(expr); + if (newMatcher.find()) { + String typeName = newMatcher.group(1); + FieldInfo varInfo = resolveVariable(typeName, position); + if (varInfo != null && varInfo.getTypeInfo() instanceof ClassTypeInfo) { + return ((ClassTypeInfo) varInfo.getTypeInfo()).getInstanceType(); + } + if (isJavaScript() && typeName.equals("Array")) { + String rest = expr.substring(newMatcher.end()).trim(); + String argsText = (rest.startsWith("(") && rest.endsWith(")")) + ? rest.substring(1, rest.length() - 1).trim() + : ""; + return TypeInfo.arrayOf(unifyJsArrayElementType(argsText, position)); + } + TypeInfo baseType = resolveType(typeName, position); + if (baseType == null) return null; + + // Parameterize with generic type arguments (e.g., new Box(...)) + String typeArgsClause = newMatcher.group(2); + if (typeArgsClause != null && !typeArgsClause.trim().isEmpty()) { + int typeArgsTextOffset = position + newMatcher.start(2); + baseType = parameterizeWithClause(baseType, typeArgsClause, position, typeArgsTextOffset); + } + + String rest = expr.substring(newMatcher.end()); + int dims = 0; + for (int i = 0; i < rest.length() && rest.charAt(i) != '('; i++) { + if (rest.charAt(i) == '[') { dims++; i = rest.indexOf(']', i); } + } + for (int i = 0; i < dims; i++) baseType = TypeInfo.arrayOf(baseType); + return baseType; + } + } + + // Now handle the complex case: chains of fields and method calls + // Parse the expression into segments + List segments = parseExpressionChain(expr); + + if (segments.isEmpty()) { + return null; + } + + // Resolve the first segment + ChainSegment first = segments.get(0); + TypeInfo currentType = null; + + if (first.name.equals("this")) { + currentType = resolveThisType(position); + // Handle this.field where we don't have a script type + if (currentType == null && segments.size() > 1 && !segments.get(1).isMethodCall) { + String fieldName = segments.get(1).name; + if (globalFields.containsKey(fieldName)) { + currentType = globalFields.get(fieldName).getTypeInfo(); + currentType = applyBracketAccess(currentType, segments.get(1)); + // Continue from segment 2 + for (int i = 2; i < segments.size(); i++) { + currentType = resolveChainSegment(currentType, segments.get(i)); + currentType = applyBracketAccess(currentType, segments.get(i)); + if (currentType == null) return null; + } + return currentType; + } + } + } else if (first.name.equals("super")) { + // Resolve super to parent class + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null && enclosingType.hasSuperClass()) { + currentType = enclosingType.getSuperClass(); + } else { + return null; // No parent class + } + } else { + // Check if first segment is a type name for static access + TypeInfo typeCheck = resolveType(first.name, position); + if (typeCheck != null && typeCheck.isResolved()) { + currentType = typeCheck; + } + } + + if (currentType == null && !first.isMethodCall) { + // Regular variable + FieldInfo varInfo = resolveVariable(first.name, position); + if (varInfo != null) { + currentType = varInfo.getTypeInfo(); + } else if (isScriptMethod(first.name)) { + // Script method reference used as an expression. + // In JS, this is commonly used as a SAM callback (e.g., schedule("id", actionFunction)). + TypeInfo expectedType = ExpressionTypeResolver.CURRENT_EXPECTED_TYPE; + TypeInfo samType = resolveScriptMethodAsSam(first.name, expectedType); + if (samType != null) { + currentType = samType; + } else if (isJavaScript()) { + // Provide a non-null placeholder type so overload selection can prefer functional-interface params. + currentType = TypeInfo.unresolved("", "__script_method_ref__"); + } + } + } else { + // First segment is a method call - check script methods + if (isScriptMethod(first.name)) { + MethodInfo scriptMethod = getScriptMethodInfo(first.name); + if (scriptMethod != null) { + currentType = scriptMethod.getReturnType(); + } + } + if (currentType == null && isGlobalEngineFunction(first.name)) { + currentType = getGlobalEngineFunctionReturnType(first.name); + } + if (currentType == null) { + // Implicit 'this' call: bare method name inside a ScriptTypeInfo body (e.g. getYaw() inside AbilityLine.foo()) + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null && enclosingType.hasMethodInHierarchy(first.name)) { + MethodInfo implicitMethod = enclosingType.getMethodInfoInHierarchy(first.name); + if (implicitMethod != null) { + currentType = implicitMethod.getReturnType(); + } + } + } + } + + currentType = applyBracketAccess(currentType, first); + + // Resolve the rest of the chain + for (int i = 1; i < segments.size(); i++) { + currentType = resolveChainSegment(currentType, segments.get(i)); + currentType = applyBracketAccess(currentType, segments.get(i)); + if (currentType == null) { + return null; + } + } + + return currentType; + } + + /** + * Resolve a cast or parenthesized expression. + * Delegates to CastExpressionResolver helper class. + * Handles: + * - Simple casts: (Type) expr + * - Nested casts: ((Type) expr) + * - Cast chains: ((Type) expr).method() + * - Parenthesized expressions: (expr) + * + * @param expr The expression starting with '(' + * @param position The position in the source text + * @return The resolved type + */ + private TypeInfo resolveCastOrParenthesizedExpression(String expr, int position) { + return CastExpressionResolver.resolveCastOrParenthesizedExpression( + expr, + position, + this::resolveType, + this::resolveExpressionType, + this::parseExpressionChain, + this::resolveChainSegment + ); + } + + + /** + * Parse an expression string into chain segments. + * Handles dots, method calls, and nested expressions. + * Examples: + * - "a.b.c" -> [a, b, c] (all fields) + * - "a().b()" -> [a(), b()] (all methods) + * - "a.b().c" -> [a, b(), c] (mixed) + */ + private List parseExpressionChain(String expr) { + List segments = new ArrayList<>(); + int i = 0; + + while (i < expr.length()) { + // Skip whitespace + while (i < expr.length() && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + if (i >= expr.length()) break; + + // Read identifier + int start = i; + while (i < expr.length() && Character.isJavaIdentifierPart(expr.charAt(i))) { + i++; + } + + if (i == start) { + // Not an identifier, skip this character + i++; + continue; + } + + String name = expr.substring(start, i); + + // Skip whitespace + while (i < expr.length() && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + // Check if followed by parentheses (method call) + boolean isMethodCall = false; + String arguments = null; + if (i < expr.length() && expr.charAt(i) == '(') { + isMethodCall = true; + int argsStart = i + 1; + // Skip to the matching closing paren + int depth = 1; + i++; + while (i < expr.length() && depth > 0) { + char c = expr.charAt(i); + if (c == '(') depth++; + else if (c == ')') depth--; + i++; + } + // Extract argument text (between parentheses) + int argsEnd = i - 1; // Position of closing paren + if (argsEnd > argsStart) { + arguments = expr.substring(argsStart, argsEnd); + } else { + arguments = ""; // Empty arguments + } + } + + boolean hasArrayAccess = false; + String bracketKey = null; + while (i < expr.length() && Character.isWhitespace(expr.charAt(i))) { + i++; + } + if (i < expr.length() && expr.charAt(i) == '[') { + hasArrayAccess = true; + int bracketStart = i + 1; + int depth = 1; + i++; + while (i < expr.length() && depth > 0) { + char c = expr.charAt(i); + if (c == '[') depth++; + else if (c == ']') depth--; + i++; + } + String bracketContent = expr.substring(bracketStart, i - 1).trim(); + if (bracketContent.length() >= 2) { + char q = bracketContent.charAt(0); + if ((q == '"' || q == '\'') && bracketContent.charAt(bracketContent.length() - 1) == q) { + bracketKey = bracketContent.substring(1, bracketContent.length() - 1); + } + } + } + + segments.add(new ChainSegment(name, start, i, isMethodCall, arguments, hasArrayAccess, bracketKey)); + + // Skip whitespace + while (i < expr.length() && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + // Check for dot (continuing chain) + if (i < expr.length() && expr.charAt(i) == '.') { + i++; // Skip the dot + } + } + + return segments; + } + + /** + * Resolve the full receiver chain before a method call position. + * For example, for "mc.thePlayer.worldObj.weatherEffects.get()", + * this would resolve mc -> Minecraft -> thePlayer -> EntityPlayer -> worldObj -> World -> weatherEffects -> List + * and return the final TypeInfo (List). + * + * Also handles method calls in chains like "Minecraft.getMinecraft().thePlayer" by resolving + * the return type of getMinecraft() and continuing resolution. + * + * @param methodNameStart The start position of the method name + * @return The TypeInfo of the final receiver, or null if no receiver or couldn't resolve + */ + TypeInfo resolveReceiverChain(int methodNameStart) { + // First check if preceded by a dot + int scanPos = methodNameStart - 1; + while (scanPos >= 0 && Character.isWhitespace(text.charAt(scanPos))) + scanPos--; + + // Guard: dot inside a comment/string must not be treated as a receiver chain separator + if (scanPos < 0 || isExcluded(scanPos) || text.charAt(scanPos) != '.') { + return null; // No receiver + } + + // Use the shared helper to locate the receiver expression before the dot, + // then delegate resolution to the comprehensive resolver. + int[] bounds = findReceiverBoundsBefore(scanPos); + if (bounds == null) return null; + int start = bounds[0]; + int end = bounds[1]; + String receiverExpr = text.substring(start, end).trim(); + if (receiverExpr.isEmpty()) return null; + return resolveExpressionType(receiverExpr, start); + } + + /** + * Parse argument types from a method call's argument list. + * @param argsText The text between parentheses (e.g., "20, 20" or "x, y.toString()") + * @param position The position in the source text + * @return Array of TypeInfo for each argument, or empty array if no arguments + */ + private TypeInfo[] parseArgumentTypes(String argsText, int position) { + if (argsText == null || argsText.trim().isEmpty()) { + return new TypeInfo[0]; + } + + // Split arguments by comma, respecting nested parentheses and strings + java.util.List args = new java.util.ArrayList<>(); + int depth = 0; + int start = 0; + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < argsText.length(); i++) { + char c = argsText.charAt(i); + + // Handle strings + if ((c == '"' || c == '\'') && (i == 0 || argsText.charAt(i-1) != '\\')) { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + continue; + } + + if (inString) continue; + + // Track parentheses depth + if (c == '(' || c == '[' || c == '{') { + depth++; + } else if (c == ')' || c == ']' || c == '}') { + depth--; + } else if (c == ',' && depth == 0) { + // Found argument separator at top level + args.add(argsText.substring(start, i).trim()); + start = i + 1; + } + } + + // Add the last argument + if (start < argsText.length()) { + args.add(argsText.substring(start).trim()); + } + + // Resolve each argument's type + TypeInfo[] argTypes = new TypeInfo[args.size()]; + for (int i = 0; i < args.size(); i++) { + argTypes[i] = resolveExpressionType(args.get(i), position); + } + + return argTypes; + } + + /** + * For JavaScript array literals, unify the element types to determine the array's element type. + */ + private TypeInfo unifyJsArrayElementType(String argsText, int position) { + if (argsText.isEmpty()) return TypeInfo.ANY; + TypeInfo[] elementTypes = parseArgumentTypes(argsText, position); + if (elementTypes.length == 1 && TypeInfo.NUMBER.equals(elementTypes[0])) return TypeInfo.ANY; + TypeInfo common = null; + boolean allSame = true; + for (TypeInfo t : elementTypes) { + boolean isUnresolvable = t == null || TypeInfo.NULL.equals(t); + if (isUnresolvable) continue; + if (common == null) { + common = t; + } else if (!common.equals(t)) { + allSame = false; + break; + } + } + return allSame && common != null ? common : TypeInfo.ANY; + } + + /** + * Helper class for chain segments (can be field access or method call). + */ + private static class ChainSegment { + final String name; + final int start; + final int end; + final boolean isMethodCall; + final String arguments; + final boolean hasArrayAccess; + final String bracketKey; + + ChainSegment(String name, int start, int end, boolean isMethodCall, String arguments, boolean hasArrayAccess, String bracketKey) { + this.name = name; + this.start = start; + this.end = end; + this.isMethodCall = isMethodCall; + this.arguments = arguments; + this.hasArrayAccess = hasArrayAccess; + this.bracketKey = bracketKey; + } + } + + /** + * + */ + private String stripLineComments(String expr) { + if (!expr.contains("//")) + return expr; + + String[] lines = expr.split("\n", -1); + StringBuilder result = new StringBuilder(); + for (String line : lines) { + int ci = findLineCommentStart(line); + String part = (ci >= 0 ? line.substring(0, ci) : line).trim(); + if (!part.isEmpty()) { + if (result.length() > 0) result.append(' '); + result.append(part); + } + } + return result.toString().trim(); + } + + private static int findLineCommentStart(String line) { + boolean inString = false; + char stringChar = 0; + for (int i = 0; i < line.length(); i++) { + char c = line.charAt(i); + if (inString) { + if (c == '\\' && i + 1 < line.length()) { + i++; + continue; + } + if (c == stringChar) { + inString = false; + } + continue; + } + if (c == '"' || c == '\'') { + inString = true; + stringChar = c; + continue; + } + if (c == '/' && i + 1 < line.length() && line.charAt(i + 1) == '/') { + return i; + } + } + return -1; + } + + /** + * Handle ObjectLiteral bracket access (e.g., obj["field"] or obj[fieldName]) and array access (e.g., items[0]). + * @param type + * @param seg + * @return + */ + private TypeInfo applyBracketAccess(TypeInfo type, ChainSegment seg) { + if (type == null || !seg.hasArrayAccess) return type; + if (seg.bracketKey != null) { + FieldInfo f = type.getFieldInfo(seg.bracketKey); + return f != null ? f.getTypeInfo() : TypeInfo.ANY; + } + if (type.isSyntheticObjectLiteralType()) return TypeInfo.ANY; + return unwrapArrayElement(type); + } + /** + * Extract the element type from an array type, using multiple fallback strategies. + * + * Used when a chain segment has array subscript notation (e.g., items[1]). + * Given an array type like IItemStack[], returns IItemStack so that subsequent + * chain resolution (e.g., .getName()) operates on the element type, not the array type. + * + * Strategy (in priority order): + * 1. If TypeInfo stores elementType (preferred, from arrayOf factory), use it directly + * 2. If fullName has [] suffix (legacy or JS types), strip it and re-resolve + * 3. If underlying javaClass is an array, use Class.getComponentType() + * 4. Fallback to ANY type to prevent null propagation + * + * @param arrayType The array type to unwrap + * @return The element type, or TypeInfo.ANY if unwrapping fails + */ + private TypeInfo unwrapArrayElement(TypeInfo arrayType) { + if (arrayType == null) return null; + TypeInfo el = arrayType.getElementType(); + if (el != null) return el; + String name = arrayType.getFullName(); + if (name != null && name.endsWith("[]")) { + return resolveType(name.substring(0, name.length() - 2)); + } + if (arrayType.getJavaClass() != null && arrayType.getJavaClass().isArray()) { + return TypeInfo.fromClass(arrayType.getJavaClass().getComponentType()); + } + return TypeInfo.ANY; + } + + /** + * Resolve a single segment of a chain given the current type context. + */ + private TypeInfo resolveChainSegment(TypeInfo currentType, ChainSegment segment) { + if (currentType == null || !currentType.isResolved()) { + return null; + } + + // Check if current type is a synthetic type + if (isJavaScript()) { + SyntheticType syntheticType = typeResolver.getSyntheticType(currentType.getSimpleName()); + if (syntheticType != null) { + return resolveSyntheticChainSegment(syntheticType, segment); + } + } + + if (segment.isMethodCall) { + // Method call - get return type with argument-based overload resolution + // Check for method existence using hierarchy search if it's a ScriptTypeInfo + boolean hasMethod = false; + TypeInfo rawType = currentType.getRawType(); + if (rawType instanceof ScriptTypeInfo) { + hasMethod = ((ScriptTypeInfo) rawType).hasMethodInHierarchy(segment.name); + } else { + hasMethod = currentType.hasMethod(segment.name); + } + + if (hasMethod) { + // Parse argument types from the method call + TypeInfo[] argTypes = parseArgumentTypes(segment.arguments, segment.start); + + // Get the best matching overload based on argument types + // getBestMethodOverload is now overridden in ScriptTypeInfo to search hierarchy + MethodInfo methodInfo = currentType.getBestMethodOverload(segment.name, argTypes); + return (methodInfo != null) ? methodInfo.getReturnType() : null; + } + return null; + } else { + // Field access - use hierarchy search for ScriptTypeInfo + boolean hasField = false; + FieldInfo fieldInfo = null; + + TypeInfo rawType = currentType.getRawType(); + if (rawType instanceof ScriptTypeInfo) { + hasField = ((ScriptTypeInfo) rawType).hasFieldInHierarchy(segment.name); + if (hasField) { + fieldInfo = currentType.getFieldInfo(segment.name); + } + } else { + hasField = currentType.hasField(segment.name); + if (hasField) { + fieldInfo = currentType.getFieldInfo(segment.name); + } + } + + if (hasField) { + return (fieldInfo != null) ? fieldInfo.getTypeInfo() : null; + } + + // Field not found — check if the segment names an inner class. + // This handles chains like Outer.Inner where Inner is a nested type, not a field. + if (rawType instanceof ScriptTypeInfo) { + ScriptTypeInfo innerClass = ((ScriptTypeInfo) rawType).getInnerClass(segment.name); + if (innerClass != null) { + return innerClass; + } + } + // Also check Java inner classes via reflection (e.g., Map.Entry) + if (currentType.getJavaClass() != null) { + try { + for (Class nested : currentType.getJavaClass().getDeclaredClasses()) { + if (java.lang.reflect.Modifier.isPublic(nested.getModifiers()) + && nested.getSimpleName().equals(segment.name)) { + return TypeInfo.fromClass(nested); + } + } + } catch (SecurityException ignored) { } + } + + return null; + } + } + + /** + * Resolve a chain segment on a synthetic type (like Nashorn's Java object). + */ + /** + * Resolve a chain segment for a synthetic type (method call or field access). + * Handles dynamic return type resolution for methods like Java.type(). + */ + private TypeInfo resolveSyntheticChainSegment(SyntheticType syntheticType, ChainSegment segment) { + if (segment.isMethodCall) { + SyntheticMethod method = syntheticType.getMethod(segment.name); + if (method != null) { + // For methods with dynamic return type resolvers (like Java.type), + // extract string arguments and resolve + if (segment.arguments != null) { + String[] args = TypeResolver.parseStringArguments(segment.arguments); + TypeInfo resolved = method.resolveReturnType(args); + if (resolved != null) { + return resolved; + } + } + // Fall back to static return type + TypeInfo returnType = typeResolver.resolve(method.returnType); + return returnType != null ? returnType : TypeInfo.unresolved(method.returnType, method.returnType); + } + } else { + SyntheticField field = syntheticType.getField(segment.name); + if (field != null) { + TypeInfo fieldType = typeResolver.resolve(field.typeName); + return fieldType != null ? fieldType : TypeInfo.unresolved(field.typeName, field.typeName); + } + } + return null; + } + + /** + * Resolve the type of "this" at a given position by finding the innermost scope and checking for containing object types. + * For both Java and JavaScript, this will correctly resolve to the appropriate type based on the current context (e.g., enclosing class, script type, or synthetic type). + * @param position + * @return + */ + TypeInfo resolveThisType(int position) { + Object innermostScope = findInnermostScopeAt(position); + if (innermostScope instanceof InnerCallableScope) { + TypeInfo objectType = ((InnerCallableScope) innermostScope).getContainingObjectType(); + if (objectType != null && objectType.isResolved()) { + return objectType; + } + } + return findEnclosingScriptType(position); + } + + // ==================== OPERATOR EXPRESSION RESOLUTION ==================== + + /** + * Check if an expression contains operators that need advanced resolution. + * This is a quick heuristic check - it may have false positives for operators + * inside strings, but those are handled by the full parser. + */ + public boolean containsOperators(String expr) { + if (expr == null) return false; + + boolean inString = false; + boolean inChar = false; + + for (int i = 0; i < expr.length(); i++) { + char c = expr.charAt(i); + char next = (i + 1 < expr.length()) ? expr.charAt(i + 1) : 0; + + // Track string literals + if (c == '"' && !inChar) { + if (!inString) { + inString = true; + } else if (i > 0 && expr.charAt(i - 1) != '\\') { + inString = false; + } + continue; + } + + // Track char literals + if (c == '\'' && !inString) { + if (!inChar) { + inChar = true; + } else if (i > 0 && expr.charAt(i - 1) != '\\') { + inChar = false; + } + continue; + } + + // Skip content inside strings/chars + if (inString || inChar) continue; + + // Check for operators (excluding . which is used for member access) + switch (c) { + case '+': + // + is arithmetic unless it's unary at start or after operator + if (next == '+') return true; // ++ + if (next == '=') return true; // += + // Check if this is binary + by looking at previous non-whitespace + int prevIdx = i - 1; + while (prevIdx >= 0 && Character.isWhitespace(expr.charAt(prevIdx))) prevIdx--; + if (prevIdx >= 0) { + char prev = expr.charAt(prevIdx); + // If previous char is identifier char or ), this is binary + if (Character.isJavaIdentifierPart(prev) || prev == ')' || prev == ']' || prev == '"' || prev == '\'' || Character.isDigit(prev)) { + return true; + } + } + break; + + case '-': + // - is arithmetic unless it's unary minus before a number + if (next == '-') return true; // -- + if (next == '=') return true; // -= + // Check if this is binary - by looking at previous non-whitespace + prevIdx = i - 1; + while (prevIdx >= 0 && Character.isWhitespace(expr.charAt(prevIdx))) prevIdx--; + if (prevIdx >= 0) { + char prev = expr.charAt(prevIdx); + // If previous char is identifier char or ), this is binary + if (Character.isJavaIdentifierPart(prev) || prev == ')' || prev == ']' || Character.isDigit(prev)) { + return true; + } + } + break; + + case '*': case '/': case '%': + return true; + + case '&': + if (next == '&' || next == '=') return true; + // Single & is bitwise AND + return true; + + case '|': + if (next == '|' || next == '=') return true; + // Single | is bitwise OR + return true; + + case '^': case '~': + return true; + + case '<': + // <<, <= are always operators + if (next == '<' || next == '=') return true; + // If preceded by digit/)/] it's definitely a relational operator (not a generic) + prevIdx = i - 1; + while (prevIdx >= 0 && Character.isWhitespace(expr.charAt(prevIdx))) prevIdx--; + if (prevIdx >= 0) { + char prevC = expr.charAt(prevIdx); + if (Character.isDigit(prevC) || prevC == ')' || prevC == ']') return true; + } + // Generics follow an uppercase type name; anything else is relational + int nextNonSpace = i + 1; + while (nextNonSpace < expr.length() && Character.isWhitespace(expr.charAt(nextNonSpace))) nextNonSpace++; + if (nextNonSpace < expr.length() && !Character.isUpperCase(expr.charAt(nextNonSpace))) { + return true; + } + break; + + case '>': + // >>, >= are always operators + if (next == '>' || next == '=') return true; + // If preceded by digit/)/] it's definitely a relational operator (not closing generic) + prevIdx = i - 1; + while (prevIdx >= 0 && Character.isWhitespace(expr.charAt(prevIdx))) prevIdx--; + if (prevIdx >= 0) { + char prevC = expr.charAt(prevIdx); + if (Character.isDigit(prevC) || prevC == ')' || prevC == ']') return true; + } + break; + + case '!': + if (next == '=') return true; // != + // Standalone ! is logical NOT + return true; + + case '=': + if (next == '=') return true; // == + // Single = is assignment + return true; + + case '?': + // Ternary operator - but be careful of generics with ? + // If followed by :, it's definitely ternary + for (int j = i + 1; j < expr.length(); j++) { + if (expr.charAt(j) == ':') return true; + } + break; + } + } + + // Check for instanceof keyword + if (expr.contains(" instanceof ")) { + return true; + } + + return false; + } + + /** + * Check if an expression looks like a JS function or arrow lambda. + * This is a fast heuristic to detect: + * - JS function expressions: function(...) {} + * - Arrow lambdas: (...) => ... + * These need to be routed through the parser for proper SAM typing. + */ + private boolean looksLikeFunctionOrLambda(String expr) { + if (expr == null || expr.isEmpty()) return false; + String trimmed = expr.trim(); + if (trimmed.startsWith("function")) return true; + if (trimmed.contains("=>")) return true; + if (trimmed.contains("->")) return true; + return false; + } + + /** + * Resolve an expression that contains operators or casts using the full expression parser. + * This handles all Java operators with proper precedence and type promotion rules. + */ + private TypeInfo resolveExpressionWithParserAPI(String expr, int position) { + // Create a context that bridges to ScriptDocument's existing resolution methods + ExpressionNode.TypeResolverContext context = createExpressionResolverContext(position); + + // Use the expression resolver to parse and resolve the type + // Pass the position as basePosition so lambda position calculations work correctly + ExpressionTypeResolver resolver = new ExpressionTypeResolver(context, this, position); + TypeInfo result = resolver.resolve(expr); + + // Special case: null literal type is "unresolved" but valid + if (result != null && "".equals(result.getFullName())) { + return result; + } + + // If the expression resolver couldn't resolve it, fall back to simple resolution + if (result == null || !result.isResolved()) { + // Try the simple path in case the operator detection was a false positive + return resolveSimpleExpression(expr, position); + } + + return result; + } + + /** + * Create a type resolver context that connects the expression resolver + * to ScriptDocument's existing type resolution infrastructure. + */ + private ExpressionNode.TypeResolverContext createExpressionResolverContext(int position) { + return new ExpressionNode.TypeResolverContext() { + @Override + public TypeInfo resolveIdentifier(String name) { + if ("this".equals(name)) { + return resolveThisType(position); + } + if ("super".equals(name)) { + // Resolve super to parent class type + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null && enclosingType.hasSuperClass()) { + return enclosingType.getSuperClass(); + } + return null; + } + if ("true".equals(name) || "false".equals(name)) { + return TypeInfo.fromPrimitive("boolean"); + } + if ("null".equals(name)) { + return TypeInfo.unresolved("null", ""); + } + + // Variable shadowing: variables take precedence over script methods + FieldInfo varInfo = resolveVariable(name, position); + if (varInfo != null) { + return varInfo.getTypeInfo(); + } + + if (name.length() > 0) { + TypeInfo typeCheck = resolveType(name, position); + if (typeCheck != null && typeCheck.isResolved()) { + return typeCheck; + } + } + + // Named script function as SAM callback: schedule("id", actionFunction) + TypeInfo expectedType = ExpressionTypeResolver.CURRENT_EXPECTED_TYPE; + TypeInfo samType = resolveScriptMethodAsSam(name, expectedType); + if (samType != null) { + return samType; + } + + return null; + } + + @Override + public TypeInfo resolveMemberAccess(TypeInfo targetType, String memberName) { + if (targetType == null || !targetType.isResolved()) { + return null; + } + + if (targetType.hasField(memberName)) { + FieldInfo fieldInfo = targetType.getFieldInfo(memberName); + return (fieldInfo != null) ? fieldInfo.getTypeInfo() : null; + } + + return null; + } + + @Override + public TypeInfo resolveMethodCall(TypeInfo targetType, String methodName, TypeInfo[] argTypes) { + if (targetType == null || !targetType.isResolved()) { + // Try as a script-defined method + if (isScriptMethod(methodName)) { + MethodInfo scriptMethod = getScriptMethodInfo(methodName); + if (scriptMethod != null) { + return scriptMethod.getReturnType(); + } + } + if (isGlobalEngineFunction(methodName)) { + return getGlobalEngineFunctionReturnType(methodName); + } + return null; + } + + if (targetType.hasMethod(methodName)) { + MethodInfo methodInfo = targetType.getBestMethodOverload(methodName, argTypes); + return (methodInfo != null) ? methodInfo.getReturnType() : null; + } + + return null; + } + + @Override + public TypeInfo resolveArrayAccess(TypeInfo arrayType) { + if (arrayType == null || !arrayType.isResolved()) { + return null; + } + + String typeName = arrayType.getFullName(); + if (typeName.endsWith("[]")) { + String elementTypeName = typeName.substring(0, typeName.length() - 2); + // Try to resolve the element type properly + return resolveType(elementTypeName); + } + + // For List or similar, try to extract the element type + // This is a simplified version - could be enhanced for full generic support + return null; + } + + @Override + public TypeInfo resolveTypeName(String typeName) { + return resolveType(typeName); + } + }; + } + + /** + * Resolve a simple expression without operators. + * This is the fallback path when operator detection was a false positive. + */ + private TypeInfo resolveSimpleExpression(String expr, int position) { + // String literals + if (expr.startsWith("\"") && expr.endsWith("\"")) { + return TypeInfo.string(); + } + + // Character literals + if (expr.startsWith("'") && expr.endsWith("'")) { + return TypeInfo.fromPrimitive("char"); + } + + // Boolean literals + if (expr.equals("true") || expr.equals("false")) { + return TypeInfo.fromPrimitive("boolean"); + } + + // Null literal + if (expr.equals("null")) { + return null; + } + + // Numeric literals + if (expr.matches("-?\\d*\\.?\\d+[fF]")) { + if (hasExcessivePrecision(expr, 7)) { + return TypeInfo.fromPrimitive("double"); + } + return TypeInfo.fromPrimitive("float"); + } + if (expr.matches("-?\\d*\\.\\d+[dD]?") || expr.matches("-?\\d+\\.[dD]?") || expr.matches("-?\\d+[dD]")) { + if (hasExcessivePrecision(expr, 15)) { + return null; + } + return TypeInfo.fromPrimitive("double"); + } + if (expr.matches("-?\\d+[lL]")) { + return TypeInfo.fromPrimitive("long"); + } + // Hex integer literals: 0x7F, -0x80, 0X1A + if (expr.matches("[-+]?0[xX][0-9a-fA-F][0-9a-fA-F_]*")) { + return narrowIntLiteral(expr); + } + // Binary integer literals: 0b1010, -0b1100, 0B1111 + if (expr.matches("[-+]?0[bB][01][01_]*")) { + return narrowIntLiteral(expr); + } + if (expr.matches("[-+]?\\d[\\d_]*")) { + return narrowIntLiteral(expr); + } + + // "this" keyword + if (expr.equals("this")) { + return resolveThisType(position); + } + + // "new Type()" expressions + if (expr.startsWith("new ")) { + Matcher newMatcher = NEW_TYPE_PATTERN.matcher(expr); + if (newMatcher.find()) { + String typeName = newMatcher.group(1); + + // First check if it's a variable holding a ClassTypeInfo (like var File = Java.type("java.io.File")) + FieldInfo varInfo = resolveVariable(typeName, position); + if (varInfo != null && varInfo.getTypeInfo() instanceof ClassTypeInfo) { + // It's a variable holding a class reference, return the wrapped class + ClassTypeInfo classRef = (ClassTypeInfo) varInfo.getTypeInfo(); + return classRef.getInstanceType(); + } + + // Otherwise treat it as a type name + TypeInfo baseType = resolveType(typeName); + if (baseType != null) { + String typeArgsClause = newMatcher.group(2); + if (typeArgsClause != null && !typeArgsClause.trim().isEmpty()) { + int typeArgsTextOffset = position + newMatcher.start(2); + baseType = parameterizeWithClause(baseType, typeArgsClause, position, typeArgsTextOffset); + } + } + return baseType; + } + } + + // Try as variable or field chain + List segments = parseExpressionChain(expr); + if (segments.isEmpty()) { + return null; + } + + ChainSegment first = segments.get(0); + TypeInfo currentType = null; + + if (first.name.equals("this")) { + currentType = resolveThisType(position); + } else { + // Check if first segment is a type name + TypeInfo typeCheck = resolveType(first.name, position); + if (typeCheck != null && typeCheck.isResolved()) { + currentType = typeCheck; + } + } + + if (currentType == null && !first.isMethodCall) { + FieldInfo varInfo = resolveVariable(first.name, position); + if (varInfo != null) { + currentType = varInfo.getTypeInfo(); + } + } else { + if (isScriptMethod(first.name)) { + MethodInfo scriptMethod = getScriptMethodInfo(first.name); + if (scriptMethod != null) { + currentType = scriptMethod.getReturnType(); + } + } + if (currentType == null && isGlobalEngineFunction(first.name)) { + currentType = getGlobalEngineFunctionReturnType(first.name); + } + } + + currentType = applyBracketAccess(currentType, first); + + for (int i = 1; i < segments.size(); i++) { + currentType = resolveChainSegment(currentType, segments.get(i)); + currentType = applyBracketAccess(currentType, segments.get(i)); + if (currentType == null) { + return null; + } + } + + return currentType; + } + + /** + * Find the matching opening parenthesis when given a closing paren position. + */ + private int findMatchingParenBackward(int closeParenPos) { + if (closeParenPos < 0 || closeParenPos >= text.length() || text.charAt(closeParenPos) != ')') { + return -1; + } + + int depth = 1; + boolean inString = false; + char stringChar = 0; + + for (int i = closeParenPos - 1; i >= 0; i--) { + char c = text.charAt(i); + char next = (i < text.length() - 1) ? text.charAt(i + 1) : 0; + + // Handle string literals (going backward, check for escapes) + if (!inString && (c == '"' || c == '\'')) { + // Check if this quote is escaped (look back for backslash) + int backslashCount = 0; + for (int j = i - 1; j >= 0 && text.charAt(j) == '\\'; j--) { + backslashCount++; + } + if (backslashCount % 2 == 0) { + inString = true; + stringChar = c; + } + } else if (inString && c == stringChar) { + int backslashCount = 0; + for (int j = i - 1; j >= 0 && text.charAt(j) == '\\'; j--) { + backslashCount++; + } + if (backslashCount % 2 == 0) { + inString = false; + } + } + + if (inString) continue; + + // Skip excluded regions (comments) + if (isExcluded(i)) continue; + + if (c == ')') { + depth++; + } else if (c == '(') { + depth--; + if (depth == 0) { + return i; + } + } + } + + return -1; // No matching paren found + } + + /** + * Find the matching opening bracket of a given closing bracket position. + * Supports any pair of open/close chars (e.g., '[' and ']'). + */ + private int findMatchingBracketBackward(int closePos, char openChar, char closeChar) { + if (closePos < 0 || closePos >= text.length() || text.charAt(closePos) != closeChar) { + return -1; + } + + int depth = 1; + boolean inString = false; + char stringChar = 0; + + for (int i = closePos - 1; i >= 0; i--) { + char c = text.charAt(i); + + // Handle string literals (backward) + if (!inString && (c == '"' || c == '\'')) { + int backslashCount = 0; + for (int j = i - 1; j >= 0 && text.charAt(j) == '\\'; j--) backslashCount++; + if (backslashCount % 2 == 0) { + inString = true; + stringChar = c; + } + } else if (inString && c == stringChar) { + int backslashCount = 0; + for (int j = i - 1; j >= 0 && text.charAt(j) == '\\'; j--) backslashCount++; + if (backslashCount % 2 == 0) { + inString = false; + } + } + + if (inString) continue; + + if (isExcluded(i)) continue; + + if (c == closeChar) depth++; + else if (c == openChar) { + depth--; + if (depth == 0) return i; + } + } + return -1; + } + + /** + * Given the position of a dot ('.') in `text`, find the bounds [start, end) + * of the receiver expression immediately to the left of the dot. The end + * returned will be the dot index (exclusive). Returns null if not found or malformed. + */ + int[] findReceiverBoundsBefore(int dotIndex) { + if (dotIndex < 0 || dotIndex >= text.length() || text.charAt(dotIndex) != '.') { + return null; + } + + int pos = dotIndex - 1; + // Skip whitespace + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--; + if (pos < 0) return null; + + while (pos >= 0) { + // Check if we're in an excluded range (comment, string, etc.) + // Skip excluded regions to avoid picking up types from comment text + if (isExcluded(pos)) { + // Find the excluded range and skip to before it + for (int[] range : excludedRanges) { + if (pos >= range[0] && pos < range[1]) { + pos = range[0] - 1; // Jump to before the excluded range + break; + } + } + continue; // Continue scanning from before the excluded range + } + + char c = text.charAt(pos); + if (Character.isWhitespace(c)) { pos--; continue; } + + if (c == ')') { + int open = findMatchingParenBackward(pos); + if (open < 0) return null; + pos = open - 1; + continue; + } + + if (c == ']') { + int open = findMatchingBracketBackward(pos, '[', ']'); + if (open < 0) return null; + pos = open - 1; + continue; + } + + if (Character.isJavaIdentifierPart(c)) { + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) pos--; + // Skip whitespace AND excluded ranges to check for chained identifier (preceded by a dot). + // Without skipping excluded ranges, a dot inside a comment (e.g. "//event.\n player") + // would be mistaken for a chain continuation dot. + int checkPos = pos; + while (checkPos >= 0) { + if (isExcluded(checkPos)) { + for (int[] range : excludedRanges) { + if (checkPos >= range[0] && checkPos < range[1]) { + checkPos = range[0] - 1; + break; + } + } + continue; + } + if (Character.isWhitespace(text.charAt(checkPos))) { checkPos--; continue; } + break; + } + if (checkPos >= 0 && !isExcluded(checkPos) && text.charAt(checkPos) == '.') { pos = checkPos - 1; continue; } + break; + } + + // Unexpected char - stop and treat as start after this + break; + } + + int start = pos + 1; + int end = dotIndex; // exclusive + if (start >= end) return null; + return new int[]{start, end}; + } + + /** + * Find the innermost script-defined type that contains the given position. + * Uses recursive descent: starts from top-level types in scriptTypes, then drills + * into inner classes. This is O(depth) rather than O(total_types). + */ + public ScriptTypeInfo findEnclosingScriptType(int position) { +for (ScriptTypeInfo type:scriptTypes.values()) { + if (type.containsPosition(position)) { + return findInnermostType(type,position); + } + } + return null; + } + + /** + * Recursively descend into inner classes to find the innermost type containing the position. + * At each level, if an inner class contains the position, recurse into it. + * If no inner class matches, the current parent is the innermost enclosing type. + */ + private ScriptTypeInfo findInnermostType(ScriptTypeInfo parent, int position) { + for (ScriptTypeInfo inner : parent.getInnerClasses()) { + if (inner.containsPosition(position)) { + return findInnermostType(inner, position); + } + } + return parent; + } + + /** + * Find the constructor that contains the given position. + * Used for validating super() calls. + */ + private MethodInfo findEnclosingConstructor(int position) { + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType == null) + return null; + + for (MethodInfo constructor : enclosingType.getConstructors()) { + int bodyStart = constructor.getBodyStart(); + int bodyEnd = constructor.getBodyEnd(); + if (bodyStart >= 0 && bodyEnd > bodyStart && position >= bodyStart && position < bodyEnd) { + return constructor; + } + } + return null; + } + + /** + * Handle super() constructor calls with validation and argument matching. + */ + private void handleSuperConstructorCall(List marks, int nameStart, int nameEnd, int openParen, + int closeParen) { + // Validate that we're in a constructor + TokenErrorMessage errorMsg = null; + + //Parent class + ScriptTypeInfo enclosingType = findEnclosingScriptType(nameStart); + MethodInfo enclosingConstructor = findEnclosingConstructor(nameStart); + TypeInfo superClass = enclosingType != null ? enclosingType.getSuperClass() : null; + + // Parse arguments and find matching parent constructor + List arguments = parseMethodArguments(openParen + 1, closeParen, null, superClass); + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType).toArray(TypeInfo[]::new); + + // Find matching constructor in parent class + MethodInfo parentConstructor = superClass != null ? superClass.findConstructor(argTypes) : null; + + if (enclosingType == null || !enclosingType.hasSuperClass()) { + // No parent class - error + errorMsg = TokenErrorMessage + .from(enclosingType == null ? "'super()' can only be used within a class" : "Class '" + enclosingType.getSimpleName() + "' does not have a parent class") + .clearOtherErrors(); + } else if (enclosingConstructor == null) { + // Not in a constructor - error + errorMsg = TokenErrorMessage.from("Call to 'super()' only allowed in constructor body").clearOtherErrors(); + } else if (superClass == null || !superClass.isResolved()) { + // Parent class not resolved - error + errorMsg = TokenErrorMessage.from( + "Cannot resolve parent class '" + enclosingType.getSuperClassName() + "'"); + } else if (parentConstructor == null) { + // No matching constructor found + String argTypeStr = java.util.Arrays.stream(argTypes) + .map(t -> t != null ? t.getSimpleName() : "unknown") + .collect(java.util.stream.Collectors.joining(", ")); + errorMsg = TokenErrorMessage + .from("No constructor found in '" + superClass.getSimpleName() + "' matching super(" + argTypeStr + ")") + .clearOtherErrors(); + } + + // Successfully resolved - mark as a valid method call (constructor call) + MethodCallInfo callInfo = new MethodCallInfo("super", nameStart, nameEnd, openParen, closeParen, arguments, + superClass, parentConstructor, false).setConstructor(true); + callInfo.validate(); + methodCalls.add(callInfo); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.KEYWORD, + errorMsg != null ? errorMsg : callInfo)); + } + + /** + * Check if a method name is defined in this script. + */ + private boolean isScriptMethod(String methodName) { + for (MethodInfo method : methods) { + if (method.getName().equals(methodName)) { + return true; + } + } + return false; + } + + private TypeInfo resolveScriptMethodAsSam(String methodName, TypeInfo expectedType) { + if (methodName == null || expectedType == null || !expectedType.isFunctionalInterface() || !isScriptMethod(methodName)) { + return null; + } + + // Java mode: bare method names are invalid as SAM callbacks + if (!isJavaScript()) { + CURRENT_SAM_CONFLICT_ERROR.set( + "Bare method name '" + methodName + "' cannot be used as callback in Java. Use this::" + methodName + ); + return expectedType; + } + + MethodInfo sam = expectedType.getSingleAbstractMethod(); + if (sam == null) { + return null; + } + + int samArity = sam.getParameters().size(); + MethodInfo bestMatch = getScriptMethodBySamArity(methodName, samArity); + if (bestMatch == null) { + return null; + } + + injectSamParameterTypes(bestMatch, sam); + return expectedType; + } + + /** + * Get the MethodInfo for a script-defined method by name. + */ + private MethodInfo getScriptMethodInfo(String methodName) { + for (MethodInfo method : methods) { + if (method.getName().equals(methodName)) { + return method; + } + } + return null; + } + + /** + * Get the best matching script method overload based on argument types. + */ + MethodInfo getScriptMethodInfo(String methodName, TypeInfo[] argTypes) { + List candidates = new ArrayList<>(); + + // Collect all methods with matching name + for (MethodInfo method : methods) { + if (method.getName().equals(methodName)) { + candidates.add(method); + } + } + + if (candidates.isEmpty()) { + return null; + } + + if (candidates.size() == 1) { + return candidates.get(0); + } + + // Use same 3-phase matching as TypeInfo.getBestMethodOverload + + // Phase 1: Look for exact match + for (MethodInfo method : candidates) { + List params = method.getParameters(); + if (params.size() != argTypes.length) { + continue; + } + + boolean exactMatch = true; + for (int i = 0; i < argTypes.length; i++) { + TypeInfo paramType = params.get(i).getDeclaredType(); + TypeInfo argType = argTypes[i]; + + if (argType == null || paramType == null || !argType.equals(paramType)) { + exactMatch = false; + break; + } + } + + if (exactMatch) { + return method; + } + } + + // Phase 2: Look for compatible match (widening/autoboxing) + for (MethodInfo method : candidates) { + List params = method.getParameters(); + if (params.size() != argTypes.length) { + continue; + } + + boolean compatible = true; + for (int i = 0; i < argTypes.length; i++) { + TypeInfo paramType = params.get(i).getDeclaredType(); + TypeInfo argType = argTypes[i]; + + if (argType != null && paramType != null && !TypeChecker.isTypeCompatible(paramType, argType)) { + compatible = false; + break; + } + } + + if (compatible) { + return method; + } + } + + // Phase 3: Fallback to first overload + return candidates.get(0); + } + + /** + * Get the best matching script method for use as a SAM callback by arity. + * Returns null if no match found, or if multiple overloads match by arity (ambiguous). + * + * @param methodName Name of the script method + * @param samArity Number of parameters in the SAM interface method + * @return The matching MethodInfo, or null if no unambiguous match + */ + private MethodInfo getScriptMethodBySamArity(String methodName, int samArity) { + List matchingByArity = new ArrayList<>(); + + for (MethodInfo method : methods) { + if (method.getName().equals(methodName)) { + if (method.getParameters().size() == samArity) { + matchingByArity.add(method); + } + } + } + + if (matchingByArity.size() == 1) { + return matchingByArity.get(0); + } + + if (matchingByArity.isEmpty()) { + return getScriptMethodInfo(methodName); + } + + CURRENT_SAM_CONFLICT_ERROR.set( + "Ambiguous overload for '" + methodName + "' with " + samArity + " parameter(s): " + + matchingByArity.size() + " overloads match" + ); + return null; + } + + /** + * True if in JS mode and name is a registered global engine function (parseInt, parseFloat, etc.). + */ + private boolean isGlobalEngineFunction(String name) { + return isJavaScript() && JSTypeRegistry.getInstance().isGlobalEngineFunction(name); + } + + /** + * Return the resolved return type of a global engine function call, or null if unknown. + */ + private TypeInfo getGlobalEngineFunctionReturnType(String name) { + JSMethodInfo m = JSTypeRegistry.getInstance().getGlobalEngineFunction(name); + return m != null ? m.getResolvedReturnType(null) : null; + } + + private void injectSamParameterTypes(MethodInfo scriptMethod, MethodInfo sam) { + String methodName = scriptMethod.getName(); + + MethodInfo previousSam = scriptMethodSamContexts.get(methodName); + if (previousSam != null) { + if (!areSamSignaturesCompatible(previousSam, sam)) { + String existingSig = formatSamSignature(previousSam); + String newSig = formatSamSignature(sam); + CURRENT_SAM_CONFLICT_ERROR.set( + "Function '" + methodName + "' used in incompatible SAM contexts: " + + existingSig + " vs " + newSig + ); + return; + } + } else { + scriptMethodSamContexts.put(methodName, sam); + } + + List scriptParams = scriptMethod.getParameters(); + List samParams = sam.getParameters(); + + if (scriptParams.size() != samParams.size()) { + return; + } + + for (int i = 0; i < scriptParams.size(); i++) { + FieldInfo scriptParam = scriptParams.get(i); + TypeInfo samParamType = samParams.get(i).getTypeInfo(); + + if (samParamType == null) { + continue; + } + + TypeInfo declaredType = scriptParam.getDeclaredType(); + + boolean hasExplicitType = declaredType != null + && declaredType.isResolved() + && !"any".equals(declaredType.getFullName()); + + if (hasExplicitType) { + if (!TypeChecker.isTypeCompatible(declaredType, samParamType)) { + scriptMethod.addSamTypeError(i, samParamType, declaredType); + } + } else { + scriptParam.setInferredType(samParamType); + } + } + } + + private boolean areSamSignaturesCompatible(MethodInfo sam1, MethodInfo sam2) { + List params1 = sam1.getParameters(); + List params2 = sam2.getParameters(); + + if (params1.size() != params2.size()) { + return false; + } + + for (int i = 0; i < params1.size(); i++) { + TypeInfo type1 = params1.get(i).getTypeInfo(); + TypeInfo type2 = params2.get(i).getTypeInfo(); + + if (type1 == null || type2 == null) { + continue; + } + + if (!TypeChecker.isTypeCompatible(type1, type2) && !TypeChecker.isTypeCompatible(type2, type1)) { + return false; + } + } + + TypeInfo return1 = sam1.getReturnType(); + TypeInfo return2 = sam2.getReturnType(); + + if (return1 != null && return2 != null) { + if (!TypeChecker.isTypeCompatible(return1, return2) && !TypeChecker.isTypeCompatible(return2, return1)) { + return false; + } + } + + return true; + } + + private String formatSamSignature(MethodInfo sam) { + StringBuilder sb = new StringBuilder(); + sb.append("("); + List params = sam.getParameters(); + for (int i = 0; i < params.size(); i++) { + if (i > 0) sb.append(", "); + TypeInfo type = params.get(i).getTypeInfo(); + sb.append(type != null ? type.getSimpleName() : "?"); + } + sb.append(") -> "); + TypeInfo returnType = sam.getReturnType(); + sb.append(returnType != null ? returnType.getSimpleName() : "void"); + return sb.toString(); + } + + /** + * Check if a method belongs to a script-defined type (class/interface/enum). + * Returns true if the method is defined inside a script type. + */ + private boolean isMethodFromScriptType(MethodInfo method) { + if (method == null || !method.isDeclaration()) { + return false; + } + + int declPos = method.getDeclarationOffset(); + if (declPos < 0) { + return false; + } + + // Check if the method's declaration position is inside any script type's body + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + if (scriptType.containsPosition(declPos)) { + return true; + } + } + + return false; + } + + private void markVariables(List marks) { + Set knownKeywords = new HashSet<>(Arrays.asList( + "boolean", "int", "float", "double", "long", "char", "byte", "short", "void", + "null", "true", "false", "if", "else", "switch", "case", "for", "while", "do", + "try", "catch", "finally", "return", "throw", "var", "let", "const", "function", + "continue", "break", "this", "new", "typeof", "instanceof", "class", "interface", + "extends", "implements", "import", "package", "public", "private", "protected", + "static", "final", "abstract", "synchronized", "native", "default", "enum", + "throws", "super", "assert", "volatile", "transient" + )); + + if (isJavaScript()) { + knownKeywords.add("delete"); + knownKeywords.add("undefined"); + } + + // First pass: mark method parameters in their declaration positions + List allMethods = getAllMethods(); + allMethods.addAll(getAllConstructors()); + + for (MethodInfo method : allMethods) { + for (FieldInfo param : method.getParameters()) { + int pos = param.getDeclarationOffset(); + String name = param.getName(); + marks.add(new ScriptLine.Mark(pos, pos + name.length(), TokenType.PARAMETER, param)); + } + } + + Pattern identifier = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b"); + Matcher m = identifier.matcher(text); + + identifierLoop: + while (m.find()) { + String name = m.group(1); + int position = m.start(1); + + if (isExcluded(position)) + continue; + if (knownKeywords.contains(name)) + continue; + + // Skip if preceded by dot (field access - handled separately) + if (isPrecededByDot(position)) + continue; + + // Skip import/package statements + if (isInImportOrPackage(position)) + continue; + + // Skip method calls (followed by paren) + if (isFollowedByParen(m.end(1))) + continue; + + // Find containing method + MethodInfo containingMethod = findMethodAtPosition(position); + // Check if this variable is an argument to a method call + MethodCallInfo callInfo = findMethodCallContainingPosition(position); + + // For uppercase identifiers, only process if it's a known field + // Otherwise, let type handling (markImportedClassUsages) handle it + boolean isUppercase = Character.isUpperCase(name.charAt(0)); + + // Scope resolution order: + // 1. Inner callable scope parameters (lambda/function expressions) + // 2. Inner callable scope locals + // 3. Method parameters (if inside method) + // 4. Method local variables (if inside method) + // 5. Enclosing type fields (if inside method) + // 6. Global fields + // 7. Script type fields + + boolean breakOuterLoop = false; + // Mark the parameter name at its declaration site in the parameter list. + // Example: marks the first 'item' in func = (item) => item + 1 + // Needed because the header region is outside the scope body, so findInnermostScopeAt won't find it. + for (InnerCallableScope scope : innerScopes) { + for (FieldInfo param : scope.getParameters()) { + int declStart = param.getDeclarationOffset(); + if (declStart == m.start(1) && name.equals(param.getName())) { + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.PARAMETER, param)); + breakOuterLoop = true; + break; + } + } + if (breakOuterLoop) + break; + + } + if (breakOuterLoop) + continue; + + + // Resolve parameter/local usage sites inside the scope body via the innermost enclosing scope. + // Example: marks the second 'item' in func = (item) => item + 1 + Object innermostScope = findInnermostScopeAt(m.start(1)); + if (innermostScope instanceof InnerCallableScope) { + InnerCallableScope innerScope = (InnerCallableScope) innermostScope; + FieldInfo innerParam = innerScope.getParameter(name); + if (innerParam != null) { + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.PARAMETER, innerParam)); + continue; + } + // Also check locals + FieldInfo innerLocal = innerScope.getLocals().get(name); + if (innerLocal != null) { + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.LOCAL_FIELD, innerLocal)); + continue; + } + } + + // Check parameters (method scope) - fallback if not in inner scope + if (containingMethod != null && containingMethod.hasParameter(name)) { + FieldInfo paramInfo = containingMethod.getParameter(name); + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.PARAMETER, paramInfo)); + continue; + } + + FieldInfo localInfo = null; + if (containingMethod != null) { + Map> locals = methodLocals.get(containingMethod.getDeclarationOffset()); + if (locals != null) { + localInfo = pickVisibleLocal(locals.get(name), position); + } + } else { + localInfo = pickVisibleTopLevelLocal(name, position); + } + if (localInfo != null) { + Object metadata = callInfo != null ? new FieldInfo.ArgInfo(localInfo, callInfo) : localInfo; + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.LOCAL_FIELD, metadata)); + continue; + } + + // Check enclosing type fields (when inside method) + if (containingMethod != null) { + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null && enclosingType.hasField(name)) { + FieldInfo fieldInfo = enclosingType.getFieldInfo(name); + if (fieldInfo.isVisibleAt(position)) { + Object metadata = callInfo != null ? new FieldInfo.ArgInfo(fieldInfo, callInfo) : fieldInfo; + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD, metadata)); + continue; + } + } + } + + // Check other script type fields (only if position is within that type's boundaries). + // Use continue identifierLoop to exit the outer while when a match is found — + // a plain 'continue' would only skip to the next scriptType, causing fall-through + // to the UNDEFINED_VAR mark even after a GLOBAL_FIELD mark was already added. + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + if (scriptType.hasField(name)) { + // Only check if position is within this script type's class body + if (position >= scriptType.getBodyStart() && position <= scriptType.getBodyEnd()) { + FieldInfo fieldInfo = scriptType.getFieldInfo(name); + if(fieldInfo.isEnumConstant()) + continue; + + if (fieldInfo.isVisibleAt(position)) { + Object metadata = callInfo != null ? new FieldInfo.ArgInfo(fieldInfo, callInfo) : fieldInfo; + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD, metadata)); + continue identifierLoop; + } + } + } + } + + // Check global fields + if (globalFields.containsKey(name)) { + FieldInfo fieldInfo = globalFields.get(name); + if (fieldInfo.isVisibleAt(position)) { + Object metadata = callInfo != null ? new FieldInfo.ArgInfo(fieldInfo, callInfo) : fieldInfo; + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD, metadata)); + continue; + } + } + + if (isJavaScript()) { + // check if a variable in global objects + JSTypeRegistry registry = JSTypeRegistry.getInstance(); + String globalObjectType = registry.getGlobalObjectType(name); + if (globalObjectType != null) { + // Resolve the type and create a FieldInfo for it + FieldInfo fieldInfo = resolveVariable(name, position); + if (fieldInfo != null && fieldInfo.isResolved()) { + Object metadata = callInfo != null ? new FieldInfo.ArgInfo(fieldInfo, callInfo) : fieldInfo; + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD, metadata)); + continue; + } + } + + // Mark DataScript global variable definitions + if (!editorGlobals.isEmpty() && editorGlobals.containsKey(name)) { + FieldInfo fieldInfo = resolveVariable(name, position); + if (fieldInfo != null) { + Object metadata = callInfo != null ? new FieldInfo.ArgInfo(fieldInfo, callInfo) : fieldInfo; + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD, metadata)); + continue; + } + } + } + + // Skip uppercase if not a known field - type handling will deal with it + if (isUppercase) + continue; + + // Check if it's a script method used as a value (e.g., in schedule("action", methodName)) + if (isScriptMethod(name)) { + MethodInfo scriptMethod = getScriptMethodInfo(name); + if (scriptMethod != null) { + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.METHOD_CALL, scriptMethod)); + continue; + } + } + + // Unknown variable - mark as undefined + if (containingMethod != null) { + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.UNDEFINED_VAR, callInfo)); + } + } + } + + /** + * Mark chained field accesses like: mc.player.world, array.length, this.field, etc. + * This handles dot-separated access chains and colors each segment appropriately. + * Does NOT mark method calls (identifiers followed by parentheses) - those are handled by {@link #markMethodCalls}. + */ + private void markChainedFieldAccesses(List marks) { + FieldChainMarker marker = new FieldChainMarker(this, text); + marker.markChainedFieldAccesses(marks); + } + + + /** + * Parse assignment statements (reassignments, not declarations) and validate type compatibility. + * This detects patterns like: varName = expr; or obj.field = expr; + * Assignments are stored in the corresponding FieldInfo, not as marks. + */ + private void parseAssignments() { + // First clear any existing assignments in all FieldInfo objects + for (FieldInfo field : globalFields.values()) { + field.clearAssignments(); + } + for (Map> locals : methodLocals.values()) { + for (List fields : locals.values()) { + for (FieldInfo field : fields) { + field.clearAssignments(); + } + } + } + for (List fields : topLevelLocals.values()) { + for (FieldInfo field : fields) { + field.clearAssignments(); + } + } + // Also clear assignments in script type fields (including inner classes) + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + for (FieldInfo field : scriptType.getFields().values()) { + field.clearAssignments(); + } + } + externalFieldAssignments.clear(); + + // Pattern to find assignments: identifier = expression; + // But NOT declarations (Type varName = expr) or compound assignments (+=, -=, etc.) + // We need to find '=' that is: + // 1. Not preceded by another operator (!, <, >, =) + // 2. Not followed by '=' + // 3. The LHS must be a valid l-value (variable or field access) + + int pos = 0; + while (pos < text.length()) { + // Find the next '=' character + int equalsPos = text.indexOf('=', pos); + if (equalsPos < 0) break; + + // Skip if in excluded region (string/comment) + if (isExcluded(equalsPos)) { + pos = equalsPos + 1; + continue; + } + + // Check it's not part of ==, !=, <=, >=, +=, -=, *=, /=, %=, &=, |=, ^= + if (equalsPos > 0 && "!<>=+-*/%&|^".indexOf(text.charAt(equalsPos - 1)) >= 0) { + pos = equalsPos + 1; + continue; + } + if (equalsPos < text.length() - 1 && text.charAt(equalsPos + 1) == '=') { + pos = equalsPos + 2; + continue; + } + + // Find the start of this statement: walk backward to ';', '{', '}', or a + // depth-0 ',' (multi-declarator separator like "int x=1, y=2"). + // Track '()'/`[]` depth so commas inside argument lists are not treated + // as declarator separators. + int stmtStart = equalsPos - 1; + { + int backDepth = 0; + while (stmtStart >= 0) { + char c = text.charAt(stmtStart); + if (c == ')' || c == ']') { + backDepth++; + } else if (c == '(' || c == '[') { + if (backDepth == 0) { stmtStart++; break; } + backDepth--; + } else if (c == ';' || c == '{' || c == '}') { + stmtStart++; + break; + } else if (c == ',' && backDepth == 0) { + stmtStart++; + break; + } + stmtStart--; + } + } + if (stmtStart < 0) stmtStart = 0; + + // Skip leading whitespace to get to the actual first character of the statement + while (stmtStart < equalsPos && Character.isWhitespace(text.charAt(stmtStart))) { + stmtStart++; + } + + int stmtEnd; + if (isJavaScript()) { + int rhsBoundaryStart = equalsPos + 1; + while (rhsBoundaryStart < text.length() && Character.isWhitespace(text.charAt(rhsBoundaryStart))) { + rhsBoundaryStart++; + } + // For multi-declarator JS statements (var a=1, b=2), the RHS of + // each declarator must stop at the top-level comma. We detect this + // by checking if the statement begins with var/let/const. + boolean isMultiDecl = MultiDeclaratorParser.startsWithJSKeyword(text, stmtStart, equalsPos); + stmtEnd = findJsInitializerEnd(text, rhsBoundaryStart, isMultiDecl); + if (stmtEnd < equalsPos + 1) { + stmtEnd = equalsPos + 1; + } + } else { + // For Java, stop at depth-0 ',' or ';' so that each declarator in + // "int x='str', y=20, z='str'" is bounded independently. + // findJsInitializerEnd handles string literals and bracket depth correctly. + stmtEnd = findJsInitializerEnd(text, equalsPos + 1, true); + if (stmtEnd < equalsPos + 1) stmtEnd = equalsPos + 1; + } + + // Extract LHS (before =) and RHS (after =) + String lhsRaw = text.substring(stmtStart, equalsPos).trim(); + String rhsRaw = text.substring(equalsPos + 1, stmtEnd).trim(); + + // Skip empty assignments + if (lhsRaw.isEmpty() || rhsRaw.isEmpty()) { + pos = equalsPos + 1; + continue; + } + + // Check if this is a declaration (has type before variable name) + // Declarations have: Type varName = expr + // Reassignments have: varName = expr or obj.field = expr + boolean isDeclaration = isVariableDeclaration(lhsRaw); + + if (isDeclaration) { + // This is a declaration with initializer - validate the initial value + createAndAttachDeclarationAssignment(lhsRaw, rhsRaw, stmtStart, equalsPos, stmtEnd); + } else { + // This is a reassignment - create AssignmentInfo and attach to FieldInfo + createAndAttachAssignment(lhsRaw, rhsRaw, stmtStart, equalsPos, stmtEnd); + } + + pos = stmtEnd + 1; + } + } + + /** + * Check if the LHS represents a variable declaration (has a type before the variable name). + */ + private boolean isVariableDeclaration(String lhs) { + // Split by whitespace + String[] parts = lhs.trim().split("\\s+"); + + // Single word = reassignment (e.g., "x") + if (parts.length == 1) { + // Could also be a.b = expr (field access) + return false; + } + + // Check if it matches pattern: [modifiers] Type varName + // Last part is the variable name, second-to-last should be a type + String potentialType = parts[parts.length - 2]; + String potentialVar = parts[parts.length - 1]; + + // Type patterns: primitives, or capitalized class names, or generic types + if (TypeResolver.isPrimitiveType(potentialType) || + (Character.isUpperCase(potentialType.charAt(0)) && potentialType.matches("[A-Za-z_][A-Za-z0-9_<>\\[\\],\\s]*")) || + potentialType.equals("var") || potentialType.equals("let") || potentialType.equals("const")) { + + // Make sure the variable name is a valid identifier (not a field access chain) + if (potentialVar.matches("[a-zA-Z_][a-zA-Z0-9_]*") && !potentialVar.contains(".")) { + return true; + } + } + + return false; + } + + /** + * Create an AssignmentInfo for a reassignment statement and attach it to the appropriate FieldInfo. + */ + private void createAndAttachAssignment(String lhs, String rhs, int stmtStart, int equalsPos, int stmtEnd) { + lhs = lhs.trim(); + rhs = rhs.trim(); + + ObjectLiteralParser.DynamicPropertyAccess dynamicPropertyAccess = isJavaScript() ? ObjectLiteralParser.parseDynamicPropertyAccess(lhs, stmtStart) : null; + + // Parse the target (LHS) + // Could be: varName or obj.field or this.field or array[index] + String targetName = lhs; + FieldInfo targetField = null; + TypeInfo targetType = null; + TypeInfo receiverType = null; + java.lang.reflect.Field reflectionField = null; + + // Find the position where the LHS starts in the actual text (skip leading whitespace) + int lhsStart = stmtStart; + while (lhsStart < equalsPos && Character.isWhitespace(text.charAt(lhsStart))) { + lhsStart++; + } + + // Calculate the actual LHS end (before '=' minus trailing whitespace) + int lhsEnd = equalsPos; + while (lhsEnd > lhsStart && Character.isWhitespace(text.charAt(lhsEnd - 1))) { + lhsEnd--; + } + + // Calculate RHS start (first non-whitespace after '=') + int rhsStart = equalsPos + 1; + while (rhsStart < stmtEnd && Character.isWhitespace(text.charAt(rhsStart))) { + rhsStart++; + } + + // RHS end is at the semicolon position (inclusive for error underline) + int rhsEnd = stmtEnd; + + // Handle chained field access (obj.field) + if (lhs.contains(".")) { + // Split into segments + String[] segments = lhs.split("\\."); + targetName = segments[segments.length - 1].trim(); + + // Check if the last segment has array subscript (e.g., obj.items[0]) + boolean lastSegmentHasArrayAccess = targetName.contains("["); + if (lastSegmentHasArrayAccess) { + targetName = targetName.substring(0, targetName.indexOf('[')).trim(); + } + + // Resolve the chain to get the target type + String receiverExpr = lhs.substring(0, lhs.lastIndexOf('.')).trim(); + receiverType = resolveExpressionType(receiverExpr, lhsStart); + + if (receiverType != null && receiverType.isResolved()) { + // Get the field from the receiver type + if (receiverType.hasField(targetName)) { + targetField = receiverType.getFieldInfo(targetName); + targetType = targetField.getTypeInfo(); + if (lastSegmentHasArrayAccess) { + targetType = unwrapArrayElement(targetType); + } + reflectionField = targetField.getReflectionField(); + } + } + // Minecraft.getMinecraft().thePlayer.PERSISTED_NBT_TAG = null; + + } else if (lhs.contains("[")) { + // Array subscript access (e.g., items[0]) + // Extract the variable name before the bracket + String varName = lhs.substring(0, lhs.indexOf('[')).trim(); + targetName = varName; + if (dynamicPropertyAccess != null) { + ObjectLiteralParser.DynamicFieldResult res = ObjectLiteralParser.resolveExistingField( + dynamicPropertyAccess, this::resolveExpressionType, this::resolveVariable); + receiverType = res.receiverType; + targetName = res.propertyName; + targetField = res.field; + if (targetField != null) { + targetType = targetField.getTypeInfo(); + reflectionField = targetField.getReflectionField(); + } + } + + if (targetField == null) { + targetField = resolveVariable(varName, lhsStart); + } + + if (targetField != null && targetType == null) { + // The variable type is the array type (e.g., ItemStack[]) + // Unwrap to get the element type (e.g., ItemStack) + targetType = unwrapArrayElement(targetField.getTypeInfo()); + reflectionField = targetField.getReflectionField(); + } + } else { + // Simple variable + targetField = resolveVariable(targetName, lhsStart); + if (targetField != null) { + targetType = targetField.getTypeInfo(); + reflectionField = targetField.getReflectionField(); + } + } + + // Resolve the source type (RHS) with expected type context + TypeInfo sourceType; + ExpressionTypeResolver.CURRENT_EXPECTED_TYPE = targetType; + try { + sourceType = resolveExpressionType(rhs, equalsPos + 1); + } finally { + ExpressionTypeResolver.CURRENT_EXPECTED_TYPE = null; + } + + if (dynamicPropertyAccess != null) { + ObjectLiteralParser.DynamicFieldResult res = ObjectLiteralParser.extendAndGetField( + dynamicPropertyAccess, receiverType, sourceType, rhs, + this::resolveExpressionType, this::resolveVariable); + if (res != null) { + receiverType = res.receiverType; + targetName = res.propertyName; + targetField = res.field; + if (targetField != null) { + targetType = targetField.getTypeInfo(); + reflectionField = targetField.getReflectionField(); + } + } + } + + // Type inference: If the target field has "any" type and no inferred type yet, + // set the inferred type from the resolved source type (first assignment wins) + if (targetField != null && targetField.canInferType() && targetField.getInferredType() == null + && sourceType != null && sourceType.isResolved()) { + // Don't infer "any" type - that doesn't refine anything + if (!"any".equals(sourceType.getFullName())) { + targetField.setInferredType(sourceType); + } + } + + // Determine if this is a script-defined field or external field + FieldInfo finalTargetField = targetField; + boolean isScriptField = targetField != null && + (globalFields.containsValue(targetField) || + methodLocals.values().stream().anyMatch(m -> m.values().stream().anyMatch(list -> list.contains(finalTargetField))) || + topLevelLocals.values().stream().anyMatch(list -> list.contains(finalTargetField))); + + // Determine if the target field is final + // For script fields, use the modifiers; for external fields, use reflection + // Array element assignment (items[0] = ...) is always allowed even if the array itself is final + boolean isFinal = false; + if (targetField != null && !lhs.contains("[")) { + isFinal = targetField.isFinal(); + } + + // Allow final field initialization inside a constructor of the declaring type. + // In Java, final fields can be assigned exactly once in the constructor. + if (isFinal && targetField != null) { + MethodInfo enclosingCtor = findEnclosingConstructor(stmtStart); + if (enclosingCtor != null) { + ScriptTypeInfo enclosingType = findEnclosingScriptType(stmtStart); + if (enclosingType != null && enclosingType.getFields().containsValue(targetField)) { + isFinal = false; + } + } + } + + // Create the assignment info using the new constructor + AssignmentInfo info = new AssignmentInfo( + targetName, + stmtStart, + lhsStart, + lhsEnd, + targetType, + rhsStart, + rhsEnd, + sourceType, + rhs, + receiverType, + reflectionField, + isFinal + ); + + if (targetField != null) { + info.setScopeInfo(targetField.getScopeInfo()); + } + + // Validate the assignment + info.validate(); + + // Attach to the appropriate location + if (isScriptField && targetField != null) { + // Script-defined field - attach to FieldInfo + targetField.addAssignment(info); + } else { + // External field or unresolved - store separately + externalFieldAssignments.add(info); + } + } + + /** + * Create an AssignmentInfo for a declaration with initializer and attach it to the appropriate FieldInfo. + * Example: String str = 20; or final int x = "test"; + */ + private void createAndAttachDeclarationAssignment(String lhs, String rhs, int stmtStart, int equalsPos, int stmtEnd) { + lhs = lhs.trim(); + rhs = rhs.trim(); + + // Parse the declaration: [modifiers] Type varName + String[] parts = lhs.split("\\s+"); + if (parts.length < 2) { + return; // Invalid declaration format + } + + // Last part is the variable name + String varName = parts[parts.length - 1].trim(); + + // Find the actual position of the variable name in the text + int varNameStart = stmtStart; + int searchStart = stmtStart; + while (searchStart < equalsPos) { + int found = text.indexOf(varName, searchStart); + if (found >= 0 && found < equalsPos) { + // Verify it's the actual variable name (not part of type name) + // Check that it's either at start or preceded by whitespace + if (found == stmtStart || Character.isWhitespace(text.charAt(found - 1))) { + // Check that it's followed by whitespace or '=' + int afterVar = found + varName.length(); + if (afterVar >= text.length() || Character.isWhitespace(text.charAt(afterVar)) || text.charAt(afterVar) == '=') { + varNameStart = found; + break; + } + } + searchStart = found + 1; + } else { + break; + } + } + + int varNameEnd = varNameStart + varName.length(); + + // Calculate RHS positions + int rhsStart = equalsPos + 1; + while (rhsStart < stmtEnd && Character.isWhitespace(text.charAt(rhsStart))) { + rhsStart++; + } + int rhsEnd = stmtEnd; + + // Resolve the target field (should already exist from parseGlobalFields or parseLocalVariables) + FieldInfo targetField = resolveVariable(varName, varNameStart); + if (targetField == null || targetField.getDeclarationAssignment() != null) { + return; // Field doesn't exist, can't attach assignment + } + + TypeInfo targetType = targetField.getTypeInfo(); + + // Resolve the source type with expected type context + TypeInfo sourceType; + ExpressionTypeResolver.CURRENT_EXPECTED_TYPE = targetType; + try { + sourceType = resolveExpressionType(rhs, rhsStart); + } finally { + ExpressionTypeResolver.CURRENT_EXPECTED_TYPE = null; + } + + // Type inference: If the target field has "any" type and no inferred type yet, + // set the inferred type from the resolved source type + if (targetField.canInferType() && targetField.getInferredType() == null && sourceType != null && sourceType.isResolved()) { + // Don't infer "any" type - that doesn't refine anything + if (!"any".equals(sourceType.getFullName())) { + targetField.setInferredType(sourceType); + } + } + + // Create the assignment info + // Declaration assignments should NOT check final status - this is the one place where final fields can be assigned + AssignmentInfo info = new AssignmentInfo( + varName, + stmtStart, + varNameStart, + varNameEnd, + targetType, + rhsStart, + rhsEnd, + sourceType, + rhs, + null, // No receiver for simple declarations + targetField.getReflectionField(), + false // Don't flag as final for declaration assignments - initial assignment is always allowed + ); + + info.setScopeInfo(targetField.getScopeInfo()); + + // Validate the assignment + info.validate(); + + // Attach as the declaration assignment + targetField.setDeclarationAssignment(info); + } + + // ==================== METHOD INHERITANCE DETECTION ==================== + + /** + * Detect method overrides and interface implementations for all script-defined types. + * This analyzes each method in each ScriptTypeInfo to determine if it: + * - Overrides a method from a parent class (extends) + * - Implements a method from an interface (implements) + * + * The detection uses signature matching (method name + parameter types). + * Also validates that all interface methods are implemented and constructors match. + */ + private void detectMethodInheritance() { + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + scriptType.clearErrors(); // Clear previous errors + detectMethodInheritanceForType(scriptType); + scriptType.validate(); // Validate after detecting inheritance + } + } + + /** + * Detect method inheritance for a single script type. + */ + private void detectMethodInheritanceForType(ScriptTypeInfo scriptType) { + // Check each method in this type + for (List overloads : scriptType.getMethods().values()) { + for (MethodInfo method : overloads) { + // Check if method overrides a parent class method + if (scriptType.hasSuperClass()) { + TypeInfo superClass = scriptType.getSuperClass(); + if (superClass != null && superClass.isResolved()) { + TypeInfo overrideSource = findMethodInHierarchy(superClass, method, false); + if (overrideSource != null) { + method.setOverridesFrom(overrideSource); + } + } + } + + // Check if method implements an interface method (only if not already marked as override) + if (!method.isOverride() && scriptType.hasImplementedInterfaces()) { + for (TypeInfo iface : scriptType.getImplementedInterfaces()) { + if (iface != null && iface.isResolved()) { + TypeInfo implementsSource = findMethodInInterface(iface, method); + if (implementsSource != null) { + method.setImplementsFrom(implementsSource); + break; // Only mark first matching interface + } + } + } + } + } + } + } + + /** + * Search for a matching method in a type hierarchy (class inheritance). + * @param type The type to search in (and its superclasses) + * @param method The method to find a match for + * @param includeInterfaces Whether to also search interfaces + * @return The TypeInfo containing the matching method, or null if not found + */ + private TypeInfo findMethodInHierarchy(TypeInfo type, MethodInfo method, boolean includeInterfaces) { + if (type == null || !type.isResolved()) + return null; + + // Check if this type has the method + if (hasMatchingMethod(type, method)) { + return type; + } + + // If it's a ScriptTypeInfo, check its super class + if (type instanceof ScriptTypeInfo) { + ScriptTypeInfo scriptType = (ScriptTypeInfo) type; + if (scriptType.hasSuperClass()) { + TypeInfo result = findMethodInHierarchy(scriptType.getSuperClass(), method, includeInterfaces); + if (result != null) + return result; + } + } + + // If it's a Java class, check its superclass + Class javaClass = type.getJavaClass(); + if (javaClass != null) { + Class superClass = javaClass.getSuperclass(); + if (superClass != null && superClass != Object.class) { + TypeInfo superType = TypeInfo.fromClass(superClass); + TypeInfo result = findMethodInHierarchy(superType, method, includeInterfaces); + if (result != null) + return result; + } + } + + return null; + } + + /** + * Search for a matching method in an interface and its super-interfaces. + * @param iface The interface to search in + * @param method The method to find a match for + * @return The TypeInfo containing the matching method, or null if not found + */ + private TypeInfo findMethodInInterface(TypeInfo iface, MethodInfo method) { + if (iface == null || !iface.isResolved()) + return null; + + // Check if this interface has the method + if (hasMatchingMethod(iface, method)) { + return iface; + } + + // Check super-interfaces + Class javaClass = iface.getJavaClass(); + if (javaClass != null && javaClass.isInterface()) { + for (Class superIface : javaClass.getInterfaces()) { + TypeInfo superType = TypeInfo.fromClass(superIface); + TypeInfo result = findMethodInInterface(superType, method); + if (result != null) + return result; + } + } + + return null; + } + + /** + * Check if a type has a method matching the given signature. + * Uses method name and parameter types for matching. + */ + private boolean hasMatchingMethod(TypeInfo type, MethodInfo method) { + String methodName = method.getName(); + int paramCount = method.getParameterCount(); + + // For ScriptTypeInfo, check its methods map + if (type instanceof ScriptTypeInfo) { + ScriptTypeInfo scriptType = (ScriptTypeInfo) type; + List overloads = scriptType.getAllMethodOverloads(methodName); + for (MethodInfo candidate : overloads) { + if (signaturesMatch(method, candidate)) { + return true; + } + } + return false; + } + + // For Java classes, use reflection + Class javaClass = type.getJavaClass(); + if (javaClass == null) + return false; + + try { + for (java.lang.reflect.Method javaMethod : javaClass.getMethods()) { + if (javaMethod.getName().equals(methodName) && + javaMethod.getParameterCount() == paramCount) { + // Check parameter types match + if (parameterTypesMatch(method, javaMethod)) { + return true; + } + } + } + } catch (Exception e) { + // Security or linkage error + } + + return false; + } + + /** + * Check if two MethodInfo signatures match (same name and parameter types). + */ + private boolean signaturesMatch(MethodInfo m1, MethodInfo m2) { + if (!m1.getName().equals(m2.getName())) + return false; + if (m1.getParameterCount() != m2.getParameterCount()) + return false; + + List params1 = m1.getParameters(); + List params2 = m2.getParameters(); + + for (int i = 0; i < params1.size(); i++) { + TypeInfo type1 = params1.get(i).getDeclaredType(); + TypeInfo type2 = params2.get(i).getDeclaredType(); + + // Both null = match + if (type1 == null && type2 == null) + continue; + + // One null, one not = no match + if (type1 == null || type2 == null) + return false; + + // Compare full names + if (!type1.getFullName().equals(type2.getFullName())) { + return false; + } + } + + return true; + } + + /** + * Check if a MethodInfo's parameter types match a Java reflection Method's parameter types. + */ + private boolean parameterTypesMatch(MethodInfo methodInfo, java.lang.reflect.Method javaMethod) { + List params = methodInfo.getParameters(); + Class[] javaParams = javaMethod.getParameterTypes(); + + if (params.size() != javaParams.length) + return false; + + for (int i = 0; i < params.size(); i++) { + TypeInfo paramType = params.get(i).getDeclaredType(); + if (paramType == null) + continue; // Unresolved param, skip check + + Class javaParamClass = javaParams[i]; + String javaParamName = javaParamClass.getName(); + + // Compare type names + if (!paramType.getFullName().equals(javaParamName) && + !paramType.getSimpleName().equals(javaParamClass.getSimpleName())) { + return false; + } + } + + return true; + } + + /** + * Mark types in cast expressions with their appropriate type color. + * Handles: (Type), (Type[]), (pkg.Type), etc. + */ + private void markCastTypes(List marks) { + Matcher m = CAST_TYPE_PATTERN.matcher(text); + + while (m.find()) { + String typeName = m.group(1); + int typeStart = m.start(1); + int typeEnd = m.end(1); + + // Skip if inside string or comment + if (isExcluded(typeStart)) continue; + + // Skip in import/package statements + if (isInImportOrPackage(typeStart)) continue; + + // Resolve the type with position context for inner class names + TypeInfo info = resolveType(typeName, typeStart); + if (info != null && info.isResolved()) { + // Mark the type with its appropriate color + marks.add(new ScriptLine.Mark(typeStart, typeEnd, info.getTokenType(), info)); + } else { + // Unknown type - check if it's a primitive + if (isPrimitiveType(typeName)) { + marks.add(new ScriptLine.Mark(typeStart, typeEnd, TokenType.KEYWORD)); + } else { + // Mark as undefined type + marks.add(new ScriptLine.Mark(typeStart, typeEnd, TokenType.UNDEFINED_VAR)); + } + } + } + } + + /** + * Check if a type name is a primitive type. + */ + private boolean isPrimitiveType(String typeName) { + switch (typeName) { + case "byte": case "short": case "int": case "long": + case "float": case "double": case "char": case "boolean": + case "void": + return true; + default: + return false; + } + } + + /** + * Early SAM inference for all lambda/function parameters inside method and constructor calls. + * Runs during parseStructure() (before parseAssignments) so that lambda body variable + * resolution sees typed parameters. The mark-phase methods (markMethodCalls, + * inferConstructorLambdaTypes) will re-run the same inference harmlessly later. + */ + private void inferLambdaParameterTypes() { + inferMethodCallLambdaTypes(); + inferConstructorLambdaTypes(); + inferFieldAssignmentLambdaTypes(); + populateLambdaCache(); + } + + private void inferMethodCallLambdaTypes() { + Matcher m = METHOD_CALL_PATTERN.matcher(text); + while (m.find()) { + int nameStart = m.start(1); + String methodName = m.group(1); + + if (isExcluded(nameStart) || isKeyword(methodName)) + continue; + if (isInImportOrPackage(nameStart)) + continue; + + boolean isDecl = false; + for (MethodInfo decl : methods) + if (decl.getNameOffset() == nameStart) + isDecl = true; + if (isDecl) + continue; + + int openParen = m.end(1); + while (openParen < text.length() && Character.isWhitespace(text.charAt(openParen))) + openParen++; + if (openParen >= text.length() || text.charAt(openParen) != '(') + continue; + + int closeParen = findMatchingParen(openParen); + if (closeParen < 0) + continue; + + String argsText = text.substring(openParen + 1, closeParen); + boolean hasLambda = isJavaScript() + ? (argsText.contains("function") || argsText.contains("=>")) + : argsText.contains("->"); + if (!hasLambda) + continue; + + List arguments = parseMethodArguments(openParen + 1, closeParen, null, null); + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType) + .toArray(TypeInfo[]::new); + + TypeInfo receiverType = resolveReceiverChain(nameStart); + MethodInfo resolvedMethod = null; + + if (receiverType != null) { + if (receiverType.hasMethod(methodName)) { + resolvedMethod = receiverType.getBestMethodOverload(methodName, argTypes); + } + } else if (!isPrecededByDot(nameStart)) { + if (isScriptMethod(methodName)) { + resolvedMethod = getScriptMethodInfo(methodName, argTypes); + } else if (isGlobalEngineFunction(methodName)) { + JSMethodInfo jsGlobal = JSTypeRegistry.getInstance().getGlobalEngineFunction(methodName); + if (jsGlobal != null) + resolvedMethod = MethodInfo.fromJSMethod(jsGlobal, null); + } + } + + if (resolvedMethod != null && resolvedMethod.getParameters().size() == arguments.size()) { + parseMethodArguments(openParen + 1, closeParen, resolvedMethod, receiverType); + } + } + } + + /** + * Pre-infer lambda parameter types for constructor arguments (new Foo(... lambda ...)). + * Constructor SAM inference normally happens in markImportedClassUsages, which runs AFTER + * markMethodCalls/markVariables/markChainedFieldAccesses. That ordering means lambda body + * resolution (e.g., event.getHookName()) fails because parameter types aren't set yet. + * This early pass sets inferredType on lambda parameters so body resolution works correctly. + */ + private void inferConstructorLambdaTypes() { + Pattern newExpr = Pattern.compile("\\bnew\\s+([A-Za-z][a-zA-Z0-9_.]*?)\\s*(?:<[^>]*>)?\\s*\\("); + Matcher m = newExpr.matcher(text); + + while (m.find()) { + if (isExcluded(m.start())) + continue; + if (isInImportOrPackage(m.start())) + continue; + + String className = m.group(1); + int openParen = m.end() - 1; + int closeParen = findMatchingParen(openParen); + if (closeParen < 0) + continue; + + String argsText = text.substring(openParen + 1, closeParen); + boolean hasLambda = isJavaScript() + ? (argsText.contains("function") || argsText.contains("=>")) + : argsText.contains("->"); + if (!hasLambda) + continue; + + TypeInfo info = resolveType(className, m.start(1)); + if (info == null || !info.isResolved()) + continue; + if (!info.hasConstructors()) + continue; + + List arguments = parseMethodArguments(openParen + 1, closeParen, null, info); + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType) + .toArray(TypeInfo[]::new); + + MethodInfo constructor = info.findConstructor(argTypes); + if (constructor == null) { + constructor = info.findConstructor(arguments.size()); + } + + if (constructor != null && constructor.getParameters().size() == arguments.size()) { + parseMethodArguments(openParen + 1, closeParen, constructor, info); + } + } + } + + private void inferFieldAssignmentLambdaTypes() { + if (isJavaScript()) { + inferJSFieldAssignmentLambdaTypes(); + } else { + inferJavaFieldAssignmentLambdaTypes(); + } + } + + private void inferJavaFieldAssignmentLambdaTypes() { + Matcher m = FIELD_DECL_PATTERN.matcher(normalizeGenericNewlines(text)); + while (m.find()) { + String typeName = m.group(1); + String varName = m.group(2); + String delimiter = m.group(3); + + if (!"=".equals(delimiter)) + continue; + + int absTypeStart = m.start(1); + int absVarStart = m.start(2); + if (isExcluded(absTypeStart) || isExcluded(absVarStart)) + continue; + if (hasExcludedRange(absTypeStart, m.end(1))) + continue; + if (isInImportOrPackage(absTypeStart)) + continue; + + if (typeName.equals("return") || typeName.equals("if") || typeName.equals("while") || + typeName.equals("for") || typeName.equals("switch") || typeName.equals("catch") || + typeName.equals("new") || typeName.equals("throw")) + continue; + + int rhsStart = m.end(3); + while (rhsStart < text.length() && Character.isWhitespace(text.charAt(rhsStart))) + rhsStart++; + if (rhsStart >= text.length()) + continue; + + int rhsEnd = findStatementEnd(rhsStart); + if (rhsEnd <= rhsStart) + continue; + + String rhs = text.substring(rhsStart, rhsEnd).trim(); + if (!rhs.contains("->")) + continue; + + TypeInfo declaredType = resolveType(stripModifiers(typeName), absVarStart); + if (declaredType == null || !declaredType.isResolved()) + continue; + if (!declaredType.isFunctionalInterface()) + continue; + + MethodInfo sam = declaredType.getSingleAbstractMethod(); + if (sam == null) + continue; + + List samParams = sam.getParameters(); + + for (InnerCallableScope scope : innerScopes) { + if (scope.getKind() != InnerCallableScope.Kind.JAVA_LAMBDA) + continue; + if (scope.getHeaderStart() < rhsStart || scope.getFullEnd() > rhsEnd + 1) + continue; + if (scope.getExpectedType() != null) + continue; + + List lambdaParams = scope.getParameters(); + if (samParams.size() != lambdaParams.size()) + continue; + + scope.setExpectedType(declaredType); + for (int i = 0; i < lambdaParams.size(); i++) { + TypeInfo inferredType = samParams.get(i).getTypeInfo(); + if (inferredType != null) { + lambdaParams.get(i).setInferredType(inferredType); + } + } + } + } + } + + private void inferJSFieldAssignmentLambdaTypes() { + Pattern varPattern = Pattern.compile("(?:var|let|const)\\s+(\\w+)(?:\\s*(=))?"); + Matcher m = varPattern.matcher(text); + + while (m.find()) { + if (m.group(2) == null) + continue; + + int position = m.start(1); + if (isExcluded(position)) + continue; + + int initializerStart = skipSegmentWhitespace(text, m.end(2)); + int initializerEnd = findJsInitializerEnd(text, initializerStart, true); + if (initializerEnd <= initializerStart) + continue; + + String initializer = text.substring(initializerStart, initializerEnd).trim(); + if (!initializer.contains("function") && !initializer.contains("=>")) + continue; + + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, m.start()); + if (jsDoc == null || !jsDoc.hasTypeTag()) + continue; + + TypeInfo declaredType = jsDoc.getDeclaredType(); + if (declaredType == null || !declaredType.isResolved()) + continue; + if (!declaredType.isFunctionalInterface()) + continue; + + MethodInfo sam = declaredType.getSingleAbstractMethod(); + if (sam == null) + continue; + + List samParams = sam.getParameters(); + + for (InnerCallableScope scope : innerScopes) { + if (scope.getKind() != InnerCallableScope.Kind.JS_FUNCTION_EXPR && + scope.getKind() != InnerCallableScope.Kind.JS_ARROW_FUNC) + continue; + if (scope.getHeaderStart() < initializerStart || scope.getFullEnd() > initializerEnd + 1) + continue; + if (scope.getExpectedType() != null) + continue; + + List funcParams = scope.getParameters(); + if (samParams.size() != funcParams.size()) + continue; + + scope.setExpectedType(declaredType); + for (int i = 0; i < funcParams.size(); i++) { + TypeInfo inferredType = samParams.get(i).getTypeInfo(); + if (inferredType != null) { + funcParams.get(i).setInferredType(inferredType); + } + } + } + } + } + + private void populateLambdaCache() { + for (InnerCallableScope scope : innerScopes) { + if (scope.getExpectedType() != null) { + lambdaCache.put(scope.getHeaderStart(), new LambdaCacheEntry(scope, scope.getExpectedType())); + } + } + } + + private int findStatementEnd(int startPos) { + int depth = 0; + for (int i = startPos; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '(' || c == '{' || c == '[') + depth++; + else if (c == ')' || c == '}' || c == ']') { + depth--; + if (depth < 0) + return i; + } else if (c == ';' && depth == 0) { + return i; + } + } + return text.length(); + } + + private void markImportedClassUsages(List marks) { + // Find uppercase identifiers followed by dot (static method calls, field access) + Pattern classUsage = Pattern.compile("\\b([A-Za-z][a-zA-Z0-9_]*)\\s*\\."); + Matcher m = classUsage.matcher(text); + + while (m.find()) { + String className = m.group(1); + int start = m.start(1); + int end = m.end(1); + + if (isExcluded(start)) + continue; + + // Skip in import/package statements + if (isInImportOrPackage(start)) + continue; + + // For JavaScript, first check synthetic types (Nashorn built-ins like Java, print, etc.) + if (isJavaScript()) { + if (typeResolver.isSyntheticType(className)) { + SyntheticType syntheticType = typeResolver.getSyntheticType(className); + // Mark as IMPORTED_CLASS since it's a type reference + // Pass the TypeInfo (which the hover system can display) + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.IMPORTED_CLASS, + syntheticType.getTypeInfo())); + continue; + } + JSTypeRegistry jsRegistry = JSTypeRegistry.getInstance(); + if (jsRegistry.isGlobalImport(className)) { + // Mark as IMPORTED_CLASS since it's a type reference + TypeInfo globalType = TypeInfo.fromJSTypeInfo(jsRegistry.getGlobalImportType(className)); + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.INTERFACE_DECL, globalType)); + continue; + } + } + + // Use position-aware resolution so inner class names (e.g., OrbBuilder inside Outer) + // resolve via the positional fallback that walks enclosing.getInnerClass(name). + TypeInfo info = resolveType(className, start); + if (info != null && info.isResolved()) { + marks.add(new ScriptLine.Mark(start, end, info.getTokenType(), info)); + } else { + // Unknown type - mark as undefined + marks.add(new ScriptLine.Mark(start, end, TokenType.UNDEFINED_VAR)); + } + } + + // Also mark uppercase identifiers in type positions (new X(), X variable, etc.) + Pattern typeUsage = Pattern.compile("\\b(new\\s+)?([A-Za-z][a-zA-Z0-9_]*)(?:\\s*<[^>]*>)?\\s*(?:\\(|\\[|\\b[a-z])"); + Matcher tm = typeUsage.matcher(text); + + while (tm.find()) { + String className = tm.group(2); + String newKeyword = tm.group(1); + int start = tm.start(2); + int end = tm.end(2); + + if (isExcluded(start)) + continue; + + // Skip in import/package statements + if (isInImportOrPackage(start)) + continue; + + // When the class name is preceded by a dot (e.g., OrbBuilder in AbilityLine.OrbBuilder), + // walk backwards to reconstruct the full qualified name and resolve via scriptTypesByDotName. + // resolveType(simpleNameOnly) fails outside the enclosing class body; the qualified name always works. + // We also track outerQualStart so we can detect 'new' before the full qualified name. + String resolveKey = className; + int outerQualStart = start; + if (isPrecededByDot(start)) { + int pos = start - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--; + while (pos >= 0 && text.charAt(pos) == '.') { + pos--; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--; + int identEnd = pos + 1; + while (pos > 0 && (Character.isLetterOrDigit(text.charAt(pos - 1)) || text.charAt(pos - 1) == '_')) pos--; + resolveKey = text.substring(pos, identEnd) + "." + resolveKey; + outerQualStart = pos; + pos--; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) pos--; + } + } + TypeInfo info = resolveType(resolveKey, start); + if (info == null || !info.isResolved()) { + info = resolveType(className, start); + } + boolean isClassTypeInfo = false; + ClassTypeInfo classRef = null; + FieldInfo varInfo = null; + // If not a class name, check if it's a variable holding a ClassTypeInfo + if ((info == null || !info.isResolved()) && isJavaScript()) { + varInfo = resolveVariable(className, start); + if (varInfo != null && varInfo.getTypeInfo() instanceof ClassTypeInfo) { + // Variable holds a class reference (like var File = Java.type("java.io.File")) + classRef = (ClassTypeInfo) varInfo.getTypeInfo(); + info = classRef.getInstanceType(); + isClassTypeInfo = true; + } + } + + if (info != null && info.isResolved()) { + boolean isNewCreation = newKeyword != null && newKeyword.trim().equals("new"); + // For dot-qualified types like 'new AbilityLine.OrbBuilder(...)', the regex never + // captures 'new' in group 1 because 'new' precedes 'AbilityLine', not 'OrbBuilder'. + // Detect it by checking whether outerQualStart is preceded by the 'new' keyword. + if (!isNewCreation && outerQualStart < start) { + int checkPos = outerQualStart - 1; + while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) checkPos--; + if (checkPos >= 2 && "new".equals(text.substring(checkPos - 2, checkPos + 1))) { + char beforeNew = checkPos >= 3 ? text.charAt(checkPos - 3) : ' '; + if (!Character.isLetterOrDigit(beforeNew) && beforeNew != '_') { + isNewCreation = true; + } + } + } + boolean isConstructorDecl = info instanceof ScriptTypeInfo && className.equals(info.getSimpleName()); + + // Check if this is a "new" expression or constructor declaration + if (isNewCreation || isConstructorDecl) { + // Find opening paren after the class name + int searchPos = end; + while (searchPos < text.length() && Character.isWhitespace(text.charAt(searchPos))) + searchPos++; + + // Skip generic args or diamond operator (e.g., or <>) + if (searchPos < text.length() && text.charAt(searchPos) == '<') { + int closeAngle = text.indexOf('>', searchPos); + if (closeAngle >= 0) { + searchPos = closeAngle + 1; + while (searchPos < text.length() && Character.isWhitespace(text.charAt(searchPos))) + searchPos++; + } + } + + if (searchPos < text.length() && text.charAt(searchPos) == '(') { + int openParen = searchPos; + int closeParen = findMatchingParen(openParen); + + if (closeParen >= 0) { + // For constructor declarations, verify it's followed by opening brace + if (isConstructorDecl && !isNewCreation) { + int braceSearch = closeParen + 1; + while (braceSearch < text.length() && Character.isWhitespace(text.charAt(braceSearch))) + braceSearch++; + + if (braceSearch >= text.length() || text.charAt(braceSearch) != '{') { + // Not a constructor declaration, treat as normal type usage + marks.add(new ScriptLine.Mark(start, end, info.getTokenType(), info)); + continue; + } + } + + // Parse arguments to find matching constructor + List arguments = parseMethodArguments(openParen + 1, closeParen, + null, info); + int argCount = arguments.size(); + TypeInfo[] argTypes = arguments.stream().map(MethodCallInfo.Argument::getResolvedType) + .toArray(TypeInfo[]::new); + + + // Try to find matching constructor (may be null if not found). + // First try exact type-match; if that fails but constructors exist, fall back to + // arg-count match so validate() can fire a WRONG_ARG_TYPE error instead of + // incorrectly treating the call as "no constructor matches N arguments". + MethodInfo constructor = null; + if (info.hasConstructors()) { + constructor = info.findConstructor(argTypes); + if (constructor == null) { + constructor = info.findConstructor(argCount); + } + } + + // Second pass: re-parse arguments with expected parameter types from resolved constructor + // This enables SAM type inference for lambda arguments (e.g., Consumer parameters) + if (constructor != null && constructor.getParameters().size() == arguments.size()) { + arguments = parseMethodArguments(openParen + 1, closeParen, constructor, info); + } + + // Create MethodCallInfo for constructor + // Use the actual variable name (className) for variables, not the class's simple name + MethodCallInfo ctorCall; + if (isClassTypeInfo) { + // Use constructor directly with variable name + ctorCall = new MethodCallInfo( + className, // Use variable name, not class name + start, end, + openParen, closeParen, + arguments, + classRef, // The actual class type + constructor, + false + ).setConstructor(true); + ctorCall.isClassTypeAccess = true; + } else { + ctorCall = MethodCallInfo.constructor( + info, constructor, start, end, openParen, closeParen, arguments + ); + } + + ctorCall.validate(); + methodCalls.add(ctorCall); // Add to methodCalls list for error tracking + + + TokenType type = isClassTypeInfo ? varInfo.isGlobal() ? TokenType.GLOBAL_FIELD + : TokenType.LOCAL_FIELD : TokenType.METHOD_CALL; + marks.add(new ScriptLine.Mark(start, end, type, isClassTypeInfo ? varInfo : ctorCall)); + continue; + } + } + } + + marks.add(new ScriptLine.Mark(start, end, info.getTokenType(), info)); + } else { + // Unknown type - mark as undefined + marks.add(new ScriptLine.Mark(start, end, TokenType.UNDEFINED_VAR)); + } + } + } + + // ==================== PHASE 5: CONFLICT RESOLUTION ==================== + + private List resolveConflicts(List marks) { + // Sort by start position, then by descending priority + marks.sort((a, b) -> { + if (a.start != b.start) + return Integer.compare(a.start, b.start); + return Integer.compare(b.type.getPriority(), a.type.getPriority()); + }); + + List result = new ArrayList<>(); + for (ScriptLine.Mark m : marks) { + boolean skip = false; + + // Remove lower-priority overlapping marks + for (int i = result.size() - 1; i >= 0; i--) { + ScriptLine.Mark r = result.get(i); + if (m.start < r.end && m.end > r.start) { + if (r.type.getPriority() < m.type.getPriority()) { + result.remove(i); + } else { + skip = true; + break; + } + } + } + + if (!skip) { + result.add(m); + } + } + + result.sort(Comparator.comparingInt(m -> m.start)); + return result; + } + + // ==================== PHASE 7: INDENT GUIDES ==================== + + private void computeIndentGuides(List marks) { + for (ScriptLine line : lines) { + line.clearIndentGuides(); + } + + // Build ignored ranges from STRING and COMMENT marks + Set ignored = new HashSet<>(); + for (ScriptLine.Mark m : marks) { + if (m.type == TokenType.STRING || m.type == TokenType.COMMENT) { + ignored.add(new int[]{m.start, m.end}); + } + } + + class OpenBrace { + int lineIdx, col; + + OpenBrace(int l, int c) { + lineIdx = l; + col = c; + } + } + Deque stack = new ArrayDeque<>(); + final int tabSize = 4; + + for (int li = 0; li < lines.size(); li++) { + ScriptLine line = lines.get(li); + String s = line.getText(); + + for (int i = 0; i < s.length(); i++) { + int absPos = line.getGlobalStart() + i; + + // Check if in ignored range + boolean isIgnored = false; + for (int[] range : ignored) { + if (absPos >= range[0] && absPos < range[1]) { + isIgnored = true; + break; + } + } + if (isIgnored) + continue; + + char c = s.charAt(i); + if (c == '{') { + int leading = 0; + for (int k = 0; k < i; k++) { + char ch = s.charAt(k); + leading += (ch == '\t') ? tabSize : 1; + } + stack.push(new OpenBrace(li, leading)); + } else if (c == '}') { + if (!stack.isEmpty()) { + OpenBrace open = stack.pop(); + if (open.lineIdx == li) + continue; + + int from = Math.max(0, open.lineIdx + 1); + int to = Math.min(lines.size() - 1, li); + for (int l = from; l <= to; l++) { + lines.get(l).addIndentGuide(open.col); + } + } + } + } + } + } + + // ==================== UTILITY METHODS ==================== + + /** + * Helper to create and validate a FieldAccessInfo. Does NOT add marks or register the info — + * callers should add to `fieldAccesses` and `marks` as appropriate so marking logic remains in-place. + */ + FieldAccessInfo createFieldAccessInfo(String name, int start, int end, + TypeInfo receiverType, FieldInfo fieldInfo, + boolean isLastSegment, boolean isStaticAccess) { + FieldAccessInfo accessInfo = new FieldAccessInfo(name, start, end, receiverType, fieldInfo, isStaticAccess); + if (isLastSegment) { + TypeInfo expectedType = findExpectedTypeAtPosition(start); + if (expectedType != null) { + accessInfo.setExpectedType(expectedType); + } + } + accessInfo.validate(); + fieldAccesses.add(accessInfo); + return accessInfo; + } + + /** + * Resolve a variable by name at a given position. + * Works for BOTH Java and JavaScript using unified data structures. + * Checks innermost scope first (lambda or method), then walks up parent chain. + */ + public FieldInfo resolveVariable(String name, int position) { + // 1. Check innermost scope (lambda or method) + Object innermostScope = findInnermostScopeAt(position); + + if (innermostScope instanceof InnerCallableScope) { + InnerCallableScope scope = (InnerCallableScope) innermostScope; + + // Check lambda parameters and locals, walking up parent chain + InnerCallableScope currentScope = scope; + while (currentScope != null) { + // Check parameters + FieldInfo param = currentScope.getParameter(name); + if (param != null) { + return param; + } + + // Check locals + FieldInfo local = currentScope.getLocals().get(name); + if (local != null) { + return local; + } + + currentScope = currentScope.getParentScope(); + } + + // Not found in lambda scopes - fall back to enclosing method + // Find which method this lambda is inside + innermostScope = findMethodAtPosition(position); + } + + // 2. Check method scope (params + locals) + if (innermostScope instanceof MethodInfo) { + MethodInfo method = (MethodInfo) innermostScope; + + // Check method parameters + if (method.hasParameter(name)) { + return method.getParameter(name); + } + + // Check method locals + Map> locals = methodLocals.get(method.getDeclarationOffset()); + if (locals != null) { + FieldInfo localInfo = pickVisibleLocal(locals.get(name), position); + if (localInfo != null) { + return localInfo; + } + } + } + + FieldInfo topLocal = pickVisibleTopLevelLocal(name, position); + if (topLocal != null) return topLocal; + + // 4. For Java only: Check if we're inside a script type and look for fields there + if (!isJavaScript()) { + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null && enclosingType.hasField(name)) { + return enclosingType.getFieldInfo(name); + } + } + + // 4. Check global fields (stores both Java global fields and JS global var/let/const) + if (globalFields.containsKey(name)) { + return globalFields.get(name); + } + + // 5. Check JS global objects from JSTypeRegistry (like API, DBCAPI) + if (isJavaScript()) { + JSTypeRegistry registry = JSTypeRegistry.getInstance(); + String globalObjectType = registry.getGlobalObjectType(name); + if (globalObjectType != null) { + // Resolve the type and create a FieldInfo for it + TypeInfo typeInfo = resolveType(globalObjectType); + if (typeInfo != null && typeInfo.isResolved()) { + // Create a global field for this object with GLOBAL scope + return FieldInfo.globalField(name, typeInfo, -1); + } + } + + // Check if is DataScript global variable definition + String editorGlobalType = editorGlobals.get(name); + if (editorGlobalType != null) { + TypeInfo typeInfo = resolveType(editorGlobalType); + if (typeInfo == null || !typeInfo.isResolved()) { + typeInfo = TypeInfo.ANY; + } + return FieldInfo.globalField(name, typeInfo, -1); + } + } + + return null; + } + + boolean isPrecededByDot(int position) { + if (position <= 0) + return false; + int i = position - 1; + while (i >= 0 && Character.isWhitespace(text.charAt(i))) + i--; + return i >= 0 && text.charAt(i) == '.' && !isExcluded(i); + } + + boolean isInImportOrPackage(int position) { + if (position < 0 || position >= text.length()) + return false; + + int lineStart = text.lastIndexOf('\n', position); + lineStart = lineStart < 0 ? 0 : lineStart + 1; + + int i = lineStart; + while (i < text.length() && Character.isWhitespace(text.charAt(i))) + i++; + + if (text.startsWith("import", i) || text.startsWith("package", i)) { + return true; + } + return false; + } + + /** Check if position is followed by '(' (method call) */ + boolean isFollowedByParen(int pos) { + int check = skipWhitespace(pos); + return check < text.length() && text.charAt(check) == '('; + } + + /** Check if position is followed by '.' */ + boolean isFollowedByDot(int pos) { + int check = skipWhitespace(pos); + return check < text.length() && text.charAt(check) == '.'; + } + + /** Skip whitespace and return new position */ + int skipWhitespace(int pos) { + while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) + pos++; + return pos; + } + + MethodInfo findMethodAtPosition(int position) { + for (MethodInfo method : getAllMethods()) { + if (method.containsPosition(position)) { + return method; + } + } + for (MethodInfo constructor : getAllConstructors()) { + if (constructor.containsPosition(position)) { + return constructor; + } + } + return null; + } + + /** + * Find the innermost scope (method or inner callable) at a position. + * Returns null if not inside any scope. + */ + public Object findInnermostScopeAt(int position) { + // First check inner callable scopes (most specific) + InnerCallableScope innermost = null; + for (InnerCallableScope scope : innerScopes) { + if (scope.containsPosition(position) || scope.containsHeaderPosition(position)) { + if (innermost == null || scope.getBodyStart() > innermost.getBodyStart()) { + innermost = scope; + } + } + } + + if (innermost != null) { + return innermost; + } + + // Fall back to method scope + return findMethodAtPosition(position); + } + + int findMatchingBrace(int openBraceIndex) { + if (openBraceIndex < 0 || openBraceIndex >= text.length()) + return -1; + + int depth = 0; + for (int i = openBraceIndex; i < text.length(); i++) { + if (isExcluded(i)) + continue; + + char c = text.charAt(i); + if (c == '{') + depth++; + else if (c == '}') { + depth--; + if (depth == 0) + return i; + } + } + return -1; + } + + // ==================== ACCESSORS ==================== + + public List getLines() { + return Collections.unmodifiableList(lines); + } + + public List getImports() { + return Collections.unmodifiableList(imports); + } + + public List getMethods() { + return Collections.unmodifiableList(methods); + } + + public List getInnerScopes() { + return Collections.unmodifiableList(innerScopes); + } + + public ObjectLiteralParser.ObjectLiteralAnalysis getObjectLiteral(int braceOffset) { + return objectLiterals.get(braceOffset); + } + + public LambdaCacheEntry getLambdaCacheEntry(int headerOffset) { + return lambdaCache.get(headerOffset); + } + + public List getScriptTypes() { + // Return all types including inner classes — needed by error underline rendering, + // validation loops, and mark building so inner classes get full treatment + return new ArrayList<>(scriptTypesByFullName.values()); + } + + public List getAllMethods() { + List allMethods = new ArrayList<>(methods); + // Iterate all types (including inner) so nested class methods are included + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + allMethods.addAll(scriptType.getAllMethodsFlat()); + } + + return allMethods; + } + + public List getAllConstructors() { + List allConstructors = new ArrayList<>(); + // Iterate all types (including inner) so nested class constructors are included + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + allConstructors.addAll(scriptType.getConstructors()); + } + return allConstructors; + } + + public List getMethodCalls() { + List allCalls = new ArrayList<>(methodCalls); + + for (EnumConstantInfo constant : getAllEnumConstants()) { + if (constant.getConstructorCall() != null) + allCalls.add(constant.getConstructorCall()); + } + + + return allCalls; + } + + public List getFieldAccesses() { + return Collections.unmodifiableList(fieldAccesses); + } + + public List getAllEnumConstants() { + List enums = new ArrayList<>(); + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + if (!scriptType.hasEnumConstants()) + continue; + + enums.addAll(scriptType.getEnumConstants().values()); + } + return enums; + } + /** + * Find an assignment at the given position, prioritizing LHS over RHS. + * Searches across all script fields and external field assignments. + * Used by TokenHoverInfo for finding assignment errors. + */ + public AssignmentInfo findAssignmentAtPosition(int position) { + // Check script fields (FieldInfo.findAssignmentAtPosition already handles LHS/RHS priority) + for (FieldInfo field : globalFields.values()) { + AssignmentInfo assign = field.findAssignmentAtPosition(position); + if (assign != null) { + return assign; + } + } + + for (Map> locals : methodLocals.values()) { + for (List fields : locals.values()) { + for (FieldInfo field : fields) { + AssignmentInfo assign = field.findAssignmentAtPosition(position); + if (assign != null) { + return assign; + } + } + } + } + for (List fields : topLevelLocals.values()) { + for (FieldInfo field : fields) { + AssignmentInfo assign = field.findAssignmentAtPosition(position); + if (assign != null) { + return assign; + } + } + } + + for (AssignmentInfo assign : declarationErrors) { + if (assign.containsLhsPosition(position)) { + return assign; + } + } + + // Check external field assignments with same LHS-first priority + for (AssignmentInfo assign : externalFieldAssignments) { + if (assign.containsLhsPosition(position)) { + return assign; + } + } + + for (AssignmentInfo assign : externalFieldAssignments) { + if (assign.containsRhsPosition(position)) { + return assign; + } + } + + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + for (FieldInfo field : scriptType.getFields().values()) { + AssignmentInfo assign = field.findAssignmentAtPosition(position); + if (assign != null) + return assign; + } + } + + return null; + } + + public Map getGlobalFields() { + return Collections.unmodifiableMap(globalFields); + } + + /** + * Get all variables available at a specific position. + * Used by autocomplete to show scope-aware suggestions. + * Returns variables from innermost scope first (parameters, then locals), + * walking up through parent scopes, then method scope, then globals. + * + * @param position The cursor position + * @return List of FieldInfo for all available variables, ordered by priority + */ + public List getAvailableVariablesAt(int position) { + List variables = new ArrayList<>(); + + // Check innermost scope (lambda or method) + Object innermostScope = findInnermostScopeAt(position); + + if (innermostScope instanceof InnerCallableScope) { + InnerCallableScope scope = (InnerCallableScope) innermostScope; + + // Add lambda parameters and locals, walking up parent chain + InnerCallableScope currentScope = scope; + while (currentScope != null) { + // Add parameters from this scope + variables.addAll(currentScope.getParameters()); + + // Add locals from this scope (only those visible at position) + for (FieldInfo local : currentScope.getLocals().values()) { + if (local.isVisibleAt(position)) { + variables.add(local); + } + } + + currentScope = currentScope.getParentScope(); + } + + // Fall back to enclosing method + innermostScope = findMethodAtPosition(position); + } + + // Add method scope variables + if (innermostScope instanceof MethodInfo) { + MethodInfo method = (MethodInfo) innermostScope; + + // Add method parameters + variables.addAll(method.getParameters()); + + // Add method locals (only those visible at position) + Map> locals = methodLocals.get(method.getDeclarationOffset()); + if (locals != null) { + for (List candidates : locals.values()) { + FieldInfo best = pickVisibleLocal(candidates, position); + if (best != null) { + variables.add(best); + } + } + } + } + + variables.addAll(getVisibleTopLevelLocals(position)); + + // Add global fields (only those visible at position) + for (FieldInfo globalField : globalFields.values()) { + if (globalField.isVisibleAt(position)) { + variables.add(globalField); + } + } + + // For Java: add fields from enclosing type + if (!isJavaScript()) { + ScriptTypeInfo enclosingType = findEnclosingScriptType(position); + if (enclosingType != null) { + for (FieldInfo field : enclosingType.getFields().values()) { + if (field.isVisibleAt(position)) { + variables.add(field); + } + } + } + } + + // For JS: add global engine objects and editor globals + if (isJavaScript()) { + JSTypeRegistry registry = JSTypeRegistry.getInstance(); + + // Add global engine objects (like API, DBCAPI) + for (String globalName : registry.getGlobalEngineObjects().keySet()) { + FieldInfo field = resolveVariable(globalName, position); + if (field != null && field.isResolved()) { + variables.add(field); + } + } + + // Add editor/DataScript global variables + for (String globalName : editorGlobals.keySet()) { + FieldInfo field = resolveVariable(globalName, position); + if (field != null && field.isResolved()) { + variables.add(field); + } + } + } + + return variables; + } + + /** + * Get all errored assignments across all fields (global, local, and external). + * Used by ScriptLine to draw error underlines. + * + * @deprecated Use {@link #getErrors()} instead. Errors are now collected in {@link #populateErrors()}. + */ + @Deprecated + public List getAllErroredAssignments() { + List errored = new ArrayList<>(); + + // Check global fields + for (FieldInfo field : globalFields.values()) { + errored.addAll(field.getErroredAssignments()); + } + + // Check method locals + for (Map> locals : methodLocals.values()) { + for (List fields : locals.values()) { + for (FieldInfo field : fields) { + errored.addAll(field.getErroredAssignments()); + } + } + } + for (List fields : topLevelLocals.values()) { + for (FieldInfo field : fields) { + errored.addAll(field.getErroredAssignments()); + } + } + + // Check external field assignments + for (AssignmentInfo assign : externalFieldAssignments) { + if (assign.hasError()) { + errored.add(assign); + } + } + + + for (ScriptTypeInfo scriptType : scriptTypesByFullName.values()) { + for (FieldInfo field : scriptType.getFields().values()) { + errored.addAll(field.getErroredAssignments()); + } + } + + for (InnerCallableScope scope : getInnerScopes()) { + for (FieldInfo field : scope.getParameters()) + errored.addAll(field.getErroredAssignments()); + + for (FieldInfo field : scope.getLocals().values()) + errored.addAll(field.getErroredAssignments()); + } + + + // Include declaration errors (duplicates, etc.) + errored.addAll(declarationErrors); + + return errored; + } + + public void addError(Token token, int startPos, int endPos, String message) { + errors.add(new DocumentError(token, startPos, endPos, message)); + } + + public List getErrors() { + return Collections.unmodifiableList(errors); + } + + /** + * Collect all validation errors from MethodCallInfo, AssignmentInfo, MethodInfo, and ScriptTypeInfo + * into the centralized error list. Called once during analysis (formatCodeText), not during rendering. + */ + private void populateErrors() { + // Method call errors + List allMethods = getAllMethods(); + for (MethodCallInfo call : getMethodCalls()) { + boolean isDeclaration = false; + int methodStart = call.getMethodNameStart(); + for (MethodInfo mi : allMethods) { + if (!call.isConstructor() && mi.getDeclarationOffset() <= methodStart && mi.getBodyStart() >= methodStart) { + isDeclaration = true; + break; + } + } + if (isDeclaration) + continue; + + if (call.hasArgCountError()) { + int methodEnd = methodStart + call.getMethodName().length(); + addError(null, methodStart, methodEnd, call.getErrorMessage()); + } else if (call.hasArgTypeError()) { + for (MethodCallInfo.ArgumentTypeError error : call.getArgumentTypeErrors()) { + MethodCallInfo.Argument arg = error.getArg(); + addError(null, arg.getStartOffset(), arg.getEndOffset(), error.getMessage()); + } + } else if (call.hasError()) { + addError(null, call.getMethodNameStart(), call.getCloseParenOffset() + 1, call.getErrorMessage()); + } + } + + // Assignment errors + for (AssignmentInfo assign : getAllErroredAssignments()) { + int underlineStart, underlineEnd; + + if (assign.isLhsError()) { + underlineStart = assign.getLhsStart(); + underlineEnd = assign.getLhsEnd(); + } else if (assign.isRhsError()) { + underlineStart = assign.getRhsStart(); + underlineEnd = assign.getRhsEnd(); + } else if (assign.isFullLineError()) { + underlineStart = assign.getStatementStart(); + underlineEnd = assign.getRhsEnd(); + } else { + continue; + } + + addError(null, underlineStart, underlineEnd, assign.getErrorMessage()); + } + + // Method declaration errors + for (MethodInfo method : allMethods) { + if (!method.isDeclaration() || !method.hasError()) + continue; + + if (method.hasReturnStatementErrors()) { + for (MethodInfo.ReturnStatementError returnError : method.getReturnStatementErrors()) { + addError(null, returnError.getStartOffset(), returnError.getEndOffset(), returnError.getMessage()); + } + } else if (method.hasMissingReturnError()) { + int methodNameStart = method.getNameOffset(); + int methodNameEnd = methodNameStart + method.getName().length(); + addError(null, methodNameStart, methodNameEnd, method.getErrorMessage()); + } else if (method.hasParameterErrors()) { + for (MethodInfo.ParameterError paramError : method.getParameterErrors()) { + FieldInfo param = paramError.getParameter(); + if (param == null || param.getDeclarationOffset() < 0) + continue; + + int paramStart = param.getDeclarationOffset(); + int paramEnd = paramStart + param.getName().length(); + addError(null, paramStart, paramEnd, paramError.getMessage()); + } + } else if (method.hasError()) { + addError(null, method.getFullDeclarationOffset(), method.getDeclarationEnd(), method.getErrorMessage()); + } + } + + for (EnumConstantInfo enumConst : getAllEnumConstants()) { + if (enumConst != null && enumConst.hasError()) { + addError(null, 0, 0, enumConst.getErrorMessage()); + } + } + + // Script type declaration errors + for (ScriptTypeInfo type : getScriptTypes()) { + if (!type.hasError()) + continue; + + int typeStart = type.getDeclarationOffset(); + int typeEnd = type.getBodyStart(); + + for (ScriptTypeInfo.MissingMethodError err : type.getMissingMethodErrors()) + addError(null, typeStart, typeEnd, err.getMessage()); + + // Constructor mismatch errors + for (ScriptTypeInfo.ConstructorMismatchError err : type.getConstructorMismatchErrors()) + addError(null, typeStart, typeEnd, err.getMessage()); + + // General error message + String msg = type.getErrorMessage(); + if(msg != null && !msg.isEmpty()) + addError(null, typeStart, typeEnd, type.getErrorMessage()); + } + } + + public TypeResolver getTypeResolver() { + return typeResolver; + } + + public ScriptLine getLine(int index) { + for (ScriptLine line : lines) { + if (line.getLineIndex() == index) { + return line; + } + } + return null; + } + + public ScriptLine getLineAt(int globalPosition) { + for (ScriptLine line : lines) { + if (line.containsPosition(globalPosition)) { + return line; + } + } + return null; + } + + public int getLineIndexAt(int globalPosition) { + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).containsPosition(globalPosition)) { + return i; + } + } + return -1; + } + + /** + * Get all tokens that fall within a given range [start, end). + * Returns tokens in order. Tokens that span across the range boundaries + * are included if any part of them is within the range. + */ + public List getTokensInRange(int start, int end) { + List result = new ArrayList<>(); + if (start < 0 || end <= start) return result; + + for (ScriptLine line : lines) { + // Skip lines entirely before the range + if (line.getGlobalEnd() <= start) continue; + // Stop if line is entirely after the range + if (line.getGlobalStart() >= end) break; + + for (Token token : line.getTokens()) { + // Check if token overlaps with range + if (token.getGlobalEnd() > start && token.getGlobalStart() < end) { + result.add(token); + } + } + } + return result; + } + + /** + * Find the expected type for an expression at the given position by looking for assignment context. + * Returns the type of the variable being assigned to, or null if not in an assignment. + * + * Examples: + * - "Type varName = expr;" -> returns Type + * - "varName = expr;" -> returns type of varName + */ + public TypeInfo findExpectedTypeAtPosition(int position) { + // Walk backward from position to find '=' + int pos = position - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + + // Look for '=' that precedes this position + int equalsPos = -1; + int depth = 0; // Track parentheses/brackets depth + for (int i = pos; i >= 0; i--) { + if (isExcluded(i)) continue; + + char c = text.charAt(i); + if (c == ')' || c == ']') depth++; + else if (c == '(' || c == '[') depth--; + else if (c == '=' && depth == 0) { + // Make sure it's not ==, !=, <=, >= + if (i > 0 && "!<>=".indexOf(text.charAt(i - 1)) >= 0) continue; + if (i < text.length() - 1 && text.charAt(i + 1) == '=') continue; + equalsPos = i; + break; + } + else if (c == ';' || c == '{' || c == '}') { + // Reached statement boundary without finding assignment + break; + } + } + + if (equalsPos < 0) { + return null; // Not in an assignment + } + + // Now parse the left-hand side of the assignment + // Could be: "Type varName = expr" or "varName = expr" + pos = equalsPos - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + + if (pos < 0) return null; + + // Find the variable name (work backward to find identifier) + int varNameEnd = pos + 1; + int varNameStart = pos; + while (varNameStart >= 0 && (Character.isJavaIdentifierPart(text.charAt(varNameStart)))) { + varNameStart--; + } + varNameStart++; // Move to first char of identifier + + if (varNameStart >= varNameEnd) return null; + + String varName = text.substring(varNameStart, varNameEnd); + + // Now check if there's a type declaration before the variable name + pos = varNameStart - 1; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { + pos--; + } + + if (pos < 0) { + // Just "varName = expr" - look up varName in scope + return lookupVariableType(varName, position); + } + + // Check if this could be a type declaration (look for identifier before varName) + int typeEnd = pos + 1; + int typeStart = pos; + while (typeStart >= 0 && (Character.isJavaIdentifierPart(text.charAt(typeStart)) || + text.charAt(typeStart) == '<' || text.charAt(typeStart) == '>' || + text.charAt(typeStart) == '[' || text.charAt(typeStart) == ']' || + text.charAt(typeStart) == ',')) { + typeStart--; + } + typeStart++; + + if (typeStart >= typeEnd) { + // Just "varName = expr" - look up varName + return lookupVariableType(varName, position); + } + + String typeStr = text.substring(typeStart, typeEnd).trim(); + + // Check if this is a var/let/const keyword (type inference) + if (typeStr.equals("var") || typeStr.equals("let") || typeStr.equals("const")) { + // Can't determine expected type from var/let/const + return null; + } + + // Resolve the type + return resolveType(typeStr); + } + + /** + * Look up the type of a variable by name at the given position. + */ + private TypeInfo lookupVariableType(String varName, int position) { + // Check method locals + MethodInfo containingMethod = findMethodAtPosition(position); + if (containingMethod != null) { + Map> locals = methodLocals.get(containingMethod.getDeclarationOffset()); + if (locals != null) { + FieldInfo field = pickVisibleLocal(locals.get(varName), position); + if (field != null) { + return field.getTypeInfo(); + } + } + } + + FieldInfo topLevelLocal = pickVisibleTopLevelLocal(varName, position); + if (topLevelLocal != null) { + return topLevelLocal.getTypeInfo(); + } + + // Check global fields + if (globalFields.containsKey(varName)) { + return globalFields.get(varName).getTypeInfo(); + } + + return null; + } + + // ==================== AUTOCOMPLETE SUPPORT ==================== + + /** + * Find the method that contains the given position. + * Public accessor for autocomplete. + */ + public MethodInfo findContainingMethod(int position) { + return findMethodAtPosition(position); + } + + /** + * Get local variables for a specific method. + * Used by autocomplete to show variables in scope. + */ + public Map getLocalsForMethod(MethodInfo method) { + if (method == null) return null; + Map> locals = methodLocals.get(method.getDeclarationOffset()); + if (locals == null) { + return null; + } + Map flattened = new HashMap<>(); + for (Map.Entry> e : locals.entrySet()) { + List fields = e.getValue(); + if (fields != null && !fields.isEmpty()) { + flattened.put(e.getKey(), fields.get(0)); + } + } + return flattened; + } + + /** + * Get all imported types that have been resolved. + * Used by autocomplete to show available types. + */ + public Set getImportedTypes() { + Set types = new HashSet<>(); + for (ImportData imp : imports) { + if (!imp.isWildcard() && imp.isResolved()) { + TypeInfo type = typeResolver.resolveSimpleName(imp.getSimpleName(), importsBySimpleName, wildcardPackages); + if (type != null && type.isResolved()) { + types.add(type); + } + } + } + // For class-level wildcard imports (e.g. INpcEvent.*), add the outer class itself. + // Package-level wildcards (e.g. noppes.npcs.api.event.*) are skipped — those are + // already covered by addUnimportedClassSuggestions via ClassIndex. + for (String pkg : wildcardPackages) { + TypeInfo outerType = typeResolver.resolveFullName(pkg); + if (outerType != null && outerType.isResolved()) { + // resolveFullName succeeded → pkg is a class, not a package + types.add(outerType); + } + } + return types; + } + + /** + * Get script types as a Map (needed by autocomplete). + * Returns only top-level types keyed by simple name for backward compatibility. + */ + public Map getScriptTypesMap() { + return Collections.unmodifiableMap(scriptTypes); + } + + /** + * Get all script types including inner classes, keyed by full ($-separated) name. + * Use this when you need to iterate or look up inner classes. + */ + public Map getAllScriptTypes() { + return Collections.unmodifiableMap(scriptTypesByFullName); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptLine.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptLine.java new file mode 100644 index 000000000..1265aa582 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptLine.java @@ -0,0 +1,482 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.Token; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenErrorMessage; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.ImportData; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; + +/** + * Represents a single line of source code with its tokens. + * Handles token management, navigation, and rendering. + * + * A ScriptLine is responsible for: + * - Storing tokens that fall within this line's character range + * - Managing token navigation (prev/next within line) + * - Rendering the line with proper syntax highlighting + * - Computing indent guides for this line + */ +public class ScriptLine { + + private static final char COLOR_CHAR = '\u00A7'; + + private final String text; // The actual text of this line + public final int globalStart; // Start offset in the full document + public final int globalEnd; // End offset in the full document (exclusive) + public final int lineIndex; // 0-based line number + + private final List tokens = new ArrayList<>(); + private final List indentGuides = new ArrayList<>(); // Column positions for indent guides + + // Navigation + private ScriptLine prev; + private ScriptLine next; + private ScriptDocument parent; + + public ScriptLine(String text, int globalStart, int globalEnd, int lineIndex) { + this.text = text; + this.globalStart = globalStart; + this.globalEnd = globalEnd; + this.lineIndex = lineIndex; + } + + // ==================== GETTERS ==================== + + public String getText() { return text; } + public int getGlobalStart() { return globalStart; } + public int getGlobalEnd() { return globalEnd; } + public int getLineIndex() { return lineIndex; } + public int getLength() { return text.length(); } + public List getTokens() { return Collections.unmodifiableList(tokens); } + public List getIndentGuides() { return Collections.unmodifiableList(indentGuides); } + public ScriptDocument getParent() { return parent; } + + void setParent(ScriptDocument parent) { this.parent = parent; } + void setPrev(ScriptLine prev) { this.prev = prev; } + void setNext(ScriptLine next) { this.next = next; } + + // ==================== NAVIGATION ==================== + + public ScriptLine prev() { return prev; } + public ScriptLine next() { return next; } + + public Token getFirstToken() { + return tokens.isEmpty() ? null : tokens.get(0); + } + + public Token getLastToken() { + return tokens.isEmpty() ? null : tokens.get(tokens.size() - 1); + } + + public Token getTokenAt(int globalPosition) { + for (Token t : tokens) + if (globalPosition >= t.getGlobalStart() && globalPosition <= t.getGlobalEnd()) + return t; + + return null; + } + + public Token getTokenAt(int globalPosition, Predicate condition) { + for (Token t : tokens) + if (globalPosition >= t.getGlobalStart() && globalPosition <= t.getGlobalEnd() && condition.test(t)) + return t; + + return null; + + } + + // ==================== TOKEN MANAGEMENT ==================== + + /** + * Clear all tokens from this line. + */ + public void clearTokens() { + tokens.clear(); + } + + /** + * Add a token to this line and set up navigation links. + */ + public void addToken(Token token) { + if (!tokens.isEmpty()) { + Token last = tokens.get(tokens.size() - 1); + last.setNext(token); + token.setPrev(last); + } + token.setParentLine(this); + tokens.add(token); + } + + /** + * Build tokens from a list of marks (highlight regions). + * Fills gaps between marks with DEFAULT tokens. + * Attaches metadata from marks to the created tokens. + * + * @param marks List of highlight marks that overlap this line + * @param fullText The complete document text + * @param document The parent ScriptDocument (for context lookups) + */ + public void buildTokensFromMarks(List marks, String fullText, ScriptDocument document) { + clearTokens(); + int cursor = globalStart; + + /* + * globalEnd includes the newline character position (lineEnd = lineStart + text.length() + 1), + * but the line's text field does NOT include the newline. We must clamp all token boundaries + * to the displayable text end so that '\n' never leaks into rendered token text. + */ + int displayEnd = Math.min(globalStart + text.length(), fullText.length()); + + for (Mark mark : marks) { + // Skip marks that don't overlap the displayable portion of this line + if (mark.end <= globalStart || mark.start >= displayEnd) { + continue; + } + + // Clamp mark to displayable line boundaries (excludes trailing newline) + int tokenStart = Math.max(mark.start, globalStart); + int tokenEnd = Math.min(mark.end, displayEnd); + + // Validate bounds + tokenStart = Math.max(0, Math.min(tokenStart, fullText.length())); + tokenEnd = Math.max(0, Math.min(tokenEnd, fullText.length())); + + // Add default token for any gap before this mark + if (cursor < tokenStart) { + int gapEnd = Math.min(tokenStart, fullText.length()); + String gapText = fullText.substring(cursor, gapEnd); + addToken(Token.defaultToken(gapText, cursor, gapEnd)); + } + + // Add the marked token with metadata + if (tokenStart < tokenEnd) { + String tokenText = fullText.substring(tokenStart, tokenEnd); + Token token = new Token(tokenText, tokenStart, tokenEnd, mark.type); + + // Attach metadata based on type + if (mark.metadata != null) + applyTokenMetadata(token, mark.metadata); + + addToken(token); + } + + cursor = tokenEnd; + } + + // Add trailing default token if needed (clamped to displayable text, excluding newline) + if (cursor < displayEnd) { + String trailingText = fullText.substring(cursor, displayEnd); + addToken(Token.defaultToken(trailingText, cursor, displayEnd)); + } + } + + public void applyTokenMetadata(Token token, Object metadata) { + if (metadata instanceof TypeInfo) { + token.setTypeInfo((TypeInfo) metadata); + } else if (metadata instanceof TypeParamInfo) { + TypeParamInfo typeParam = (TypeParamInfo) metadata; + token.setTypeInfo(TypeInfo.typeParameter(typeParam.getName(), typeParam)); + } else if (metadata instanceof MethodCallInfo) { + MethodCallInfo callInfo = (MethodCallInfo) metadata; + if (callInfo.isConstructor()) { + token.setTypeInfo(callInfo.getReceiverType()); + token.setMethodInfo(callInfo.getResolvedMethod()); + } + token.setMethodCallInfo(callInfo); + } else if (metadata instanceof FieldInfo.ArgInfo) { + FieldInfo.ArgInfo ctx = (FieldInfo.ArgInfo) metadata; + token.setFieldInfo(ctx.fieldInfo); + token.setMethodCallInfo(ctx.methodCallInfo); + } else if (metadata instanceof FieldInfo) { + token.setFieldInfo((FieldInfo) metadata); + } else if (metadata instanceof MethodInfo) { + token.setMethodInfo((MethodInfo) metadata); + } else if (metadata instanceof ImportData) { + token.setImportData((ImportData) metadata); + } else if (metadata instanceof FieldAccessInfo) { + FieldAccessInfo accessInfo = (FieldAccessInfo) metadata; + token.setFieldAccessInfo(accessInfo); + token.setFieldInfo(accessInfo.getResolvedField()); + } else if (metadata instanceof TokenErrorMessage) { + token.setErrorMessage((TokenErrorMessage) metadata); + } + } + // ==================== INDENT GUIDES ==================== + + /** + * Clear indent guides for this line. + */ + public void clearIndentGuides() { + indentGuides.clear(); + } + + /** + * Add an indent guide at the specified column. + */ + public void addIndentGuide(int column) { + if (!indentGuides.contains(column)) { + indentGuides.add(column); + } + } + + // ==================== RENDERING ==================== + + /** + * Compute the rendered pixel width of a substring of this line, accounting for + * bold/italic token styles. Characters covered by bold or italic tokens will be + * measured with the appropriate font style, producing the same widths as the + * actual rendered output. + * + * @param localStart start index within the line text (inclusive) + * @param localEnd end index within the line text (exclusive) + * @return pixel width matching the rendered output + */ + public int getRenderedWidth(int localStart, int localEnd) { + localStart = Math.max(0, Math.min(localStart, text.length())); + localEnd = Math.max(localStart, Math.min(localEnd, text.length())); + if (localStart >= localEnd) return 0; + + int width = 0; + int cursor = localStart; + + for (Token t : tokens) { + if (cursor >= localEnd) break; + + int tokenLocalStart = t.getGlobalStart() - globalStart; + int tokenLocalEnd = tokenLocalStart + t.getText().length(); + + // Gap before this token (rendered as plain text) + if (cursor < tokenLocalStart) { + int gapEnd = Math.min(tokenLocalStart, localEnd); + if (gapEnd > cursor) { + width += ClientProxy.Font.width(text.substring(cursor, gapEnd)); + cursor = gapEnd; + } + } + + if (cursor >= localEnd) break; + + // Token overlap with [localStart, localEnd) + int overlapStart = Math.max(cursor, tokenLocalStart); + int overlapEnd = Math.min(tokenLocalEnd, localEnd); + if (overlapEnd > overlapStart) { + String substr = text.substring(overlapStart, overlapEnd); + width += ClientProxy.Font.width(substr, t.getFontStyle()); + cursor = overlapEnd; + } + } + + // Trailing text after last token (plain) + if (cursor < localEnd) { + width += ClientProxy.Font.width(text.substring(cursor, localEnd)); + } + + return width; + } + + /** + * Draw this line with syntax highlighting using Minecraft color codes. + * Compatible with the existing rendering system. + * Also draws curly underlines for tokens with errors (method call validation failures). + * Supports bold (§l) and italic (§o) formatting for certain token types. + */ + public void drawString(int x, int y, int defaultColor) { + StringBuilder builder = new StringBuilder(); + int lastIndex = 0; + + // Track positions for underlines + int currentX = x; + + for (Token t : tokens) { + int tokenStart = t.getGlobalStart() - globalStart; // relative position in line + int tokenWidth = ClientProxy.Font.width(t.getText(), t.getFontStyle()); + + // Calculate gap width before this token + if (tokenStart > lastIndex && tokenStart <= text.length()) { + String gapText = text.substring(lastIndex, tokenStart); + builder.append(gapText); + currentX += ClientProxy.Font.width(gapText); + } + + + // Append style codes (bold/italic) if applicable + String stylePrefix = t.getStylePrefix(); + + // Append the colored token with style + builder.append(COLOR_CHAR) + .append(t.getColorCode()) + .append(stylePrefix) + .append(t.getText()) + .append(COLOR_CHAR) + .append('r'); // Reset all formatting (color + bold/italic) + + currentX += tokenWidth; + lastIndex = tokenStart + t.getText().length(); + } + + // Append any remaining text after the last token + if (lastIndex < text.length()) { + builder.append(text.substring(lastIndex)); + } + + // Draw the text + ClientProxy.Font.drawString(builder.toString(), x, y, defaultColor); +// Minecraft.getMinecraft().fontRenderer.drawString(builder.toString(), x, y, defaultColor); + + + // Draw underlines for validation errors (method calls and field accesses) + drawErrorUnderlines(x, y + ClientProxy.Font.height() - 1); + } + /** + * Draw this line with hex colors instead of Minecraft color codes. + * More flexible but requires custom font rendering. + * Also draws wavy underlines for tokens with errors. + */ + public void drawStringHex(int x, int y) { + int lastIndex = 0; + + // Build segments with token position info and compute positions using style-aware widths + java.util.List segments = new java.util.ArrayList<>(); + + for (Token t : tokens) { + int tokenStart = t.getGlobalStart() - globalStart; + + // Add any gap before this token + if (tokenStart > lastIndex && tokenStart <= text.length()) { + String gap = text.substring(lastIndex, tokenStart); + segments.add(new TextSegment(lastIndex, gap, 0xFFFFFFFF, false)); + } + + // Add the colored token (with style prefix for rendering) + String styledText = t.getStylePrefix() + t.getText(); + segments.add(new TextSegment(tokenStart, styledText, t.getHexColor(), true)); + + lastIndex = tokenStart + t.getText().length(); + } + + // Add any remaining text after the last token + if (lastIndex < text.length()) { + String remaining = text.substring(lastIndex); + segments.add(new TextSegment(lastIndex, remaining, 0xFFFFFFFF, false)); + } + + // Draw each segment at the correct position using style-aware width + for (TextSegment seg : segments) { + if (!seg.text.isEmpty()) { + int prefixWidth = getRenderedWidth(0, seg.startPos); + int color = seg.color; + + ClientProxy.Font.drawString(seg.text, x + prefixWidth, y, color); + } + } + + drawErrorUnderlines(x, y + ClientProxy.Font.height() - 1); + } + + /** + * Draw underlines for all validation errors (method calls and field accesses) that intersect this line. + * Delegates to ErrorUnderlineRenderer for the actual rendering logic. + */ + private void drawErrorUnderlines(int lineStartX, int baselineY) { + if (parent == null) + return; + + ErrorUnderlineRenderer.drawErrorUnderlines( + parent, + this, + lineStartX, + baselineY, + getText(), + getGlobalStart(), + getGlobalEnd() + ); + } + + + // Helper class to track text segments + private static class TextSegment { + final int startPos; + final String text; + final int color; + final boolean isToken; + + TextSegment(int startPos, String text, int color, boolean isToken) { + this.startPos = startPos; + this.text = text; + this.color = color; + this.isToken = isToken; + } + } + // ==================== UTILITIES ==================== + + /** + * Check if a global position falls within this line. + */ + public boolean containsPosition(int globalPosition) { + return globalPosition >= globalStart && globalPosition < globalEnd; + } + + /** + * Convert a global position to a column (local offset) within this line. + */ + public int toColumn(int globalPosition) { + return Math.max(0, Math.min(globalPosition - globalStart, text.length())); + } + + /** + * Convert a column (local offset) to a global position. + */ + public int toGlobal(int column) { + return globalStart + Math.max(0, Math.min(column, text.length())); + } + + @Override + public String toString() { + return "ScriptLine{" + lineIndex + ": '" + text + "' [" + globalStart + "-" + globalEnd + "], " + tokens.size() + " tokens}"; + } + + // ==================== MARK CLASS (for token building) ==================== + + /** + * A simple mark representing a highlighted region. + * Used during token building phase. + * Can optionally carry metadata (TypeInfo, FieldInfo, MethodInfo, ImportData). + */ + public static class Mark { + public final int start; + public final int end; + public final TokenType type; + public final Object metadata; + + public Mark(int start, int end, TokenType type) { + this.start = start; + this.end = end; + this.type = type; + this.metadata = null; + } + + public Mark(int start, int end, TokenType type, Object metadata) { + this.start = start; + this.end = end; + this.type = type; + this.metadata = metadata; + } + + @Override + public String toString() { + return "Mark{" + type + " [" + start + "-" + end + "]" + (metadata != null ? " " + metadata.getClass().getSimpleName() : "") + "}"; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java new file mode 100644 index 000000000..7a712ae6c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java @@ -0,0 +1,258 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.script.JavaTextContainer; +import noppes.npcs.constants.ScriptContext; + +import java.util.Collections; +import java.util.Map; + +/** + * New interpreter-based text container that replaces JavaTextContainer. + * + * This class provides the same interface as JavaTextContainer but uses the + * new modular interpreter system internally. It produces compatible LineData + * objects for seamless integration with GuiScriptTextArea. + * + * Key differences from JavaTextContainer: + * - Clean single-pass tokenization with 7 distinct phases + * - Proper token navigation via prev()/next() methods + * - Type-specific metadata on tokens (TypeInfo, FieldInfo, MethodInfo) + * - Better separation of concerns (TypeResolver, ScriptDocument, ScriptLine) + * - Hex color support in addition to Minecraft color codes + */ +public class ScriptTextContainer extends JavaTextContainer { + + /** + * Feature flag to enable/disable the new interpreter system. + * When false, falls back to original JavaTextContainer behavior. + */ + public static boolean USE_NEW_INTERPRETER = true; + + private ScriptDocument document; + + /** The scripting language: "ECMAScript", "Groovy", etc. */ + private String language = "ECMAScript"; + + /** The script context: NPC, PLAYER, BLOCK, ITEM, etc. */ + private ScriptContext scriptContext = ScriptContext.GLOBAL; + + /** Editor-injected globals (name -> type name) */ + private Map editorGlobals = Collections.emptyMap(); + + public ScriptTextContainer(String text) { + super(text); + if (USE_NEW_INTERPRETER) { + document = new ScriptDocument(text); + } + } + + public ScriptTextContainer(String text, String language) { + super(text); + this.language = language != null ? language : "ECMAScript"; + if (USE_NEW_INTERPRETER) { + document = new ScriptDocument(text, this.language); + } + } + + /** + * Set the scripting language. This affects syntax highlighting and type inference. + * @param language The language name (e.g., "ECMAScript", "Groovy") + */ + public void setLanguage(String language) { + this.language = language != null ? language : "ECMAScript"; + if (document != null) { + document.setLanguage(this.language); + } + } + + /** + * Get the current scripting language. + */ + public String getLanguage() { + return language; + } + + /** + * Set the script context (NPC, PLAYER, BLOCK, ITEM, etc.). + * This determines which hooks and event types are available for autocomplete. + * + * @param context The script context + */ + public void setScriptContext(ScriptContext context) { + this.scriptContext = context != null ? context : ScriptContext.GLOBAL; + if (document != null) { + document.setScriptContext(this.scriptContext); + } + } + + /** + * Get the current script context. + * + * @return The script context (NPC, PLAYER, BLOCK, ITEM, etc.) + */ + public ScriptContext getScriptContext() { + return scriptContext; + } + + /** + * Set editor-injected globals (name -> type name). + */ + public void setEditorGlobalsMap(java.util.Map globals) { + this.editorGlobals = globals != null ? globals : java.util.Collections.emptyMap(); + if (document != null) { + document.setEditorGlobals(this.editorGlobals); + } + } + + /** + * Add implicit imports that should be resolved without explicit import statements. + * Used for JaninoScript default imports and hook parameter types. + * + * @param patterns Array of import patterns to add (wildcard packages like "noppes.npcs.api.*" or FQ class names) + */ + public void addImplicitImports(String... patterns) { + if (document != null) { + document.addImplicitImports(patterns); + } + } + + @Override + public void init(int width, int height) { + if (!USE_NEW_INTERPRETER) { + super.init(width, height); + return; + } + + lineHeight = ClientProxy.Font.height(); + if (lineHeight == 0) lineHeight = 12; + + // Initialize the document + document.setText(text); + document.init(width, height); + + // Convert ScriptLines to LineData for compatibility + rebuildLineData(); + + linesCount = lines.size(); + totalHeight = linesCount * lineHeight; + visibleLines = Math.max(height / lineHeight - 1, 1); + } + + /** + * Initialize with explicit text (called when text changes). + */ + @Override + public void init(String text, int width, int height) { + this.text = text == null ? "" : text.replaceAll("\\r?\\n|\\r", "\n"); + + if (!USE_NEW_INTERPRETER) { + super.init(text, width, height); + return; + } + + if (document == null) { + document = new ScriptDocument(this.text, this.language); + document.setScriptContext(this.scriptContext); + document.setEditorGlobals(this.editorGlobals); + } + + init(width, height); + } + + /** + * Convert ScriptDocument lines to the legacy LineData format. + */ + private void rebuildLineData() { + lines.clear(); + for (ScriptLine scriptLine : document.getLines()) { + LineData ld = new LineData( + scriptLine.getText(), + scriptLine.getGlobalStart(), + scriptLine.getGlobalEnd() + ); + + // Copy indent guides + ld.indentCols.addAll(scriptLine.getIndentGuides()); + + // Convert tokens - use fully qualified name to avoid conflict with inherited Token + for (noppes.npcs.client.gui.util.script.interpreter.token.Token interpreterToken : scriptLine.getTokens()) { + ld.tokens.add(new JavaTextContainer.Token( + interpreterToken.getText(), + toLegacyTokenType(interpreterToken.getType()), + interpreterToken.getGlobalStart(), + interpreterToken.getGlobalEnd() + )); + } + + lines.add(ld); + } + } + + /** + * Main formatting entry point - matches JavaTextContainer signature. + */ + @Override + public void formatCodeText() { + if (!USE_NEW_INTERPRETER) { + super.formatCodeText(); + return; + } + + document.formatCodeText(); + rebuildLineData(); + } + + /** + * Convert new interpreter TokenType to legacy JavaTextContainer.TokenType format. + */ + private JavaTextContainer.TokenType toLegacyTokenType( + noppes.npcs.client.gui.util.script.interpreter.token.TokenType type) { + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.COMMENT) return JavaTextContainer.TokenType.COMMENT; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.STRING) return JavaTextContainer.TokenType.STRING; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.KEYWORD) return JavaTextContainer.TokenType.KEYWORD; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.INTERFACE_DECL) return JavaTextContainer.TokenType.INTERFACE_DECL; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.ENUM_DECL) return JavaTextContainer.TokenType.ENUM_DECL; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.CLASS_DECL) return JavaTextContainer.TokenType.CLASS_DECL; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.IMPORTED_CLASS) return JavaTextContainer.TokenType.IMPORTED_CLASS; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.TYPE_DECL) return JavaTextContainer.TokenType.TYPE_DECL; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.METHOD_DECL) return JavaTextContainer.TokenType.METHOD_DECARE; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.METHOD_CALL) return JavaTextContainer.TokenType.METHOD_CALL; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.LITERAL) return JavaTextContainer.TokenType.NUMBER; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.GLOBAL_FIELD) return JavaTextContainer.TokenType.GLOBAL_FIELD; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.LOCAL_FIELD) return JavaTextContainer.TokenType.LOCAL_FIELD; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.PARAMETER) return JavaTextContainer.TokenType.PARAMETER; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.UNDEFINED_VAR) return JavaTextContainer.TokenType.UNDEFINED_VAR; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.VARIABLE) return JavaTextContainer.TokenType.VARIABLE; + return JavaTextContainer.TokenType.DEFAULT; + } + + // ==================== ACCESSORS ==================== + + /** + * Get the underlying ScriptDocument for advanced operations. + */ + public ScriptDocument getDocument() { + return document; + } + + /** + * Get the interpreter Token at a specific global position in the text. + * Returns null if no token is at that position or if the interpreter is disabled. + * + * @param globalPosition Position in the document text + * @return The Token at that position, or null + */ + public noppes.npcs.client.gui.util.script.interpreter.token.Token getInterpreterTokenAt(int globalPosition) { + if (!USE_NEW_INTERPRETER || document == null) { + return null; + } + + ScriptLine line = document.getLineAt(globalPosition); + if (line == null) { + return null; + } + + return line.getTokenAt(globalPosition); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/bridge/DtsJavaBridge.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/bridge/DtsJavaBridge.java new file mode 100644 index 000000000..c18f138b1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/bridge/DtsJavaBridge.java @@ -0,0 +1,307 @@ +package noppes.npcs.client.gui.util.script.interpreter.bridge; + +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSFieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSMethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public final class DtsJavaBridge { + + /** Cache of reflection Method -> matching JS method info (for docs/param names). */ + private static final Map METHOD_CACHE = new ConcurrentHashMap<>(); + /** Cache of reflection Field -> matching JS field info (for docs/typing). */ + private static final Map FIELD_CACHE = new ConcurrentHashMap<>(); + /** Cache of reflection Method -> resolved Java TypeInfo override from .d.ts. */ + private static final Map RETURN_OVERRIDE_CACHE = new ConcurrentHashMap<>(); + /** Negative cache for methods with no usable override. */ + private static final Set RETURN_OVERRIDE_MISSES = ConcurrentHashMap.newKeySet(); + + private DtsJavaBridge() {} + + public static void clearCache() { + METHOD_CACHE.clear(); + FIELD_CACHE.clear(); + RETURN_OVERRIDE_CACHE.clear(); + RETURN_OVERRIDE_MISSES.clear(); + } + + /** + * Resolve a Java return type override for a reflected method using its .d.ts twin. + * + * The override is used only for editor typing (e.g., Janino hover/autocomplete) and + * never changes runtime reflection. This returns a Java-resolved TypeInfo when the + * .d.ts return type can be mapped to a concrete Java class. + */ + public static TypeInfo resolveReturnTypeOverride(Method method, TypeInfo containingType, JSMethodInfo jsMethod) { + if (method == null || jsMethod == null) return null; + + TypeInfo cached = RETURN_OVERRIDE_CACHE.get(method); + if (cached != null) return cached; + if (RETURN_OVERRIDE_MISSES.contains(method)) return null; + + String jsReturnType = jsMethod.getReturnType(); + if (jsReturnType == null || jsReturnType.isEmpty()) { + RETURN_OVERRIDE_MISSES.add(method); + return null; + } + + String normalizedJsReturn = jsReturnType; + if (normalizedJsReturn.contains("|")) { + normalizedJsReturn = normalizedJsReturn.split("\\|")[0].trim(); + } + normalizedJsReturn = normalizedJsReturn.replace("?", "").trim(); + + // Fast-path: skip resolver if the .d.ts return matches reflection (common case). + Class reflectedReturn = method.getReturnType(); + if (reflectedReturn != null) { + if (normalizedJsReturn.equals(reflectedReturn.getName()) + || normalizedJsReturn.equals(reflectedReturn.getSimpleName()) + || normalizedJsReturn.equals("Java." + reflectedReturn.getName())) { + RETURN_OVERRIDE_MISSES.add(method); + return null; + } + + String lower = normalizedJsReturn.toLowerCase(); + if (("void".equals(lower) && (reflectedReturn == void.class || reflectedReturn == Void.class)) + || ("boolean".equals(lower) && (reflectedReturn == boolean.class || reflectedReturn == Boolean.class)) + || ("string".equals(lower) && reflectedReturn == String.class) + || ("number".equals(lower) && (reflectedReturn == double.class || reflectedReturn == Double.class))) { + RETURN_OVERRIDE_MISSES.add(method); + return null; + } + } + + TypeResolver resolver = TypeResolver.getInstance(); + TypeInfo resolved = resolver.resolveJSType(normalizedJsReturn); + TypeInfo javaResolved = null; + + if (resolved != null) { + if (resolved.getJavaClass() != null) { + javaResolved = resolved; + } else if (resolved.isJSType() && resolved.getJSTypeInfo() != null) { + String javaFqn = resolved.getJSTypeInfo().getJavaFqn(); + if (javaFqn != null && !javaFqn.isEmpty()) { + javaResolved = resolver.resolveFullName(javaFqn); + } + } + } + + if (javaResolved == null || javaResolved.getJavaClass() == null) { + RETURN_OVERRIDE_MISSES.add(method); + return null; + } + + RETURN_OVERRIDE_CACHE.put(method, javaResolved); + return javaResolved; + } + + public static JSMethodInfo findMatchingMethod(Method method, TypeInfo containingType) { + JSMethodInfo cached = METHOD_CACHE.get(method); + if (cached != null) return cached; + + JSTypeInfo jsType = findJSTypeInfo(method, containingType); + if (jsType == null) return null; + + List overloads = jsType.getMethodOverloads(method.getName()); + if (overloads.isEmpty()) return null; + + Class[] paramTypes = method.getParameterTypes(); + JSMethodInfo best = null; + int bestScore = -1; + + for (JSMethodInfo candidate : overloads) { + if (candidate.getParameterCount() != paramTypes.length) continue; + int score = scoreOverload(candidate, paramTypes, containingType, method.isVarArgs()); + if (score > bestScore) { + bestScore = score; + best = candidate; + } + } + + if (bestScore >= 0 && best != null) { + METHOD_CACHE.put(method, best); + return best; + } + return null; + } + + public static JSFieldInfo findMatchingField(Field field, TypeInfo containingType) { + JSFieldInfo cached = FIELD_CACHE.get(field); + if (cached != null) return cached; + + JSTypeInfo jsType = findJSTypeInfo(field, containingType); + if (jsType == null) return null; + JSFieldInfo match = jsType.getField(field.getName()); + if (match != null) { + FIELD_CACHE.put(field, match); + } + return match; + } + + private static int scoreOverload(JSMethodInfo method, Class[] paramTypes, TypeInfo containingType, boolean isVarArgs) { + int score = 0; + List jsParams = method.getParameters(); + for (int i = 0; i < paramTypes.length; i++) { + int paramScore = scoreParam(paramTypes[i], jsParams.get(i), containingType, isVarArgs, i == paramTypes.length - 1); + if (paramScore < 0) return -1; + score += paramScore; + } + return score; + } + + private static int scoreParam(Class javaParam, JSMethodInfo.JSParameterInfo jsParam, TypeInfo containingType, boolean isVarArgs, boolean isLastParam) { + if (javaParam == null || jsParam == null) return -1; + + TypeInfo resolved = jsParam.getResolvedType(containingType); + if (resolved != null && resolved.getJavaClass() != null) { + Class jsClass = resolved.getJavaClass(); + if (javaParam.equals(jsClass)) return 4; + if (jsClass.isAssignableFrom(javaParam)) return 3; + if (javaParam.isAssignableFrom(jsClass)) return 2; + } + + String jsTypeName = jsParam.getType(); + if (jsTypeName == null || jsTypeName.isEmpty()) return -1; + + if (isVarArgs && isLastParam && javaParam.isArray()) { + if (matchesArrayElement(javaParam.getComponentType(), jsTypeName, containingType)) { + return 2; + } + } + + if (matchesPrimitive(jsTypeName, javaParam)) { + return 3; + } + + if (javaParam.isArray() && jsTypeName.endsWith("[]")) { + String elementType = jsTypeName.substring(0, jsTypeName.length() - 2); + return matchesArrayElement(javaParam.getComponentType(), elementType, containingType) ? 2 : -1; + } + + JSTypeInfo jsType = resolveJSTypeInfo(jsTypeName); + if (jsType != null && jsType.getJavaFqn() != null) { + String javaFqn = normalizeJavaFqn(jsType.getJavaFqn()); + String paramFqn = normalizeJavaFqn(javaParam.getName()); + if (javaFqn.equals(paramFqn)) return 3; + } + + if (jsTypeName.equals(javaParam.getSimpleName())) return 1; + if (jsTypeName.equals(javaParam.getName())) return 1; + if ("any".equals(jsTypeName)) return 1; + return -1; + } + + private static boolean matchesArrayElement(Class elementClass, String jsElementType, TypeInfo containingType) { + if (elementClass == null) return false; + if (matchesPrimitive(jsElementType, elementClass)) return true; + + JSTypeInfo jsType = resolveJSTypeInfo(jsElementType); + if (jsType != null && jsType.getJavaFqn() != null) { + String javaFqn = normalizeJavaFqn(jsType.getJavaFqn()); + String elementFqn = normalizeJavaFqn(elementClass.getName()); + return javaFqn.equals(elementFqn); + } + + return jsElementType.equals(elementClass.getSimpleName()) || jsElementType.equals(elementClass.getName()); + } + + private static boolean matchesPrimitive(String jsTypeName, Class javaParam) { + switch (jsTypeName.toLowerCase()) { + case "string": + case "char": + return javaParam == String.class || javaParam == char.class || javaParam == Character.class; + case "boolean": + case "bool": + return javaParam == boolean.class || javaParam == Boolean.class; + case "number": + case "byte": + case "short": + case "int": + case "integer": + case "long": + case "float": + case "double": + return isNumberType(javaParam); + case "void": + return javaParam == void.class || javaParam == Void.class; + default: + return false; + } + } + + private static boolean isNumberType(Class type) { + if (type == null) return false; + return type == byte.class || type == short.class || type == int.class || type == long.class + || type == float.class || type == double.class + || Number.class.isAssignableFrom(type); + } + + private static JSTypeInfo findJSTypeInfo(Method method, TypeInfo containingType) { + if (containingType != null && containingType.isJSType()) { + return containingType.getJSTypeInfo(); + } + + Class javaClass = containingType != null ? containingType.getJavaClass() : method.getDeclaringClass(); + return resolveJSTypeInfo(javaClass); + } + + private static JSTypeInfo findJSTypeInfo(Field field, TypeInfo containingType) { + if (containingType != null && containingType.isJSType()) { + return containingType.getJSTypeInfo(); + } + + Class javaClass = containingType != null ? containingType.getJavaClass() : field.getDeclaringClass(); + return resolveJSTypeInfo(javaClass); + } + + private static JSTypeInfo resolveJSTypeInfo(Class javaClass) { + if (javaClass == null) return null; + + JSTypeInfo direct = resolveJSTypeInfo(javaClass.getName()); + if (direct != null) return direct; + + for (Class iface : javaClass.getInterfaces()) { + JSTypeInfo ifaceType = resolveJSTypeInfo(iface.getName()); + if (ifaceType != null) return ifaceType; + } + + Class superClass = javaClass.getSuperclass(); + if (superClass != null && superClass != Object.class) { + return resolveJSTypeInfo(superClass); + } + + return null; + } + + private static JSTypeInfo resolveJSTypeInfo(String javaFqnOrType) { + if (javaFqnOrType == null || javaFqnOrType.isEmpty()) return null; + if (javaFqnOrType.startsWith("Java.")) { + javaFqnOrType = javaFqnOrType.substring(5); + } + JSTypeRegistry registry = TypeResolver.getInstance().getJSTypeRegistry(); + JSTypeInfo direct = registry.getTypeByJavaFqn(javaFqnOrType); + if (direct != null) return direct; + + String normalized = normalizeJavaFqn(javaFqnOrType); + if (!normalized.equals(javaFqnOrType)) { + JSTypeInfo normalizedType = registry.getTypeByJavaFqn(normalized); + if (normalizedType != null) return normalizedType; + } + + return registry.getType(javaFqnOrType); + } + + private static String normalizeJavaFqn(String javaFqn) { + if (javaFqn == null) return null; + return javaFqn.replace('$', '.'); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/CastExpressionResolver.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/CastExpressionResolver.java new file mode 100644 index 000000000..d2b37c64a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/CastExpressionResolver.java @@ -0,0 +1,223 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import java.util.List; +import java.util.function.Function; + +/** + * Helper class for resolving cast expressions and distinguishing them from parenthesized expressions. + * Handles: + * - Simple casts: (Type) expr + * - Nested casts: ((Type) expr) + * - Cast chains: ((Type) expr).method() + * - Parenthesized expressions: (expr) + * + * @Deprecated ExpressionTypeResolver API has all this built in. + */ +@Deprecated +public class CastExpressionResolver { + + /** + * Resolve a cast or parenthesized expression. + * + * @param expr The expression starting with '(' + * @param position The position in the source text + * @param resolveType Function to resolve type names to TypeInfo + * @param resolveExpression Function to resolve arbitrary expressions + * @param parseChain Function to parse expression chain + * @param resolveChainSegment Function to resolve chain segments + * @return The resolved type + */ + public static TypeInfo resolveCastOrParenthesizedExpression( + String expr, + int position, + Function resolveType, + TypeResolver resolveExpression, + ChainParser parseChain, + ChainSegmentResolver resolveChainSegment) { + + if (!expr.startsWith("(")) return null; + + // Find the matching closing parenthesis for the first open paren + int depth = 0; + int closeParen = -1; + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < expr.length(); i++) { + char c = expr.charAt(i); + + // Handle string literals + if ((c == '"' || c == '\'') && (i == 0 || expr.charAt(i - 1) != '\\')) { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + continue; + } + if (inString) continue; + + if (c == '(') { + depth++; + } else if (c == ')') { + depth--; + if (depth == 0) { + closeParen = i; + break; + } + } + } + + if (closeParen < 0) return null; + + // Extract content inside parens + String insideParens = expr.substring(1, closeParen).trim(); + String afterParens = expr.substring(closeParen + 1).trim(); + + // Check if this is a cast expression + // A cast has a type name inside the parens (starts with uppercase or is primitive) + // and is followed by an expression (not an operator or nothing) + if (looksLikeCastType(insideParens) && looksLikeExpressionStart(afterParens)) { + // This is a cast: (Type) rest + TypeInfo castType = resolveType.apply(insideParens); + if (castType != null && castType.isResolved()) { + // If there's more after the cast target, resolve the chain + // E.g., ((EntityPlayer) entity).worldObj + if (!afterParens.isEmpty()) { + // Check if afterParens starts with '.' for a method/field chain + if (afterParens.startsWith(".")) { + // Continue resolving the chain from the cast type + String chainExpr = afterParens.substring(1).trim(); + List segments = parseChain.parse(chainExpr); + TypeInfo currentType = castType; + for (T segment : segments) { + currentType = resolveChainSegment.resolve(currentType, segment); + if (currentType == null) return null; + } + return currentType; + } + } + return castType; + } + } + + // Not a cast - treat as parenthesized expression + // Could be ((expr).method()) or just (expr) + + // First, resolve what's inside the parens + TypeInfo innerType = resolveExpression.resolve(insideParens, position); + + // If there's a chain after the parens, continue resolving + if (innerType != null && !afterParens.isEmpty() && afterParens.startsWith(".")) { + String chainExpr = afterParens.substring(1).trim(); + List segments = parseChain.parse(chainExpr); + TypeInfo currentType = innerType; + for (T segment : segments) { + currentType = resolveChainSegment.resolve(currentType, segment); + if (currentType == null) return null; + } + return currentType; + } + + return innerType; + } + + /** + * Check if a string looks like a valid type name for a cast. + * Valid: EntityPlayer, int, String, java.lang.String, int[] + */ + public static boolean looksLikeCastType(String s) { + if (s == null || s.isEmpty()) return false; + s = s.trim(); + + // Handle array types: Type[] or Type[][] + while (s.endsWith("[]")) { + s = s.substring(0, s.length() - 2).trim(); + } + + if (s.isEmpty()) return false; + + // Primitive types + switch (s) { + case "byte": case "short": case "int": case "long": + case "float": case "double": case "char": case "boolean": + return true; + } + + // Class type: starts with uppercase or is fully qualified + if (Character.isUpperCase(s.charAt(0))) return true; + + // Fully qualified name: contains dots and ends with uppercase segment + if (s.contains(".")) { + String[] parts = s.split("\\."); + String lastPart = parts[parts.length - 1]; + return !lastPart.isEmpty() && Character.isUpperCase(lastPart.charAt(0)); + } + + return false; + } + + /** + * Check if a string looks like the start of an expression (what follows a cast). + * Valid: identifier, (, new, literals, this, etc. + * Invalid: empty, operators like +, -, etc. + */ + public static boolean looksLikeExpressionStart(String s) { + if (s == null || s.isEmpty()) return false; + s = s.trim(); + if (s.isEmpty()) return false; + + char first = s.charAt(0); + + // Parenthesis (nested cast or parenthesized expr) + if (first == '(') return true; + + // Identifier or keyword + if (Character.isJavaIdentifierStart(first)) return true; + + // String or char literal + if (first == '"' || first == '\'') return true; + + // Number literal (could start with digit or dot for .5) + if (Character.isDigit(first)) return true; + if (first == '.' && s.length() > 1 && Character.isDigit(s.charAt(1))) return true; + + // Unary operators followed by expression + if (first == '!' || first == '~') return true; + if ((first == '+' || first == '-') && s.length() > 1) { + // Could be unary +/- or ++/-- + char second = s.charAt(1); + if (second == first || Character.isDigit(second) || Character.isJavaIdentifierStart(second) || second == '(') { + return true; + } + } + + return false; + } + + /** + * Functional interface for resolving type expressions. + */ + @FunctionalInterface + public interface TypeResolver { + TypeInfo resolve(String expr, int position); + } + + /** + * Functional interface for parsing expression chains. + */ + @FunctionalInterface + public interface ChainParser { + List parse(String expr); + } + + /** + * Functional interface for resolving chain segments. + */ + @FunctionalInterface + public interface ChainSegmentResolver { + TypeInfo resolve(TypeInfo currentType, T segment); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionNode.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionNode.java new file mode 100644 index 000000000..93e85156f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionNode.java @@ -0,0 +1,403 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +import noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public abstract class ExpressionNode { + protected final int start; + protected final int end; + + protected ExpressionNode(int start, int end) { + this.start = start; + this.end = end; + } + + public int getStart() { return start; } + public int getEnd() { return end; } + public abstract TypeInfo resolveType(TypeResolverContext resolver); + + public static class IntLiteralNode extends ExpressionNode { + private final String value; + public IntLiteralNode(String value, int start, int end) { super(start, end); this.value = value; } + public String getValue() { return value; } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("int"); } + } + + public static class LongLiteralNode extends ExpressionNode { + public LongLiteralNode(String value, int start, int end) { super(start, end); } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("long"); } + } + + public static class FloatLiteralNode extends ExpressionNode { + public FloatLiteralNode(String value, int start, int end) { super(start, end); } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("float"); } + } + + public static class DoubleLiteralNode extends ExpressionNode { + public DoubleLiteralNode(String value, int start, int end) { super(start, end); } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("double"); } + } + + public static class BooleanLiteralNode extends ExpressionNode { + public BooleanLiteralNode(boolean value, int start, int end) { super(start, end); } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("boolean"); } + } + + public static class CharLiteralNode extends ExpressionNode { + public CharLiteralNode(String value, int start, int end) { super(start, end); } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("char"); } + } + + public static class StringLiteralNode extends ExpressionNode { + private final String value; + public StringLiteralNode(String value, int start, int end) { super(start, end); this.value = value; } + public String getValue() { return value; } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.string(); } + } + + public static class NullLiteralNode extends ExpressionNode { + public NullLiteralNode(int start, int end) { super(start, end); } + public TypeInfo resolveType(TypeResolverContext resolver) { + return TypeInfo.unresolved("null", ""); + } + } + + public static class IdentifierNode extends ExpressionNode { + private final String name; + public IdentifierNode(String name, int start, int end) { super(start, end); this.name = name; } + public String getName() { return name; } + public TypeInfo resolveType(TypeResolverContext resolver) { return resolver.resolveIdentifier(name); } + } + + public static class MemberAccessNode extends ExpressionNode { + private final ExpressionNode target; + private final String memberName; + public MemberAccessNode(ExpressionNode target, String memberName, int start, int end) { + super(start, end); this.target = target; this.memberName = memberName; + } + public ExpressionNode getTarget() { return target; } + public String getMemberName() { return memberName; } + public TypeInfo resolveType(TypeResolverContext resolver) { + TypeInfo targetType = target.resolveType(resolver); + if (targetType == null || !targetType.isResolved()) return null; + return resolver.resolveMemberAccess(targetType, memberName); + } + } + + public static class MethodCallNode extends ExpressionNode { + private final ExpressionNode target; + private final String methodName; + private final List arguments; + public MethodCallNode(ExpressionNode target, String methodName, List arguments, int start, int end) { + super(start, end); this.target = target; this.methodName = methodName; + this.arguments = arguments != null ? new ArrayList<>(arguments) : new ArrayList<>(); + } + public ExpressionNode getTarget() { return target; } + public String getMethodName() { return methodName; } + public List getArguments() { return Collections.unmodifiableList(arguments); } + public TypeInfo resolveType(TypeResolverContext resolver) { + TypeInfo targetType = target != null ? target.resolveType(resolver) : null; + TypeInfo[] argTypes = new TypeInfo[arguments.size()]; + for (int i = 0; i < arguments.size(); i++) argTypes[i] = arguments.get(i).resolveType(resolver); + return resolver.resolveMethodCall(targetType, methodName, argTypes); + } + } + + public static class ArrayAccessNode extends ExpressionNode { + private final ExpressionNode array; + private final ExpressionNode index; + public ArrayAccessNode(ExpressionNode array, ExpressionNode index, int start, int end) { + super(start, end); this.array = array; this.index = index; + } + public ExpressionNode getArray() { return array; } + public ExpressionNode getIndex() { return index; } + public TypeInfo resolveType(TypeResolverContext resolver) { + TypeInfo arrayType = array.resolveType(resolver); + if (arrayType == null || !arrayType.isResolved()) return null; + return resolver.resolveArrayAccess(arrayType); + } + } + + public static class NewNode extends ExpressionNode { + private final String typeName; + private final List arguments; + public NewNode(String typeName, List arguments, int start, int end) { + super(start, end); this.typeName = typeName; + this.arguments = arguments != null ? new ArrayList<>(arguments) : new ArrayList<>(); + } + public String getTypeName() { return typeName; } + public List getArguments() { return Collections.unmodifiableList(arguments); } + public TypeInfo resolveType(TypeResolverContext resolver) { return resolver.resolveTypeName(typeName); } + } + + public static class BinaryOpNode extends ExpressionNode { + private final ExpressionNode left; + private final OperatorType operator; + private final ExpressionNode right; + public BinaryOpNode(ExpressionNode left, OperatorType operator, ExpressionNode right, int start, int end) { + super(start, end); this.left = left; this.operator = operator; this.right = right; + } + public ExpressionNode getLeft() { return left; } + public OperatorType getOperator() { return operator; } + public ExpressionNode getRight() { return right; } + public TypeInfo resolveType(TypeResolverContext resolver) { + TypeInfo leftType = left.resolveType(resolver); + TypeInfo rightType = right.resolveType(resolver); + return TypeRules.resolveBinaryOperatorType(operator, leftType, rightType); + } + } + + public static class UnaryOpNode extends ExpressionNode { + private final OperatorType operator; + private final ExpressionNode operand; + private final boolean prefix; + public UnaryOpNode(OperatorType operator, ExpressionNode operand, boolean prefix, int start, int end) { + super(start, end); this.operator = operator; this.operand = operand; this.prefix = prefix; + } + public OperatorType getOperator() { return operator; } + public ExpressionNode getOperand() { return operand; } + public boolean isPrefix() { return prefix; } + public TypeInfo resolveType(TypeResolverContext resolver) { + TypeInfo operandType = operand.resolveType(resolver); + return TypeRules.resolveUnaryOperatorType(operator, operandType); + } + } + + public static class TernaryNode extends ExpressionNode { + private final ExpressionNode condition; + private final ExpressionNode thenExpr; + private final ExpressionNode elseExpr; + public TernaryNode(ExpressionNode condition, ExpressionNode thenExpr, ExpressionNode elseExpr, int start, int end) { + super(start, end); this.condition = condition; this.thenExpr = thenExpr; this.elseExpr = elseExpr; + } + public ExpressionNode getCondition() { return condition; } + public ExpressionNode getThenExpr() { return thenExpr; } + public ExpressionNode getElseExpr() { return elseExpr; } + public TypeInfo resolveType(TypeResolverContext resolver) { + TypeInfo thenType = thenExpr.resolveType(resolver); + TypeInfo elseType = elseExpr.resolveType(resolver); + return TypeRules.resolveTernaryType(thenType, elseType); + } + } + + public static class InstanceofNode extends ExpressionNode { + private final ExpressionNode expression; + private final String typeName; + public InstanceofNode(ExpressionNode expression, String typeName, int start, int end) { + super(start, end); this.expression = expression; this.typeName = typeName; + } + public ExpressionNode getExpression() { return expression; } + public String getTypeName() { return typeName; } + public TypeInfo resolveType(TypeResolverContext resolver) { return TypeInfo.fromPrimitive("boolean"); } + } + + public static class CastNode extends ExpressionNode { + private final String typeName; + private final ExpressionNode expression; + public CastNode(String typeName, ExpressionNode expression, int start, int end) { + super(start, end); this.typeName = typeName; this.expression = expression; + } + public String getTypeName() { return typeName; } + public ExpressionNode getExpression() { return expression; } + public TypeInfo resolveType(TypeResolverContext resolver) { return resolver.resolveTypeName(typeName); } + } + + public static class AssignmentNode extends ExpressionNode { + private final ExpressionNode target; + private final OperatorType operator; + private final ExpressionNode value; + public AssignmentNode(ExpressionNode target, OperatorType operator, ExpressionNode value, int start, int end) { + super(start, end); this.target = target; this.operator = operator; this.value = value; + } + public ExpressionNode getTarget() { return target; } + public OperatorType getOperator() { return operator; } + public ExpressionNode getValue() { return value; } + public TypeInfo resolveType(TypeResolverContext resolver) { return target.resolveType(resolver); } + } + + public static class ParenthesizedNode extends ExpressionNode { + private final ExpressionNode inner; + public ParenthesizedNode(ExpressionNode inner, int start, int end) { super(start, end); this.inner = inner; } + public ExpressionNode getInner() { return inner; } + public TypeInfo resolveType(TypeResolverContext resolver) { return inner.resolveType(resolver); } + } + + public static class LambdaNode extends ExpressionNode { + private final List parameterNames; + private final ExpressionNode body; + private final boolean isBlock; + private noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope scopeRef; + + public LambdaNode(List parameterNames, ExpressionNode body, boolean isBlock, int start, int end) { + super(start, end); + this.parameterNames = parameterNames != null ? new ArrayList<>(parameterNames) : new ArrayList<>(); + this.body = body; + this.isBlock = isBlock; + this.scopeRef = null; + } + + public List getParameterNames() { return Collections.unmodifiableList(parameterNames); } + public ExpressionNode getBody() { return body; } + public boolean isBlock() { return isBlock; } + public noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope getScopeRef() { return scopeRef; } + public void setScopeRef(noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope scope) { + this.scopeRef = scope; + } + + @Override + public TypeInfo resolveType(TypeResolverContext resolver) { + // Lambda type is determined by the expected functional interface type + // See ExpressionTypeResolver.resolveLambdaType() + return TypeInfo.fromClass(Object.class); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (parameterNames.size() == 1 && !isBlock) { + sb.append(parameterNames.get(0)); + } else { + sb.append("("); + sb.append(String.join(", ", parameterNames)); + sb.append(")"); + } + sb.append(" -> "); + if (isBlock) { + sb.append("{ ... }"); + } else { + sb.append(body); + } + return sb.toString(); + } + } + + public static class JSFunctionNode extends ExpressionNode { + private final String name; // Optional name for named function expressions + private final List parameterNames; + private final String bodyText; // Raw body text (for block functions) + private noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope scopeRef; + + public JSFunctionNode(String name, List parameterNames, String bodyText, int start, int end) { + super(start, end); + this.name = name; + this.parameterNames = parameterNames != null ? new ArrayList<>(parameterNames) : new ArrayList<>(); + this.bodyText = bodyText; + this.scopeRef = null; + } + + public String getName() { return name; } + public List getParameterNames() { return Collections.unmodifiableList(parameterNames); } + public String getBodyText() { return bodyText; } + public noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope getScopeRef() { return scopeRef; } + public void setScopeRef(noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope scope) { + this.scopeRef = scope; + } + + @Override + public TypeInfo resolveType(TypeResolverContext resolver) { + // JS function type is determined by the expected functional interface type + // See ExpressionTypeResolver.resolveJSFunctionType() + return TypeInfo.fromClass(Object.class); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("function"); + if (name != null && !name.isEmpty()) { + sb.append(" ").append(name); + } + sb.append("("); + sb.append(String.join(", ", parameterNames)); + sb.append(") { "); + if (bodyText.length() > 30) { + sb.append(bodyText.substring(0, 30)).append("..."); + } else { + sb.append(bodyText); + } + sb.append(" }"); + return sb.toString(); + } + } + + public static class JSArrowNode extends ExpressionNode { + private final List parameterNames; + private final ExpressionNode body; + private final boolean isBlock; + private InnerCallableScope scopeRef; + + public JSArrowNode(List parameterNames, ExpressionNode body, boolean isBlock, int start, int end) { + super(start, end); + this.parameterNames = parameterNames != null ? new ArrayList<>(parameterNames) : new ArrayList<>(); + this.body = body; + this.isBlock = isBlock; + } + + public List getParameterNames() { return Collections.unmodifiableList(parameterNames); } + public ExpressionNode getBody() { return body; } + public boolean isBlock() { return isBlock; } + public InnerCallableScope getScopeRef() { return scopeRef; } + public void setScopeRef(InnerCallableScope scope) { + this.scopeRef = scope; + } + + @Override + public TypeInfo resolveType(TypeResolverContext resolver) { + return TypeInfo.fromClass(Object.class); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("("); + sb.append(String.join(", ", parameterNames)); + sb.append(") => "); + if (isBlock) { + sb.append("{ ... }"); + } else if (body != null) { + sb.append(body); + } + return sb.toString(); + } + } + + public static class MethodReferenceNode extends ExpressionNode { + private final ExpressionNode target; // Object or class name + private final String methodName; + private final boolean isStatic; // Whether it's Class::method vs obj::method + + public MethodReferenceNode(ExpressionNode target, String methodName, boolean isStatic, int start, int end) { + super(start, end); + this.target = target; + this.methodName = methodName; + this.isStatic = isStatic; + } + + public ExpressionNode getTarget() { return target; } + public String getMethodName() { return methodName; } + public boolean isStatic() { return isStatic; } + + @Override + public TypeInfo resolveType(TypeResolverContext resolver) { + // Method reference type is determined by the expected functional interface type + // See ExpressionTypeResolver.resolveMethodReferenceType() + return TypeInfo.fromClass(Object.class); + } + + @Override + public String toString() { + return target + "::" + methodName; + } + } + + public interface TypeResolverContext { + TypeInfo resolveIdentifier(String name); + TypeInfo resolveMemberAccess(TypeInfo targetType, String memberName); + TypeInfo resolveMethodCall(TypeInfo targetType, String methodName, TypeInfo[] argTypes); + TypeInfo resolveArrayAccess(TypeInfo arrayType); + TypeInfo resolveTypeName(String typeName); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionParser.java new file mode 100644 index 000000000..204fe80c2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionParser.java @@ -0,0 +1,559 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +import java.util.ArrayList; +import java.util.List; + +public class ExpressionParser { + private final List tokens; + private int pos; + + public ExpressionParser(List tokens) { + this.tokens = tokens; + this.pos = 0; + } + + public ExpressionNode parse() { + if (tokens.isEmpty()) return null; + return parseLambdaOrExpression(); + } + + private ExpressionNode parseLambdaOrExpression() { + // Check if this is a lambda: (params) -> or param -> + // Look ahead to see if there's a -> after the next identifier/parens + + int checkpoint = pos; + List paramNames = null; + int lambdaStart = current().getStart(); + boolean isJSArrow = false; + + // Try to parse parameter list + if (check(ExpressionToken.TokenKind.IDENTIFIER)) { + // Single param without parens + String paramName = current().getText(); + advance(); + if (check(ExpressionToken.TokenKind.LAMBDA_ARROW)) { + paramNames = new ArrayList<>(); + paramNames.add(paramName); + } else if (check(ExpressionToken.TokenKind.JS_ARROW)) { + paramNames = new ArrayList<>(); + paramNames.add(paramName); + isJSArrow = true; + } else { + // Not a lambda, rewind + pos = checkpoint; + } + } else if (check(ExpressionToken.TokenKind.LEFT_PAREN)) { + // Parenthesized params: (a, b) or () + advance(); // consume '(' + paramNames = new ArrayList<>(); + + if (!check(ExpressionToken.TokenKind.RIGHT_PAREN)) { + // Parse param list + while (true) { + if (!check(ExpressionToken.TokenKind.IDENTIFIER)) { + // Not a valid lambda param list, rewind + pos = checkpoint; + paramNames = null; + break; + } + paramNames.add(current().getText()); + advance(); + + if (check(ExpressionToken.TokenKind.COMMA)) { + advance(); + } else if (check(ExpressionToken.TokenKind.RIGHT_PAREN)) { + break; + } else { + // Invalid syntax, rewind + pos = checkpoint; + paramNames = null; + break; + } + } + } + + if (paramNames != null) { + if (check(ExpressionToken.TokenKind.RIGHT_PAREN)) { + advance(); // consume ')' + if (check(ExpressionToken.TokenKind.LAMBDA_ARROW)) { + // Valid lambda! + } else if (check(ExpressionToken.TokenKind.JS_ARROW)) { + isJSArrow = true; + } else { + // Not a lambda, rewind + pos = checkpoint; + paramNames = null; + } + } else { + // No closing paren, rewind + pos = checkpoint; + paramNames = null; + } + } + } + + if (paramNames != null) { + // This is a lambda! Parse it + advance(); // consume '->' or '=>' + + // Parse body + ExpressionNode body; + boolean isBlock = false; + int bodyEnd; + + if (check(ExpressionToken.TokenKind.LEFT_BRACE)) { + // Block lambda: { ... } + isBlock = true; + int braceStart = current().getStart(); + advance(); // consume '{' + // Skip to matching '}' + int depth = 1; + while (depth > 0 && pos < tokens.size() && !check(ExpressionToken.TokenKind.EOF)) { + if (check(ExpressionToken.TokenKind.LEFT_BRACE)) depth++; + else if (check(ExpressionToken.TokenKind.RIGHT_BRACE)) depth--; + if (depth > 0) advance(); + } + bodyEnd = current().getEnd(); + if (check(ExpressionToken.TokenKind.RIGHT_BRACE)) { + advance(); // consume '}' + } + body = new ExpressionNode.StringLiteralNode("", braceStart, bodyEnd); // Placeholder + } else { + // Expression lambda + body = parseExpressionInternal(0); + if (body == null) { + // Failed to parse body, return error recovery + return null; + } + bodyEnd = body.getEnd(); + } + + // Create lambda node (scopeRef will be set during type resolution) + if (isJSArrow) + return new ExpressionNode.JSArrowNode(paramNames, body, isBlock, lambdaStart, bodyEnd); + return new ExpressionNode.LambdaNode(paramNames, body, isBlock, lambdaStart, bodyEnd); + } + + // Not a lambda, parse as regular expression + return parseExpressionInternal(0); + } + + private ExpressionToken current() { + if (pos >= tokens.size()) return tokens.get(tokens.size() - 1); + return tokens.get(pos); + } + + private ExpressionToken advance() { + ExpressionToken tok = current(); + if (pos < tokens.size()) pos++; + return tok; + } + + private boolean check(ExpressionToken.TokenKind kind) { return current().getKind() == kind; } + + private boolean match(ExpressionToken.TokenKind kind) { + if (check(kind)) { advance(); return true; } + return false; + } + + private ExpressionNode parseExpression(int minPrecedence) { + // For top-level expressions (minPrecedence = 0), check for lambda first + if (minPrecedence == 0) { + return parseLambdaOrExpression(); + } + + return parseExpressionInternal(minPrecedence); + } + + private ExpressionNode parseExpressionInternal(int minPrecedence) { + ExpressionNode left = parsePrefixExpression(); + if (left == null) return null; + + while (true) { + if (check(ExpressionToken.TokenKind.QUESTION) && minPrecedence <= 2) { + left = parseTernary(left); + continue; + } + + OperatorType op = getCurrentBinaryOperator(); + if (op == null) break; + + int precedence = op.getPrecedence(); + if (precedence < minPrecedence) break; + + advance(); + + int nextMinPrecedence = (op.getAssociativity() == OperatorType.Associativity.LEFT) + ? precedence + 1 : precedence; + + ExpressionNode right = parseExpression(nextMinPrecedence); + if (right == null) break; + + if (op == OperatorType.INSTANCEOF) { + String typeName = extractTypeName(right); + left = new ExpressionNode.InstanceofNode(left, typeName, left.getStart(), right.getEnd()); + } else if (op.isAssignment()) { + left = new ExpressionNode.AssignmentNode(left, op, right, left.getStart(), right.getEnd()); + } else { + left = new ExpressionNode.BinaryOpNode(left, op, right, left.getStart(), right.getEnd()); + } + } + + return parsePostfixExpression(left); + } + + private String extractTypeName(ExpressionNode node) { + if (node instanceof ExpressionNode.IdentifierNode) { + return ((ExpressionNode.IdentifierNode) node).getName(); + } + if (node instanceof ExpressionNode.MemberAccessNode) { + ExpressionNode.MemberAccessNode ma = (ExpressionNode.MemberAccessNode) node; + return extractTypeName(ma.getTarget()) + "." + ma.getMemberName(); + } + return "Object"; + } + + private ExpressionNode parseTernary(ExpressionNode condition) { + int start = condition.getStart(); + advance(); + ExpressionNode thenExpr = parseExpression(0); + if (thenExpr == null) return condition; + if (!match(ExpressionToken.TokenKind.COLON)) return condition; + ExpressionNode elseExpr = parseExpression(2); + if (elseExpr == null) return condition; + return new ExpressionNode.TernaryNode(condition, thenExpr, elseExpr, start, elseExpr.getEnd()); + } + + private OperatorType getCurrentBinaryOperator() { + ExpressionToken tok = current(); + if (tok.getKind() == ExpressionToken.TokenKind.OPERATOR) { + OperatorType op = tok.getOperatorType(); + if (op != null && (op.isBinary() || op.isAssignment())) return op; + } + if (tok.getKind() == ExpressionToken.TokenKind.INSTANCEOF) return OperatorType.INSTANCEOF; + return null; + } + + private ExpressionNode parsePrefixExpression() { + ExpressionToken tok = current(); + int start = tok.getStart(); + + // Check for function expression (JS only) + if (tok.getKind() == ExpressionToken.TokenKind.FUNCTION) { + return parseFunctionExpression(); + } + + if (tok.getKind() == ExpressionToken.TokenKind.OPERATOR) { + OperatorType op = tok.getOperatorType(); + if (op != null && isUnaryOperator(op)) { + advance(); + ExpressionNode operand = parsePrefixExpression(); + if (operand == null) return null; + OperatorType unaryOp = toUnaryOperator(op); + return new ExpressionNode.UnaryOpNode(unaryOp, operand, true, start, operand.getEnd()); + } + } + + if (tok.getKind() == ExpressionToken.TokenKind.LEFT_PAREN) { + return parseCastOrParenthesized(); + } + + return parsePrimaryExpression(); + } + + private ExpressionNode parseFunctionExpression() { + int start = current().getStart(); + advance(); // consume 'function' + + // Optional function name + String functionName = null; + if (check(ExpressionToken.TokenKind.IDENTIFIER)) { + functionName = current().getText(); + advance(); + } + + // Expect '(' + if (!check(ExpressionToken.TokenKind.LEFT_PAREN)) { + return null; // Invalid syntax + } + advance(); // consume '(' + + // Parse parameters + List params = new ArrayList<>(); + while (!check(ExpressionToken.TokenKind.RIGHT_PAREN) && !check(ExpressionToken.TokenKind.EOF)) { + if (!check(ExpressionToken.TokenKind.IDENTIFIER)) { + return null; // Invalid parameter + } + params.add(current().getText()); + advance(); + + if (check(ExpressionToken.TokenKind.COMMA)) { + advance(); + } else if (!check(ExpressionToken.TokenKind.RIGHT_PAREN)) { + return null; // Expected comma or closing paren + } + } + + if (!check(ExpressionToken.TokenKind.RIGHT_PAREN)) { + return null; // Expected closing paren + } + advance(); // consume ')' + + // Expect '{' + if (!check(ExpressionToken.TokenKind.LEFT_BRACE)) { + return null; // Invalid syntax + } + advance(); // consume '{' + + // Collect body tokens until matching '}' + StringBuilder bodyBuilder = new StringBuilder(); + int depth = 1; + while (depth > 0 && !check(ExpressionToken.TokenKind.EOF)) { + ExpressionToken bodyToken = current(); + if (bodyToken.getKind() == ExpressionToken.TokenKind.LEFT_BRACE) { + depth++; + } else if (bodyToken.getKind() == ExpressionToken.TokenKind.RIGHT_BRACE) { + depth--; + if (depth == 0) { + break; + } + } + bodyBuilder.append(bodyToken.getText()).append(" "); + advance(); + } + + String bodyText = bodyBuilder.toString().trim(); + int end = current().getEnd(); + + if (!check(ExpressionToken.TokenKind.RIGHT_BRACE)) { + return null; // Expected closing brace + } + advance(); // consume final '}' + + // Find the corresponding InnerCallableScope from ScriptDocument + // This will be set during type resolution when we have access to ScriptDocument + return new ExpressionNode.JSFunctionNode(functionName, params, bodyText, start, end); + } + + private boolean isUnaryOperator(OperatorType op) { + switch (op) { + case ADD: case SUBTRACT: case LOGICAL_NOT: case BITWISE_NOT: + case PRE_INCREMENT: case PRE_DECREMENT: return true; + default: return false; + } + } + + private OperatorType toUnaryOperator(OperatorType op) { + switch (op) { + case ADD: return OperatorType.UNARY_PLUS; + case SUBTRACT: return OperatorType.UNARY_MINUS; + default: return op; + } + } + + private ExpressionNode parseCastOrParenthesized() { + int start = current().getStart(); + advance(); + + if (check(ExpressionToken.TokenKind.IDENTIFIER)) { + String possibleType = current().getText(); + int savedPos = pos; + advance(); + + while (check(ExpressionToken.TokenKind.DOT)) { + advance(); + if (check(ExpressionToken.TokenKind.IDENTIFIER)) { + possibleType += "." + current().getText(); + advance(); + } + } + + while (check(ExpressionToken.TokenKind.LEFT_BRACKET)) { + advance(); + if (!match(ExpressionToken.TokenKind.RIGHT_BRACKET)) { pos = savedPos; break; } + possibleType += "[]"; + } + + if (check(ExpressionToken.TokenKind.RIGHT_PAREN)) { + advance(); + if (canStartExpression()) { + ExpressionNode expr = parsePrefixExpression(); + if (expr != null) { + return new ExpressionNode.CastNode(possibleType, expr, start, expr.getEnd()); + } + } + } + pos = savedPos; + } + + ExpressionNode inner = parseExpression(0); + if (inner != null && match(ExpressionToken.TokenKind.RIGHT_PAREN)) { + ExpressionNode paren = new ExpressionNode.ParenthesizedNode(inner, start, current().getStart()); + return parseAccessChain(paren); + } + return inner; + } + + private boolean canStartExpression() { + ExpressionToken.TokenKind kind = current().getKind(); + switch (kind) { + case IDENTIFIER: case INT_LITERAL: case LONG_LITERAL: case FLOAT_LITERAL: + case DOUBLE_LITERAL: case BOOLEAN_LITERAL: case CHAR_LITERAL: case STRING_LITERAL: + case NULL_LITERAL: case NEW: case LEFT_PAREN: case OPERATOR: return true; + default: return false; + } + } + + private ExpressionNode parsePrimaryExpression() { + ExpressionToken tok = current(); + int start = tok.getStart(); + + switch (tok.getKind()) { + case INT_LITERAL: advance(); return new ExpressionNode.IntLiteralNode(tok.getText(), start, tok.getEnd()); + case LONG_LITERAL: advance(); return new ExpressionNode.LongLiteralNode(tok.getText(), start, tok.getEnd()); + case FLOAT_LITERAL: advance(); return new ExpressionNode.FloatLiteralNode(tok.getText(), start, tok.getEnd()); + case DOUBLE_LITERAL: advance(); return new ExpressionNode.DoubleLiteralNode(tok.getText(), start, tok.getEnd()); + case BOOLEAN_LITERAL: advance(); return new ExpressionNode.BooleanLiteralNode("true".equals(tok.getText()), start, tok.getEnd()); + case CHAR_LITERAL: advance(); return new ExpressionNode.CharLiteralNode(tok.getText(), start, tok.getEnd()); + case STRING_LITERAL: advance(); return new ExpressionNode.StringLiteralNode(tok.getText(), start, tok.getEnd()); + case NULL_LITERAL: advance(); return new ExpressionNode.NullLiteralNode(start, tok.getEnd()); + case NEW: return parseNewExpression(); + case IDENTIFIER: return parseIdentifierOrMethodCall(); + case LEFT_PAREN: return parseCastOrParenthesized(); + default: return null; + } + } + + private ExpressionNode parseNewExpression() { + int start = current().getStart(); + advance(); + if (!check(ExpressionToken.TokenKind.IDENTIFIER)) return null; + + StringBuilder typeName = new StringBuilder(current().getText()); + advance(); + + while (check(ExpressionToken.TokenKind.DOT)) { + advance(); + if (check(ExpressionToken.TokenKind.IDENTIFIER)) { + typeName.append(".").append(current().getText()); + advance(); + } + } + + List args = new ArrayList<>(); + if (match(ExpressionToken.TokenKind.LEFT_PAREN)) { + args = parseArgumentList(); + match(ExpressionToken.TokenKind.RIGHT_PAREN); + } + + return new ExpressionNode.NewNode(typeName.toString(), args, start, current().getStart()); + } + + private ExpressionNode parseIdentifierOrMethodCall() { + int start = current().getStart(); + String name = current().getText(); + advance(); + + ExpressionNode result = new ExpressionNode.IdentifierNode(name, start, current().getStart()); + return parseAccessChain(result); + } + + private ExpressionNode parseAccessChain(ExpressionNode base) { + while (true) { + if (check(ExpressionToken.TokenKind.METHOD_REFERENCE)) { + advance(); // consume '::' + + if (!check(ExpressionToken.TokenKind.IDENTIFIER)) { + // Invalid syntax, return what we have + break; + } + + String methodName = current().getText(); + int end = current().getEnd(); + advance(); + + // isStatic is determined during type resolution, not parsing + // We pass false as a placeholder - ExpressionTypeResolver will compute + // the real value based on whether target resolves to a ClassTypeInfo + base = new ExpressionNode.MethodReferenceNode(base, methodName, false, base.getStart(), end); + // Method references don't chain further (can't do obj::method.something) + break; + } else if (check(ExpressionToken.TokenKind.LEFT_PAREN)) { + advance(); + List args = parseArgumentList(); + int end = current().getStart(); + match(ExpressionToken.TokenKind.RIGHT_PAREN); + + String methodName; + ExpressionNode target; + + if (base instanceof ExpressionNode.IdentifierNode) { + methodName = ((ExpressionNode.IdentifierNode) base).getName(); + target = null; + } else if (base instanceof ExpressionNode.MemberAccessNode) { + ExpressionNode.MemberAccessNode ma = (ExpressionNode.MemberAccessNode) base; + methodName = ma.getMemberName(); + target = ma.getTarget(); + } else { + methodName = "apply"; + target = base; + } + + base = new ExpressionNode.MethodCallNode(target, methodName, args, base.getStart(), end); + } else if (check(ExpressionToken.TokenKind.DOT)) { + advance(); + if (!check(ExpressionToken.TokenKind.IDENTIFIER)) break; + String memberName = current().getText(); + int end = current().getEnd(); + advance(); + base = new ExpressionNode.MemberAccessNode(base, memberName, base.getStart(), end); + } else if (check(ExpressionToken.TokenKind.LEFT_BRACKET)) { + advance(); + ExpressionNode index = parseExpression(0); + int end = current().getStart(); + match(ExpressionToken.TokenKind.RIGHT_BRACKET); + if (index != null) { + base = new ExpressionNode.ArrayAccessNode(base, index, base.getStart(), end); + } + } else { + break; + } + } + return base; + } + + private List parseArgumentList() { + List args = new ArrayList<>(); + if (check(ExpressionToken.TokenKind.RIGHT_PAREN)) return args; + + ExpressionNode first = parseExpression(0); + if (first != null) args.add(first); + + while (match(ExpressionToken.TokenKind.COMMA)) { + ExpressionNode arg = parseExpression(0); + if (arg != null) args.add(arg); + } + return args; + } + + private ExpressionNode parsePostfixExpression(ExpressionNode expr) { + if (expr == null) return null; + + while (true) { + ExpressionToken tok = current(); + if (tok.getKind() != ExpressionToken.TokenKind.OPERATOR) break; + + OperatorType op = tok.getOperatorType(); + if (op == OperatorType.PRE_INCREMENT) { + advance(); + expr = new ExpressionNode.UnaryOpNode(OperatorType.POST_INCREMENT, expr, false, expr.getStart(), tok.getEnd()); + } else if (op == OperatorType.PRE_DECREMENT) { + advance(); + expr = new ExpressionNode.UnaryOpNode(OperatorType.POST_DECREMENT, expr, false, expr.getStart(), tok.getEnd()); + } else { + break; + } + } + return expr; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionToken.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionToken.java new file mode 100644 index 000000000..2d482ed2a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionToken.java @@ -0,0 +1,65 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +public class ExpressionToken { + + public enum TokenKind { + INT_LITERAL, LONG_LITERAL, FLOAT_LITERAL, DOUBLE_LITERAL, + BOOLEAN_LITERAL, CHAR_LITERAL, STRING_LITERAL, NULL_LITERAL, + IDENTIFIER, NEW, INSTANCEOF, FUNCTION, + OPERATOR, + LEFT_PAREN, RIGHT_PAREN, LEFT_BRACKET, RIGHT_BRACKET, + LEFT_BRACE, RIGHT_BRACE, + DOT, COMMA, QUESTION, COLON, SEMICOLON, + LAMBDA_ARROW, JS_ARROW, METHOD_REFERENCE, + EOF + } + + private final TokenKind kind; + private final String text; + private final int start; + private final int end; + private final OperatorType operatorType; + + public ExpressionToken(TokenKind kind, String text, int start, int end) { + this(kind, text, start, end, null); + } + + public ExpressionToken(TokenKind kind, String text, int start, int end, OperatorType operatorType) { + this.kind = kind; + this.text = text; + this.start = start; + this.end = end; + this.operatorType = operatorType; + } + + public TokenKind getKind() { return kind; } + public String getText() { return text; } + public int getStart() { return start; } + public int getEnd() { return end; } + public OperatorType getOperatorType() { return operatorType; } + + public static ExpressionToken operator(String symbol, int start, int end) { + OperatorType op = OperatorType.fromBinarySymbol(symbol); + if (op == null) op = OperatorType.fromSymbol(symbol); + return new ExpressionToken(TokenKind.OPERATOR, symbol, start, end, op); + } + + public static ExpressionToken identifier(String name, int start, int end) { + if ("true".equals(name) || "false".equals(name)) { + return new ExpressionToken(TokenKind.BOOLEAN_LITERAL, name, start, end); + } + if ("null".equals(name)) { + return new ExpressionToken(TokenKind.NULL_LITERAL, name, start, end); + } + if ("new".equals(name)) { + return new ExpressionToken(TokenKind.NEW, name, start, end); + } + if ("instanceof".equals(name)) { + return new ExpressionToken(TokenKind.INSTANCEOF, name, start, end); + } + if ("function".equals(name)) { + return new ExpressionToken(TokenKind.FUNCTION, name, start, end); + } + return new ExpressionToken(TokenKind.IDENTIFIER, name, start, end); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionTokenizer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionTokenizer.java new file mode 100644 index 000000000..5c0aa8d62 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionTokenizer.java @@ -0,0 +1,176 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +import java.util.ArrayList; +import java.util.List; + +public class ExpressionTokenizer { + + public static List tokenize(String expr) { + List tokens = new ArrayList<>(); + int pos = 0; + int len = expr.length(); + + while (pos < len) { + char c = expr.charAt(pos); + + if (Character.isWhitespace(c)) { pos++; continue; } + + if (c == '"') { + int start = pos++; + while (pos < len && expr.charAt(pos) != '"') { + if (expr.charAt(pos) == '\\' && pos + 1 < len) pos++; + pos++; + } + if (pos < len) pos++; + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.STRING_LITERAL, expr.substring(start, pos), start, pos)); + continue; + } + + if (c == '\'') { + int start = pos++; + while (pos < len && expr.charAt(pos) != '\'') { + if (expr.charAt(pos) == '\\' && pos + 1 < len) pos++; + pos++; + } + if (pos < len) pos++; + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.CHAR_LITERAL, expr.substring(start, pos), start, pos)); + continue; + } + + if (Character.isDigit(c) || (c == '.' && pos + 1 < len && Character.isDigit(expr.charAt(pos + 1)))) { + int start = pos; + if (c == '0' && pos + 1 < len) { + char next = expr.charAt(pos + 1); + if (next == 'x' || next == 'X') { + pos += 2; + while (pos < len && isHexDigit(expr.charAt(pos))) pos++; + if (pos < len && (expr.charAt(pos) == 'L' || expr.charAt(pos) == 'l')) { + pos++; + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.LONG_LITERAL, expr.substring(start, pos), start, pos)); + } else { + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.INT_LITERAL, expr.substring(start, pos), start, pos)); + } + continue; + } + if (next == 'b' || next == 'B') { + pos += 2; + while (pos < len && (expr.charAt(pos) == '0' || expr.charAt(pos) == '1')) pos++; + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.INT_LITERAL, expr.substring(start, pos), start, pos)); + continue; + } + } + + while (pos < len && Character.isDigit(expr.charAt(pos))) pos++; + boolean hasDecimal = false; + if (pos < len && expr.charAt(pos) == '.') { + if (pos + 1 < len && Character.isDigit(expr.charAt(pos + 1))) { + hasDecimal = true; + pos++; + while (pos < len && Character.isDigit(expr.charAt(pos))) pos++; + } + } + if (pos < len && (expr.charAt(pos) == 'e' || expr.charAt(pos) == 'E')) { + pos++; + if (pos < len && (expr.charAt(pos) == '+' || expr.charAt(pos) == '-')) pos++; + while (pos < len && Character.isDigit(expr.charAt(pos))) pos++; + hasDecimal = true; + } + + ExpressionToken.TokenKind kind = ExpressionToken.TokenKind.INT_LITERAL; + if (pos < len) { + char suffix = expr.charAt(pos); + if (suffix == 'f' || suffix == 'F') { kind = ExpressionToken.TokenKind.FLOAT_LITERAL; pos++; } + else if (suffix == 'd' || suffix == 'D') { kind = ExpressionToken.TokenKind.DOUBLE_LITERAL; pos++; } + else if (suffix == 'L' || suffix == 'l') { kind = ExpressionToken.TokenKind.LONG_LITERAL; pos++; } + else if (hasDecimal) kind = ExpressionToken.TokenKind.DOUBLE_LITERAL; + } else if (hasDecimal) kind = ExpressionToken.TokenKind.DOUBLE_LITERAL; + + tokens.add(new ExpressionToken(kind, expr.substring(start, pos), start, pos)); + continue; + } + + if (Character.isJavaIdentifierStart(c)) { + int start = pos; + while (pos < len && Character.isJavaIdentifierPart(expr.charAt(pos))) pos++; + tokens.add(ExpressionToken.identifier(expr.substring(start, pos), start, pos)); + continue; + } + + int start = pos; + String op = null; + + // Check for method reference :: (before lambda arrow and single colon) + if (pos + 1 < len && c == ':' && expr.charAt(pos + 1) == ':') { + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.METHOD_REFERENCE, "::", pos, pos + 2)); + pos += 2; + continue; + } + + // Check for lambda arrow (Java ->) + if (pos + 1 < len && c == '-' && expr.charAt(pos + 1) == '>') { + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.LAMBDA_ARROW, "->", pos, pos + 2)); + pos += 2; + continue; + } + + // Check for JS arrow (=>) + if (pos + 1 < len && c == '=' && expr.charAt(pos + 1) == '>') { + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.JS_ARROW, "=>", pos, pos + 2)); + pos += 2; + continue; + } + + if (pos + 3 <= len) { + String s3 = expr.substring(pos, pos + 3); + if (">>>".equals(s3) || "<<=".equals(s3) || ">>=".equals(s3)) op = s3; + } + if (op == null && pos + 4 <= len) { + String s4 = expr.substring(pos, pos + 4); + if (">>>=".equals(s4)) op = s4; + } + if (op == null && pos + 2 <= len) { + String s2 = expr.substring(pos, pos + 2); + if ("++".equals(s2) || "--".equals(s2) || "+=".equals(s2) || "-=".equals(s2) || + "*=".equals(s2) || "/=".equals(s2) || "%=".equals(s2) || "&=".equals(s2) || + "|=".equals(s2) || "^=".equals(s2) || "==".equals(s2) || "!=".equals(s2) || + "<=".equals(s2) || ">=".equals(s2) || "&&".equals(s2) || "||".equals(s2) || + "<<".equals(s2) || ">>".equals(s2)) op = s2; + } + if (op == null) { + switch (c) { + case '+': case '-': case '*': case '/': case '%': case '&': case '|': + case '^': case '~': case '!': case '<': case '>': case '=': + op = String.valueOf(c); break; + } + } + + if (op != null) { + pos += op.length(); + tokens.add(ExpressionToken.operator(op, start, pos)); + continue; + } + + switch (c) { + case '(': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.LEFT_PAREN, "(", pos, pos + 1)); break; + case ')': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.RIGHT_PAREN, ")", pos, pos + 1)); break; + case '[': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.LEFT_BRACKET, "[", pos, pos + 1)); break; + case ']': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.RIGHT_BRACKET, "]", pos, pos + 1)); break; + case '{': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.LEFT_BRACE, "{", pos, pos + 1)); break; + case '}': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.RIGHT_BRACE, "}", pos, pos + 1)); break; + case '.': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.DOT, ".", pos, pos + 1)); break; + case ',': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.COMMA, ",", pos, pos + 1)); break; + case '?': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.QUESTION, "?", pos, pos + 1)); break; + case ':': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.COLON, ":", pos, pos + 1)); break; + case ';': tokens.add(new ExpressionToken(ExpressionToken.TokenKind.SEMICOLON, ";", pos, pos + 1)); break; + } + pos++; + } + + tokens.add(new ExpressionToken(ExpressionToken.TokenKind.EOF, "", len, len)); + return tokens; + } + + private static boolean isHexDigit(char c) { + return Character.isDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionTypeResolver.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionTypeResolver.java new file mode 100644 index 000000000..f773d6e84 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/ExpressionTypeResolver.java @@ -0,0 +1,949 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.InnerCallableScope; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.ClassTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.OverloadSelector; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.ArrayList; +import java.util.List; + +public class ExpressionTypeResolver { + private final ExpressionNode.TypeResolverContext context; + private final ScriptDocument document; // Access to document for inner scope lookups + private final int basePosition; // Document offset for this expression + + /** + * Static field to track the expected/desired type for the current expression being resolved. + * This allows TypeRules to validate type compatibility in context (e.g., ternary operator branches + * must be compatible with the assignment target type). + * Should be set before calling resolve() and cleared after. + */ + public static TypeInfo CURRENT_EXPECTED_TYPE = null; + + public ExpressionTypeResolver(ExpressionNode.TypeResolverContext context) { + this.context = context; + this.document = null; + this.basePosition = 0; + } + + public ExpressionTypeResolver(ExpressionNode.TypeResolverContext context, ScriptDocument document) { + this(context, document, 0); + } + + public ExpressionTypeResolver(ExpressionNode.TypeResolverContext context, ScriptDocument document, int basePosition) { + this.context = context; + this.document = document; + this.basePosition = basePosition; + } + + public TypeInfo resolve(String expression) { + if (expression == null || expression.trim().isEmpty()) return null; + + try { + List tokens = ExpressionTokenizer.tokenize(expression); + if (tokens.isEmpty()) return null; + + ExpressionParser parser = new ExpressionParser(tokens); + ExpressionNode ast = parser.parse(); + if (ast == null) return null; + + return resolveNodeType(ast); + } catch (Exception e) { + return null; + } + } + + public static boolean containsOperators(String expression) { + if (expression == null) return false; + for (int i = 0; i < expression.length(); i++) { + char c = expression.charAt(i); + switch (c) { + case '+': case '-': case '*': case '/': case '%': + case '&': case '|': case '^': case '~': + case '<': case '>': case '=': case '!': + case '?': case ':': return true; + } + } + return false; + } + + private TypeInfo resolveNodeType(ExpressionNode node) { + if (node == null) return null; + + if (node instanceof ExpressionNode.IntLiteralNode) { + if (CURRENT_EXPECTED_TYPE != null) { + TypeInfo narrowed = TypeChecker.narrowLiteralToExpectedType( + ((ExpressionNode.IntLiteralNode) node).getValue(), CURRENT_EXPECTED_TYPE); + if (narrowed != null) return narrowed; + } + return TypeInfo.fromPrimitive("int"); + } + if (node instanceof ExpressionNode.LongLiteralNode) return TypeInfo.fromPrimitive("long"); + if (node instanceof ExpressionNode.FloatLiteralNode) return TypeInfo.fromPrimitive("float"); + if (node instanceof ExpressionNode.DoubleLiteralNode) return TypeInfo.fromPrimitive("double"); + if (node instanceof ExpressionNode.BooleanLiteralNode) return TypeInfo.fromPrimitive("boolean"); + if (node instanceof ExpressionNode.CharLiteralNode) return TypeInfo.fromPrimitive("char"); + if (node instanceof ExpressionNode.StringLiteralNode) return TypeInfo.string(); + if (node instanceof ExpressionNode.NullLiteralNode) return TypeInfo.unresolved("null", ""); + + if (node instanceof ExpressionNode.IdentifierNode) { + return context.resolveIdentifier(((ExpressionNode.IdentifierNode) node).getName()); + } + + if (node instanceof ExpressionNode.MemberAccessNode) { + ExpressionNode.MemberAccessNode ma = (ExpressionNode.MemberAccessNode) node; + TypeInfo targetType = resolveNodeType(ma.getTarget()); + if (targetType == null || !targetType.isResolved()) return null; + if (targetType == TypeInfo.ANY || "any".equals(targetType.getFullName())) return TypeInfo.ANY; + return context.resolveMemberAccess(targetType, ma.getMemberName()); + } + + if (node instanceof ExpressionNode.MethodCallNode) { + ExpressionNode.MethodCallNode mc = (ExpressionNode.MethodCallNode) node; + TypeInfo targetType = mc.getTarget() == null ? context.resolveIdentifier("this") : resolveNodeType(mc.getTarget()); + if (targetType == null || !targetType.isResolved()) return null; + if (targetType == TypeInfo.ANY || "any".equals(targetType.getFullName())) return TypeInfo.ANY; + TypeInfo[] argTypes = new TypeInfo[mc.getArguments().size()]; + for (int i = 0; i < argTypes.length; i++) argTypes[i] = resolveNodeType(mc.getArguments().get(i)); + return context.resolveMethodCall(targetType, mc.getMethodName(), argTypes); + } + + if (node instanceof ExpressionNode.ArrayAccessNode) { + ExpressionNode.ArrayAccessNode aa = (ExpressionNode.ArrayAccessNode) node; + TypeInfo arrayType = resolveNodeType(aa.getArray()); + if (arrayType == null || !arrayType.isResolved()) return null; + if (arrayType == TypeInfo.ANY || "any".equals(arrayType.getFullName())) return TypeInfo.ANY; + String typeName = arrayType.getFullName(); + if (typeName.endsWith("[]")) { + String elementTypeName = typeName.substring(0, typeName.length() - 2); + return context.resolveTypeName(elementTypeName); + } + return context.resolveArrayAccess(arrayType); + } + + if (node instanceof ExpressionNode.NewNode) { + return context.resolveTypeName(((ExpressionNode.NewNode) node).getTypeName()); + } + + if (node instanceof ExpressionNode.BinaryOpNode) { + ExpressionNode.BinaryOpNode bin = (ExpressionNode.BinaryOpNode) node; + TypeInfo leftType = resolveNodeType(bin.getLeft()); + TypeInfo rightType = resolveNodeType(bin.getRight()); + return TypeRules.resolveBinaryOperatorType(bin.getOperator(), leftType, rightType); + } + + if (node instanceof ExpressionNode.UnaryOpNode) { + ExpressionNode.UnaryOpNode un = (ExpressionNode.UnaryOpNode) node; + // Special case: negation of an IntLiteralNode can narrow to byte/short + if (un.getOperator() == OperatorType.UNARY_MINUS + && un.getOperand() instanceof ExpressionNode.IntLiteralNode + && CURRENT_EXPECTED_TYPE != null) { + String negatedText = "-" + ((ExpressionNode.IntLiteralNode) un.getOperand()).getValue(); + TypeInfo narrowed = TypeChecker.narrowLiteralToExpectedType(negatedText, CURRENT_EXPECTED_TYPE); + if (narrowed != null) return narrowed; + } + TypeInfo operandType = resolveNodeType(un.getOperand()); + return TypeRules.resolveUnaryOperatorType(un.getOperator(), operandType); + } + + if (node instanceof ExpressionNode.TernaryNode) { + ExpressionNode.TernaryNode tern = (ExpressionNode.TernaryNode) node; + TypeInfo thenType = resolveNodeType(tern.getThenExpr()); + TypeInfo elseType = resolveNodeType(tern.getElseExpr()); + return TypeRules.resolveTernaryType(thenType, elseType); + } + + if (node instanceof ExpressionNode.CastNode) { + return context.resolveTypeName(((ExpressionNode.CastNode) node).getTypeName()); + } + + if (node instanceof ExpressionNode.InstanceofNode) { + return TypeInfo.fromPrimitive("boolean"); + } + + if (node instanceof ExpressionNode.AssignmentNode) { + return resolveNodeType(((ExpressionNode.AssignmentNode) node).getTarget()); + } + + if (node instanceof ExpressionNode.ParenthesizedNode) { + return resolveNodeType(((ExpressionNode.ParenthesizedNode) node).getInner()); + } + + if (node instanceof ExpressionNode.LambdaNode) { + return resolveLambdaType((ExpressionNode.LambdaNode) node); + } + + if (node instanceof ExpressionNode.JSFunctionNode) { + return resolveJSFunctionType((ExpressionNode.JSFunctionNode) node); + } + + if (node instanceof ExpressionNode.JSArrowNode) { + return resolveJSArrowType((ExpressionNode.JSArrowNode) node); + } + + if (node instanceof ExpressionNode.MethodReferenceNode) { + return resolveMethodReferenceType((ExpressionNode.MethodReferenceNode) node); + } + + return null; + } + + private TypeInfo resolveLambdaType(ExpressionNode.LambdaNode lambda) { + // Lambda type is determined by the expected functional interface + TypeInfo expectedType = CURRENT_EXPECTED_TYPE; + + if (expectedType == null) { + // No expected type context + // Return a generic Object type + return TypeInfo.fromClass(Object.class); + } + + // Get SAM method from the expected functional interface + MethodInfo sam = expectedType.getSingleAbstractMethod(); + if (sam != null && document != null) { + // Find the InnerCallableScope for this lambda by matching position and parameters + InnerCallableScope scope = findLambdaScopeByPosition(lambda.getStart(), lambda.getParameterNames()); + + if (scope != null) { + scope.setExpectedType(expectedType); + + // Extract and apply parameter types from SAM to lambda parameters + List samParams = sam.getParameters(); + List lambdaParams = scope.getParameters(); + + if (samParams.size() == lambdaParams.size()) { + for (int i = 0; i < lambdaParams.size(); i++) { + FieldInfo lambdaParam = lambdaParams.get(i); + TypeInfo inferredType = samParams.get(i).getTypeInfo(); + + // Set inferred type on the parameter + if (inferredType != null) { + lambdaParam.setInferredType(inferredType); + } + } + } + } + + // Type check lambda body (if expression lambda) + if (!lambda.isBlock() && lambda.getBody() != null) { + // Resolve body type for validation + TypeInfo bodyType = resolveNodeType(lambda.getBody()); + // The actual compatibility check will be done during marking phase + } + + return expectedType; + } + + // Fallback: check if it's a recognized functional interface by name + String typeName = expectedType.getFullName(); + if (typeName != null && (typeName.contains("Function") || typeName.contains("Consumer") || + typeName.contains("Predicate") || typeName.contains("Supplier") || + typeName.equals("java.lang.Runnable"))) { + // Update the scope reference if available + if (lambda.getScopeRef() != null) { + lambda.getScopeRef().setExpectedType(expectedType); + } + + return expectedType; + } + + // Not a recognized functional interface, return Object + return TypeInfo.fromClass(Object.class); + } + + /** + * Find the InnerCallableScope for a lambda by matching position and parameter names. + * + * @param expressionRelativePos The start position of the lambda (relative to expression string) + * @param paramNames The parameter names of the lambda + * @return The matching InnerCallableScope, or null if not found + */ + private InnerCallableScope findLambdaScopeByPosition(int expressionRelativePos, List paramNames) { + if (document == null) { + return null; + } + + // Convert expression-relative position to absolute document position + int absolutePos = basePosition + expressionRelativePos; + + for (InnerCallableScope scope : document.getInnerScopes()) { + if (scope.getKind() == InnerCallableScope.Kind.JAVA_LAMBDA) { + // Check if absolute position is in range + if (absolutePos >= scope.getHeaderStart() && absolutePos < scope.getFullEnd()) { + // Verify parameter names match + if (scope.getParameters().size() == paramNames.size()) { + boolean match = true; + for (int i = 0; i < paramNames.size(); i++) { + if (!scope.getParameters().get(i).getName().equals(paramNames.get(i))) { + match = false; + break; + } + } + if (match) { + return scope; + } + } + } + } + } + return null; + } + + private TypeInfo resolveJSFunctionType(ExpressionNode.JSFunctionNode functionNode) { + // JS function type is determined by the expected functional interface (if any) + TypeInfo expectedType = CURRENT_EXPECTED_TYPE; + + if (expectedType == null) { + // No expected type - return generic Function type or Object + // Try to resolve "Function" as a type from the context + TypeInfo functionType = context.resolveTypeName("Function"); + if (functionType != null && functionType.isResolved()) { + return functionType; + } + return TypeInfo.fromClass(Object.class); // Fallback + } + + // Get SAM method from the expected functional interface + MethodInfo sam = expectedType.getSingleAbstractMethod(); + if (sam != null && document != null) { + // Find the InnerCallableScope for this JS function by matching position and parameters + InnerCallableScope scope = findJSFunctionScopeByPosition(functionNode.getStart(), functionNode.getParameterNames()); + + if (scope != null) { + scope.setExpectedType(expectedType); + + // Extract and apply parameter types from SAM to function parameters + List samParams = sam.getParameters(); + List functionParams = scope.getParameters(); + + if (samParams.size() == functionParams.size()) { + for (int i = 0; i < functionParams.size(); i++) { + FieldInfo functionParam = functionParams.get(i); + TypeInfo inferredType = samParams.get(i).getTypeInfo(); + + // Set inferred type on the parameter + if (inferredType != null) { + functionParam.setInferredType(inferredType); + } + } + } + } + + return expectedType; + } + + // Fallback: check if expected type is compatible with a function + String typeName = expectedType.getFullName(); + if (typeName != null && (typeName.contains("Function") || typeName.contains("Consumer") || + typeName.contains("Predicate") || typeName.contains("Supplier") || + typeName.equals("java.lang.Runnable"))) { + // This is likely a functional interface + + // Update the InnerCallableScope with the expected type + if (functionNode.getScopeRef() != null) { + functionNode.getScopeRef().setExpectedType(expectedType); + } + + return expectedType; + } + + // Expected type is not a recognized functional interface + // Check if it's a generic JS "Function" type expectation + if (typeName != null && typeName.equals("Function")) { + return expectedType; + } + + return TypeInfo.fromClass(Object.class); // Fallback + } + + /** + * Find the InnerCallableScope for a JS function by matching position and parameter names. + * + * @param expressionRelativePos The start position of the function (relative to expression string) + * @param paramNames The parameter names of the function + * @return The matching InnerCallableScope, or null if not found + */ + private InnerCallableScope findJSFunctionScopeByPosition(int expressionRelativePos, List paramNames) { + if (document == null) { + return null; + } + + // Convert expression-relative position to absolute document position + int absolutePos = basePosition + expressionRelativePos; + + for (InnerCallableScope scope : document.getInnerScopes()) { + if (scope.getKind() == InnerCallableScope.Kind.JS_FUNCTION_EXPR) { + // Check if absolute position is in range + if (absolutePos >= scope.getHeaderStart() && absolutePos < scope.getFullEnd()) { + // Verify parameter names match + if (scope.getParameters().size() == paramNames.size()) { + boolean match = true; + for (int i = 0; i < paramNames.size(); i++) { + if (!scope.getParameters().get(i).getName().equals(paramNames.get(i))) { + match = false; + break; + } + } + if (match) { + return scope; + } + } + } + } + } + return null; + } + + private TypeInfo resolveJSArrowType(ExpressionNode.JSArrowNode arrowNode) { + TypeInfo expectedType = CURRENT_EXPECTED_TYPE; + + if (expectedType == null) { + TypeInfo functionType = context.resolveTypeName("Function"); + if (functionType != null && functionType.isResolved()) { + return functionType; + } + return TypeInfo.fromClass(Object.class); + } + + MethodInfo sam = expectedType.getSingleAbstractMethod(); + if (sam != null && document != null) { + InnerCallableScope scope = findJSArrowScopeByPosition(arrowNode.getStart(), arrowNode.getParameterNames()); + + if (scope != null) { + scope.setExpectedType(expectedType); + + List samParams = sam.getParameters(); + List arrowParams = scope.getParameters(); + + if (samParams.size() == arrowParams.size()) { + for (int i = 0; i < arrowParams.size(); i++) { + TypeInfo inferredType = samParams.get(i).getTypeInfo(); + if (inferredType != null) { + arrowParams.get(i).setInferredType(inferredType); + } + } + } + } + + return expectedType; + } + + String typeName = expectedType.getFullName(); + if (typeName != null && (typeName.contains("Function") || typeName.contains("Consumer") || + typeName.contains("Predicate") || typeName.contains("Supplier") || + typeName.equals("java.lang.Runnable"))) { + if (arrowNode.getScopeRef() != null) { + arrowNode.getScopeRef().setExpectedType(expectedType); + } + return expectedType; + } + + if (typeName != null && typeName.equals("Function")) { + return expectedType; + } + + return TypeInfo.fromClass(Object.class); + } + + private InnerCallableScope findJSArrowScopeByPosition(int expressionRelativePos, List paramNames) { + if (document == null) { + return null; + } + + int absolutePos = basePosition + expressionRelativePos; + + for (InnerCallableScope scope : document.getInnerScopes()) { + if (scope.getKind() == InnerCallableScope.Kind.JS_ARROW_FUNC) { + if (absolutePos >= scope.getHeaderStart() && absolutePos < scope.getFullEnd()) { + if (scope.getParameters().size() == paramNames.size()) { + boolean match = true; + for (int i = 0; i < paramNames.size(); i++) { + if (!scope.getParameters().get(i).getName().equals(paramNames.get(i))) { + match = false; + break; + } + } + if (match) { + return scope; + } + } + } + } + } + return null; + } + + // ==================== Method Reference Resolution ==================== + + /** + * Resolve the type of a method reference expression (target::methodName). + * + * Supports all Java method reference forms: + * - this::method - Instance method on current object + * - super::method - Instance method on superclass + * - variable::method - Instance method on a variable's value + * - ClassName::method - Static method OR unbound instance method + * - pkg.ClassName::method - Fully qualified class reference + * - ClassName::new - Constructor reference + * - Type[]::new - Array constructor reference + * + * @param methodRef The method reference AST node + * @return The resolved type (functional interface type if valid, Object if invalid) + */ + private TypeInfo resolveMethodReferenceType(ExpressionNode.MethodReferenceNode methodRef) { + TypeInfo expectedType = CURRENT_EXPECTED_TYPE; + + // Must have expected functional interface context + if (expectedType == null || !expectedType.isFunctionalInterface()) { + return TypeInfo.fromClass(Object.class); + } + + MethodInfo sam = expectedType.getSingleAbstractMethod(); + if (sam == null) { + return TypeInfo.fromClass(Object.class); + } + + // Resolve target and determine if it's a class reference (static context) + MethodReferenceTarget resolvedTarget = resolveMethodReferenceTarget(methodRef); + if (resolvedTarget == null || resolvedTarget.type == null) { + // Unresolved target - return expected type to allow forward references + return expectedType; + } + + String methodName = methodRef.getMethodName(); + + // Handle constructor references (ClassName::new or Type[]::new) + if ("new".equals(methodName)) { + return resolveConstructorReference(resolvedTarget, sam, expectedType); + } + + // Handle method references + return resolveMethodReference(resolvedTarget, methodName, sam, expectedType); + } + + /** + * Encapsulates the resolved target of a method reference. + */ + private static class MethodReferenceTarget { + final TypeInfo type; // The resolved type + final boolean isClassRef; // True if target is a class reference (for static access) + + MethodReferenceTarget(TypeInfo type, boolean isClassRef) { + this.type = type; + this.isClassRef = isClassRef; + } + } + + /** + * Resolve the target (left side of ::) for a method reference. + * Returns both the type and whether it's a class reference. + */ + private MethodReferenceTarget resolveMethodReferenceTarget(ExpressionNode.MethodReferenceNode methodRef) { + ExpressionNode target = methodRef.getTarget(); + if (target == null) { + return null; + } + + // Handle simple identifiers: this, super, variable, ClassName + if (target instanceof ExpressionNode.IdentifierNode) { + String name = ((ExpressionNode.IdentifierNode) target).getName(); + return resolveSimpleTarget(name); + } + + // Handle qualified names: pkg.ClassName or outer.Inner + if (target instanceof ExpressionNode.MemberAccessNode) { + return resolveQualifiedTarget((ExpressionNode.MemberAccessNode) target); + } + + // Handle array type targets: Type[] + if (target instanceof ExpressionNode.ArrayAccessNode) { + TypeInfo arrayType = resolveNodeType(target); + if (arrayType != null && arrayType.isResolved()) { + // Array type is always a class reference (for Type[]::new) + return new MethodReferenceTarget(arrayType, true); + } + } + + // Fallback: resolve as expression (e.g., (expr)::method) + TypeInfo exprType = resolveNodeType(target); + if (exprType != null && exprType.isResolved()) { + // Expression results are always instance references + return new MethodReferenceTarget(exprType, false); + } + + return null; + } + + /** + * Resolve a simple identifier as method reference target. + */ + private MethodReferenceTarget resolveSimpleTarget(String name) { + // this::method - instance method on current object + if ("this".equals(name)) { + TypeInfo thisType = context.resolveIdentifier("this"); + return thisType != null ? new MethodReferenceTarget(thisType, false) : null; + } + + // super::method - instance method on superclass + if ("super".equals(name)) { + TypeInfo superType = context.resolveIdentifier("super"); + return superType != null ? new MethodReferenceTarget(superType, false) : null; + } + + // Try as type name first (ClassName::method) + TypeInfo typeInfo = context.resolveTypeName(name); + if (typeInfo != null && typeInfo.isResolved()) { + // Wrap as ClassTypeInfo to indicate class reference + TypeInfo classRef = new ClassTypeInfo(typeInfo); + return new MethodReferenceTarget(classRef, true); + } + + // Try as variable (instance::method) + TypeInfo varType = context.resolveIdentifier(name); + if (varType != null && varType.isResolved()) { + // Check if variable holds a Class reference (e.g., var File = Java.type("java.io.File")) + boolean isClassRef = varType.isClassReference(); + return new MethodReferenceTarget(varType, isClassRef); + } + + return null; + } + + /** + * Resolve a qualified name (a.b.c) as method reference target. + * Handles both package-qualified class names and nested class access. + */ + private MethodReferenceTarget resolveQualifiedTarget(ExpressionNode.MemberAccessNode memberAccess) { + // Try to build qualified name and resolve as type + String qualifiedName = buildQualifiedName(memberAccess); + if (qualifiedName != null) { + TypeInfo typeInfo = context.resolveTypeName(qualifiedName); + if (typeInfo != null && typeInfo.isResolved()) { + TypeInfo classRef = new ClassTypeInfo(typeInfo); + return new MethodReferenceTarget(classRef, true); + } + } + + // Try resolving as expression chain (object.field::method) + TypeInfo exprType = resolveNodeType(memberAccess); + if (exprType != null && exprType.isResolved()) { + boolean isClassRef = exprType.isClassReference(); + return new MethodReferenceTarget(exprType, isClassRef); + } + + return null; + } + + /** + * Build a qualified name string from a MemberAccessNode chain. + * Example: a.b.c.ClassName -> "a.b.c.ClassName" + */ + private String buildQualifiedName(ExpressionNode node) { + if (node instanceof ExpressionNode.IdentifierNode) { + return ((ExpressionNode.IdentifierNode) node).getName(); + } + + if (node instanceof ExpressionNode.MemberAccessNode) { + ExpressionNode.MemberAccessNode ma = (ExpressionNode.MemberAccessNode) node; + String baseName = buildQualifiedName(ma.getTarget()); + if (baseName != null) { + return baseName + "." + ma.getMemberName(); + } + } + + return null; + } + + /** + * Resolve a method reference (target::methodName). + */ + private TypeInfo resolveMethodReference(MethodReferenceTarget target, String methodName, + MethodInfo sam, TypeInfo expectedType) { + TypeInfo targetType = target.isClassRef && target.type instanceof ClassTypeInfo + ? ((ClassTypeInfo) target.type).getInstanceType() + : target.type; + + if (targetType == null || !targetType.hasMethod(methodName)) { + return TypeInfo.fromClass(Object.class); + } + + // Find best matching method using OverloadSelector + MethodInfo method = findBestMethodForReference(targetType, methodName, sam, target.isClassRef); + if (method == null) { + return TypeInfo.fromClass(Object.class); + } + + // Validate signature compatibility + String error = validateMethodSignature(method, sam, target.isClassRef, targetType); + if (error != null) { + return TypeInfo.fromClass(Object.class); + } + + return expectedType; + } + + /** + * Find the best matching method for a method reference using OverloadSelector logic. + */ + private MethodInfo findBestMethodForReference(TypeInfo targetType, String methodName, + MethodInfo sam, boolean isClassRef) { + List allOverloads = targetType.getAllMethodOverloads(methodName); + if (allOverloads.isEmpty()) { + return null; + } + + // Extract SAM parameter types for overload matching + TypeInfo[] samParamTypes = extractSamParamTypes(sam, isClassRef, targetType); + + // Filter candidates by arity first, then use OverloadSelector + List candidates = new ArrayList<>(); + int expectedArity = samParamTypes.length; + + for (MethodInfo method : allOverloads) { + int methodArity = method.getParameters().size(); + + // Direct match: instance::method or ClassName::staticMethod + if (methodArity == expectedArity) { + candidates.add(method); + } + // Unbound instance method: ClassName::instanceMethod (first SAM param is receiver) + else if (isClassRef && methodArity == sam.getParameters().size() - 1 && !isStaticMethod(method)) { + candidates.add(method); + } + } + + if (candidates.isEmpty()) { + return null; + } + + if (candidates.size() == 1) { + return candidates.get(0); + } + + // Use OverloadSelector for multi-candidate selection + return OverloadSelector.selectBestOverload(candidates, samParamTypes); + } + + /** + * Extract the effective parameter types from SAM for method matching. + * For unbound instance methods, excludes the first receiver parameter. + */ + private TypeInfo[] extractSamParamTypes(MethodInfo sam, boolean isClassRef, TypeInfo targetType) { + List samParams = sam.getParameters(); + + // For class references, we might be matching an unbound instance method + // where the first SAM param is the receiver - handled in findBestMethodForReference + TypeInfo[] types = new TypeInfo[samParams.size()]; + for (int i = 0; i < samParams.size(); i++) { + types[i] = samParams.get(i).getTypeInfo(); + } + return types; + } + + /** + * Check if a method is static (Java reflection). + */ + private boolean isStaticMethod(MethodInfo method) { + java.lang.reflect.Method javaMethod = method.getJavaMethod(); + if (javaMethod != null) { + return java.lang.reflect.Modifier.isStatic(javaMethod.getModifiers()); + } + // For script-defined methods, assume non-static unless marked + return method.isStatic(); + } + + /** + * Validate method signature compatibility with SAM. + */ + private String validateMethodSignature(MethodInfo method, MethodInfo sam, + boolean isClassRef, TypeInfo targetType) { + List methodParams = method.getParameters(); + List samParams = sam.getParameters(); + + int methodArity = methodParams.size(); + int samArity = samParams.size(); + + // Check for unbound instance method reference (ClassName::instanceMethod) + boolean isUnbound = isClassRef && methodArity == samArity - 1 && !isStaticMethod(method); + + // Validate parameter count + if (methodArity != samArity && !isUnbound) { + return "Parameter count mismatch"; + } + + // Validate parameter types + int offset = isUnbound ? 1 : 0; + for (int i = 0; i < methodArity; i++) { + TypeInfo methodParamType = methodParams.get(i).getTypeInfo(); + TypeInfo samParamType = samParams.get(i + offset).getTypeInfo(); + + if (methodParamType != null && samParamType != null) { + if (!TypeChecker.isTypeCompatible(methodParamType, samParamType)) { + return "Parameter type mismatch at position " + (i + 1); + } + } + } + + // For unbound reference, validate receiver compatibility + if (isUnbound && samArity > 0) { + TypeInfo firstSamParam = samParams.get(0).getTypeInfo(); + if (firstSamParam != null && !TypeChecker.isTypeCompatible(targetType, firstSamParam)) { + return "Receiver type mismatch"; + } + } + + // Validate return type (covariant) + TypeInfo methodReturn = method.getReturnType(); + TypeInfo samReturn = sam.getReturnType(); + + if (samReturn != null && methodReturn != null) { + boolean samIsVoid = "void".equals(samReturn.getFullName()) || samReturn.getJavaClass() == void.class; + if (!samIsVoid && !TypeChecker.isTypeCompatible(samReturn, methodReturn)) { + return "Return type mismatch"; + } + } + + return null; + } + + /** + * Resolve a constructor reference (ClassName::new or Type[]::new). + */ + private TypeInfo resolveConstructorReference(MethodReferenceTarget target, MethodInfo sam, + TypeInfo expectedType) { + TypeInfo targetType = target.type; + + // Handle array constructor reference: Type[]::new + if (isArrayType(targetType)) { + return resolveArrayConstructorReference(targetType, sam, expectedType); + } + + // Get the actual class type for constructor lookup + TypeInfo classType = target.type instanceof ClassTypeInfo + ? ((ClassTypeInfo) target.type).getInstanceType() + : target.type; + + if (classType == null) { + return TypeInfo.fromClass(Object.class); + } + + // Cannot construct interfaces or abstract classes + if (classType.getKind() == TypeInfo.Kind.INTERFACE) { + return TypeInfo.fromClass(Object.class); + } + + // Extract SAM parameter types for constructor matching + List samParams = sam.getParameters(); + TypeInfo[] paramTypes = new TypeInfo[samParams.size()]; + for (int i = 0; i < samParams.size(); i++) { + paramTypes[i] = samParams.get(i).getTypeInfo(); + } + + // Find matching constructor + MethodInfo constructor = classType.findConstructor(paramTypes); + if (constructor == null && samParams.size() > 0) { + // Try by arity if exact type match fails + constructor = classType.findConstructor(samParams.size()); + } + + if (constructor == null) { + return TypeInfo.fromClass(Object.class); + } + + // Validate return type compatibility + TypeInfo samReturn = sam.getReturnType(); + if (samReturn != null && !TypeChecker.isTypeCompatible(samReturn, classType)) { + return TypeInfo.fromClass(Object.class); + } + + return expectedType; + } + + /** + * Resolve an array constructor reference: Type[]::new + * Must match IntFunction or similar single-int-param functional interface. + */ + private TypeInfo resolveArrayConstructorReference(TypeInfo arrayType, MethodInfo sam, + TypeInfo expectedType) { + List samParams = sam.getParameters(); + + // Array constructor takes exactly one int parameter (the size) + if (samParams.size() != 1) { + return TypeInfo.fromClass(Object.class); + } + + TypeInfo sizeParam = samParams.get(0).getTypeInfo(); + if (sizeParam == null || !isIntLike(sizeParam)) { + return TypeInfo.fromClass(Object.class); + } + + // Return type must be compatible with array type + TypeInfo samReturn = sam.getReturnType(); + if (samReturn != null && !TypeChecker.isTypeCompatible(samReturn, arrayType)) { + return TypeInfo.fromClass(Object.class); + } + + return expectedType; + } + + /** + * Check if a type is an array type. + */ + private boolean isArrayType(TypeInfo type) { + if (type == null) return false; + String name = type.getFullName(); + return name != null && name.endsWith("[]"); + } + + /** + * Check if a type is int-like (int, Integer, or numeric that can represent array size). + */ + private boolean isIntLike(TypeInfo type) { + if (type == null) return false; + String name = type.getFullName(); + return "int".equals(name) || "java.lang.Integer".equals(name) + || "long".equals(name) || "java.lang.Long".equals(name); + } + + public static ExpressionNode.TypeResolverContext createBasicContext() { + return new ExpressionNode.TypeResolverContext() { + public TypeInfo resolveIdentifier(String name) { + if ("true".equals(name) || "false".equals(name)) return TypeInfo.fromPrimitive("boolean"); + if ("null".equals(name)) return TypeInfo.unresolved("null", ""); + return null; + } + public TypeInfo resolveMemberAccess(TypeInfo targetType, String memberName) { return null; } + public TypeInfo resolveMethodCall(TypeInfo targetType, String methodName, TypeInfo[] argTypes) { return null; } + public TypeInfo resolveArrayAccess(TypeInfo arrayType) { + String typeName = arrayType.getFullName(); + if (typeName.endsWith("[]")) { + // For primitive arrays, we need to map back to primitive TypeInfo + String elementType = typeName.substring(0, typeName.length() - 2); + switch (elementType) { + case "int": case "long": case "float": case "double": + case "byte": case "short": case "char": case "boolean": + return TypeInfo.fromPrimitive(elementType); + default: + return TypeInfo.unresolved(elementType, elementType); + } + } + return null; + } + public TypeInfo resolveTypeName(String typeName) { + // Handle primitives + switch (typeName) { + case "int": case "long": case "float": case "double": + case "byte": case "short": case "char": case "boolean": case "void": + return TypeInfo.fromPrimitive(typeName); + default: + return TypeInfo.unresolved(typeName, typeName); + } + } + }; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/OperatorType.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/OperatorType.java new file mode 100644 index 000000000..2d4bf32dc --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/OperatorType.java @@ -0,0 +1,147 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +public enum OperatorType { + + ADD("+", 11, Associativity.LEFT, Category.ARITHMETIC), + SUBTRACT("-", 11, Associativity.LEFT, Category.ARITHMETIC), + MULTIPLY("*", 12, Associativity.LEFT, Category.ARITHMETIC), + DIVIDE("/", 12, Associativity.LEFT, Category.ARITHMETIC), + MODULO("%", 12, Associativity.LEFT, Category.ARITHMETIC), + + + ASSIGN("=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + ADD_ASSIGN("+=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + SUBTRACT_ASSIGN("-=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + MULTIPLY_ASSIGN("*=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + DIVIDE_ASSIGN("/=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + MODULO_ASSIGN("%=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + AND_ASSIGN("&=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + OR_ASSIGN("|=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + XOR_ASSIGN("^=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + LEFT_SHIFT_ASSIGN("<<=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + RIGHT_SHIFT_ASSIGN(">>=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + UNSIGNED_RIGHT_SHIFT_ASSIGN(">>>=", 1, Associativity.RIGHT, Category.ASSIGNMENT), + + TERNARY_QUESTION("?", 2, Associativity.RIGHT, Category.TERNARY), + TERNARY_COLON(":", 2, Associativity.RIGHT, Category.TERNARY), + + LOGICAL_OR("||", 3, Associativity.LEFT, Category.LOGICAL), + LOGICAL_AND("&&", 4, Associativity.LEFT, Category.LOGICAL), + + BITWISE_OR("|", 5, Associativity.LEFT, Category.BITWISE), + BITWISE_XOR("^", 6, Associativity.LEFT, Category.BITWISE), + BITWISE_AND("&", 7, Associativity.LEFT, Category.BITWISE), + + EQUALS("==", 8, Associativity.LEFT, Category.RELATIONAL), + NOT_EQUALS("!=", 8, Associativity.LEFT, Category.RELATIONAL), + LESS_THAN("<", 9, Associativity.LEFT, Category.RELATIONAL), + GREATER_THAN(">", 9, Associativity.LEFT, Category.RELATIONAL), + LESS_THAN_OR_EQUAL("<=", 9, Associativity.LEFT, Category.RELATIONAL), + GREATER_THAN_OR_EQUAL(">=", 9, Associativity.LEFT, Category.RELATIONAL), + + LEFT_SHIFT("<<", 10, Associativity.LEFT, Category.BITWISE), + RIGHT_SHIFT(">>", 10, Associativity.LEFT, Category.BITWISE), + UNSIGNED_RIGHT_SHIFT(">>>", 10, Associativity.LEFT, Category.BITWISE), + + UNARY_PLUS("+", 14, Associativity.RIGHT, Category.UNARY), + UNARY_MINUS("-", 14, Associativity.RIGHT, Category.UNARY), + LOGICAL_NOT("!", 14, Associativity.RIGHT, Category.UNARY), + BITWISE_NOT("~", 14, Associativity.RIGHT, Category.UNARY), + PRE_INCREMENT("++", 14, Associativity.RIGHT, Category.UNARY), + PRE_DECREMENT("--", 14, Associativity.RIGHT, Category.UNARY), + POST_INCREMENT("++", 15, Associativity.LEFT, Category.UNARY_POSTFIX), + POST_DECREMENT("--", 15, Associativity.LEFT, Category.UNARY_POSTFIX), + + MEMBER_ACCESS(".", 16, Associativity.LEFT, Category.ACCESS), + ARRAY_ACCESS("[]", 16, Associativity.LEFT, Category.ACCESS), + METHOD_CALL("()", 16, Associativity.LEFT, Category.ACCESS), + + CAST("(type)", 14, Associativity.RIGHT, Category.CAST), + INSTANCEOF("instanceof", 9, Associativity.LEFT, Category.INSTANCEOF); + + + private final String symbol; + private final int precedence; + private final Associativity associativity; + private final Category category; + + OperatorType(String symbol, int precedence, Associativity associativity, Category category) { + this.symbol = symbol; + this.precedence = precedence; + this.associativity = associativity; + this.category = category; + } + + public String getSymbol() { return symbol; } + public int getPrecedence() { return precedence; } + public Associativity getAssociativity() { return associativity; } + public Category getCategory() { return category; } + + public boolean isBinary() { + return category == Category.ARITHMETIC || category == Category.RELATIONAL || + category == Category.LOGICAL || category == Category.BITWISE; + } + + public boolean isUnary() { + return category == Category.UNARY || category == Category.UNARY_POSTFIX; + } + + public boolean isAssignment() { + return category == Category.ASSIGNMENT; + } + + public boolean isComparison() { + return category == Category.RELATIONAL; + } + + public enum Associativity { LEFT, RIGHT } + + public enum Category { + ARITHMETIC, UNARY, UNARY_POSTFIX, RELATIONAL, LOGICAL, BITWISE, + TERNARY, INSTANCEOF, ASSIGNMENT, CAST, ACCESS + } + + public static OperatorType fromSymbol(String symbol) { + for (OperatorType op : values()) { + if (op.symbol.equals(symbol)) return op; + } + return null; + } + + public static OperatorType fromBinarySymbol(String symbol) { + switch (symbol) { + case "+": return ADD; + case "-": return SUBTRACT; + case "*": return MULTIPLY; + case "/": return DIVIDE; + case "%": return MODULO; + case "==": return EQUALS; + case "!=": return NOT_EQUALS; + case "<": return LESS_THAN; + case ">": return GREATER_THAN; + case "<=": return LESS_THAN_OR_EQUAL; + case ">=": return GREATER_THAN_OR_EQUAL; + case "&&": return LOGICAL_AND; + case "||": return LOGICAL_OR; + case "&": return BITWISE_AND; + case "|": return BITWISE_OR; + case "^": return BITWISE_XOR; + case "<<": return LEFT_SHIFT; + case ">>": return RIGHT_SHIFT; + case ">>>": return UNSIGNED_RIGHT_SHIFT; + case "=": return ASSIGN; + case "+=": return ADD_ASSIGN; + case "-=": return SUBTRACT_ASSIGN; + case "*=": return MULTIPLY_ASSIGN; + case "/=": return DIVIDE_ASSIGN; + case "%=": return MODULO_ASSIGN; + case "&=": return AND_ASSIGN; + case "|=": return OR_ASSIGN; + case "^=": return XOR_ASSIGN; + case "<<=": return LEFT_SHIFT_ASSIGN; + case ">>=": return RIGHT_SHIFT_ASSIGN; + case ">>>=": return UNSIGNED_RIGHT_SHIFT_ASSIGN; + default: return null; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/TypeRules.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/TypeRules.java new file mode 100644 index 000000000..d20f8709a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/expression/TypeRules.java @@ -0,0 +1,349 @@ +package noppes.npcs.client.gui.util.script.interpreter.expression; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +public class TypeRules { + + private static boolean isJsNumber(TypeInfo type) { + if (type == null || !type.isResolved()) return false; + String name = type.getSimpleName(); + String full = type.getFullName(); + return "number".equals(name) || "number".equals(full); + } + + private static boolean isNumericPrimitiveOrWrapper(TypeInfo type) { + if (type == null || type.getJavaClass() == null) return false; + Class cls = type.getJavaClass(); + return cls == byte.class || cls == Byte.class || + cls == short.class || cls == Short.class || + cls == int.class || cls == Integer.class || + cls == long.class || cls == Long.class || + cls == float.class || cls == Float.class || + cls == double.class || cls == Double.class || + cls == char.class || cls == Character.class; + } + + private static boolean isAny(TypeInfo type) { + if (type == null) return false; + if (type == TypeInfo.ANY) return true; + String full = type.getFullName(); + return "any".equals(full); + } + + public static boolean isNumeric(TypeInfo type) { + if (type == null || !type.isResolved()) return false; + if (isJsNumber(type)) return true; + String name = type.getSimpleName(); + return "int".equals(name) || "long".equals(name) || "float".equals(name) || + "double".equals(name) || "byte".equals(name) || "short".equals(name) || "char".equals(name); + } + + public static boolean isIntegral(TypeInfo type) { + if (type == null || !type.isResolved()) return false; + String name = type.getSimpleName(); + return "int".equals(name) || "long".equals(name) || "byte".equals(name) || + "short".equals(name) || "char".equals(name); + } + + public static boolean isFloatingPoint(TypeInfo type) { + if (type == null || !type.isResolved()) return false; + if (isJsNumber(type)) return true; + String name = type.getSimpleName(); + return "float".equals(name) || "double".equals(name); + } + + public static boolean isBoolean(TypeInfo type) { + if (type == null || !type.isResolved()) return false; + return "boolean".equals(type.getSimpleName()); + } + + public static boolean isString(TypeInfo type) { + if (type == null || !type.isResolved()) return false; + String name = type.getSimpleName(); + String fullName = type.getFullName(); + return "String".equals(name) || "java.lang.String".equals(fullName); + } + + public static TypeInfo binaryNumericPromotion(TypeInfo left, TypeInfo right) { + if (isJsNumber(left) || isJsNumber(right)) return TypeInfo.NUMBER; + if (left == null || right == null || !left.isResolved() || !right.isResolved()) { + return null; + } + String l = left.getSimpleName(); + String r = right.getSimpleName(); + if ("double".equals(l) || "double".equals(r)) return TypeInfo.fromPrimitive("double"); + if ("float".equals(l) || "float".equals(r)) return TypeInfo.fromPrimitive("float"); + if ("long".equals(l) || "long".equals(r)) return TypeInfo.fromPrimitive("long"); + return TypeInfo.fromPrimitive("int"); + } + + public static TypeInfo unaryNumericPromotion(TypeInfo type) { + if (type == null || !type.isResolved()) return null; + if (isJsNumber(type)) return TypeInfo.NUMBER; + String name = type.getSimpleName(); + if ("double".equals(name) || "float".equals(name) || "long".equals(name)) return type; + if ("byte".equals(name) || "short".equals(name) || "char".equals(name) || "int".equals(name)) { + return TypeInfo.fromPrimitive("int"); + } + return null; + } + + public static TypeInfo resolveBinaryOperatorType(OperatorType op, TypeInfo left, TypeInfo right) { + if (op == null) return null; + + switch (op.getCategory()) { + case ARITHMETIC: + if (op == OperatorType.ADD && (isString(left) || isString(right))) { + return validateAgainstExpectedType(TypeInfo.string()); + } + if (isAny(left) || isAny(right)) { + return validateAgainstExpectedType(TypeInfo.ANY); + } + if (isNumeric(left) && isNumeric(right)) { + TypeInfo promoted = binaryNumericPromotion(left, right); + return validateAgainstExpectedType(promoted); + } + return null; + + case RELATIONAL: + if (op == OperatorType.EQUALS || op == OperatorType.NOT_EQUALS) { + return TypeInfo.fromPrimitive("boolean"); + } + if (isAny(left) || isAny(right)) { + return TypeInfo.fromPrimitive("boolean"); + } + if (isNumeric(left) && isNumeric(right)) { + return TypeInfo.fromPrimitive("boolean"); + } + return null; + + case LOGICAL: + if (isAny(left) || isAny(right)) { + return TypeInfo.ANY; + } + if (isBoolean(left) && isBoolean(right)) { + return TypeInfo.fromPrimitive("boolean"); + } + return null; + + case BITWISE: + if (isAny(left) || isAny(right)) { + return validateAgainstExpectedType(TypeInfo.ANY); + } + if (op == OperatorType.LEFT_SHIFT || op == OperatorType.RIGHT_SHIFT || + op == OperatorType.UNSIGNED_RIGHT_SHIFT) { + if (isIntegral(left)) { + TypeInfo promoted = unaryNumericPromotion(left); + return validateAgainstExpectedType(promoted); + } + } + if (isIntegral(left) && isIntegral(right)) { + TypeInfo promoted = binaryNumericPromotion(left, right); + return validateAgainstExpectedType(promoted); + } + if (isBoolean(left) && isBoolean(right)) { + return TypeInfo.fromPrimitive("boolean"); + } + return null; + + case ASSIGNMENT: + return left; + + default: + return null; + } + } + + public static TypeInfo resolveUnaryOperatorType(OperatorType op, TypeInfo operand) { + if (op == null || operand == null || !operand.isResolved()) { + return null; + } + + if (isAny(operand)) { + if (op == OperatorType.LOGICAL_NOT) { + return TypeInfo.fromPrimitive("boolean"); + } + return TypeInfo.ANY; + } + + switch (op) { + case UNARY_PLUS: + case UNARY_MINUS: + if (isNumeric(operand)) { + TypeInfo promoted = unaryNumericPromotion(operand); + return validateAgainstExpectedType(promoted); + } + return null; + + case BITWISE_NOT: + if (isIntegral(operand)) { + TypeInfo promoted = unaryNumericPromotion(operand); + return validateAgainstExpectedType(promoted); + } + return null; + + case LOGICAL_NOT: + if (isBoolean(operand)) return TypeInfo.fromPrimitive("boolean"); + return null; + + case PRE_INCREMENT: + case PRE_DECREMENT: + case POST_INCREMENT: + case POST_DECREMENT: + if (isNumeric(operand)) return operand; + return null; + + default: + return null; + } + } + + /** + * Check if sourceType can be assigned to targetType. + * Handles primitives, numeric conversions, null compatibility, and reference types. + */ + public static boolean isAssignmentCompatible(TypeInfo sourceType, TypeInfo targetType) { + if (sourceType == null || targetType == null) + return false; + if (!targetType.isResolved()) + return true; // Can't validate against unresolved type + + if (isAny(sourceType) || isAny(targetType)) { + return true; + } + + // Null literal can be assigned to any reference type + if ("".equals(sourceType.getFullName())) { + return !isPrimitive(targetType); + } + + if (!sourceType.isResolved()) + return false; + + if ((isJsNumber(sourceType) && isNumericPrimitiveOrWrapper(targetType)) || + (isJsNumber(targetType) && isNumericPrimitiveOrWrapper(sourceType))) { + return true; + } + + // Exact match + if (sourceType.equals(targetType)) + return true; + if (sourceType.getFullName().equals(targetType.getFullName())) + return true; + + // Numeric conversions (widening primitive conversions) + String source = sourceType.getSimpleName(); + String target = targetType.getSimpleName(); + + // byte -> short, int, long, float, double + if ("byte".equals(source)) { + return "short".equals(target) || "int".equals(target) || "long".equals(target) || + "float".equals(target) || "double".equals(target); + } + // short -> int, long, float, double + if ("short".equals(source)) { + return "int".equals(target) || "long".equals(target) || + "float".equals(target) || "double".equals(target); + } + // char -> int, long, float, double + if ("char".equals(source)) { + return "int".equals(target) || "long".equals(target) || + "float".equals(target) || "double".equals(target); + } + // int -> long, float, double + if ("int".equals(source)) { + return "long".equals(target) || "float".equals(target) || "double".equals(target); + } + // long -> float, double + if ("long".equals(source)) { + return "float".equals(target) || "double".equals(target); + } + // float -> double + if ("float".equals(source)) { + return "double".equals(target); + } + + // For reference types, we'd need inheritance/interface checking + // For now, return false for incompatible types + return false; + } + + /** + * Check if a type is a primitive type. + */ + public static boolean isPrimitive(TypeInfo type) { + if (type == null || !type.isResolved()) + return false; + String name = type.getSimpleName(); + return "int".equals(name) || "long".equals(name) || "float".equals(name) || + "double".equals(name) || "byte".equals(name) || "short".equals(name) || + "char".equals(name) || "boolean".equals(name) || "void".equals(name); + } + + /** + * Validate a computed type against the current expected type context. + * If there's an expected type and the computed type is compatible, returns the expected type. + * If incompatible, returns the computed type so the error can be properly reported. + * If no expected type context, returns the computed type unchanged. + * + * @param computedType The type computed by normal type rules + * @return The type to use (either expectedType if compatible, or computedType) + */ + public static TypeInfo validateAgainstExpectedType(TypeInfo computedType) { + if (computedType == null) return null; + + TypeInfo expectedType = ExpressionTypeResolver.CURRENT_EXPECTED_TYPE; + if (expectedType != null && expectedType.isResolved() && computedType.isResolved()) { + if (isAssignmentCompatible(computedType, expectedType)) { + return expectedType; + } + // Return computed type so error can be detected (incompatible with expected) + return computedType; + } + + return computedType; + } + + public static TypeInfo resolveTernaryType(TypeInfo thenType, TypeInfo elseType) { + if (thenType == null && elseType == null) return null; + if (thenType == null) return elseType; + if (elseType == null) return thenType; + + // Handle null literal type + boolean thenIsNull = "".equals(thenType.getFullName()); + boolean elseIsNull = "".equals(elseType.getFullName()); + + if (thenIsNull && elseIsNull) return thenType; // both null -> null + if (thenIsNull) return elseType; // null : T -> T + if (elseIsNull) return thenType; // T : null -> T + + if (!thenType.isResolved()) return elseType.isResolved() ? elseType : null; + if (!elseType.isResolved()) return thenType; + + // If there's an expected type context, validate both branches against it + TypeInfo expectedType = ExpressionTypeResolver.CURRENT_EXPECTED_TYPE; + if (expectedType != null && expectedType.isResolved()) { + boolean thenCompatible = isAssignmentCompatible(thenType, expectedType); + boolean elseCompatible = isAssignmentCompatible(elseType, expectedType); + + // If both branches are compatible with expected type, return expected type + if (thenCompatible && elseCompatible) { + return expectedType; + } else if (!elseCompatible) { + // Return the incompatible type so error can be detected + return elseType; + } else { + // thenType is incompatible + return thenType; + } + } + + // Normal ternary type resolution without expected type context + if (thenType.equals(elseType)) return thenType; + if (isNumeric(thenType) && isNumeric(elseType)) { + return binaryNumericPromotion(thenType, elseType); + } + + return thenType; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/AssignmentInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/AssignmentInfo.java new file mode 100644 index 000000000..8089ebe27 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/AssignmentInfo.java @@ -0,0 +1,250 @@ +package noppes.npcs.client.gui.util.script.interpreter.field; + +import noppes.npcs.client.gui.util.script.ScopeInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +/** + * Metadata for assignment validation. + * Tracks assignment statements like "varName = expr" or "obj.field = expr" + * and validates type compatibility, access modifiers, and final status. + * + * Each AssignmentInfo represents a single assignment to a field. + * The positions are: + * - lhsStart/lhsEnd: The target variable/field position (left-hand side) + * - rhsStart/rhsEnd: From first token of RHS to the semicolon (inclusive) + */ +public class AssignmentInfo { + + /** + * Error type for assignment validation. + */ + public enum ErrorType { + NONE, + TYPE_MISMATCH, // Assigned value type doesn't match target type + FINAL_REASSIGNMENT, // Attempting to reassign a final field + PRIVATE_ACCESS, // Attempting to access private field + PROTECTED_ACCESS, // Attempting to access protected field from invalid context + UNRESOLVED_TARGET, // Target variable/field doesn't exist + STATIC_CONTEXT_ERROR, // Accessing instance field from static context + DUPLICATE_DECLARATION // Variable is already defined in the scope + } + + // Statement position + private final int statementStart; // Absolute start of statement (includes modifiers/type for declarations) + + // Target/LHS info + private final String targetName; + private final int lhsStart; // Position of first char of target variable/field + private final int lhsEnd; // Position after last char of target + private final TypeInfo targetType; // Declared type of target + + // Source/RHS info (from first token of RHS expression to semicolon) + private final int rhsStart; // Position of first non-whitespace char after '=' + private final int rhsEnd; // Position of ';' (inclusive in the range for underlining) + private final TypeInfo sourceType; // Resolved type of RHS expression + private final String sourceExpr; // The RHS expression text (for display) + + // For chained field access (e.g., obj.field = value) + private final TypeInfo receiverType; // Type of receiver (null for simple variables) + private final Field reflectionField; // Java reflection field (for modifier checks) + + // Flag for script-defined final variables + private final boolean isFinal; + + // Validation + private ErrorType errorType = ErrorType.NONE; + private String errorMessage; + private String requiredType; + private String providedType; + + private ScopeInfo scopeInfo; + + public AssignmentInfo(String targetName, int statementStart, int lhsStart, int lhsEnd, + TypeInfo targetType, int rhsStart, int rhsEnd, + TypeInfo sourceType, String sourceExpr, + TypeInfo receiverType, java.lang.reflect.Field reflectionField, + boolean isFinal) { + this.targetName = targetName; + this.statementStart = statementStart; + this.lhsStart = lhsStart; + this.lhsEnd = lhsEnd; + this.targetType = targetType; + this.rhsStart = rhsStart; + this.rhsEnd = rhsEnd; + this.sourceType = sourceType; + this.sourceExpr = sourceExpr; + this.receiverType = receiverType; + this.reflectionField = reflectionField; + this.isFinal = isFinal; + } + + /** + * Factory method to create an AssignmentInfo representing a duplicate declaration error. + * Only the LHS (variable name) position is relevant for underlining. + */ + public static AssignmentInfo duplicateDeclaration(String varName, int nameStart, int nameEnd, String errorMessage) { + AssignmentInfo info = new AssignmentInfo( + varName, + nameStart, // statementStart = nameStart for underline positioning + nameStart, // lhsStart + nameEnd, // lhsEnd + null, // targetType + -1, // rhsStart (not applicable) + -1, // rhsEnd (not applicable) + null, // sourceType + null, // sourceExpr + null, // receiverType + null, // reflectionField + false // isFinal + ); + info.setError(ErrorType.DUPLICATE_DECLARATION, errorMessage); + return info; + } + + // ==================== VALIDATION ==================== + + /** + * Validate this assignment. + * Checks type compatibility, final status, and access modifiers. + */ + public void validate() { + // Check for final field reassignment from reflection + if (reflectionField != null && Modifier.isFinal(reflectionField.getModifiers())) { + setError(ErrorType.FINAL_REASSIGNMENT, + "Cannot assign a value to final variable '" + targetName + "'"); + return; + } + + // Check for final field reassignment from FieldInfo (script-defined finals) + if (isFinal) { + setError(ErrorType.FINAL_REASSIGNMENT, + "Cannot assign a value to final variable '" + targetName + "'"); + return; + } + + // Check access modifiers for chained field access + if (reflectionField != null && receiverType != null) { + int mods = reflectionField.getModifiers(); + if (Modifier.isPrivate(mods)) { + setError(ErrorType.PRIVATE_ACCESS, + "'" + targetName + "' has private access in '" + receiverType.getFullName() + "'"); + return; + } + } + + // Check type compatibility + if (targetType != null && sourceType != null) { + if (!TypeChecker.isTypeCompatible(targetType, sourceType)) { + this.requiredType = MethodCallInfo.getTypeDisplayName(targetType); + this.providedType = MethodCallInfo.getTypeDisplayName(sourceType); + setError(ErrorType.TYPE_MISMATCH, buildTypeMismatchMessage()); + } + } + } + + /** + * Build a formatted type mismatch error message (IntelliJ style). + */ + private String buildTypeMismatchMessage() { + return "Provided type: " + providedType + "\nRequired: " + requiredType; + } + + private void setError(ErrorType type, String message) { + this.errorType = type; + this.errorMessage = message; + } + + // ==================== POSITION CHECKS ==================== + + /** + * Check if the given global position falls within the LHS (target) of this assignment. + */ + public boolean containsLhsPosition(int position) { + return position >= statementStart && position < lhsEnd; + } + + /** + * Check if the given global position falls within the RHS (source) of this assignment. + */ + public boolean containsRhsPosition(int position) { + return position >= rhsStart && position <= rhsEnd; + } + + /** + * Check if the given global position falls anywhere in this assignment (LHS or RHS). + */ + public boolean containsPosition(int position) { + return position >= statementStart && position <= rhsEnd; + } + + // ==================== ERROR TYPE CHECKS ==================== + + /** + * Check if this is an LHS error (final reassignment, access errors, duplicate declarations). + * These errors should underline the LHS. + */ + public boolean isLhsError() { + return errorType == ErrorType.FINAL_REASSIGNMENT || + errorType == ErrorType.PRIVATE_ACCESS || + errorType == ErrorType.PROTECTED_ACCESS || + errorType == ErrorType.STATIC_CONTEXT_ERROR || + errorType == ErrorType.DUPLICATE_DECLARATION; + } + + /** + * Check if this is an RHS error (type mismatch). + * These errors should underline the RHS. + */ + public boolean isRhsError() { + return false; + } + + public boolean isFullLineError() { + return errorType == ErrorType.TYPE_MISMATCH; + } + + // ==================== GETTERS ==================== + + public String getTargetName() { return targetName; } + public int getStatementStart() { return statementStart; } + public int getLhsStart() { return lhsStart; } + public int getLhsEnd() { return lhsEnd; } + public TypeInfo getTargetType() { return targetType; } + public int getRhsStart() { return rhsStart; } + public int getRhsEnd() { return rhsEnd; } + public TypeInfo getSourceType() { return sourceType; } + public String getSourceExpr() { return sourceExpr; } + public TypeInfo getReceiverType() { return receiverType; } + public java.lang.reflect.Field getReflectionField() { return reflectionField; } + + public ErrorType getErrorType() { return errorType; } + public String getErrorMessage() { return errorMessage; } + public String getRequiredType() { return requiredType; } + public String getProvidedType() { return providedType; } + + public boolean hasError() { return errorType != ErrorType.NONE; } + public boolean hasTypeMismatch() { return errorType == ErrorType.TYPE_MISMATCH; } + public boolean hasFinalReassignment() { return errorType == ErrorType.FINAL_REASSIGNMENT; } + public boolean hasAccessError() { return errorType == ErrorType.PRIVATE_ACCESS || errorType == ErrorType.PROTECTED_ACCESS; } + + public ScopeInfo getScopeInfo() { return scopeInfo; } + public void setScopeInfo(ScopeInfo scopeInfo) { this.scopeInfo = scopeInfo; } + + @Override + public String toString() { + return "AssignmentInfo{" + + "target='" + targetName + "', " + + "stmt=" + statementStart + ", " + + "lhs=[" + lhsStart + "-" + lhsEnd + "], " + + "rhs=[" + rhsStart + "-" + rhsEnd + "], " + + "targetType=" + targetType + ", " + + "sourceType=" + sourceType + ", " + + "error=" + errorType + + '}'; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/EnumConstantInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/EnumConstantInfo.java new file mode 100644 index 000000000..031c733cc --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/EnumConstantInfo.java @@ -0,0 +1,318 @@ +package noppes.npcs.client.gui.util.script.interpreter.field; + +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Represents an enum constant declaration with its constructor call. + * Combines a FieldInfo (the constant itself) with a MethodCallInfo (the constructor call validation). + * This allows us to reuse existing method call validation logic for enum constructor matching. + */ +public class EnumConstantInfo { + + private final FieldInfo fieldInfo; + private final MethodCallInfo constructorCall; // Can be null if no args provided + private final TypeInfo enumType; + + public EnumConstantInfo(FieldInfo fieldInfo, MethodCallInfo constructorCall, TypeInfo enumType) { + this.fieldInfo = fieldInfo; + this.constructorCall = constructorCall; + this.enumType = enumType; + } + + /** + * Parse enum constants from an enum body. + * Returns a list of EnumConstantInfo objects, each representing one constant. + * + * @param enumType The enum type being parsed + * @param bodyText The text content of the enum body + * @param bodyOffset The absolute offset where the enum body starts + * @param keywordPattern Pattern to detect Java keywords (to skip them) + * @return List of parsed enum constants + */ + public static List parseEnumConstants( + ScriptTypeInfo enumType, + String bodyText, + int bodyOffset, + Pattern keywordPattern) { + + List constants = new ArrayList<>(); + + // Find where enum constants end (first semicolon not in parens, or first method/field declaration) + int constantsEnd = findEnumConstantsEnd(bodyText); + if (constantsEnd <= 0) { + // No semicolon found - entire body might be constants + constantsEnd = bodyText.length(); + } + + // Pattern to match enum constants: NAME or NAME() or NAME(args) + Pattern constantPattern = Pattern.compile( + "([A-Za-z_][a-zA-Z0-9_]*)\\s*(\\(([^)]*)\\))?"); + + Matcher m = constantPattern.matcher(bodyText); + int lastEnd = 0; + + while (m.find()) { + // Skip if we're past the constants section + if (m.start() >= constantsEnd) { + break; + } + + int absPos = bodyOffset + m.start(); + if (ScriptDocument.INSTANCE.isExcluded(absPos)) { + lastEnd = m.end(); + continue; + } + + // Check if this is at a valid position (after comma or at start) + String beforeMatch = bodyText.substring(lastEnd, m.start()).trim(); + if (!beforeMatch.isEmpty() && !beforeMatch.equals(",")) { + // Not a valid enum constant position - might be inside parens + continue; + } + + String constantName = m.group(1); + String argsClause = m.group(2); // includes parens if present + String args = m.group(3); // just the args without parens + + // Skip keywords + if (keywordPattern.matcher(constantName).matches()) { + lastEnd = m.end(); + continue; + } + + // Determine init range (the constructor arguments) + int initStart = -1; + int initEnd = -1; + + // Create MethodCallInfo for constructor validation if args present + MethodCallInfo constructorCall = null; + if (argsClause != null && !argsClause.isEmpty()) { + initStart = bodyOffset + m.start(2); // Position of '(' + initEnd = bodyOffset + m.end(2) - 1; // Position after ')' + + constructorCall = createConstructorCall( + enumType, + constantName, + absPos, + initStart, + initEnd + ); + } else if (enumType.hasConstructors()) { + // No args provided, but enum has constructors - validate against no-arg constructor + initStart = absPos + constantName.length(); + initEnd = initStart; + + constructorCall = createConstructorCall( + enumType, + constantName, + absPos, + initStart, + initEnd + ); + } + + + // Create FieldInfo for the enum constant + FieldInfo fieldInfo = FieldInfo.enumConstant( + constantName, + enumType, + absPos, + initStart, + initEnd, + null + ); + + EnumConstantInfo constantInfo = new EnumConstantInfo(fieldInfo, constructorCall, enumType); + fieldInfo.setEnumConstantInfo(constantInfo); + constants.add(constantInfo); + + lastEnd = m.end(); + } + + return constants; + } + + /** + * Create a MethodCallInfo for an enum constant's constructor call. + * Validates the arguments against available constructors. + */ + private static MethodCallInfo createConstructorCall( + ScriptTypeInfo enumType, + String constantName, + int constantStart, + int openParenPos, + int closeParenPos) { + + List constructors = enumType.getConstructors(); + + // Parse arguments - pass absolute positions (bodyOffset accounts for the offset into the document) + List arguments = ScriptDocument.INSTANCE.parseMethodArguments( + openParenPos + 1, + closeParenPos, + null, + enumType + ); + + // Find matching constructor + MethodInfo matchedConstructor = null; + List candidates = new ArrayList<>(); + + for (MethodInfo constructor : constructors) { + candidates.add(constructor); + if (constructor.getParameterCount() == arguments.size()) { + matchedConstructor = constructor; + break; + } + } + + // Create MethodCallInfo + MethodCallInfo callInfo = new MethodCallInfo( + constantName, // Use constant name as "method" name + constantStart, + openParenPos, + openParenPos, + closeParenPos, + arguments, + enumType, // Receiver is the enum type + matchedConstructor + ); + + + callInfo.setConstructor(true); + callInfo.validate(); + return callInfo; + } + + /** + * Create EnumConstantInfo from a reflection-based enum constant. + * Used for enum constants from external libraries (via reflection). + * + * @param constantName The name of the enum constant + * @param enumType The enum type this constant belongs to + * @return EnumConstantInfo representing this constant, or null if not found + */ + public static EnumConstantInfo fromReflection(String constantName, TypeInfo enumType, Field javaField) { + if (enumType == null || enumType.getJavaClass() == null || !enumType.getJavaClass().isEnum()) { + return null; + } + + try { + FieldInfo fieldInfo = FieldInfo.enumConstant( + constantName, + enumType, + -1, // No declaration offset for reflection-based constants + -1, + -1, + javaField + ); + + EnumConstantInfo enumInfo = new EnumConstantInfo(fieldInfo, null, enumType); + fieldInfo.setEnumConstantInfo(enumInfo); + return enumInfo; + } catch (SecurityException e) { + // Constant not found or access denied + return null; + } + } + + /** + * Find where enum constants section ends. + * Returns the position of the first semicolon that's not inside parentheses, + * or the position of the first method/field declaration. + */ + private static int findEnumConstantsEnd(String bodyText) { + int parenDepth = 0; + boolean foundConstant = false; + + for (int i = 0; i < bodyText.length(); i++) { + char c = bodyText.charAt(i); + + if (c == '(') { + parenDepth++; + } else if (c == ')') { + parenDepth--; + } else if (c == ';' && parenDepth == 0) { + return i; + } else if (c == '{' && parenDepth == 0) { + // Start of method body - constants end before this + return findStatementStart(bodyText, i); + } + + // Track if we've found at least one identifier (potential constant) + if (Character.isJavaIdentifierStart(c)) { + foundConstant = true; + } + } + + // If we found constants but no semicolon, return the full length + return foundConstant ? bodyText.length() : -1; + } + + /** + * Find the start of a statement by going backwards from a position. + */ + private static int findStatementStart(String text, int fromPos) { + int pos = fromPos - 1; + int parenDepth = 0; + + while (pos >= 0) { + char c = text.charAt(pos); + if (c == ')') + parenDepth++; + else if (c == '(') + parenDepth--; + else if ((c == ',' || c == ';' || c == '{' || c == '}') && parenDepth == 0) { + return pos + 1; + } + pos--; + } + return 0; + } + + // ==================== GETTERS ==================== + + public FieldInfo getFieldInfo() { + return fieldInfo; + } + + public MethodCallInfo getConstructorCall() { + return constructorCall; + } + + public TypeInfo getEnumType() { + return enumType; + } + + public String getName() { + return fieldInfo.getName(); + } + + public int getDeclarationOffset() { + return fieldInfo.getDeclarationOffset(); + } + + /** + * Check if this enum constant has any errors (constructor mismatch, etc). + */ + public boolean hasError() { + return (constructorCall != null && constructorCall.hasError()); + } + + /** + * Get the error message if any. + */ + public String getErrorMessage() { + return null; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldAccessInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldAccessInfo.java new file mode 100644 index 000000000..fc87898f7 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldAccessInfo.java @@ -0,0 +1,152 @@ +package noppes.npcs.client.gui.util.script.interpreter.field; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +/** + * Metadata for field access validation. + * Parallel to MethodCallInfo but for field accesses like `obj.field` or `Class.staticField`. + */ +public class FieldAccessInfo { + + /** + * Validation error type for field accesses. + */ + public enum ErrorType { + NONE, + TYPE_MISMATCH, // Field type doesn't match expected type (e.g., assignment LHS) + UNRESOLVED_FIELD, // Field doesn't exist on the receiver type + STATIC_ACCESS_ERROR // Trying to access instance field statically or vice versa + } + + private final String fieldName; + private final int fieldNameStart; + private final int fieldNameEnd; + private final TypeInfo receiverType; // The type on which this field is accessed + private final FieldInfo resolvedField; // The resolved field (null if unresolved) + private final boolean isStaticAccess; // True if this is Class.field style access + private TypeInfo expectedType; // Expected field type (from assignment LHS, etc.) + + private ErrorType errorType = ErrorType.NONE; + private String errorMessage; + + public FieldAccessInfo(String fieldName, int fieldNameStart, int fieldNameEnd, + TypeInfo receiverType, FieldInfo resolvedField, boolean isStaticAccess) { + this.fieldName = fieldName; + this.fieldNameStart = fieldNameStart; + this.fieldNameEnd = fieldNameEnd; + this.receiverType = receiverType; + this.resolvedField = resolvedField; + this.isStaticAccess = isStaticAccess; + } + + // Getters + public String getFieldName() { + return fieldName; + } + + public int getFieldNameStart() { + return fieldNameStart; + } + + public int getFieldNameEnd() { + return fieldNameEnd; + } + + public TypeInfo getReceiverType() { + return receiverType; + } + + public FieldInfo getResolvedField() { + return resolvedField; + } + + public boolean isStaticAccess() { + return isStaticAccess; + } + + public boolean isEnumConstantAccess() { + return resolvedField != null && resolvedField.isEnumConstant(); + } + + public TypeInfo getExpectedType() { + return expectedType; + } + + public void setExpectedType(TypeInfo expectedType) { + this.expectedType = expectedType; + } + + public ErrorType getErrorType() { + return errorType; + } + + public String getErrorMessage() { + return errorMessage; + } + + /** + * Validate this field access. + * Checks type compatibility with expected type. + */ + public void validate() { + // Check if field was resolved + if (resolvedField == null) { + setError(ErrorType.UNRESOLVED_FIELD, "Cannot resolve field '" + fieldName + "'"); + return; + } + + // Check return type compatibility with expected type (e.g., assignment LHS) + if (expectedType != null && resolvedField != null) { + TypeInfo fieldType = resolvedField.getTypeInfo(); + if (fieldType != null && !TypeChecker.isTypeCompatible(expectedType, fieldType)) { + //extra space is necessary for alignment + //setError(ErrorType.TYPE_MISMATCH, "Provided type: " + fieldType.getSimpleName()+ + //"\nRequired: " + expectedType.getSimpleName()); + } + } + } + + private void setError(ErrorType type, String message) { + this.errorType = type; + this.errorMessage = message; + } + + /** + * Check if this field access has any validation error. + */ + public boolean hasError() { + return errorType != ErrorType.NONE; + } + + /** + * Check if this is a type mismatch error. + */ + public boolean hasTypeMismatch() { + return errorType == ErrorType.TYPE_MISMATCH; + } + + /** + * Check if this is an unresolved field error. + */ + public boolean hasUnresolvedField() { + return errorType == ErrorType.UNRESOLVED_FIELD; + } + + /** + * Check if this is a static access error. + */ + public boolean hasStaticAccessError() { + return errorType == ErrorType.STATIC_ACCESS_ERROR; + } + + @Override + public String toString() { + return "FieldAccessInfo{" + + "fieldName='" + fieldName + "', " + + "receiverType=" + receiverType + ", " + + "resolvedField=" + resolvedField + ", " + + "errorType=" + errorType + + '}'; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldInfo.java new file mode 100644 index 000000000..78f342db5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldInfo.java @@ -0,0 +1,643 @@ +package noppes.npcs.client.gui.util.script.interpreter.field; + +import noppes.npcs.client.gui.util.script.ScopeInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSFieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.bridge.DtsJavaBridge; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.GenericContext; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Metadata for a field (variable) declaration or reference. + * Tracks the field name, type, scope, and declaration location. + * Also tracks all assignments made to this field throughout the script. + */ +public final class FieldInfo { + + public enum Scope { + GLOBAL, // Class-level field + LOCAL, // Local variable inside a method + PARAMETER, // Method parameter + ENUM_CONSTANT // Enum constant value + } + + private final String name; + private final Scope scope; + private final TypeInfo declaredType; // The declared type (e.g., String, List) + private final int declarationOffset; // Where this field was declared in the source + private final boolean resolved; + private final String documentation; // Javadoc/comment documentation for this field + private JSDocInfo jsDocInfo; // Parsed JSDoc info for this method (may be null) + + // Initialization value range (for displaying "= value" in hover info) + private final int initStart; // Position of '=' or -1 if no initializer + private final int initEnd; // Position after initializer (before ';') or -1 + + // For local/parameter fields, track the containing method + private final MethodInfo containingMethod; + + // Modifiers for script-defined fields + private final int modifiers; // Java Modifier flags (e.g., Modifier.FINAL) + + // Reflection field for external types + private final Field reflectionField; + + private ScopeInfo scopeInfo; + + // Assignments to this field (populated after parsing) + private final List assignments = new ArrayList<>(); + + // Declaration assignment (for initial value validation) + private AssignmentInfo declarationAssignment; + + // Enum constant specific info + private EnumConstantInfo enumConstantInfo; + + private boolean isVarArg = false; + + // Type inference support (for JavaScript "any" typed variables) + // When a variable is declared without type (var x;), it starts as "any" but can be + // refined through assignments or JSDoc comments + private TypeInfo inferredType; + + private FieldInfo(String name, Scope scope, TypeInfo declaredType, + int declarationOffset, boolean resolved, MethodInfo containingMethod, + String documentation, int initStart, int initEnd, int modifiers, + Field reflectionField) { + this.name = name; + this.scope = scope; + this.declaredType = declaredType; + this.declarationOffset = declarationOffset; + this.resolved = resolved; + this.containingMethod = containingMethod; + this.documentation = documentation; + this.initStart = initStart; + this.initEnd = initEnd; + this.modifiers = modifiers; + this.reflectionField = reflectionField; + } + + // Factory methods + public static FieldInfo globalField(String name, TypeInfo type, int declOffset) { + return new FieldInfo(name, Scope.GLOBAL, type, declOffset, type != null && type.isResolved(), null, null, -1, + -1, 0, null); + } + + public static FieldInfo globalField(String name, TypeInfo type, int declOffset, String documentation) { + return new FieldInfo(name, Scope.GLOBAL, type, declOffset, type != null && type.isResolved(), null, + documentation, -1, -1, 0, null); + } + + public static FieldInfo globalField(String name, TypeInfo type, int declOffset, String documentation, int initStart, int initEnd) { + return new FieldInfo(name, Scope.GLOBAL, type, declOffset, type != null && type.isResolved(), null, + documentation, initStart, initEnd, 0, null); + } + + public static FieldInfo globalField(String name, TypeInfo type, int declOffset, String documentation, int initStart, + int initEnd, int modifiers) { + return new FieldInfo(name, Scope.GLOBAL, type, declOffset, type != null && type.isResolved(), null, + documentation, initStart, initEnd, modifiers, null); + } + + public static FieldInfo localField(String name, TypeInfo type, int declOffset, MethodInfo method) { + return new FieldInfo(name, Scope.LOCAL, type, declOffset, type != null && type.isResolved(), method, null, -1, + -1, 0, null); + } + + public static FieldInfo localField(String name, TypeInfo type, int declOffset, MethodInfo method, int initStart, int initEnd) { + return new FieldInfo(name, Scope.LOCAL, type, declOffset, type != null && type.isResolved(), method, null, + initStart, initEnd, 0, null); + } + + public static FieldInfo localField(String name, TypeInfo type, int declOffset, MethodInfo method, int initStart, + int initEnd, int modifiers) { + return new FieldInfo(name, Scope.LOCAL, type, declOffset, type != null && type.isResolved(), method, null, + initStart, initEnd, modifiers, null); + } + + public static FieldInfo parameter(String name, TypeInfo type, int declOffset, MethodInfo method) { + return new FieldInfo(name, Scope.PARAMETER, type, declOffset, type != null && type.isResolved(), method, null, + -1, -1, 0, null); + } + + public static FieldInfo unresolved(String name, Scope scope) { + return new FieldInfo(name, scope, null, -1, false, null, null, -1, -1, 0, null); + } + + /** + * Create a FieldInfo from reflection data for method parameters. + */ + public static FieldInfo reflectionParam(String name, TypeInfo type) { + return new FieldInfo(name, Scope.PARAMETER, type, -1, true, null, null, -1, -1, 0, null); + } + + /** + * Create a FieldInfo for a synthetic/external field. + * Used for built-in types like Nashorn's Java object. + */ + public static FieldInfo external(String name, TypeInfo type, String documentation, int modifiers) { + return new FieldInfo(name, Scope.GLOBAL, type, -1, true, null, documentation, -1, -1, modifiers, null); + } + + /** + * Create a FieldInfo from reflection data for a class field. + * Preserves generic type information like List. + */ + public static FieldInfo fromReflection(Field field, TypeInfo containingType) { + String name = field.getName(); + // Use getGenericType() to preserve generic information + TypeInfo type = TypeInfo.fromGenericType(field.getGenericType()); + if (type == null) { + type = TypeInfo.fromClass(field.getType()); + } + + // If the receiver is parameterized, substitute class type variables in the field type + if (GenericContext.hasGenerics(containingType)) + type = GenericContext.forReceiver(containingType).substitute(type); + + // Check if this is an enum constant + if (field.isEnumConstant()) { + // Create enum constant FieldInfo + EnumConstantInfo constantInfo = EnumConstantInfo.fromReflection(name, containingType,field); + if (constantInfo != null) + return constantInfo.getFieldInfo(); + } + + // Try to find matching JSFieldInfo to bridge over documentation + JSFieldInfo jsField = DtsJavaBridge.findMatchingField(field, containingType); + String documentation = null; + JSDocInfo jsDocInfo = null; + if (jsField != null) { + jsDocInfo = jsField.getJsDocInfo(); + String jsDocDesc = jsDocInfo != null ? jsDocInfo.getDescription() : null; + documentation = jsDocDesc != null ? jsDocDesc : jsField.getDocumentation(); + } + + FieldInfo fieldInfo = new FieldInfo(name, Scope.GLOBAL, type, -1, true, null, documentation, -1, -1, field.getModifiers(), field); + if (jsDocInfo != null) { + fieldInfo.setJSDocInfo(jsDocInfo); + } + return fieldInfo; + } + + /** + * Create a FieldInfo from a JSFieldInfo (parsed from .d.ts files). + * Used when resolving field access on JavaScript types. + * + * @param jsField The JavaScript field info from the type registry + * @param containingType The TypeInfo that owns this field + * @return A FieldInfo representing the JavaScript field + */ + public static FieldInfo fromJSField(JSFieldInfo jsField, TypeInfo containingType) { + String name = jsField.getName(); + + TypeInfo type = jsField.getResolvedType(containingType); + if (type == null || !type.isResolved()) { + type = resolveJSType(jsField.getType()); + } + + // JS fields are public by default, readonly maps to final + int modifiers = Modifier.PUBLIC; + if (jsField.isReadonly()) { + modifiers |= Modifier.FINAL; + } + if (jsField.isStatic()) { + modifiers |= Modifier.STATIC; + } + + // Use documentation if available + JSDocInfo jsDocInfo = jsField.getJsDocInfo(); + String jsDocDesc = jsDocInfo != null ? jsDocInfo.getDescription() : null; + String documentation = jsDocDesc != null ? jsDocDesc : jsField.getDocumentation(); + + FieldInfo fieldInfo = new FieldInfo(name, Scope.GLOBAL, type, -1, true, null, documentation, -1, -1, modifiers, null); + fieldInfo.setJSDocInfo(jsDocInfo); + return fieldInfo; + } + + /** + * Resolves a JavaScript type name to a TypeInfo. + * Handles primitives, mapped types, and custom types from the registry. + */ + private static TypeInfo resolveJSType(String jsTypeName) { + if (jsTypeName == null || jsTypeName.isEmpty() || "void".equals(jsTypeName)) { + return TypeInfo.fromPrimitive("void"); + } + + // Handle JS primitives + switch (jsTypeName) { + case "string": + return TypeInfo.fromClass(String.class); + case "number": + return TypeInfo.fromClass(double.class); + case "boolean": + return TypeInfo.fromClass(boolean.class); + case "any": + return TypeInfo.fromClass(Object.class); + case "void": + return TypeInfo.fromPrimitive("void"); + } + + // Handle array types + if (jsTypeName.endsWith("[]")) { + String elementType = jsTypeName.substring(0, jsTypeName.length() - 2); + TypeInfo elementTypeInfo = resolveJSType(elementType); + return TypeInfo.arrayOf(elementTypeInfo); + } + + // Try to resolve from the JS type registry + JSTypeRegistry registry = JSTypeRegistry.getInstance(); + if (registry != null) { + JSTypeInfo jsTypeInfo = registry.getType(jsTypeName); + if (jsTypeInfo != null) { + return TypeInfo.fromJSTypeInfo(jsTypeInfo); + } + } + + // Fallback: unresolved type + return TypeInfo.unresolved(jsTypeName, jsTypeName); + } + + /** + * Create a FieldInfo for an enum constant. + * @param name The constant name (e.g., "NORTH") + * @param type The enum type itself + * @param declOffset The declaration position + * @param initStart The position of '(' if args present, else -1 + * @param initEnd The position after ')' if args present, else -1 + */ + public static FieldInfo enumConstant(String name, TypeInfo type, int declOffset, int initStart, int initEnd,Field javaField) { + // Enum constants are implicitly public static final + int modifiers = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; + return new FieldInfo(name, Scope.ENUM_CONSTANT, type, declOffset, true, null, null, initStart, initEnd, + modifiers, javaField); + } + + // ==================== ENUM HANDLING ==================== + + public void setEnumConstantInfo(EnumConstantInfo enumConstantInfo) { + this.enumConstantInfo = enumConstantInfo; + } + + public EnumConstantInfo getEnumInfo() { + return enumConstantInfo; + } + /** + * Check if this is an enum constant. + */ + public boolean isEnumConstant() { + return scope == Scope.ENUM_CONSTANT; + } + + + // ==================== ASSIGNMENT MANAGEMENT ==================== + + /** + * Add an assignment to this field. + */ + public void addAssignment(AssignmentInfo assignment) { + assignments.add(assignment); + } + + /** + * Get all assignments to this field (unmodifiable). + */ + public List getAssignments() { + return Collections.unmodifiableList(assignments); + } + + /** + * Set the declaration assignment (initial value assignment). + */ + public void setDeclarationAssignment(AssignmentInfo assignment) { + this.declarationAssignment = assignment; + } + + /** + * Get the declaration assignment (initial value assignment). + * Returns null if there was no initializer or it hasn't been validated yet. + */ + public AssignmentInfo getDeclarationAssignment() { + return declarationAssignment; + } + + /** + * Find an assignment that contains the given position. + * Returns null if no assignment contains this position. + * Prioritizes LHS matches over RHS matches. + */ + public AssignmentInfo findAssignmentAtPosition(int position) { + // Check declaration assignment first + if (declarationAssignment != null && declarationAssignment.containsPosition(position)) { + // Prioritize LHS match + if (declarationAssignment.containsLhsPosition(position)) { + return declarationAssignment; + } + } + + // Check other assignments for LHS matches first (more specific) + for (AssignmentInfo assign : assignments) { + if (assign.containsLhsPosition(position)) { + return assign; + } + } + + // Then check RHS matches (less specific - might just be a reference in the value) + if (declarationAssignment != null && declarationAssignment.containsRhsPosition(position)) { + return declarationAssignment; + } + + for (AssignmentInfo assign : assignments) { + if (assign.containsRhsPosition(position)) { + return assign; + } + } + + return null; + } + + /** + * Get all errored assignments for this field. + */ + public List getErroredAssignments() { + List errored = new ArrayList<>(); + + // Include declaration assignment if it has an error + if (declarationAssignment != null && declarationAssignment.hasError()) { + errored.add(declarationAssignment); + } + + // Include all other assignments with errors + for (AssignmentInfo assign : assignments) { + if (assign.hasError()) { + errored.add(assign); + } + } + return errored; + } + + /** + * Clear all assignments (for re-parsing). + */ + public void clearAssignments() { + assignments.clear(); + declarationAssignment = null; + } + + // ==================== MODIFIER CHECKS ==================== + + /** + * Check if this field is declared as final. + * Works for both script-defined fields (via modifiers) and reflection fields. + */ + public boolean isFinal() { + if (reflectionField != null) + return Modifier.isFinal(reflectionField.getModifiers()); + + return Modifier.isFinal(modifiers); + } + + /** + * Check if this field is declared as static. + */ + public boolean isStatic() { + if (reflectionField != null) + return Modifier.isStatic(reflectionField.getModifiers()); + + return Modifier.isStatic(modifiers); + } + + /** + * Check if this field is declared as private. + */ + public boolean isPrivate() { + if (reflectionField != null) + return Modifier.isPrivate(reflectionField.getModifiers()); + + return Modifier.isPrivate(modifiers); + } + + /** + * Check if this field is declared as protected. + */ + public boolean isProtected() { + if (reflectionField != null) + return Modifier.isProtected(reflectionField.getModifiers()); + + return Modifier.isProtected(modifiers); + } + + /** + * Check if this field is declared as public. + */ + public boolean isPublic() { + if (reflectionField != null) + return Modifier.isPublic(reflectionField.getModifiers()); + + return Modifier.isPublic(modifiers); + } + + /** + * Get the raw modifiers value. + */ + public int getModifiers() { + if (reflectionField != null) + return reflectionField.getModifiers(); + + return modifiers; + } + + /** + * Get the reflection field, if available. + */ + public java.lang.reflect.Field getReflectionField() { + return reflectionField; + } + + // ==================== TYPE INFERENCE ==================== + + /** + * Get the inferred type for this field. + * This is set when a variable declared as "any" has its type refined through + * assignment analysis or JSDoc comments. + */ + public TypeInfo getInferredType() { + return inferredType; + } + + /** + * Set the inferred type for this field. + * Used when type inference determines a more specific type than the declared type. + * @param inferredType The refined type based on assignments or JSDoc + */ + public void setVarArg(boolean isVarArg) { this.isVarArg = isVarArg; } + public boolean isVarArg() { return isVarArg; } + + public void setInferredType(TypeInfo inferredType) { + this.inferredType = inferredType; + } + + /** + * Check if this field has a type that can be refined (currently "any" type). + */ + public boolean canInferType() { + return declaredType != null && "any".equals(declaredType.getFullName()); + } + + /** + * Get the effective type for this field, considering inference. + * Returns inferredType if available, otherwise declaredType. + */ + public TypeInfo getEffectiveType() { + if (inferredType != null) { + return inferredType; + } + return declaredType; + } + + // ==================== BASIC GETTERS ==================== + + public String getName() { return name; } + public Scope getScope() { return scope; } + public TypeInfo getDeclaredType() { return declaredType; } + public TypeInfo getTypeInfo() { + // Return the effective type (inferred if available, otherwise declared) + return getEffectiveType(); + } + public int getDeclarationOffset() { return declarationOffset; } + public boolean isResolved() { + // Check if we have any resolved type (declared or inferred) + TypeInfo effectiveType = getEffectiveType(); + return effectiveType != null && effectiveType.isResolved(); + } + public MethodInfo getContainingMethod() { return containingMethod; } + public String getDocumentation() { return documentation; } + public JSDocInfo getJSDocInfo() { return jsDocInfo; } + public void setJSDocInfo(JSDocInfo jsDocInfo) { this.jsDocInfo = jsDocInfo; } + + /** + * Create a copy of this field with its declared type substituted using the given context. + * Returns {@code this} unchanged if the context is null, the declared type is null, + * or substitution produces the same type (identity check). + * + * Used when a generic type is parameterized (e.g., {@code Box}) and its raw fields + * (declared with type variables like T) need to reflect the concrete type arguments. + * + * Example: for {@code class Box { T value; }}, calling this on the raw field {@code value: T} + * with a context binding {@code T → String} produces {@code value: String}. + * + * @param context the generic context containing type variable bindings; if null, returns {@code this} unchanged + * @return a new FieldInfo with the substituted declared type, or {@code this} if no substitution occurred + */ + public FieldInfo substituteTypeParams(GenericContext context) { + if (context == null || declaredType == null) { + return this; + } + TypeInfo subType = context.substitute(declaredType); + if (subType == declaredType) { + return this; + } + FieldInfo result = new FieldInfo(name, scope, subType, declarationOffset, resolved, + containingMethod, documentation, initStart, initEnd, modifiers, reflectionField); + result.jsDocInfo = this.jsDocInfo; + result.scopeInfo = this.scopeInfo; + result.isVarArg = this.isVarArg; + result.inferredType = this.inferredType; + return result; + } + + public int getInitStart() { return initStart; } + public int getInitEnd() { return initEnd; } + public boolean hasInitializer() { return initStart >= 0 && initEnd > initStart; } + + public boolean isGlobal() { return scope == Scope.GLOBAL; } + public boolean isLocal() { return scope == Scope.LOCAL; } + public boolean isParameter() { return scope == Scope.PARAMETER; } + + /** + * Check if a reference at the given position can see this field. + * For local variables, they're only visible after their declaration. + */ + public boolean isVisibleAt(int position) { + if (scopeInfo != null && !scopeInfo.containsPosition(position)) { + return false; + } + if (scope == Scope.GLOBAL || scope == Scope.PARAMETER) { + return true; // Always visible in their scope + } + // Local variables are only visible after declaration + return position >= declarationOffset; + } + + public ScopeInfo getScopeInfo() { return scopeInfo; } + public void setScopeInfo(ScopeInfo scopeInfo) { this.scopeInfo = scopeInfo; } + + /** + * Get the appropriate TokenType for highlighting this field. + */ + public TokenType getTokenType() { + if (!resolved) { + return TokenType.UNDEFINED_VAR; + } + switch (scope) { + case GLOBAL: + // Static final fields get special highlighting + if (isStatic() && isFinal()) { + return TokenType.STATIC_FINAL_FIELD; + } + return TokenType.GLOBAL_FIELD; + case LOCAL: + return TokenType.LOCAL_FIELD; + case PARAMETER: + return TokenType.PARAMETER; + case ENUM_CONSTANT: + return TokenType.ENUM_CONSTANT; + default: + return TokenType.VARIABLE; + } + } + + @Override + public String toString() { + return "FieldInfo{" + name + ", " + scope + ", type=" + declaredType + ", final=" + isFinal() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FieldInfo fieldInfo = (FieldInfo) o; + return name.equals(fieldInfo.name) && scope == fieldInfo.scope; + } + + @Override + public int hashCode() { + return name.hashCode() * 31 + scope.ordinal(); + } + + /** + * Wrapper class that holds both FieldInfo and MethodCallInfo for a variable usage. + * This is used when a variable is used as an argument to a method call. + */ + public static class ArgInfo { + public final FieldInfo fieldInfo; + public final MethodCallInfo methodCallInfo; + + public ArgInfo(FieldInfo fieldInfo, MethodCallInfo methodCallInfo) { + this.fieldInfo = fieldInfo; + this.methodCallInfo = methodCallInfo; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/GutterIconRenderer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/GutterIconRenderer.java new file mode 100644 index 000000000..69014acc9 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/GutterIconRenderer.java @@ -0,0 +1,304 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.GuiUtil; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +/** + * Renders gutter icons for method inheritance (override/implements) in the script editor. + * + * Renders IntelliJ-style tooltips when hovering over gutter icons: + * - Background + border matching TokenHoverRenderer style + * - Colored declaration showing which class/interface the method overrides/implements + * - Uses the same token highlighting system for type names + */ +public class GutterIconRenderer { + + // ==================== CONSTANTS ==================== + + /** Texture resource for script icons (64x32: first 32x32 = override, second 32x32 = implements) */ + private static final ResourceLocation SCRIPT_ICONS = new ResourceLocation("customnpcs", + "textures/gui/script/icons.png"); + + /** Icon size when rendered in the gutter (scaled from 32x32) */ + private static final int GUTTER_ICON_SIZE = 10; + + /** Extra gutter width to accommodate inheritance icons */ + public static final int ICON_GUTTER_WIDTH = 12; + + /** Padding inside the tooltip box */ + private static final int PADDING = 6; + + /** Line spacing between rows */ + private static final int LINE_SPACING = 2; + + /** Vertical offset from mouse */ + private static final int VERTICAL_OFFSET = 10; + + // ==================== COLORS ==================== + + /** Background color (dark gray like IntelliJ) */ + private static final int BG_COLOR = 0xF0313335; + + /** Border color */ + private static final int BORDER_COLOR = 0xFF3C3F41; + + /** Info text color */ + private static final int INFO_COLOR = 0xFFA9B7C6; + + // ==================== RENDERING ==================== + + /** + * Render gutter icons for a range of lines. + * + * @param lineHeight Height of each line + * @param gutterX X position for the icon in the gutter + * @param gutterY Base Y position of the gutter + * @param renderStart First line index to render + * @param renderEnd Last line index to render + * @param scrolledLine Current scroll position + * @param stringYOffset Y offset for text positioning + * @param methods All methods in the document + * @param lines Line data for position calculation + * @param xMouse Mouse X position + * @param yMouse Mouse Y position + * @param fracPixels Fractional scroll offset + * @return The hovered method, or null if no icon is hovered + */ + public static MethodInfo renderIcons( + int lineHeight, + int gutterX, + int gutterY, + int renderStart, + int renderEnd, + int scrolledLine, + int stringYOffset, + List methods, + List lines, + int xMouse, + int yMouse, + float fracPixels) { + + if (methods == null || methods.isEmpty()) + return null; + + MethodInfo hoveredMethod = null; + float adjustedMouseY = yMouse + fracPixels; + + for (int lineIndex = renderStart; lineIndex <= renderEnd; lineIndex++) { + MethodInfo method = getMethodAtLine(lineIndex, methods, lines); + if (method == null || !method.hasInheritanceMarker()) + continue; + + int posY = gutterY + (lineIndex - scrolledLine) * lineHeight + stringYOffset; + int iconY = posY + (lineHeight - GUTTER_ICON_SIZE) / 2 - 1; + + // Draw the icon + renderIcon(gutterX, iconY, method.isOverride()); + + // Check for hover + int iconScaleOffsetX = -4; + int screenPosY = gutterY + (lineIndex - scrolledLine) * lineHeight; + if (xMouse >= gutterX + iconScaleOffsetX && xMouse < gutterX + GUTTER_ICON_SIZE + iconScaleOffsetX && + adjustedMouseY >= screenPosY && adjustedMouseY < screenPosY + lineHeight) { + hoveredMethod = method; + } + } + + return hoveredMethod; + } + + /** + * Render a single gutter icon. + */ + private static void renderIcon(int x, int y, boolean isOverride) { + int iconU = isOverride ? 0 : 32; + + Minecraft.getMinecraft().renderEngine.bindTexture(SCRIPT_ICONS); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + GL11.glPushMatrix(); + float scale = 2.0f, scaleOffsetX = -4, scaleOffsetY = -3.25f; + GL11.glScalef(scale, scale, scale); + GL11.glTranslatef(scaleOffsetX, scaleOffsetY, 0); + GuiUtil.drawScaledTexturedRect( + (int) (x / scale), (int) (y / scale), + iconU, 0, 32, 32, + GUTTER_ICON_SIZE, GUTTER_ICON_SIZE, + 64, 32 + ); + GL11.glPopMatrix(); + } + + /** + * Render the tooltip for a hovered gutter icon. + */ + public static void renderTooltip(MethodInfo method, int mouseX, int mouseY, int viewportX, int viewportWidth, + int viewportY, int viewportHeight) { + if (method == null) + return; + + // Build tooltip content + List segments = buildTooltipContent(method); + if (segments.isEmpty()) + return; + + int lineHeight = ClientProxy.Font.height(); + + // Calculate dimensions + int contentWidth = calculateContentWidth(segments); + int contentHeight = lineHeight; + int boxWidth = contentWidth + PADDING * 2; + int boxHeight = contentHeight + PADDING * 2; + + // Position tooltip + int tooltipX = mouseX + VERTICAL_OFFSET; + int tooltipY = mouseY - 5; + + // Clamp to viewport + int rightBound = viewportX + viewportWidth; + int bottomBound = viewportY + viewportHeight; + + if (tooltipX + boxWidth > rightBound) { + tooltipX = mouseX - boxWidth - 5; + } + if (tooltipX < viewportX) { + tooltipX = viewportX; + } + + if (tooltipY + boxHeight > bottomBound) { + tooltipY = bottomBound - boxHeight; + } + if (tooltipY < viewportY) { + tooltipY = viewportY; + } + + // Render tooltip box + renderTooltipBox(tooltipX, tooltipY, boxWidth, boxHeight, segments); + } + + // ==================== PRIVATE HELPERS ==================== + + /** + * Get the method that starts on the given line. + */ + private static MethodInfo getMethodAtLine(int lineIndex, List methods, List lines) { + if (lineIndex < 0 || lineIndex >= lines.size()) + return null; + + Object lineObj = lines.get(lineIndex); + int lineStart, lineEnd; + + try { + java.lang.reflect.Field startField = lineObj.getClass().getField("start"); + java.lang.reflect.Field endField = lineObj.getClass().getField("end"); + lineStart = startField.getInt(lineObj); + lineEnd = endField.getInt(lineObj); + } catch (Exception e) { + return null; + } + + for (MethodInfo method : methods) { + if (!method.hasInheritanceMarker()) + continue; + int nameOffset = method.getNameOffset(); + if (nameOffset >= lineStart && nameOffset < lineEnd) { + return method; + } + } + + return null; + } + + /** + * Build the tooltip content as colored text segments. + */ + private static List buildTooltipContent(MethodInfo method) { + List segments = new ArrayList<>(); + + if (method.isOverride()) { + TypeInfo overridesFrom = method.getOverridesFrom(); + segments.add(new TextSegment("Overrides method in ", INFO_COLOR)); + + if (overridesFrom != null) { + int color = TokenType.getColor(overridesFrom); + segments.add(new TextSegment(overridesFrom.getSimpleName(), color)); + } else { + segments.add(new TextSegment("parent class", INFO_COLOR)); + } + } else if (method.isImplements()) { + TypeInfo implementsFrom = method.getImplementsFrom(); + segments.add(new TextSegment("Implements method from ", INFO_COLOR)); + + if (implementsFrom != null) { + int color = TokenType.getColor(implementsFrom); + segments.add(new TextSegment(implementsFrom.getSimpleName(), color)); + } else { + segments.add(new TextSegment("interface", INFO_COLOR)); + } + } + + return segments; + } + + /** + * Calculate the width needed for the segments. + */ + private static int calculateContentWidth(List segments) { + int totalWidth = 0; + for (TextSegment segment : segments) { + totalWidth += ClientProxy.Font.width(segment.text); + } + return totalWidth; + } + + /** + * Render the tooltip box with background, border, and content. + */ + private static void renderTooltipBox(int x, int y, int width, int height, List segments) { + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Draw background + int paddedHeight = y + height - 4; + Gui.drawRect(x, y, x + width, paddedHeight, BG_COLOR); + + // Draw border + Gui.drawRect(x, y, x + width, y + 1, BORDER_COLOR); // Top + Gui.drawRect(x, paddedHeight - 1, x + width, paddedHeight, BORDER_COLOR); // Bottom + Gui.drawRect(x, y, x + 1, paddedHeight, BORDER_COLOR); // Left + Gui.drawRect(x + width - 1, y, x + width, paddedHeight, BORDER_COLOR); // Right + + // Draw text segments + int currentX = x + PADDING; + int currentY = y + PADDING; + + for (TextSegment segment : segments) { + ClientProxy.Font.drawString(segment.text, currentX, currentY, segment.color); + currentX += ClientProxy.Font.width(segment.text); + } + } + + // ==================== DATA CLASSES ==================== + + /** + * A colored text segment. + */ + private static class TextSegment { + final String text; + final int color; + + TextSegment(String text, int color) { + this.text = text; + this.color = color; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java new file mode 100644 index 000000000..af018e5bb --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java @@ -0,0 +1,580 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; +import noppes.npcs.client.gui.util.script.interpreter.token.Token; + +/** + * Manages the hover state for token tooltips in the script editor. + * + * Tracks: + * - Current mouse position + * - Hovered token (if any) + * - Hover duration for delayed tooltip display + * - Whether tooltip should be visible + * + * Implements a 500ms delay before showing tooltips, resetting when + * the mouse moves to a different token. + */ +public class HoverState { + + /** Minimum hover time (ms) before showing tooltip */ + private static final long HOVER_DELAY_MS = 250; + + // ==================== STATE ==================== + + /** Currently hovered token (null if none) */ + private Token hoveredToken; + + /** Time when hover on current token started */ + private long hoverStartTime; + + /** Whether the tooltip should currently be displayed */ + private boolean tooltipVisible; + + /** Cached hover info for the current token */ + private TokenHoverInfo hoverInfo; + + /** Last known mouse position */ + private int lastMouseX; + private int lastMouseY; + + /** Position of the hovered token (for tooltip positioning) */ + private int tokenScreenX; + private int tokenScreenY; + private int tokenWidth; + + /** Tooltip bounding box (set after each render frame, used for mouse-over detection) */ + private int tooltipBoxX, tooltipBoxY, tooltipBoxWidth, tooltipBoxHeight; + + /** Also store the actual tooltip panel rect (not including the token-gap extension) */ + private int tooltipPanelX, tooltipPanelY, tooltipPanelW, tooltipPanelH; + + /** Scrollbar thumb rect (set each render frame, used for drag/hover detection) */ + private int scrollbarThumbX, scrollbarThumbY, scrollbarThumbH; + private int scrollbarX; + private int scrollbarTrackTop; + private int scrollbarTrackHeight; + private boolean isDraggingScrollbar; + private int dragStartMouseY; + private int dragStartScrollOffset; + + /** Tooltip panel drag state */ + private boolean isDraggingTooltip; + private int tooltipDragOffsetX, tooltipDragOffsetY; + private boolean tooltipPositionOverridden; + private int overriddenTooltipX, overriddenTooltipY; + + /** Tooltip panel resize state */ + private boolean isResizingTooltip; + private int resizeInitMouseX, resizeInitMouseY; + private int resizeInitW, resizeInitH; + private boolean tooltipSizeOverridden; + private int overriddenTooltipW, overriddenTooltipH; + /** Minimum tooltip dimensions when user-resized */ + private static final int MIN_TOOLTIP_W = 80; + private static final int MIN_TOOLTIP_H = 30; + + /** Smooth scroll: target offset (pixels), current is animated toward it each frame */ + private float targetScrollOffset; + /** Vertical scroll offset for tooltip content (pixels) */ + private float tooltipScrollOffsetF; + + /** Maximum scroll offset = totalContentHeight - visibleContentHeight (pixels) */ + private int tooltipMaxScroll; + /** Pinned token (set when user clicks a token to keep tooltip open) */ + private Token pinnedToken; + private TokenHoverInfo pinnedHoverInfo; + + /** Whether click-to-pin behaviour is enabled for this hover state. */ + private boolean clickToPinEnabled = true; + + /** Locked mouse position for tooltip placement (captured once when tooltip becomes visible) */ + private int lockedTooltipMouseX; + private int lockedTooltipMouseY; + private boolean isTooltipPositionLocked; + + // ==================== UPDATE ==================== + + /** + * Update the hover state based on current mouse position. + * Should be called every frame from drawTextBox. + * + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param document The script document + * @param viewportX X position of the text viewport (after gutter) + * @param viewportY Y position of the text viewport + * @param viewportWidth Width of the text viewport + * @param viewportHeight Height of the text viewport + * @param scrollOffset Current vertical scroll offset (in lines) + * @param lineHeight Height of each line in pixels + * @param gutterWidth Width of the line number gutter + */ + public void update(int mouseX, int mouseY, ScriptDocument document, + int viewportX, int viewportY, int viewportWidth, int viewportHeight, + float scrollOffset, int lineHeight, int gutterWidth) { + + lastMouseX = mouseX; + lastMouseY = mouseY; + + // Check if mouse is within the text viewport + if (mouseX < viewportX || mouseX > viewportX + viewportWidth || + mouseY < viewportY || mouseY > viewportY + viewportHeight) { + clearHover(); + return; + } + + if (document == null) { + clearHover(); + return; + } + + // Calculate which line the mouse is over + int relativeY = mouseY - viewportY; + int lineIndex = (int) (scrollOffset + (relativeY / (float) lineHeight)); + + // Get the line + ScriptLine line = null; + for (ScriptLine l : document.getLines()) { + if (l.getLineIndex() == lineIndex) { + line = l; + break; + } + } + + if (line == null) { + clearHover(); + return; + } + + // Calculate character position within the line + int relativeX = mouseX - viewportX; + int globalPos = line.getGlobalStart() + getCharacterIndexAtX(line, relativeX); + + // Find the token at this position + Token token = line.getTokenAt(globalPos); + + if (token == null) { + clearHover(); + return; + } + + // Check if this is a new token + if (token != hoveredToken) { + // New token - reset timer + hoveredToken = token; + hoverStartTime = System.currentTimeMillis(); + tooltipVisible = false; + hoverInfo = null; + + resetTooltipScroll(); + // Calculate token screen position for tooltip + calculateTokenPosition(line, token, viewportX, viewportY, scrollOffset, lineHeight); + } else { + // Same token - check if delay has elapsed + long elapsed = System.currentTimeMillis() - hoverStartTime; + if (elapsed >= HOVER_DELAY_MS && !tooltipVisible) { + tooltipVisible = true; + hoverInfo = TokenHoverInfo.fromToken(token); + lockedTooltipMouseX = lastMouseX; + lockedTooltipMouseY = lastMouseY; + isTooltipPositionLocked = true; + } + } + } + + /** + * Update the hover state with a specific token. + * Simplified version for when the token has already been found. + * + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param token The token at the mouse position (or null if none) + * @param tokenX Screen X position of the token + * @param tokenY Screen Y position of the token + * @param tokenW Width of the token in pixels + */ + public void update(int mouseX, int mouseY, Token token, int tokenX, int tokenY, int tokenW) { + lastMouseX = mouseX; + lastMouseY = mouseY; + clickToPinEnabled=false; + // If a token has been pinned by click, ignore mouse movement updates + if (pinnedToken != null) { + // keep pinned tooltip visible + tooltipVisible = true; + hoverInfo = pinnedHoverInfo; + return; + } + + if (token == null) { + clearHover(); + return; + } + + // Check if this is a new token + if (token != hoveredToken) { + // New token - reset timer + hoveredToken = token; + hoverStartTime = System.currentTimeMillis(); + tooltipVisible = false; + hoverInfo = null; + + resetTooltipScroll(); + // Store token position + tokenScreenX = tokenX; + tokenScreenY = tokenY; + tokenWidth = tokenW; + } else { + // Same token - check if delay has elapsed + long elapsed = System.currentTimeMillis() - hoverStartTime; + if (elapsed >= HOVER_DELAY_MS && !tooltipVisible) { + tooltipVisible = true; + hoverInfo = TokenHoverInfo.fromToken(token); + lockedTooltipMouseX = lastMouseX; + lockedTooltipMouseY = lastMouseY; + isTooltipPositionLocked = true; + } + } + } + + /** + * Clear the current hover state. + */ + public void clearHover() { + if (hoveredToken != null) { + hoveredToken = null; + hoverStartTime = 0; + // Do not clear tooltipInfo here if pinned; if not pinned, hide tooltip. + if (pinnedToken == null) { + tooltipVisible = false; + hoverInfo = null; + tooltipBoxX = tooltipBoxY = tooltipBoxWidth = tooltipBoxHeight = 0; + tooltipPanelX = tooltipPanelY = tooltipPanelW = tooltipPanelH = 0; + isDraggingScrollbar = false; + isDraggingTooltip = false; + tooltipPositionOverridden = false; + isResizingTooltip = false; + tooltipSizeOverridden = false; + tooltipScrollOffsetF = 0; + targetScrollOffset = 0; + tooltipMaxScroll = 0; + isDraggingScrollbar = false; + isTooltipPositionLocked = false; + } + } + } + + /** + * Force the tooltip to hide (e.g., when clicking). + */ + public void hideTooltip() { + tooltipVisible = false; + } + + /** + * Enable or disable click-to-pin behaviour. + */ + public void setClickToPinEnabled(boolean enabled) { + this.clickToPinEnabled = enabled; + } + + public boolean isClickToPinEnabled() { + return clickToPinEnabled; + } + + /** + * Pin a token so its tooltip stays visible until explicitly unpinned. + */ + public void pinToken(Token token, int tokenX, int tokenY, int tokenW) { + if (token == null) return; + this.pinnedToken = token; + this.pinnedHoverInfo = TokenHoverInfo.fromToken(token); + this.tooltipVisible = pinnedHoverInfo != null && pinnedHoverInfo.hasContent(); + this.tokenScreenX = tokenX; + this.tokenScreenY = tokenY; + this.tokenWidth = tokenW; + // ensure hoveredToken reflects pinned token + this.hoveredToken = token; + if (this.tooltipVisible && !this.isTooltipPositionLocked) { + this.lockedTooltipMouseX = lastMouseX; + this.lockedTooltipMouseY = lastMouseY; + this.isTooltipPositionLocked = true; + } + } + + /** + * Unpin any pinned token and hide tooltip. + */ + public void unpin() { + this.pinnedToken = null; + this.pinnedHoverInfo = null; + this.tooltipVisible = false; + this.hoverInfo = null; + this.isTooltipPositionLocked = false; + } + + public boolean isPinned() { return pinnedToken != null; } + + public int getLockedMouseX() { return lockedTooltipMouseX; } + public int getLockedMouseY() { return lockedTooltipMouseY; } + public boolean isPositionLocked() { return isTooltipPositionLocked; } + + // ==================== POSITION CALCULATION ==================== + + /** + * Get the character index within a line at the given X pixel position. + * Uses style-aware width calculation to account for bold/italic tokens. + */ + private int getCharacterIndexAtX(ScriptLine line, int x) { + String text = line.getText(); + if (text == null || text.isEmpty()) return 0; + + int accumWidth = 0; + for (int i = 0; i < text.length(); i++) { + int charWidth = line.getRenderedWidth(i, i + 1); + if (accumWidth + charWidth / 2 > x) { + return i; + } + accumWidth += charWidth; + } + return text.length(); + } + + /** + * Calculate the screen position of a token for tooltip positioning. + */ + private void calculateTokenPosition(ScriptLine line, Token token, + int viewportX, int viewportY, + float scrollOffset, int lineHeight) { + // X position: calculate width of text before the token (style-aware) + int tokenLocalStart = token.getGlobalStart() - line.getGlobalStart(); + tokenLocalStart = Math.max(0, Math.min(tokenLocalStart, line.getText().length())); + + tokenScreenX = viewportX + line.getRenderedWidth(0, tokenLocalStart); + + // Y position: line position minus scroll + int lineY = line.getLineIndex(); + tokenScreenY = viewportY + (int) ((lineY - scrollOffset) * lineHeight); + + // Token width (style-aware) + int tokenLocalEnd = tokenLocalStart + token.getText().length(); + tokenWidth = line.getRenderedWidth(tokenLocalStart, tokenLocalEnd); + } + + public void setTooltipBounds(int x, int y, int width, int height) { + tooltipBoxX = x; + tooltipBoxY = y; + tooltipBoxWidth = width; + tooltipBoxHeight = height; + } + + public void setTooltipMaxScroll(int maxScroll) { + this.tooltipMaxScroll = Math.max(0, maxScroll); + } + + public boolean isMouseOverTooltip(int mouseX, int mouseY) { + if (!tooltipVisible || tooltipBoxWidth <= 0) return false; + return mouseX >= tooltipBoxX && mouseX <= tooltipBoxX + tooltipBoxWidth + && mouseY >= tooltipBoxY && mouseY <= tooltipBoxY + tooltipBoxHeight; + } + + public void scrollTooltip(int wheelDelta) { + // LWJGL wheelDelta: positive = scrolled up (content should move up = offset increases) + // Divide by 2 for sensitivity; negate to match expected direction + targetScrollOffset = Math.max(0, Math.min(tooltipMaxScroll, targetScrollOffset - wheelDelta / 5.0f)); + } + + public int getTooltipScrollOffset() { + return (int) tooltipScrollOffsetF; + } + + public void resetTooltipScroll() { + tooltipScrollOffsetF = 0; + targetScrollOffset = 0; + } + + /** Lerp current offset toward target. Call every frame while tooltip is visible. */ + public void updateSmoothScroll() { + float diff = targetScrollOffset - tooltipScrollOffsetF; + if (Math.abs(diff) < 0.5f) { + tooltipScrollOffsetF = targetScrollOffset; + } else { + tooltipScrollOffsetF += diff * 0.04f; + } + } + + /** Called by renderer each frame to store thumb bounds for drag/hover detection. */ + public void setScrollbarThumb(int barX, int thumbY, int thumbH, int trackTop, int trackHeight) { + scrollbarX = barX; + scrollbarThumbX = barX; + scrollbarThumbY = thumbY; + scrollbarThumbH = thumbH; + scrollbarTrackTop = trackTop; + scrollbarTrackHeight = trackHeight; + } + + public boolean isMouseOverScrollbarThumb(int mx, int my) { + if (!tooltipVisible || scrollbarThumbH <= 0) return false; + return mx >= scrollbarX && mx <= scrollbarX + 3 + && my >= scrollbarThumbY && my <= scrollbarThumbY + scrollbarThumbH; + } + + public void startScrollbarDrag(int mouseY) { + isDraggingScrollbar = true; + dragStartMouseY = mouseY; + dragStartScrollOffset = (int) tooltipScrollOffsetF; + } + + public void updateScrollbarDrag(int mouseY) { + if (!isDraggingScrollbar || scrollbarTrackHeight <= 0 || tooltipMaxScroll <= 0) return; + float scrollRatio = (float) (scrollbarTrackHeight) / Math.max(1, scrollbarTrackHeight + tooltipMaxScroll); + int thumbH = Math.max(6, (int)(scrollbarTrackHeight * scrollRatio)); + int effectiveTrack = scrollbarTrackHeight - thumbH; + if (effectiveTrack <= 0) return; + int deltaY = mouseY - dragStartMouseY; + float scrollDelta = (float) deltaY / effectiveTrack * tooltipMaxScroll; + targetScrollOffset = Math.max(0, Math.min(tooltipMaxScroll, dragStartScrollOffset + scrollDelta)); + tooltipScrollOffsetF = targetScrollOffset; // snap during drag + } + + public void releaseScrollbarDrag() { + isDraggingScrollbar = false; + } + + // ==================== TOOLTIP PANEL DRAG ==================== + + /** Record the actual rendered tooltip panel rect (used for drag hit-testing). */ + public void setTooltipPanel(int x, int y, int w, int h) { + tooltipPanelX = x; + tooltipPanelY = y; + tooltipPanelW = w; + tooltipPanelH = h; + } + + public boolean isMouseOverTooltipPanel(int mx, int my) { + if (!tooltipVisible || tooltipPanelW <= 0) return false; + return mx >= tooltipPanelX && mx <= tooltipPanelX + tooltipPanelW + && my >= tooltipPanelY && my <= tooltipPanelY + tooltipPanelH; + } + + public int getTooltipPanelX() { return tooltipPanelX; } + public int getTooltipPanelY() { return tooltipPanelY; } + + /** Begin dragging the tooltip; offsets are from mouse to tooltip top-left. */ + public void startTooltipDrag(int mouseX, int mouseY) { + isDraggingTooltip = true; + tooltipDragOffsetX = mouseX - tooltipPanelX; + tooltipDragOffsetY = mouseY - tooltipPanelY; + } + + /** Called every frame while M1 is held to move the tooltip. */ + public void updateTooltipDrag(int mouseX, int mouseY) { + if (!isDraggingTooltip) return; + overriddenTooltipX = mouseX - tooltipDragOffsetX; + overriddenTooltipY = mouseY - tooltipDragOffsetY; + tooltipPositionOverridden = true; + } + + public void releaseTooltipDrag() { + isDraggingTooltip = false; + } + + public boolean isDraggingTooltip() { return isDraggingTooltip; } + public boolean hasOverriddenPosition() { return tooltipPositionOverridden; } + public int getOverriddenTooltipX() { return overriddenTooltipX; } + public int getOverriddenTooltipY() { return overriddenTooltipY; } + + // ==================== TOOLTIP PANEL RESIZE ==================== + + /** Returns true when the mouse is over the resize handle (bottom-right corner). */ + public boolean isMouseOverResizeHandle(int mx, int my) { + if (!tooltipVisible || tooltipPanelW <= 0) return false; + int rx = tooltipPanelX + tooltipPanelW - 8; + int ry = tooltipPanelY + tooltipPanelH - 8; + return mx >= rx && mx <= tooltipPanelX + tooltipPanelW + && my >= ry && my <= tooltipPanelY + tooltipPanelH; + } + + /** Begin resizing; captures current panel dimensions as the baseline. */ + public void startTooltipResize(int mouseX, int mouseY) { + isResizingTooltip = true; + resizeInitMouseX = mouseX; + resizeInitMouseY = mouseY; + resizeInitW = tooltipSizeOverridden ? overriddenTooltipW : tooltipPanelW; + resizeInitH = tooltipSizeOverridden ? overriddenTooltipH : tooltipPanelH; + } + + /** Called every frame while M1 is held to resize the tooltip panel. */ + public void updateTooltipResize(int mouseX, int mouseY) { + if (!isResizingTooltip) return; + overriddenTooltipW = Math.max(MIN_TOOLTIP_W, resizeInitW + (mouseX - resizeInitMouseX)); + overriddenTooltipH = Math.max(MIN_TOOLTIP_H, resizeInitH + (mouseY - resizeInitMouseY)); + tooltipSizeOverridden = true; + } + + public void releaseTooltipResize() { + isResizingTooltip = false; + } + + public boolean isResizingTooltip() { return isResizingTooltip; } + public boolean hasOverriddenSize() { return tooltipSizeOverridden; } + public int getOverriddenTooltipW() { return overriddenTooltipW; } + public int getOverriddenTooltipH() { return overriddenTooltipH; } + + public boolean isDraggingScrollbar() { + return isDraggingScrollbar; + } + + public int getScrollbarThumbY() { return scrollbarThumbY; } + public int getScrollbarThumbH() { return scrollbarThumbH; } + public int getScrollbarX() { return scrollbarX; } + + // ==================== GETTERS ==================== + + public boolean isTooltipVisible() { + return tooltipVisible && hoverInfo != null && hoverInfo.hasContent(); + } + + public TokenHoverInfo getHoverInfo() { + return hoverInfo; + } + + public Token getHoveredToken() { + return hoveredToken; + } + + public int getTokenScreenX() { + return tokenScreenX; + } + + public int getTokenScreenY() { + return tokenScreenY; + } + + public int getTokenWidth() { + return tokenWidth; + } + + public int getLastMouseX() { + return lastMouseX; + } + + public int getLastMouseY() { + return lastMouseY; + } + public void setLastMousePosition(int x, int y) { + lastMouseX = x; + lastMouseY = y; + } + + /** + * Get the progress (0.0 to 1.0) of the hover delay. + * Can be used for fade-in animation. + */ + public float getHoverProgress() { + if (hoveredToken == null) return 0f; + long elapsed = System.currentTimeMillis() - hoverStartTime; + return Math.min(1.0f, elapsed / (float) HOVER_DELAY_MS); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java new file mode 100644 index 000000000..9bfb9ff3d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java @@ -0,0 +1,1616 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import noppes.npcs.client.gui.util.script.interpreter.*; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParamTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocReturnTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocSeeTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocTypeTag; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.Token; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenErrorMessage; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * Data class containing all displayable information for a token hover tooltip. + * Extracts and formats information from Token metadata for rendering. + * + * Supports display for: + * - Classes/Interfaces/Enums: Package, declaration with modifiers/extends/implements + * - Methods: Return type, signature, parameters, Javadoc + * - Fields: Type, containing class, declaration + * - Variables: Type, scope (local/parameter/global) + * - Errors: Validation errors, type mismatches + */ +public class TokenHoverInfo { + + // ==================== DISPLAY SECTIONS ==================== + + /** Package name (e.g., "net.minecraft.client") - shown in gray */ + private String packageName; + + /** Icon indicator (e.g., "C" for class, "I" for interface, "m" for method) */ + private String iconIndicator; + + /** Primary declaration line with syntax coloring */ + private List declaration = new ArrayList<>(); + + /** Javadoc/documentation comment lines */ + private List documentation = new ArrayList<>(); + + /** JSDoc-formatted documentation with colored segments (sections like Params, Returns) */ + private List jsDocLines = new ArrayList<>(); + + /** Error messages (shown in red) */ + private List errors = new ArrayList<>(); + + /** Additional info lines (e.g., "Variable 'x' is never used") */ + private List additionalInfo = new ArrayList<>(); + + /** The token this info was built from */ + private final Token token; + + // ==================== DOCUMENTATION LINE ==================== + + /** + * A line of documentation that may contain colored segments. + * Used for JSDoc-style rendering with "Params:", parameter names, etc. + */ + public static class DocumentationLine { + public final List segments; + + /** True for every line (including empty ones) inside a ``` code fence */ + public boolean isCodeLine = false; + /** True only for the FIRST line of each code block (triggers background draw) */ + public boolean isCodeBlockFirst = false; + /** Number of stripped leading spaces — used to apply explicit pixel indentation */ + public int codeLeadingSpaces = 0; + + public DocumentationLine() { + this.segments = new ArrayList<>(); + } + + public void addSegment(String text, int color) { + segments.add(new TextSegment(text, color)); + } + + public void addText(String text) { + segments.add(new TextSegment(text, TextSegment.COLOR_DEFAULT)); + } + + public boolean isEmpty() { + return segments.isEmpty() || segments.stream().allMatch(s -> s.text == null || s.text.isEmpty()); + } + } + + // ==================== TEXT SEGMENT ==================== + + /** + * A colored segment of text within the declaration line. + */ + public static class TextSegment { + public final String text; + public final int color; + + public TextSegment(String text, int color) { + this.text = text; + this.color = color; + } + + // Predefined colors matching IntelliJ dark theme + public static final int COLOR_KEYWORD = 0xCC7832; // Orange for keywords/modifiers + public static final int COLOR_TYPE = 0x6897BB; // Blue for types + public static final int COLOR_CLASS = 0xA9B7C6; // Light gray for class names + public static final int COLOR_METHOD = 0xFFC66D; // Yellow for method names + public static final int COLOR_FIELD = 0x9876AA; // Purple for fields + public static final int COLOR_PARAM = 0xA9B7C6; // Light gray for parameters + public static final int COLOR_PACKAGE = 0x808080; // Gray for package + public static final int COLOR_DEFAULT = 0xA9B7C6; // Default text + public static final int COLOR_ERROR = 0xFF6B68; // Red for errors + public static final int COLOR_STRING = 0x6A8759; // Green for strings + public static final int COLOR_ANNOTATION = 0xBBB529; // Yellow-green for annotations + } + + // ==================== CONSTRUCTOR ==================== + + private TokenHoverInfo(Token token) { + this.token = token; + } + + // ==================== FACTORY METHOD ==================== + + /** + * Build hover info from a token based on its type and metadata. + */ + public static TokenHoverInfo fromToken(Token token) { + if (token == null) return null; + + TokenHoverInfo info = new TokenHoverInfo(token); + + // First, check for errors + info.extractErrors(token); + + // Then, extract type-specific information + switch (token.getType()) { + case IMPORTED_CLASS: + case CLASS_DECL: + case INTERFACE_DECL: + case ENUM_DECL: + case TYPE_DECL: + case GENERIC_TYPE_PARAM: + info.extractClassInfo(token); + break; + + case METHOD_CALL: + info.extractMethodCallInfo(token); + break; + + case METHOD_DECL: + info.extractMethodDeclInfo(token); + break; + + case ENUM_CONSTANT: + info.extractEnumConstantInfo(token); + break; + case GLOBAL_FIELD: + info.extractGlobalFieldInfo(token); + break; + + case LOCAL_FIELD: + info.extractLocalFieldInfo(token); + break; + + case PARAMETER: + info.extractParameterInfo(token); + break; + + case UNDEFINED_VAR: + info.extractUndefinedInfo(token); + break; + case LITERAL: + case KEYWORD: + case STRING: + case COMMENT: + if (info.hasErrors()) + return info; + return null; + default: + // For other types, try to extract any available metadata + if (token.getTypeInfo() != null) { + info.extractClassInfo(token); + } else if (token.getMethodInfo() != null) { + info.extractMethodDeclInfo(token); + } else if (token.getFieldInfo() != null) { + info.extractFieldInfoGeneric(token); + } else if (info.hasErrors()) + return info; + else { + return null; // Nothing to show + } + break; + } + + return info; + } + + // ==================== EXTRACTION METHODS ==================== + + private void extractErrors(Token token) { + if (token.getType() == TokenType.UNDEFINED_VAR) + errors.add("Cannot resolve symbol '" + token.getText() + "'"); + + TokenErrorMessage msg = token.getErrorMessage(); + if (msg != null && !msg.getMessage().isEmpty()) { + if (msg.clearOtherErrors) + errors.clear(); + + errors.add(msg.getMessage()); + } + + // Detailed error detection happens once in ScriptDocument.populateErrors(); + // hover just looks up by position. + ScriptDocument doc = ScriptDocument.INSTANCE; + if (doc != null) { + int tokenStart = token.getGlobalStart(); + int tokenEnd = token.getGlobalEnd(); + for (DocumentError error : doc.getErrors()) { + if (tokenStart < error.getEndPos() && tokenEnd > error.getStartPos()) { + errors.add(error.getMessage()); + } + } + } + } + + + private void extractClassInfo(Token token) { + TypeInfo typeInfo = token.getTypeInfo(); + if (typeInfo == null) return; + + if (typeInfo.isTypeParameter()) { + extractTypeParameterInfo(typeInfo); + return; + } + + packageName = getPackageName(typeInfo); + + Class clazz = typeInfo.getJavaClass(); + if (clazz != null) { + boolean isEnum = clazz.isEnum(); + // Icon + if (clazz.isInterface()) { + iconIndicator = "I"; + } else if (isEnum) { + iconIndicator = "E"; + } else { + iconIndicator = "C"; + } + + // Build declaration + int mods = clazz.getModifiers(); + + // Modifiers + if (Modifier.isPublic(mods)) addSegment("public ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isAbstract(mods) && !clazz.isInterface()) addSegment("abstract ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isFinal(mods) && !isEnum) addSegment("final ", TokenType.KEYWORD.getHexColor()); + + // Class type keyword + if (clazz.isInterface()) { + addSegment("interface ", TokenType.KEYWORD.getHexColor()); + } else if (isEnum) { + addSegment("enum ", TokenType.KEYWORD.getHexColor()); + } else { + addSegment("class ", TokenType.KEYWORD.getHexColor()); + } + + // Class name - use proper color based on type + int classColor = clazz.isInterface() ? TokenType.INTERFACE_DECL.getHexColor() + : clazz.isEnum() ? TokenType.ENUM_DECL.getHexColor() + : TokenType.IMPORTED_CLASS.getHexColor(); + // Render generics with correct segment colors if present + addTypeSegments(typeInfo); + addDeclaredTypeParamSegments(typeInfo); + + // Extends + Class superclass = clazz.getSuperclass(); + if (superclass != null && superclass != Object.class && !isEnum) { + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + addSegment(superclass.getSimpleName(), getColorForClass(superclass)); + } + + List declaration = null; + + // Implements + Class[] interfaces = clazz.getInterfaces(); + if (interfaces.length > 0) { + addSegment(clazz.isInterface() ? " extends " : " implements ", TokenType.KEYWORD.getHexColor()); + for (int i = 0; i < Math.min(interfaces.length, 3); i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + addSegment(interfaces[i].getSimpleName(), TokenType.INTERFACE_DECL.getHexColor()); + } + if (interfaces.length > 3) { + addSegment(", ...", TokenType.DEFAULT.getHexColor()); + } + } + } else if (typeInfo instanceof ScriptTypeInfo) { + // Script-defined type + ScriptTypeInfo scriptType = (ScriptTypeInfo) typeInfo; + + // Icon + if (scriptType.getKind() == TypeInfo.Kind.INTERFACE) { + iconIndicator = "I"; + } else if (scriptType.getKind() == TypeInfo.Kind.ENUM) { + iconIndicator = "E"; + } else { + iconIndicator = "C"; + } + + // Build declaration with modifiers + int mods = scriptType.getModifiers(); + + // Modifiers + if (Modifier.isPublic(mods)) addSegment("public ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isAbstract(mods) && scriptType.getKind() != TypeInfo.Kind.INTERFACE) + addSegment("abstract ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isFinal(mods)) addSegment("final ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isStatic(mods)) addSegment("static ", TokenType.KEYWORD.getHexColor()); + + // Class type keyword + if (scriptType.getKind() == TypeInfo.Kind.INTERFACE) { + addSegment("interface ", TokenType.KEYWORD.getHexColor()); + } else if (scriptType.getKind() == TypeInfo.Kind.ENUM) { + addSegment("enum ", TokenType.KEYWORD.getHexColor()); + } else { + addSegment("class ", TokenType.KEYWORD.getHexColor()); + } + + // Class name + int classColor = scriptType.getKind() == TypeInfo.Kind.INTERFACE ? TokenType.INTERFACE_DECL.getHexColor() + : scriptType.getKind() == TypeInfo.Kind.ENUM ? TokenType.ENUM_DECL.getHexColor() + : TokenType.IMPORTED_CLASS.getHexColor(); + addTypeSegments(typeInfo); + addDeclaredTypeParamSegments(typeInfo); + if (scriptType.hasSuperClass()) { + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + TypeInfo superClass = scriptType.getSuperClass(); + if (superClass != null && superClass.isResolved()) { + // Color based on resolved type + addTypeSegments(superClass); + } else { + // Unresolved - show the raw name in undefined color + String superName = scriptType.getSuperClassName(); + if (superName != null) { + addSegment(superName, TokenType.UNDEFINED_VAR.getHexColor()); + } + } + } + + // Implements clause for ScriptTypeInfo + List implementedInterfaces = scriptType.getImplementedInterfaces(); + if (!implementedInterfaces.isEmpty()) { + // For interfaces, they "extend" other interfaces; for classes, they "implement" + String keyword = scriptType.getKind() == TypeInfo.Kind.INTERFACE ? " extends " : " implements "; + if (scriptType.hasSuperClass() && scriptType.getKind() == TypeInfo.Kind.INTERFACE) { + // Already showed extends, so use comma + addSegment(", ", TokenType.DEFAULT.getHexColor()); + } else { + addSegment(keyword, TokenType.KEYWORD.getHexColor()); + } + + List interfaceNames = scriptType.getImplementedInterfaceNames(); + for (int i = 0; i < implementedInterfaces.size(); i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + + TypeInfo ifaceType = implementedInterfaces.get(i); + String ifaceName = (i < interfaceNames.size()) ? interfaceNames.get(i) : getName(ifaceType); + + if (ifaceType != null && ifaceType.isResolved()) { + // Prefer rendering from the resolved TypeInfo so generics color correctly + addTypeSegments(ifaceType); + } else { + addSegment(ifaceName, TokenType.UNDEFINED_VAR.getHexColor()); + } + } + } + + // Add ScriptTypeInfo errors + if (false) { //|| scriptType.hasError() + // Missing interface method errors + for (ScriptTypeInfo.MissingMethodError err : scriptType.getMissingMethodErrors()) { + errors.add(err.getMessage()); + } + // Constructor mismatch errors + for (ScriptTypeInfo.ConstructorMismatchError err : scriptType.getConstructorMismatchErrors()) { + errors.add(err.getMessage()); + } + // General error message + if (scriptType.getErrorMessage() != null) { + errors.add(scriptType.getErrorMessage()); + } + } + + JSDocInfo jsDocInfo = scriptType.getJSDocInfo(); + if (jsDocInfo != null) { + formatJSDocumentation(jsDocInfo, null); + } + + } else if (typeInfo.isJSType()) { + JSTypeInfo jsType = typeInfo.getJSTypeInfo(); + + iconIndicator = "I"; + addSegment("interface ", TokenType.KEYWORD.getHexColor()); + addTypeSegments(typeInfo); + addDeclaredTypeParamSegments(typeInfo); + + if (jsType.getExtendsType() != null) { + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + addSegment(jsType.getExtendsType(), TokenType.INTERFACE_DECL.getHexColor()); + } + + JSDocInfo jsDocInfo = typeInfo.getJSDocInfo(); + if (jsDocInfo != null) { + formatJSDocumentation(jsDocInfo, null); + } + + } else { + // Unresolved type + iconIndicator = "?"; + String typeName = getName(typeInfo); + splitAndAddTypeName(typeName, token.getType().getHexColor()); + if (!typeInfo.isResolved()) { + errors.add("Cannot resolve class '" + typeName + "'"); + } + } + + // If this is a NEW_TYPE token with constructor info, show the constructor signature + if (token.getMethodInfo() != null) { + MethodInfo constructor = token.getMethodInfo(); + declaration.add(new TextSegment("\n", TokenType.DEFAULT.getHexColor())); + // additionalInfo.add("Constructor"); + buildConstructorDeclaration(constructor, typeInfo); + } + } + + private void extractTypeParameterInfo(TypeInfo typeInfo) { + iconIndicator = "T"; + String paramName = typeInfo.getTypeParameterName(); + + addSegment("type parameter ", TokenType.KEYWORD.getHexColor()); + addSegment("<", TokenType.DEFAULT.getHexColor()); + addSegment(paramName, TokenType.GENERIC_TYPE_PARAM.getHexColor()); + + TypeInfo bound = typeInfo.getBoundType(); + if (bound != null && bound.getJavaClass() != null && bound.getJavaClass() != Object.class) { + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + addSegment(bound.getSimpleName(), getColorForTypeInfo(bound)); + } + addSegment(">", TokenType.DEFAULT.getHexColor()); + } + + private void extractMethodCallInfo(Token token) { + MethodCallInfo callInfo = token.getMethodCallInfo(); + MethodInfo methodInfo = callInfo != null ? callInfo.getResolvedMethod() : token.getMethodInfo(); + + if (methodInfo == null && callInfo == null) return; + + iconIndicator = "m"; + + TypeInfo containingType = null; + if (callInfo != null) { + containingType = callInfo.getReceiverType(); + + //Checks true containing type from resolved method (handles inheritance cases) + if (callInfo.getResolvedMethod() != null) { + TypeInfo trueContainingType = callInfo.getResolvedMethod().getContainingType(); + if (trueContainingType != null) + containingType = trueContainingType; + } + } + if (containingType == null && methodInfo != null) { + containingType = methodInfo.getContainingType(); + } + + if (containingType != null) { + // Show full qualified class name (like IntelliJ) + String pkg = getPackageName(containingType); + if (pkg != null && !pkg.isEmpty()) + packageName = pkg; + } + + // Try to get actual Java method for more details + if (methodInfo != null && shouldPreferMethodInfo(methodInfo)) { + buildBasicMethodDeclaration(methodInfo, containingType); + return; + } + if (methodInfo != null && methodInfo.getJavaMethod() != null) { + // When receiver is parameterized, MethodInfo has adapted generic params + // (e.g., Map.get(String) instead of get(Object)). + // Use buildBasicMethodDeclaration to show adapted types correctly. + if (containingType != null && containingType.isParameterized()) { + buildBasicMethodDeclaration(methodInfo, containingType); + return; + } + TypeInfo methodReturnType = methodInfo.getReturnType(); + Class reflectedReturnType = methodInfo.getJavaMethod().getReturnType(); + if (methodReturnType != null && methodReturnType.getJavaClass() != null + && methodReturnType.getJavaClass() != reflectedReturnType) { + // Use MethodInfo when its return type differs from reflection (e.g., .d.ts override like IDBCPlayer -> IDBCAddon in npcdbc). + buildBasicMethodDeclaration(methodInfo, containingType); + return; + } + buildMethodDeclaration(methodInfo, containingType); + extractJavadoc(methodInfo.getJavaMethod()); + return; + } + + // Fallback to basic method info + if (methodInfo != null) { + buildBasicMethodDeclaration(methodInfo, containingType); + } + } + + private void extractMethodDeclInfo(Token token) { + MethodInfo methodInfo = token.getMethodInfo(); + if (methodInfo == null) return; + + iconIndicator = "m"; + + // For script-defined methods, show basic declaration + buildBasicMethodDeclaration(methodInfo, null); + } + + private void extractGlobalFieldInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + FieldAccessInfo accessInfo = token.getFieldAccessInfo(); + if (fieldInfo == null && accessInfo != null) + fieldInfo = accessInfo.getResolvedField(); + + if (fieldInfo == null) + return; + + iconIndicator = "f"; + + // Add documentation if available + JSDocInfo jsDoc = fieldInfo.getJSDocInfo(); + if (jsDoc != null) { + formatJSDocumentation(jsDoc, null); + } else if (fieldInfo.getDocumentation() != null && !fieldInfo.getDocumentation().isEmpty()) { + String[] docLines = fieldInfo.getDocumentation().split("\n"); + for (String line : docLines) { + documentation.add(line); + } + } + + TypeInfo declaredType = fieldInfo.getTypeInfo(); + + // Try to get modifiers from Java reflection if this is a chained field + boolean foundModifiers = false; + if (accessInfo != null && accessInfo.getReceiverType() != null) { + TypeInfo receiverType = accessInfo.getReceiverType(); + if (receiverType.getJavaClass() != null) { + try { + Field javaField = receiverType.getJavaClass().getField(fieldInfo.getName()); + if (javaField != null) + addFieldModifiers(javaField.getModifiers()); + foundModifiers = true; + } catch (Exception e) { + } + } + } + + int modifiers = fieldInfo.getModifiers(); + if(modifiers !=0 && !foundModifiers) { + addFieldModifiers(modifiers); + } + +// if (!foundModifiers && fieldInfo.getDeclarationOffset() >= 0) { +// // Show modifiers from source if we have a declaration position +// String modifiers = extractModifiersAtPosition(fieldInfo.getDeclarationOffset()); +// if (modifiers != null && !modifiers.isEmpty()) { +// addSegment(modifiers + " ", TokenType.KEYWORD.getHexColor()); +// } +// } + + if (declaredType != null) { + // accessInfo For Minecraft.getMinecraft.thePlayer + // Return net.minecraft.client.Minecraft, and not net.minecraft.entity.EntityPlayer + String pkg = getPackageName(accessInfo != null ? accessInfo.getReceiverType() : declaredType); + + if (pkg != null && !pkg.isEmpty()) + packageName = pkg; + + // Type - check for actual type color + addTypeSegments(declaredType); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + + // Field name + addSegment(fieldInfo.getName(), TokenType.GLOBAL_FIELD.getHexColor()); + + // Add initialization value if available + addInitializationTokens(token, fieldInfo); + } + + private void extractEnumConstantInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) + return; + + EnumConstantInfo enumInfo = fieldInfo.getEnumInfo(); + if (enumInfo == null) + return; + + iconIndicator = "e"; + + // Add documentation if available + if (fieldInfo.getDocumentation() != null && !fieldInfo.getDocumentation().isEmpty()) { + String[] docLines = fieldInfo.getDocumentation().split("\n"); + for (String line : docLines) { + documentation.add(line); + } + } + + TypeInfo enumType = enumInfo.getEnumType(); + + if (enumType != null) { + // Show enum's package + String pkg = getPackageName(enumType); + if (pkg != null && !pkg.isEmpty()) + packageName = pkg; + + + // Type (enum type name) + addTypeSegments(enumType); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + + // Enum constant name + addSegment(token.getStylePrefix() + fieldInfo.getName(), TokenType.ENUM_CONSTANT.getHexColor()); + + // Add constructor arguments if available + addInitializationTokens(token, fieldInfo); + } + + private void extractLocalFieldInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + iconIndicator = "v"; + + // Add documentation if available (though local vars rarely have docs) + if (fieldInfo.getDocumentation() != null && !fieldInfo.getDocumentation().isEmpty()) { + String[] docLines = fieldInfo.getDocumentation().split("\n"); + for (String line : docLines) { + documentation.add(line); + } + } + + TypeInfo declaredType = fieldInfo.getTypeInfo(); + if (declaredType != null) { + addTypeSegments(declaredType); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + + addSegment(fieldInfo.getName(), TokenType.LOCAL_FIELD.getHexColor()); + + // Add initialization value if available + addInitializationTokens(token, fieldInfo); + + // Show it's a local variable + // additionalInfo.add("Local variable"); + } + + public String getPackageName(TypeInfo type) { + if (type == null) + return null; + + if (type.isTypeParameter()) + return null; + + TypeInfo base = type.isArray() ? type.getElementType() : type; + if (base == null) base = type; + + String fullName = base.getFullName(); + if (fullName != null && !fullName.isEmpty()) { + return fullName; + } else { + String pkg = base.getPackageName(); + String className = getName(base); + if (pkg != null && !pkg.isEmpty()) { + return pkg + "." + className; + } else { + return className; + } + } + } + + private void extractParameterInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + iconIndicator = "p"; + + // Add documentation if available (args/parameters might have docs from method javadoc) + if (fieldInfo.getDocumentation() != null && !fieldInfo.getDocumentation().isEmpty()) { + String[] docLines = fieldInfo.getDocumentation().split("\n"); + for (String line : docLines) { + documentation.add(line); + } + } + + TypeInfo declaredType = fieldInfo.getTypeInfo(); + if (declaredType != null) { + addTypeSegments(declaredType); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + + addSegment(fieldInfo.getName(), TokenType.PARAMETER.getHexColor()); + + // additionalInfo.add("Parameter"); + } + + private void extractUndefinedInfo(Token token) { + iconIndicator = "?"; + //addSegment(token.getText(), TokenType.UNDEFINED_VAR.getHexColor()); + } + + /** + * Get the display name for a type, including generic arguments. + * Uses the unified getDisplayName() method which handles: + * - Simple types: "String" + * - Parameterized types: "List", "Map" + * - Nested generics: "List>" + * - JS types with namespace: "IPlayerEvent.InteractEvent" + */ + public String getName(TypeInfo type){ + if (type instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) type).getDotSeparatedName(); + } + return type.getDisplayName(); + } + + /** + * Add a type name as multiple colored segments so generics render like the editor marks. + * Example: List -> "List" (interface), "<" (default), "String" (class), ">" (default) + */ + private void addTypeSegments(TypeInfo typeInfo) { + addTypeSegments(typeInfo, 0); + } + + private void addTypeSegments(TypeInfo typeInfo, int depth) { + if (typeInfo == null) { + addSegment("any", TokenType.DEFAULT.getHexColor()); + return; + } + if (depth > 25) { + addSegment(getName(typeInfo), getColorForTypeInfo(typeInfo)); + return; + } + + if (typeInfo.isParameterized()) { + TypeInfo raw = typeInfo.getRawType(); + String rawName = getName(raw); + splitAndAddTypeName(rawName, getColorForTypeInfo(raw)); + addSegment("<", TokenType.DEFAULT.getHexColor()); + + java.util.List args = typeInfo.getAppliedTypeArgs(); + for (int i = 0; i < args.size(); i++) { + if (i > 0) { + addSegment(", ", TokenType.DEFAULT.getHexColor()); + } + addTypeSegments(args.get(i), depth + 1); + } + + addSegment(">", TokenType.DEFAULT.getHexColor()); + return; + } + + String typeName = getName(typeInfo); + splitAndAddTypeName(typeName, getColorForTypeInfo(typeInfo)); + } + + private void addDeclaredTypeParamSegments(TypeInfo typeInfo) { + List params = typeInfo.getTypeParams(); + if (params == null || params.isEmpty()) return; + if (typeInfo.isParameterized()) return; + + addSegment("<", TokenType.DEFAULT.getHexColor()); + for (int i = 0; i < params.size(); i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + TypeParamInfo param = params.get(i); + addSegment(param.getName(), TokenType.GENERIC_TYPE_PARAM.getHexColor()); + if (param.getBoundTypeName() != null && !"Object".equals(param.getBoundTypeName())) { + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + TypeInfo boundType = param.getBoundTypeInfo(); + if (boundType != null && boundType.isResolved()) { + addTypeSegments(boundType); + } else { + addSegment(param.getBoundTypeName(), TokenType.IMPORTED_CLASS.getHexColor()); + } + + List additionalBoundTypes = param.getAdditionalBoundTypes(); + List additionalBoundNames = param.getAdditionalBoundNames(); + for (int j = 0; j < additionalBoundNames.size(); j++) { + addSegment(" & ", TokenType.DEFAULT.getHexColor()); + TypeInfo additionalBoundType = j < additionalBoundTypes.size() ? additionalBoundTypes.get(j) : null; + if (additionalBoundType != null && additionalBoundType.isResolved()) { + addTypeSegments(additionalBoundType); + if (!additionalBoundType.isParameterized()) { + addBoundTypeParamSegments(additionalBoundType); + } + } else { + addSegment(additionalBoundNames.get(j), TokenType.IMPORTED_CLASS.getHexColor()); + } + } + } + } + + addSegment(">", TokenType.DEFAULT.getHexColor()); + } + + private void addBoundTypeParamSegments(TypeInfo boundType) { + List params = boundType.getTypeParams(); + if (params == null || params.isEmpty()) return; + + addSegment("<", TokenType.DEFAULT.getHexColor()); + for (int i = 0; i < params.size(); i++) { + if (i > 0) + addSegment(", ", TokenType.DEFAULT.getHexColor()); + TypeParamInfo tp = params.get(i); + addSegment(tp.getName(), TokenType.GENERIC_TYPE_PARAM.getHexColor()); + + if (tp.getBoundTypeName() != null && !"Object".equals(tp.getBoundTypeName())) { + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + TypeInfo innerBound = tp.getBoundTypeInfo(); + if (innerBound != null && innerBound.isResolved()) { + addTypeSegments(innerBound); + if (!innerBound.isParameterized()) { + addBoundTypeParamSegments(innerBound); + } + } else { + addSegment(tp.getBoundTypeName(), TokenType.IMPORTED_CLASS.getHexColor()); + } + + List innerAdditional = tp.getAdditionalBoundTypes(); + List innerAdditionalNames = tp.getAdditionalBoundNames(); + for (int j = 0; j < innerAdditionalNames.size(); j++) { + addSegment(" & ", TokenType.DEFAULT.getHexColor()); + TypeInfo innerAddBound = j < innerAdditional.size() ? innerAdditional.get(j) : null; + if (innerAddBound != null && innerAddBound.isResolved()) { + addTypeSegments(innerAddBound); + if (!innerAddBound.isParameterized()) { + addBoundTypeParamSegments(innerAddBound); + } + } else { + addSegment(innerAdditionalNames.get(j), TokenType.IMPORTED_CLASS.getHexColor()); + } + } + addSegment(" extends ", TokenType.KEYWORD.getHexColor()); + } + } + addSegment(">", TokenType.DEFAULT.getHexColor()); + } + + private void splitAndAddTypeName(String typeName, int typeColor) { + if (typeName == null || !typeName.endsWith("[]")) { + addSegment(typeName, typeColor); + return; + } + int idx = typeName.length() - 2; + while (idx >= 1 && typeName.charAt(idx - 1) == '[' && typeName.charAt(idx) == ']') { + idx -= 2; + } + if (idx > 0) { + addSegment(typeName.substring(0, idx), typeColor); + } + addSegment(typeName.substring(idx), TokenType.DEFAULT.getHexColor()); + } + + private void extractFieldInfoGeneric(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + switch (fieldInfo.getScope()) { + case GLOBAL: + extractGlobalFieldInfo(token); + break; + case LOCAL: + extractLocalFieldInfo(token); + break; + case PARAMETER: + extractParameterInfo(token); + break; + } + } + + private void buildConstructorDeclaration(MethodInfo constructor, TypeInfo containingType) { + // Modifiers (public, private, etc.) + declaration.clear(); + int mods = constructor.getModifiers(); + if (Modifier.isPublic(mods)) addSegment("public ", TokenType.KEYWORD.getHexColor()); + else if (Modifier.isProtected(mods)) addSegment("protected ", TokenType.KEYWORD.getHexColor()); + else if (Modifier.isPrivate(mods)) addSegment("private ", TokenType.KEYWORD.getHexColor()); + + // Constructor name (same as class name) + addSegment(constructor.getName(), containingType.getTokenType().getHexColor()); + + // Parameters + addSegment("(", TokenType.DEFAULT.getHexColor()); + List params = constructor.getParameters(); + for (int i = 0; i < params.size(); i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + FieldInfo param = params.get(i); + TypeInfo paramType = param.getTypeInfo(); + if (paramType != null) { + addTypeSegments(paramType); + if (param.isVarArg()) { + addSegment("...", TokenType.DEFAULT.getHexColor()); + } + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + addSegment(param.getName(), TokenType.PARAMETER.getHexColor()); + } + addSegment(")", TokenType.DEFAULT.getHexColor()); + + // Add documentation if available + if (constructor.getDocumentation() != null && !constructor.getDocumentation().isEmpty()) { + String[] docLines = constructor.getDocumentation().split("\n"); + for (String line : docLines) { + documentation.add(line); + } + } + } + + private void addSegment(String text, int color) { + declaration.add(new TextSegment(text, color)); + } + + private void buildMethodDeclaration(MethodInfo methodInfo, TypeInfo containingType) { + Method method = methodInfo.getJavaMethod(); + int mods = method.getModifiers(); + + // Annotations (show @Contract if present, etc.) + // Skip for now - could add later + + // Modifiers + if (Modifier.isPublic(mods)) addSegment("public ", TokenType.KEYWORD.getHexColor()); + else if (Modifier.isProtected(mods)) addSegment("protected ", TokenType.KEYWORD.getHexColor()); + else if (Modifier.isPrivate(mods)) addSegment("private ", TokenType.KEYWORD.getHexColor()); + + if (Modifier.isStatic(mods)) addSegment("static ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isFinal(mods)) addSegment("final ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isAbstract(mods)) addSegment("abstract ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isSynchronized(mods)) addSegment("synchronized ", TokenType.KEYWORD.getHexColor()); + + // Return type - check for actual type color (handle array suffix coloring) + TypeInfo returnType = methodInfo.getReturnType(); + String returnTypeName = returnType.getSimpleName(); + splitAndAddTypeName(returnTypeName, getColorForTypeInfo(methodInfo.getReturnType())); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + + // Method name + addSegment(method.getName(), TokenType.METHOD_DECL.getHexColor()); + + // Parameters + addSegment("(", TokenType.DEFAULT.getHexColor()); + List params = methodInfo.getParameters(); + for (int i = 0; i < params.size(); i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + FieldInfo param = params.get(i); + TypeInfo paramType = param.getTypeInfo(); + if (paramType != null) { + addTypeSegments(paramType); + if (param.isVarArg()) { + addSegment("...", TokenType.DEFAULT.getHexColor()); + } + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + addSegment(param.getName(), TokenType.PARAMETER.getHexColor()); + } + addSegment(")", TokenType.DEFAULT.getHexColor()); + } + + private void buildBasicMethodDeclaration(MethodInfo methodInfo, TypeInfo containingType) { + // Try to extract modifiers from source if this is a declaration + if (methodInfo.isDeclaration() && methodInfo.getDeclarationOffset() >= 0) { + String modifiers = extractModifiersAtPosition(methodInfo.getDeclarationOffset()); + if (modifiers != null && !modifiers.isEmpty()) { + addSegment(modifiers + " ", TokenType.KEYWORD.getHexColor()); + } + } else { + // Fallback: show static if we know it + if (methodInfo.isStatic()) { + addSegment("static ", TokenType.KEYWORD.getHexColor()); + } + } + + // Return type + TypeInfo returnType = methodInfo.getReturnType(); + if (ScriptDocument.INSTANCE.isJavaScript() && methodInfo.isDeclaration()) + addSegment("function ", TokenType.KEYWORD.getHexColor()); + else if (returnType != null) { + addTypeSegments(returnType); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } else { + addSegment("void ", TokenType.KEYWORD.getHexColor()); + } + + // Method name + addSegment(methodInfo.getName(), TokenType.METHOD_DECL.getHexColor()); + + // Parameters + addSegment("(", TokenType.DEFAULT.getHexColor()); + List params = methodInfo.getParameters(); + for (int i = 0; i < params.size(); i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + FieldInfo param = params.get(i); + TypeInfo paramType = param.getTypeInfo(); + if (paramType != null) { + addTypeSegments(paramType); + if (param.isVarArg()) { + addSegment("...", TokenType.DEFAULT.getHexColor()); + } + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + addSegment(param.getName(), TokenType.PARAMETER.getHexColor()); + } + addSegment(")", TokenType.DEFAULT.getHexColor()); + + // Add documentation if available - use JSDoc formatting if we have JSDocInfo + JSDocInfo jsDoc = methodInfo.getJSDocInfo(); + if (jsDoc != null) { + formatJSDocumentation(jsDoc, methodInfo.getParameters()); + } else if (methodInfo.getDocumentation() != null && !methodInfo.getDocumentation().isEmpty()) { + // Fallback to raw documentation + String[] docLines = methodInfo.getDocumentation().split("\n"); + for (String line : docLines) { + documentation.add(line); + } + } + + } + + private boolean shouldPreferMethodInfo(MethodInfo methodInfo) { + if (methodInfo.getJSDocInfo() != null) return true; + String doc = methodInfo.getDocumentation(); + if (doc != null && !doc.isEmpty()) return true; + + for (FieldInfo param : methodInfo.getParameters()) { + String name = param.getName(); + if (name != null && !name.matches("arg\\d+")) { + return true; + } + } + return false; + } + + /** + * Parses a JSDoc description string and routes each logical line into jsDocLines[] + * with markdown-aware coloring: + * - ## / ### headings → COLOR_METHOD (yellow) + * - ``` code fences → markers suppressed; code lines → COLOR_STRING (green) + * - blank lines → empty DocumentationLine (spacer) + * - normal text → default color + */ + /** + * Simple JavaScript syntax tokenizer. + * Breaks a single code line into colored TextSegments. + * Handles: // comments, "strings", 'strings', keywords, numbers, identifiers. + */ + private static List tokenizeCodeLine(String line) { + List tokens = new ArrayList<>(); + if (line == null || line.isEmpty()) return tokens; + + // JS keywords + java.util.Set keywords = new java.util.HashSet<>(java.util.Arrays.asList( + "var","let","const","function","return","if","else","while","for","do", + "break","continue","new","this","null","undefined","true","false", + "typeof","instanceof","void","delete","in","of","class","extends", + "import","export","from","try","catch","finally","throw","switch","case", + "default","with","debugger","yield","async","await" + )); + + int i = 0; + int len = line.length(); + + while (i < len) { + char c = line.charAt(i); + + // Line comment + if (c == '/' && i + 1 < len && line.charAt(i + 1) == '/') { + tokens.add(new TextSegment(line.substring(i), 0x6A9955)); // muted green-gray + break; + } + + // String literal + if (c == '"' || c == '\'') { + char quote = c; + int start = i++; + while (i < len && line.charAt(i) != quote) { + if (line.charAt(i) == '\\') i++; // skip escape + i++; + } + if (i < len) i++; // consume closing quote + tokens.add(new TextSegment(line.substring(start, i), TextSegment.COLOR_STRING)); + continue; + } + + // Number + if (Character.isDigit(c)) { + int start = i++; + while (i < len && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.' || line.charAt(i) == 'x' || line.charAt(i) == 'X' || (line.charAt(i) >= 'a' && line.charAt(i) <= 'f') || (line.charAt(i) >= 'A' && line.charAt(i) <= 'F'))) i++; + tokens.add(new TextSegment(line.substring(start, i), 0x6897BB)); + continue; + } + + // Identifier or keyword + if (Character.isLetter(c) || c == '_' || c == '$') { + int start = i++; + while (i < len && (Character.isLetterOrDigit(line.charAt(i)) || line.charAt(i) == '_' || line.charAt(i) == '$')) i++; + String word = line.substring(start, i); + int color = keywords.contains(word) ? TextSegment.COLOR_KEYWORD : TextSegment.COLOR_DEFAULT; + tokens.add(new TextSegment(word, color)); + continue; + } + + // Anything else (operators, punctuation, spaces) — group consecutive non-identifier chars + int start = i++; + while (i < len) { + char nc = line.charAt(i); + if (Character.isLetterOrDigit(nc) || nc == '_' || nc == '$' || nc == '"' || nc == '\'' || nc == '/' ) break; + i++; + } + tokens.add(new TextSegment(line.substring(start, i), TextSegment.COLOR_DEFAULT)); + } + + return tokens; + } + + private static boolean isCodeOperatorChar(char c) { + return "=<>!+-*/%&|^~,;:([{".indexOf(c) >= 0; + } + + private void addDescriptionAsMarkdown(String description) { + if (description == null || description.isEmpty()) return; + String[] lines = description.split("\n", -1); + boolean inCodeFence = false; + boolean nextIsFirst = false; + for (String line : lines) { + DocumentationLine docLine = new DocumentationLine(); + if (line.trim().startsWith("```")) { + // Toggle code fence — suppress the fence marker, emit empty spacer + inCodeFence = !inCodeFence; + if (inCodeFence) { + nextIsFirst = true; + } + jsDocLines.add(new DocumentationLine()); + } else if (inCodeFence) { + if (line.trim().isEmpty()) { + // Empty line inside code fence — keep as code line + DocumentationLine emptyCode = new DocumentationLine(); + emptyCode.isCodeLine = true; + if (nextIsFirst) { + emptyCode.isCodeBlockFirst = true; + nextIsFirst = false; + } + jsDocLines.add(emptyCode); + } else { + // Code content — strip leading spaces for explicit indentation, then syntax-highlight + int leadingSpaces = 0; + while (leadingSpaces < line.length() && line.charAt(leadingSpaces) == ' ') { + leadingSpaces++; + } + String codeLine = leadingSpaces > 0 ? line.substring(leadingSpaces) : line; + List codeTokens = tokenizeCodeLine(codeLine); + if (codeTokens.isEmpty()) { + docLine.addSegment(codeLine, TextSegment.COLOR_STRING); + } else { + for (TextSegment tok : codeTokens) { + docLine.segments.add(tok); + } + } + docLine.isCodeLine = true; + docLine.codeLeadingSpaces = leadingSpaces; + if (nextIsFirst) { + docLine.isCodeBlockFirst = true; + nextIsFirst = false; + } + jsDocLines.add(docLine); + } + } else if (line.trim().startsWith("###")) { + // H3 heading — yellow (strip ### prefix, keep emoji if present) + String text = line.trim().substring(3).trim(); + docLine.addSegment(text, TextSegment.COLOR_METHOD); + jsDocLines.add(docLine); + } else if (line.trim().startsWith("##")) { + // H2 heading — yellow (strip ## prefix, keep emoji if present) + String text = line.trim().substring(2).trim(); + docLine.addSegment(text, TextSegment.COLOR_METHOD); + jsDocLines.add(docLine); + } else if (line.trim().isEmpty()) { + // Blank line — empty spacer + jsDocLines.add(new DocumentationLine()); + } else { + // Normal text + docLine.addText(line.trim()); + jsDocLines.add(docLine); + } + } + // Strip trailing blank lines left by description ending with \n + while (!jsDocLines.isEmpty() && jsDocLines.get(jsDocLines.size() - 1).isEmpty() && !jsDocLines.get(jsDocLines.size() - 1).isCodeLine) { + jsDocLines.remove(jsDocLines.size() - 1); + } + } + + /** + * Format JSDoc information in IntelliJ-style with "Params:" and "Returns:" sections. + * Creates colored documentation lines with parameter names highlighted. + */ + private void formatJSDocumentation(JSDocInfo jsDoc, List methodParams) { + // Add description if available (without @tags) + String description = jsDoc.getDescription(); + if (description != null && !description.isEmpty()) { + addDescriptionAsMarkdown(description); + } + + // Add Returns section if there's a @return tag + JSDocTypeTag typeTag = jsDoc.getTypeTag(); + if (typeTag != null) { + // "Type:" header + DocumentationLine typeLine = new DocumentationLine(); + typeLine.addSegment("Type:", TokenType.JSDOC_TAG.getHexColor()); + + // Type if available + if (typeTag.hasType()) { + typeLine.addText(" "); + typeLine.addSegment("{", TokenType.JSDOC_TYPE.getHexColor()); + typeLine.addSegment(typeTag.getTypeName(), TokenType.getColor(typeTag.getTypeInfo())); + typeLine.addSegment("}", TokenType.JSDOC_TYPE.getHexColor()); + } + + // Description if available + String typeDesc = typeTag.getDescription(); + if (typeDesc != null && !typeDesc.isEmpty()) { + typeLine.addText(" - "); + typeLine.addText(typeDesc.trim()); + } + + jsDocLines.add(typeLine); + } + + // Add Params section if there are @param tags + List paramTags = jsDoc.getParamTags(); + if (paramTags != null && !paramTags.isEmpty()) { + // "Params:" header + DocumentationLine paramsHeader = new DocumentationLine(); + paramsHeader.addSegment("Params:", TokenType.JSDOC_TAG.getHexColor()); + jsDocLines.add(paramsHeader); + + // Add each parameter + for (JSDocParamTag paramTag : paramTags) { + DocumentationLine paramLine = new DocumentationLine(); + + // Indent and parameter name + String paramName = paramTag.getParamName(); + if (paramName == null || paramName.isEmpty()) { + paramLine.addSegment("param", TokenType.JSDOC_TAG.getHexColor()); + } else { + boolean paramExists = methodParams != null && methodParams.stream() + .anyMatch(p -> p.getName().equals(paramName)); + paramLine.addSegment(paramName, + paramExists ? TokenType.PARAMETER.getHexColor() : TokenType.UNDEFINED_VAR.getHexColor()); + } + + // Type if available + if (paramTag.hasType()) { + paramLine.addSegment(" {", TokenType.JSDOC_TYPE.getHexColor()); + paramLine.addSegment(paramTag.getTypeName(), TokenType.getColor(paramTag.getTypeInfo())); + paramLine.addSegment("}", TokenType.JSDOC_TYPE.getHexColor()); + } + + // Description if available + String paramDesc = paramTag.getDescription(); + if (paramDesc != null && !paramDesc.isEmpty()) { + String[] paramDescLines = paramDesc.split("\n", -1); + paramLine.addText(" - "); + paramLine.addText(paramDescLines[0].trim()); + jsDocLines.add(paramLine); + for (int i = 1; i < paramDescLines.length; i++) { + if (!paramDescLines[i].trim().isEmpty()) { + DocumentationLine contLine = new DocumentationLine(); + contLine.addText(" " + paramDescLines[i].trim()); + jsDocLines.add(contLine); + } + } + } else { + jsDocLines.add(paramLine); + } + } + } + + // Add Returns section if there's a @return tag + JSDocReturnTag returnTag = jsDoc.getReturnTag(); + if (returnTag != null) { + DocumentationLine returnLine = new DocumentationLine(); + + //"Returns:" header + returnLine.addSegment("Returns:", TokenType.JSDOC_TAG.getHexColor()); + + // Type if available + if (returnTag.hasType()) { + returnLine.addText(" "); + returnLine.addSegment("{", TokenType.JSDOC_TYPE.getHexColor()); + returnLine.addSegment(returnTag.getTypeName(), TokenType.getColor(returnTag.getTypeInfo())); + returnLine.addSegment("}", TokenType.JSDOC_TYPE.getHexColor()); + } + + // Description if available + String returnDesc = returnTag.getDescription(); + if (returnDesc != null && !returnDesc.isEmpty()) { + String[] returnDescLines = returnDesc.split("\n", -1); + returnLine.addText(" - "); + returnLine.addText(returnDescLines[0].trim()); + jsDocLines.add(returnLine); + for (int i = 1; i < returnDescLines.length; i++) { + if (!returnDescLines[i].trim().isEmpty()) { + DocumentationLine contLine = new DocumentationLine(); + contLine.addText(" " + returnDescLines[i].trim()); + jsDocLines.add(contLine); + } + } + } else { + jsDocLines.add(returnLine); + } + } + + List seeTags = jsDoc.getSeeTags(); + if (seeTags != null && !seeTags.isEmpty()) { + for (JSDocSeeTag seeTag : seeTags) { + DocumentationLine seeLine = new DocumentationLine(); + seeLine.addSegment("See:", TokenType.JSDOC_TAG.getHexColor()); + + String reference = seeTag.getReference(); + if (seeTag.hasLinkText()) { + seeLine.addText(" "); + seeLine.addSegment(seeTag.getLinkText(), TokenType.INTERFACE_DECL.getHexColor()); + } else if (reference != null) { + seeLine.addText(" " + reference); + } + + jsDocLines.add(seeLine); + } + } + + List allTags = jsDoc.getAllTags(); + if (allTags != null && !allTags.isEmpty()) { + for (JSDocTag tag : allTags) { + String tagName = tag.getTagName(); + if (tagName == null) { + continue; + } + + String normalized = tagName.toLowerCase(); + if ("type".equals(normalized) + || "param".equals(normalized) + || "return".equals(normalized) + || "returns".equals(normalized) + || "see".equals(normalized)) { + continue; + } + + DocumentationLine tagLine = new DocumentationLine(); + //capitalise first letter in tag name + String capTagName = tagName.substring(0, 1).toUpperCase() + tagName.substring(1); + tagLine.addSegment(capTagName + ":", TokenType.JSDOC_TAG.getHexColor()); + + if (tag.hasType()) { + tagLine.addSegment(" {", TokenType.JSDOC_TYPE.getHexColor()); + tagLine.addSegment(tag.getTypeName(), TokenType.getColor(tag.getTypeInfo())); + tagLine.addSegment("}", TokenType.JSDOC_TYPE.getHexColor()); + } + + String tagDesc = tag.getDescription(); + if (tagDesc != null && !tagDesc.isEmpty()) { + tagLine.addText(" - "); + tagLine.addText(tagDesc.trim()); + } + + jsDocLines.add(tagLine); + } + } + } + + private void extractJavadoc(Method method) { + // Java reflection doesn't provide Javadoc at runtime + // We could potentially load it from source files or external documentation + // For now, we'll leave this as a placeholder for future enhancement + + // Check for @Deprecated annotation + if (method.isAnnotationPresent(Deprecated.class)) { + additionalInfo.add("@Deprecated"); + } + } + + /** + * Extract modifiers (public, private, static, final, etc.) before a declaration position. + * Looks backward from the position to find modifiers. + */ + private String extractModifiersAtPosition(int position) { + if (token.getParentLine().getParent() == null) + return null; + + String text = token.getParentLine().getParent().getText(); + if (position < 0 || position >= text.length()) + return null; + + // Look backward from position to find start of line or previous semicolon/brace + int searchStart = position - 1; + while (searchStart >= 0) { + char c = text.charAt(searchStart); + if (c == ';' || c == '{' || c == '}' || c == '\n') { + searchStart++; + break; + } + searchStart--; + } + if (searchStart < 0) + searchStart = 0; + + // Extract text before the declaration + String beforeDecl = text.substring(searchStart, position).trim(); + + // Match modifier keywords + StringBuilder modifiers = new StringBuilder(); + String[] words = beforeDecl.split("\\s+"); + for (String word : words) { + if (TypeResolver.isModifier(word)) { + if (modifiers.length() > 0) + modifiers.append(" "); + modifiers.append(word); + } + } + + return modifiers.toString(); + } + + /** + * Add field modifiers from Java reflection modifiers. + */ + private void addFieldModifiers(int mods) { + if (Modifier.isPublic(mods)) + addSegment("public ", TokenType.KEYWORD.getHexColor()); + else if (Modifier.isProtected(mods)) + addSegment("protected ", TokenType.KEYWORD.getHexColor()); + else if (Modifier.isPrivate(mods)) + addSegment("private ", TokenType.KEYWORD.getHexColor()); + + if (Modifier.isStatic(mods)) + addSegment("static ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isFinal(mods)) + addSegment("final ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isVolatile(mods)) + addSegment("volatile ", TokenType.KEYWORD.getHexColor()); + if (Modifier.isTransient(mods)) + addSegment("transient ", TokenType.KEYWORD.getHexColor()); + } + + /** + * Get the appropriate color for a Class based on its type. + */ + private int getColorForClass(Class clazz) { + if(clazz.isPrimitive()) return TokenType.KEYWORD.getHexColor(); + if (clazz.isInterface()) return TokenType.INTERFACE_DECL.getHexColor(); + if (clazz.isEnum()) return TokenType.ENUM_DECL.getHexColor(); + return TokenType.IMPORTED_CLASS.getHexColor(); + } + + /** + * Get the appropriate color for a TypeInfo based on its type kind. + * Works for both Java-backed TypeInfo and ScriptTypeInfo. + */ + private int getColorForTypeInfo(TypeInfo typeInfo) { + // Use the TypeInfo's own token type, which handles ScriptTypeInfo correctly + return TokenType.getColor(typeInfo); + } + + /** + * Add initialization tokens from the field's initializer to the declaration. + * Fetches the tokens in the initialization range and adds them with their proper coloring. + */ + private void addInitializationTokens(Token token, FieldInfo fieldInfo) { + if (!fieldInfo.hasInitializer()) return; + + ScriptLine line = token.getParentLine(); + if (line == null || line.getParent() == null) return; + + ScriptDocument doc = line.getParent(); + // Include the semicolon by extending range by 1 + List initTokens = doc.getTokensInRange(fieldInfo.getInitStart(), fieldInfo.getInitEnd() + 1); + + if (initTokens.isEmpty()) return; + + // Add space before '=' for readability + addSegment(" ", TokenType.DEFAULT.getHexColor()); + + // Add each token with its proper color, ensuring normalized spacing between tokens + String lastText = null; + for (Token initToken : initTokens) { + String text = initToken.getText(); + + // Normalize whitespace - replace all newlines and multiple spaces with single space + text = text.replaceAll("\\s+", " ").trim(); + + // Skip if token became empty after whitespace removal + if (text.isEmpty()) { + continue; + } + + // Determine if we need a space between last token and current token + if (lastText != null && shouldAddSpace(lastText, text)) { + addSegment(" ", TokenType.DEFAULT.getHexColor()); + } + + addSegment(text, initToken.getType().getHexColor()); + lastText = text; + } + } + + /** + * Determine if a space should be added between two tokens. + */ + private boolean shouldAddSpace(String lastToken, String currentToken) { + if (lastToken.isEmpty() || currentToken.isEmpty()) + return false; + + char lastChar = lastToken.charAt(lastToken.length() - 1); + char firstChar = currentToken.charAt(0); + + // Never add space before these closing/trailing characters + if (firstChar == '(' || firstChar == '[' || firstChar == '{' || + firstChar == '.' || firstChar == ',' || firstChar == ';' || + firstChar == '>' || // No space before closing angle bracket + (firstChar == ':' && lastToken.equals("?"))) { + return false; + } + + // Never add space after these opening/leading characters + if (lastChar == '(' || lastChar == '[' || lastChar == '{' || + lastChar == '.' || lastChar == '<') { // No space after opening angle bracket + return false; + } + + // Add space around operators (check last/first characters) + if (isOperatorChar(lastChar) || isOperatorChar(firstChar)) { + return true; + } + + // Add space after closing brackets/parens before other tokens + if (lastChar == ')' || lastChar == ']' || lastChar == '}') { + return true; + } + + // Add space after colons and commas (except after ?: ternary) + if ((lastChar == ':' && !lastToken.equals("?:")) || lastChar == ',') { + return true; + } + + // Add space between identifiers/keywords and numbers + boolean lastIsIdentifier = Character.isLetterOrDigit(lastChar) || lastChar == '_'; + boolean firstIsIdentifier = Character.isLetterOrDigit(firstChar) || firstChar == '_'; + if (lastIsIdentifier && firstIsIdentifier) { + return true; + } + + return false; + } + + /** + * Check if a character is an operator that needs spacing. + */ + private boolean isOperatorChar(char c) { + return "+-*/%<>=!&|^?:".indexOf(c) >= 0; + } + // ==================== GETTERS ==================== + + public String getPackageName() { return packageName; } + public String getIconIndicator() { return iconIndicator; } + + public List getDeclaration() { + return declaration; + } + public List getDocumentation() { return documentation; } + + public List getJSDocLines() { + return jsDocLines; + } + public List getErrors() { return errors; } + public List getAdditionalInfo() { return additionalInfo; } + public Token getToken() { return token; } + + public boolean hasContent() { + return !declaration.isEmpty() || !errors.isEmpty() || !documentation.isEmpty() || !jsDocLines.isEmpty(); + } + + public boolean hasJSDocContent() { + return !jsDocLines.isEmpty(); + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java new file mode 100644 index 000000000..ec9fae79a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java @@ -0,0 +1,762 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.GuiNPCInterface; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +/** + * Renders hover tooltips for tokens in the script editor. + * + * Renders IntelliJ-style tooltips with: + * - Package name in gray + * - Icon indicator (C/I/E/m/f/v/p) + * - Colored declaration line + * - Documentation/Javadoc + * - Error messages in red + * + * Uses a unified approach for width/height calculation based on max available width. + */ +public class TokenHoverRenderer { + + // ==================== CONSTANTS ==================== + + /** Padding inside the tooltip box */ + private static final int PADDING = 6; + + /** Line spacing between rows */ + private static final int LINE_SPACING = 2; + + /** Separator line height */ + private static final int SEPARATOR_HEIGHT = 1; + + /** Spacing above and below separator */ + private static final int SEPARATOR_SPACING = 5; + + /** Vertical offset from token */ + private static final int VERTICAL_OFFSET = 1; + + /** Maximum tooltip width as percentage of viewport */ + private static final float MAX_WIDTH_RATIO = 0.9f; + + /** Minimum tooltip width */ + private static final int MIN_WIDTH = 50; + + // ==================== COLORS ==================== + + /** Background color (dark gray like IntelliJ) */ + private static final int BG_COLOR = 0xF0313335; + + /** Border color */ + private static final int BORDER_COLOR = 0xFF3C3F41; + + /** Package text color */ + private static int PACKAGE_COLOR = 0xFF6490e2; + + /** Error text color */ + private static final int ERROR_COLOR = 0xFFFF6B68; + + /** Info text color */ + private static final int INFO_COLOR = 0xFF808080; + + /** Documentation text color */ + private static final int DOC_COLOR = 0xFFA9B7C6; + + /** Background fill for ``` code blocks */ + private static final int CODE_BG_COLOR = 0xFF1E1F22; + /** Left accent bar color for code blocks */ + private static final int CODE_ACCENT_COLOR = 0xFF4FC1FF; + /** Horizontal padding inside code block */ + private static final int CODE_INDENT = 10; + /** Vertical padding above/below code block content */ + private static final int CODE_VPAD = 6; + /** Fixed visual gap between last content line and the panel bottom (always visible, regardless of scroll) */ + private static final int BOTTOM_GAP = 4; + + // ==================== RENDERING ==================== + + /** + * Render the hover tooltip. + */ + public static void render(HoverState hoverState, int viewportX, int viewportWidth, int viewportY, int viewportHeight, GuiNPCInterface gui) { + if (!hoverState.isTooltipVisible()) return; + hoverState.updateSmoothScroll(); + + TokenHoverInfo info = hoverState.getHoverInfo(); + if (info == null || !info.hasContent()) return; + + int lineHeight = ClientProxy.Font.height(); + int tokenX = hoverState.getTokenScreenX(); + int tokenY = hoverState.getTokenScreenY(); + + // Screen dimensions for clamping when the panel has been dragged outside the editor viewport + Minecraft mc2 = Minecraft.getMinecraft(); + ScaledResolution sr2 = new ScaledResolution(mc2, mc2.displayWidth, mc2.displayHeight); + int screenW = sr2.getScaledWidth(); + int screenH = sr2.getScaledHeight(); + boolean positionOverridden = hoverState.hasOverriddenPosition(); + // Use screen bounds whenever the panel has been dragged OR resized — both escape the editor viewport + boolean useScreenBounds = positionOverridden || hoverState.hasOverriddenSize(); + + // Calculate max available width for content + int maxContentWidth = getMaxContentWidth(viewportX, viewportWidth, tokenX); + + // Calculate actual content width needed (clamped to max) + int contentWidth = calculateContentWidth(info, maxContentWidth); + + // Cap visible height at 60% of viewport + int totalContentHeight = calculateContentHeight(info, contentWidth); + int maxVisibleContentHeight = (int)((useScreenBounds ? screenH : viewportHeight) * 0.60f); + if (totalContentHeight > maxVisibleContentHeight) { + // Scrollbar will appear, reducing effective wrap width by 6px — re-measure for accurate height + totalContentHeight = calculateContentHeight(info, contentWidth - 6); + } + int visibleContentHeight = Math.min(totalContentHeight, maxVisibleContentHeight); + + // Box dimensions — use visibleContentHeight so positioning matches rendering + int boxWidth = contentWidth + PADDING * 2; + int boxHeight = visibleContentHeight + PADDING * 2; + + // Apply user size override when the panel has been resized + if (hoverState.hasOverriddenSize()) { + int overW = Math.max(MIN_WIDTH + PADDING * 2, hoverState.getOverriddenTooltipW()); + int overH = Math.max(lineHeight + PADDING * 2, hoverState.getOverriddenTooltipH()); + boxWidth = overW; + visibleContentHeight = overH - PADDING * 2; + boxHeight = overH; + // Re-measure with new wrap width so scrollbar detection is accurate + int newContentW = boxWidth - PADDING * 2; + totalContentHeight = calculateContentHeight(info, newContentW); + if (totalContentHeight > visibleContentHeight) { + totalContentHeight = calculateContentHeight(info, newContentW - 6); + } + } + + // Position the tooltip — use dragged position if user has panned the panel, + // otherwise use locked mouse position (captured when tooltip first became visible) + int tooltipX; + int tooltipY; + if (positionOverridden) { + tooltipX = hoverState.getOverriddenTooltipX(); + tooltipY = hoverState.getOverriddenTooltipY(); + } else if (hoverState.isPositionLocked()) { + tooltipX = hoverState.getLockedMouseX() + 2; + tooltipY = tokenY + lineHeight + VERTICAL_OFFSET; + } else { + tooltipX = tokenX; + tooltipY = tokenY + lineHeight + VERTICAL_OFFSET; + } + + // Clamp position — use screen bounds when user has dragged the panel outside the editor viewport + int leftBound = useScreenBounds ? 0 : viewportX; + int rightBound = useScreenBounds ? screenW : viewportX + viewportWidth; + int topBound = useScreenBounds ? 0 : viewportY; + int bottomBound = useScreenBounds ? screenH : viewportY + viewportHeight; + + if (tooltipX + boxWidth > rightBound) { + tooltipX = rightBound - boxWidth; + } + if (tooltipX < leftBound) { + tooltipX = leftBound; + } + + // If box still doesn't fit horizontally, shrink it + int availableWidth = rightBound - tooltipX; + if (boxWidth > availableWidth) { + boxWidth = availableWidth; + } + + if (tooltipY + boxHeight > bottomBound) { + if (useScreenBounds) { + tooltipY = bottomBound - boxHeight; + } else { + tooltipY = tokenY - boxHeight; + } + } + if (tooltipY < topBound) { + tooltipY = topBound; + } + + // Record actual panel rect for drag hit-testing + hoverState.setTooltipPanel(tooltipX, tooltipY, boxWidth, boxHeight); + + // Mouse-over detection bounds: + // When dragged, use panel rect only — no gap extension (token is unrelated to panel position) + // When default and tooltip is BELOW the token, union the token bottom and the tooltip rect + // so the small gap between token and tooltip doesn't break hover detection. + // When tooltip is ABOVE the token, use only the tooltip rect — bridging would cover + // intervening tokens and prevent hover-switching between them. + if (hoverState.hasOverriddenPosition()) { + hoverState.setTooltipBounds(tooltipX, tooltipY, boxWidth, boxHeight); + } else if (tooltipY >= tokenY + lineHeight) { + // Tooltip is below the token — bridge the gap + int boundsTopY = tokenY + lineHeight; + int boundsBottomY = tooltipY + boxHeight; + hoverState.setTooltipBounds(tooltipX, boundsTopY, boxWidth, boundsBottomY - boundsTopY); + } else { + // Tooltip is above the token — use tooltip rect only + hoverState.setTooltipBounds(tooltipX, tooltipY, boxWidth, boxHeight); + } + + // Render the tooltip + renderTooltipBox(tooltipX, tooltipY, boxWidth, maxContentWidth, info, hoverState, + totalContentHeight, visibleContentHeight, gui); + } + + /** + * Calculate the maximum content width based on viewport and token position. + */ + private static int getMaxContentWidth(int viewportX, int viewportWidth, int tokenX) { + // Max width is based on viewport size (80% by default) + // This scales naturally with viewport size - no artificial hard cap + int maxWidth = (int)(viewportWidth * MAX_WIDTH_RATIO); + + // The tooltip can expand across the entire viewport width + // (positioning logic will shift it left if needed) + return Math.max(MIN_WIDTH, maxWidth); + } + + /** + * Render the tooltip box with all content. + */ + private static void renderTooltipBox(int x, int y, int boxWidth, int wrapWidth, TokenHoverInfo info, + HoverState hoverState, int totalContentHeight, int visibleContentHeight, GuiNPCInterface gui) { + + boolean hasScrollbar = totalContentHeight > visibleContentHeight; + // Wrap at the actual box content area width, not the max allowed width. + // Using maxContentWidth here caused lines to never wrap at wide viewports (fullscreen). + int contentWrapWidth = boxWidth - PADDING * 2; + int effectiveWrapWidth = hasScrollbar ? contentWrapWidth - 6 : contentWrapWidth; + + int boxHeight = visibleContentHeight + PADDING * 2; + + // Store scroll metadata into HoverState + hoverState.setTooltipMaxScroll(Math.max(0, totalContentHeight - visibleContentHeight + (hasScrollbar? BOTTOM_GAP : 0))); + + // Draw background + Gui.drawRect(x, y, x + boxWidth, y + boxHeight, BG_COLOR); + + // Draw border + Gui.drawRect(x, y, x + boxWidth, y + 1, BORDER_COLOR); + Gui.drawRect(x, y + boxHeight - 1, x + boxWidth, y + boxHeight, BORDER_COLOR); + Gui.drawRect(x, y, x + 1, y + boxHeight, BORDER_COLOR); + Gui.drawRect(x + boxWidth - 1, y, x + boxWidth, y + boxHeight, BORDER_COLOR); + + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int sf = sr.getScaleFactor(); + double panX = gui != null ? gui.getPanX() : 0; + double panY = gui != null ? gui.getPanY() : 0; + int clipX = (int)((x + 1 - panX) * sf); + int clipY = (int)((sr.getScaledHeight() - (y - panY + boxHeight - 1 - BOTTOM_GAP)) * sf); + int clipW = (hasScrollbar ? boxWidth - PADDING - 1 : boxWidth - 2) * sf; + int clipH = (boxHeight - 2 - BOTTOM_GAP) * sf; + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(clipX, clipY, clipW, clipH); + + int textX = x + PADDING; + int currentY = y + PADDING - hoverState.getTooltipScrollOffset(); + int lineHeight = ClientProxy.Font.height(); + + String packageName = info.getPackageName(); + List declaration = info.getDeclaration(); + List docs = info.getDocumentation(); + List additionalInfo = info.getAdditionalInfo(); + + // Draw errors first + List errors = info.getErrors(); + if (!errors.isEmpty()) { + for (String error : errors) { + List wrappedLines = wrapText(error, effectiveWrapWidth); + for (String line : wrappedLines) { + drawText(textX, currentY, line, ERROR_COLOR); + currentY += lineHeight + LINE_SPACING; + } + } + boolean onlyErrors = errors != null && !errors.isEmpty() && (packageName == null || packageName.isEmpty()) && (declaration == null || + declaration.isEmpty()) && (docs == null || docs.isEmpty()) && (additionalInfo == null || additionalInfo.isEmpty()); + + if (!onlyErrors) { //Add error separator line + currentY += SEPARATOR_HEIGHT + SEPARATOR_SPACING - 5; + Gui.drawRect(textX, currentY, x + boxWidth - PADDING, currentY + SEPARATOR_HEIGHT, BORDER_COLOR); + currentY += SEPARATOR_HEIGHT + SEPARATOR_SPACING; + } + currentY += LINE_SPACING; + } + + // Draw package name + if (packageName != null && !packageName.isEmpty()) { + String packageText = "\u25CB " + packageName; + List wrappedLines = wrapText(packageText, effectiveWrapWidth); + for (String line : wrappedLines) { + drawText(textX, currentY, line, PACKAGE_COLOR); + currentY += lineHeight + LINE_SPACING; + } + } + + // Draw declaration (colored segments with wrapping) + if (!declaration.isEmpty()) { + currentY = drawWrappedSegments(textX, currentY, effectiveWrapWidth, declaration); + currentY += LINE_SPACING; + } + + // Draw documentation (plain text) + if (!docs.isEmpty()) { + // Draw separator line before documentation + Gui.drawRect(textX, currentY, x + boxWidth - PADDING, currentY + SEPARATOR_HEIGHT, BORDER_COLOR); + currentY += SEPARATOR_HEIGHT + SEPARATOR_SPACING; + for (String doc : docs) { + List wrappedLines = wrapText(doc, effectiveWrapWidth); + for (String line : wrappedLines) { + drawText(textX, currentY, line, DOC_COLOR); + currentY += lineHeight + LINE_SPACING; + } + } + } + + // Draw JSDoc-formatted documentation with colored segments + List jsDocLines = info.getJSDocLines(); + if (!jsDocLines.isEmpty()) { + // Draw separator line if there was plain documentation or declaration + if (docs.isEmpty() && !declaration.isEmpty()) { + Gui.drawRect(textX, currentY, x + boxWidth - PADDING, currentY + SEPARATOR_HEIGHT, BORDER_COLOR); + currentY += SEPARATOR_HEIGHT + SEPARATOR_SPACING; + } + + boolean previousVisibleJSDocWasCode = false; + for (int di = 0; di < jsDocLines.size(); di++) { + TokenHoverInfo.DocumentationLine docLine = jsDocLines.get(di); + + if (docLine.isCodeBlockFirst) { + // Lookahead: measure full block height + int blockH = CODE_VPAD; + for (int k = di; k < jsDocLines.size() && jsDocLines.get(k).isCodeLine; k++) { + TokenHoverInfo.DocumentationLine cl = jsDocLines.get(k); + if (!cl.isEmpty()) { + int clIndent = cl.codeLeadingSpaces * ClientProxy.Font.width(" "); + int clWrapW = Math.max(10, effectiveWrapWidth - CODE_INDENT - clIndent); + blockH += calculateSegmentsHeight(clWrapW, cl.segments) + LINE_SPACING; + } else { + blockH += lineHeight / 2; + } + } + blockH -= LINE_SPACING * 2; // subtract trailing LINE_SPACING (present inside bg) + one more to visually balance top/bottom + blockH += CODE_VPAD; + // Draw background + Gui.drawRect(textX , currentY - CODE_VPAD, + textX + effectiveWrapWidth + 4, currentY - CODE_VPAD + blockH, + CODE_BG_COLOR); + // Left accent bar + Gui.drawRect(textX, currentY - CODE_VPAD, + textX+2, currentY - CODE_VPAD + blockH, + CODE_ACCENT_COLOR); + } + + if (docLine.isCodeLine) { + if (!docLine.isEmpty()) { + int explicitIndent = docLine.codeLeadingSpaces * ClientProxy.Font.width(" "); + int codeX = textX + CODE_INDENT + explicitIndent; + int codeWrapW = Math.max(10, effectiveWrapWidth - CODE_INDENT - explicitIndent); + currentY = drawWrappedSegments(codeX, currentY, codeWrapW, docLine.segments); + currentY += LINE_SPACING; + previousVisibleJSDocWasCode = true; + } else { + currentY += lineHeight / 2; + } + } else if (!docLine.isEmpty()) { + if (previousVisibleJSDocWasCode) { + currentY += LINE_SPACING; + } + currentY = drawWrappedSegments(textX, currentY, effectiveWrapWidth, docLine.segments); + currentY += LINE_SPACING; + previousVisibleJSDocWasCode = false; + } else { + currentY += (di > 0 && jsDocLines.get(di - 1).isCodeLine) ? LINE_SPACING : lineHeight / 2; + } + } + } + + // Draw additional info + if (!additionalInfo.isEmpty()) { + currentY += LINE_SPACING; + for (String infoLine : additionalInfo) { + List wrappedLines = wrapText(infoLine, effectiveWrapWidth); + for (String line : wrappedLines) { + drawText(textX, currentY, line, INFO_COLOR); + currentY += lineHeight + LINE_SPACING; + } + } + } + + // Restore scissor state before drawing scrollbar (scrollbar must not be clipped) + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Draw scrollbar outside scissor rect so it is never clipped + if (hasScrollbar) { + int scrollbarX = x + boxWidth - PADDING; + int scrollbarTrackTop = y + PADDING; + int scrollbarTrackHeight = visibleContentHeight - 4; // leave room for resize handle + // Track + Gui.drawRect(scrollbarX, scrollbarTrackTop, scrollbarX + 3, + scrollbarTrackTop + scrollbarTrackHeight, 0x40888888); + // Thumb + float scrollRatio = (float) visibleContentHeight / (totalContentHeight + BOTTOM_GAP); + int thumbHeight = Math.max(6, (int)(scrollbarTrackHeight * scrollRatio)); + int effectiveMaxScroll = totalContentHeight - visibleContentHeight + BOTTOM_GAP; + // Clamp scrollProgress to [0,1] — guards against stale offset after resize shrinks content + float scrollProgress = effectiveMaxScroll > 0 + ? Math.min(1f, (float) hoverState.getTooltipScrollOffset() / effectiveMaxScroll) : 0f; + int thumbY = scrollbarTrackTop + (int)((scrollbarTrackHeight - thumbHeight) * scrollProgress); + // Clamp thumb within track bounds defensively + thumbY = Math.max(scrollbarTrackTop, Math.min(scrollbarTrackTop + scrollbarTrackHeight - thumbHeight, thumbY)); + // Store thumb bounds in HoverState for drag/hover detection + hoverState.setScrollbarThumb(scrollbarX, thumbY, thumbHeight, scrollbarTrackTop, scrollbarTrackHeight); + // Highlight thumb when hovered or dragging (darker = active, like AutocompleteMenu) + int mouseX = hoverState.getLastMouseX(); + int mouseY = hoverState.getLastMouseY(); + boolean thumbActive = hoverState.isDraggingScrollbar() + || hoverState.isMouseOverScrollbarThumb(mouseX, mouseY); + int thumbColor = thumbActive ? 0xFFCCCCCC : 0xFF808080; + Gui.drawRect(scrollbarX, thumbY, scrollbarX + 3, thumbY + thumbHeight, thumbColor); + } + + // Draw resize handle at bottom-right corner (outside scissor, same as scrollbar) + { + int mouseX = hoverState.getLastMouseX(); + int mouseY = hoverState.getLastMouseY(); + boolean resizeActive = hoverState.isResizingTooltip() + || hoverState.isMouseOverResizeHandle(mouseX, mouseY); + int dotColor = resizeActive ? 0xFFCCCCCC : 0x80888888; + int rhX = x + boxWidth - 2; + int rhY = y + boxHeight - 2; + // Three-dot diagonal pattern (◢) + Gui.drawRect(rhX - 1, rhY - 1, rhX, rhY, dotColor); + Gui.drawRect(rhX - 3, rhY - 1, rhX - 2, rhY, dotColor); + Gui.drawRect(rhX - 1, rhY - 3, rhX, rhY - 2, dotColor); + Gui.drawRect(rhX - 5, rhY - 1, rhX - 4, rhY, dotColor); + Gui.drawRect(rhX - 3, rhY - 3, rhX - 2, rhY - 2, dotColor); + Gui.drawRect(rhX - 1, rhY - 5, rhX, rhY - 4, dotColor); + } + } + + /** + * Draw colored text segments with word wrapping. + * Returns the Y position after drawing. + */ + private static int drawWrappedSegments(int startX, int startY, int maxWidth, List segments) { + int lineHeight = ClientProxy.Font.height(); + int currentX = startX; + int currentY = startY; + + for (TokenHoverInfo.TextSegment segment : segments) { + String text = segment.text; + int color = segment.color; + + // Split segment into words for wrapping + String[] words = text.split("(?<=\\s)|(?=\\s)"); // Keep whitespace as separate tokens + + for (String word : words) { + int wordWidth = ClientProxy.Font.width(word); + + // Check if word fits on current line + if (currentX + wordWidth > startX + maxWidth && currentX > startX) { + // Wrap to next line + currentY += lineHeight + LINE_SPACING; + currentX = startX; + + // Skip leading whitespace on new line + if (word.trim().isEmpty()) { + continue; + } + } + + drawText(currentX, currentY, word, color); + currentX += wordWidth; + } + } + + return currentY + lineHeight; + } + + /** + * Wrap text to fit within maxWidth. + * Returns list of lines. + */ + private static List wrapText(String text, int maxWidth) { + List lines = new ArrayList<>(); + + if (text == null || text.isEmpty()) { + return lines; + } + + // First split by explicit newlines + String[] paragraphs = text.split("\n", -1); // -1 to preserve trailing empty lines + + for (String paragraph : paragraphs) { + if (paragraph.isEmpty()) { + lines.add(""); + continue; + } + + // Then apply word wrapping to each paragraph + String[] words = paragraph.split(" "); + StringBuilder currentLine = new StringBuilder(); + + for (String word : words) { + String testLine = currentLine.length() == 0 ? word : currentLine + " " + word; + int testWidth = ClientProxy.Font.width(testLine); + + if (testWidth > maxWidth && currentLine.length() > 0) { + lines.add(currentLine.toString()); + currentLine = new StringBuilder(word); + } else { + if (currentLine.length() > 0) { + currentLine.append(" "); + } + currentLine.append(word); + } + } + + if (currentLine.length() > 0) { + lines.add(currentLine.toString()); + } + } + + if (lines.isEmpty()) { + lines.add(text); + } + return lines; + } + + /** + * Draw text using the font renderer. + */ + private static void drawText(int x, int y, String text, int color) { + ClientProxy.Font.drawString(text, x, y, color); + } + + // ==================== DIMENSION CALCULATION ==================== + + /** + * Calculate the width needed for the content, clamped to maxWidth. + * Returns the width of the longest wrapped line. + */ + private static int calculateContentWidth(TokenHoverInfo info, int maxWidth) { + int longestLineWidth = 0; + + // Package name + String packageName = info.getPackageName(); + if (packageName != null && !packageName.isEmpty()) { + String packageText = "\u25CB " + packageName; + List wrappedLines = wrapText(packageText, maxWidth); + for (String line : wrappedLines) { + longestLineWidth = Math.max(longestLineWidth, ClientProxy.Font.width(line)); + } + } + + // Declaration - wrap segments and find longest line + if (!info.getDeclaration().isEmpty()) { + int declarationLongestLine = calculateSegmentsLongestLine(maxWidth, info.getDeclaration()); + longestLineWidth = Math.max(longestLineWidth, declarationLongestLine); + } + + // Errors + for (String error : info.getErrors()) { + List wrappedLines = wrapText(error, maxWidth); + for (String line : wrappedLines) { + longestLineWidth = Math.max(longestLineWidth, ClientProxy.Font.width(line)); + } + } + + // Documentation + for (String doc : info.getDocumentation()) { + List wrappedLines = wrapText(doc, maxWidth); + for (String line : wrappedLines) { + longestLineWidth = Math.max(longestLineWidth, ClientProxy.Font.width(line)); + } + } + + // JSDoc-formatted documentation lines + List jsDocLines = info.getJSDocLines(); + if (jsDocLines != null) { + for (TokenHoverInfo.DocumentationLine docLine : jsDocLines) { + if (!docLine.isEmpty()) { + int explicitIndent = docLine.isCodeLine + ? CODE_INDENT + docLine.codeLeadingSpaces * ClientProxy.Font.width(" ") + : 0; + int lineLongest = calculateSegmentsLongestLine(maxWidth - explicitIndent, docLine.segments) + explicitIndent; + longestLineWidth = Math.max(longestLineWidth, lineLongest); + } + } + } + + // Additional info + for (String line : info.getAdditionalInfo()) { + List wrappedLines = wrapText(line, maxWidth); + for (String wrappedLine : wrappedLines) { + longestLineWidth = Math.max(longestLineWidth, ClientProxy.Font.width(wrappedLine)); + } + } + + // Ensure minimum width + return Math.max(50, longestLineWidth); + } + + /** + * Calculate the height needed for the content given the available width. + * Uses the same wrapping logic as rendering. + */ + private static int calculateContentHeight(TokenHoverInfo info, int contentWidth) { + int lineHeight = ClientProxy.Font.height(); + int totalHeight = 0; + + String packageName = info.getPackageName(); + List declaration = info.getDeclaration(); + List docs = info.getDocumentation(); + List jsDocLines = info.getJSDocLines(); + List additionalInfo = info.getAdditionalInfo(); + + // Errors + List errors = info.getErrors(); + if (!errors.isEmpty()) { + for (String error : errors) { + List wrappedLines = wrapText(error, contentWidth); + totalHeight += wrappedLines.size() * (lineHeight + LINE_SPACING); + } + + boolean onlyErrors = errors != null && !errors.isEmpty() && (packageName == null || packageName.isEmpty()) && (declaration == null || + declaration.isEmpty()) && (docs == null || docs.isEmpty()) && (jsDocLines == null || jsDocLines.isEmpty()) && (additionalInfo == null || additionalInfo.isEmpty()); + + if (!onlyErrors) //Add error separator height + totalHeight += (SEPARATOR_SPACING + SEPARATOR_HEIGHT) * 2 - 5; + + totalHeight += LINE_SPACING; // Extra space after errors + } + + // Package name + if (packageName != null && !packageName.isEmpty()) { + String packageText = "\u25CB " + packageName; + List wrappedLines = wrapText(packageText, contentWidth); + totalHeight += wrappedLines.size() * (lineHeight + LINE_SPACING); + } + + // Declaration (colored segments with wrapping) + if (!declaration.isEmpty()) { + totalHeight += calculateSegmentsHeight(contentWidth, declaration); + totalHeight += LINE_SPACING; + } + + // Documentation (plain text) + if (!docs.isEmpty()) { + // Add space for separator line and spacing + totalHeight += SEPARATOR_SPACING + SEPARATOR_HEIGHT; + for (String doc : docs) { + List wrappedLines = wrapText(doc, contentWidth); + totalHeight += wrappedLines.size() * (lineHeight + LINE_SPACING); + } + } + + // JSDoc-formatted documentation lines + if (jsDocLines != null && !jsDocLines.isEmpty()) { + if (docs.isEmpty() && !declaration.isEmpty()) { + totalHeight += SEPARATOR_HEIGHT + SEPARATOR_SPACING; + } + + boolean previousVisibleJSDocWasCode = false; + for (int i = 0; i < jsDocLines.size(); i++) { + TokenHoverInfo.DocumentationLine docLine = jsDocLines.get(i); + if (!docLine.isEmpty()) { + int explicitIndent = docLine.isCodeLine + ? docLine.codeLeadingSpaces * ClientProxy.Font.width(" ") + : 0; + int wrapW = Math.max(10, contentWidth - (docLine.isCodeLine ? CODE_INDENT : 0) - explicitIndent); + if (!docLine.isCodeLine && previousVisibleJSDocWasCode) { + totalHeight += LINE_SPACING; + } + totalHeight += calculateSegmentsHeight(wrapW, docLine.segments); + totalHeight += LINE_SPACING; + previousVisibleJSDocWasCode = docLine.isCodeLine; + } else { + totalHeight += (i > 0 && jsDocLines.get(i - 1).isCodeLine) ? LINE_SPACING : lineHeight / 2; + } + } + } + + // Additional info + if (!additionalInfo.isEmpty()) { + totalHeight += LINE_SPACING; + for (String infoLine : additionalInfo) { + List wrappedLines = wrapText(infoLine, contentWidth); + totalHeight += wrappedLines.size() * (lineHeight + LINE_SPACING); + } + } + return Math.max(lineHeight, Math.max(0, totalHeight - LINE_SPACING))-2; + } + + /** + * Calculate height needed for wrapped segments. + */ + private static int calculateSegmentsHeight(int maxWidth, List segments) { + int lineHeight = ClientProxy.Font.height(); + int currentLineWidth = 0; + int lineCount = 1; + + for (TokenHoverInfo.TextSegment segment : segments) { + String text = segment.text; + String[] words = text.split("(?<=\\s)|(?=\\s)"); + + for (String word : words) { + int wordWidth = ClientProxy.Font.width(word); + + if (currentLineWidth + wordWidth > maxWidth && currentLineWidth > 0) { + lineCount++; + currentLineWidth = word.trim().isEmpty() ? 0 : wordWidth; + } else { + currentLineWidth += wordWidth; + } + } + } + + if (lineCount <= 0) { + return 0; + } + + // Total height = (lines * lineHeight) + (spacing between lines) + return (lineCount * lineHeight) + ((lineCount - 1) * LINE_SPACING); + } + + /** + * Calculate the width of the longest line when segments are wrapped. + */ + private static int calculateSegmentsLongestLine(int maxWidth, List segments) { + int currentLineWidth = 0; + int longestLineWidth = 0; + + for (TokenHoverInfo.TextSegment segment : segments) { + String text = segment.text; + String[] words = text.split("(?<=\\s)|(?=\\s)"); + + for (String word : words) { + int wordWidth = ClientProxy.Font.width(word); + + if (currentLineWidth + wordWidth > maxWidth && currentLineWidth > 0) { + // Line break - record current line width and start new line + longestLineWidth = Math.max(longestLineWidth, currentLineWidth); + currentLineWidth = word.trim().isEmpty() ? 0 : wordWidth; + } else { + currentLineWidth += wordWidth; + } + } + } + + // Don't forget the last line + longestLineWidth = Math.max(longestLineWidth, currentLineWidth); + + return longestLineWidth; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/DTSJSDocParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/DTSJSDocParser.java new file mode 100644 index 000000000..74b3cb280 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/DTSJSDocParser.java @@ -0,0 +1,236 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DTSJSDocParser { + + private static final Pattern JSDOC_BLOCK_PATTERN = Pattern.compile( + "/\\*\\*\\s*(.*?)\\*/", Pattern.DOTALL); + + private static final Pattern TAG_PATTERN = Pattern.compile( + "@(\\w+)(?:\\s+\\{([^}]+)\\})?(?:\\s+(.*))?"); + + private static final Pattern PARAM_PATTERN = Pattern.compile( + "@param(?:\\s+\\{([^}]+)\\})?(?:\\s+(\\w+))?(?:\\s+(.*))?"); + + private static final Pattern RETURN_PATTERN = Pattern.compile( + "@returns?\\s+(?:\\{([^}]+)\\}\\s*)?(.*)"); + + private static final Pattern TYPE_PATTERN = Pattern.compile( + "@type(?:\\s+\\{([^}]+)\\})?(?:\\s+(.*))?"); + + public static JSDocInfo parseJSDocBlock(String jsDocContent) { + if (jsDocContent == null || jsDocContent.isEmpty()) { + return null; + } + + JSDocInfo info = new JSDocInfo(jsDocContent, -1, -1); + + String[] lines = jsDocContent.split("\\r?\\n"); + StringBuilder descriptionBuilder = new StringBuilder(); + boolean foundFirstTag = false; + JSDocTag lastTag = null; + + for (String line : lines) { + line = cleanLine(line); + if (line.startsWith("@")) { + foundFirstTag = true; + lastTag = parseTag(line, info); + } else if (!foundFirstTag) { + if (line.isEmpty()) { + // Preserve blank lines as paragraph gaps (only if description has started) + if (descriptionBuilder.length() > 0) { + descriptionBuilder.append("\n"); + } + } else { + if (descriptionBuilder.length() > 0) { + descriptionBuilder.append("\n"); + } + descriptionBuilder.append(line); + } + } else if (lastTag != null) { + if (!line.isEmpty()) { + String existing = lastTag.getDescription(); + if (existing == null || existing.isEmpty()) { + lastTag.setDescription(line); + } else { + lastTag.setDescription(existing + "\n" + line); + } + } + } + } + + if (descriptionBuilder.length() > 0) { + info.setDescription(descriptionBuilder.toString().trim()); + } + + return info; + } + + private static String cleanLine(String line) { + // Strip outer leading whitespace (before the * marker) and all trailing whitespace + line = line.trim(); + if (line.startsWith("/**")) { + line = line.substring(3).trim(); + } + if (line.endsWith("*/")) { + line = line.substring(0, line.length() - 2); + // Strip trailing whitespace between content and */ but preserve leading spaces + int end = line.length(); + while (end > 0 && Character.isWhitespace(line.charAt(end - 1))) end--; + line = line.substring(0, end); + } + if (line.startsWith("*")) { + line = line.substring(1); // strip the leading * + // Consume exactly ONE space after * (the JSDoc conventional separator). + // Remaining leading spaces are intentional indentation (e.g. inside code fences). + if (!line.isEmpty() && line.charAt(0) == ' ') { + line = line.substring(1); + } + // Strip trailing whitespace + int end = line.length(); + while (end > 0 && Character.isWhitespace(line.charAt(end - 1))) end--; + line = line.substring(0, end); + } + return line; + } + + private static JSDocTag parseTag(String line, JSDocInfo info) { + Matcher paramMatcher = PARAM_PATTERN.matcher(line); + if (paramMatcher.find()) { + String type = paramMatcher.group(1); + String name = paramMatcher.group(2); + String desc = paramMatcher.group(3); + if (desc == null && type == null && name != null) { + desc = name; + name = null; + } + if (desc != null) { + desc = desc.trim(); + if (desc.isEmpty()) { + desc = null; + } + } + JSDocParamTag tag = JSDocParamTag.create(-1, -1, -1, + type, null, -1, -1, name, -1, -1, desc); + info.addParamTag(tag); + return tag; + } + + Matcher returnMatcher = RETURN_PATTERN.matcher(line); + if (returnMatcher.find()) { + String type = returnMatcher.group(1); + String desc = returnMatcher.group(2); + if (desc != null) { + desc = desc.trim(); + if (desc.isEmpty()) { + desc = null; + } + } + JSDocReturnTag tag = JSDocReturnTag.create("return", -1, -1, -1, + type, null, -1, -1, desc); + info.setReturnTag(tag); + return tag; + } + + Matcher typeMatcher = TYPE_PATTERN.matcher(line); + if (typeMatcher.find()) { + String type = typeMatcher.group(1); + String desc = typeMatcher.group(2); + if (desc != null) { + desc = desc.trim(); + if (desc.isEmpty()) { + desc = null; + } + } + JSDocTypeTag tag = JSDocTypeTag.create(-1, -1, -1, + type, null, -1, -1, desc); + info.setTypeTag(tag); + return tag; + } + + Matcher tagMatcher = TAG_PATTERN.matcher(line); + if (tagMatcher.find()) { + String tagName = tagMatcher.group(1); + String typeName = tagMatcher.group(2); + String rest = tagMatcher.group(3); + + switch (tagName) { + case "see": + JSDocSeeTag seeTag = JSDocSeeTag.createSimple(rest != null ? rest.trim() : ""); + info.addSeeTag(seeTag); + return seeTag; + default: + JSDocTag genericTag = new JSDocTag(tagName, -1, -1, -1); + if (typeName != null) { + typeName = typeName.trim(); + genericTag.setType(typeName, null, -1, -1); + } + genericTag.setDescription(rest != null ? rest.trim() : ""); + info.addTag(genericTag); + return genericTag; + } + } + return null; + } + + public static String extractJSDocBefore(String content, int elementStart) { + if (elementStart <= 0) return null; + + String searchArea = content.substring(0, elementStart); + + int lastJSDocEnd = searchArea.lastIndexOf("*/"); + if (lastJSDocEnd < 0) return null; + + int jsDocStart = searchArea.lastIndexOf("/**", lastJSDocEnd); + if (jsDocStart < 0) return null; + + String between = searchArea.substring(lastJSDocEnd + 2).trim(); + if (between.isEmpty() || isOnlyWhitespaceOrModifiers(between)) { + return searchArea.substring(jsDocStart, lastJSDocEnd + 2); + } + + return null; + } + + private static boolean isOnlyWhitespaceOrModifiers(String text) { + String cleaned = text.replaceAll("\\s+", " ").trim(); + return cleaned.isEmpty() + || cleaned.matches("^(export\\s*)?(readonly\\s*)?(interface|class|type|function)?\\s*$"); + } + + public static List extractAllJSDocBlocks(String content) { + List blocks = new ArrayList<>(); + Matcher matcher = JSDOC_BLOCK_PATTERN.matcher(content); + + while (matcher.find()) { + int start = matcher.start(); + int end = matcher.end(); + String docContent = matcher.group(0); + blocks.add(new JSDocBlock(start, end, docContent)); + } + + return blocks; + } + + public static class JSDocBlock { + public final int start; + public final int end; + public final String content; + + public JSDocBlock(int start, int end, String content) { + this.start = start; + this.end = end; + this.content = content; + } + + public JSDocInfo parse() { + return parseJSDocBlock(content); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/DtsModScanner.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/DtsModScanner.java new file mode 100644 index 000000000..938e334b1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/DtsModScanner.java @@ -0,0 +1,201 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModContainer; + +import java.io.*; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +final class DtsModScanner { + + private static final Pattern MOD_DTS_PATH_PATTERN = Pattern.compile("^assets/([^/]+)/api/(.+\\.d\\.ts)$"); + + private static final List DOMAIN_PRIORITY = Arrays.asList("customnpcs", "npcdbc"); + + private DtsModScanner() {} + + static List collectDtsFilesFromMods() { + List dtsFiles = new ArrayList<>(); + try { + for (ModContainer mod : Loader.instance().getModList()) { + File source = mod.getSource(); + if (source == null || !source.exists()) { + continue; + } + if (source.isDirectory()) { + scanDirectoryForModDts(source, mod.getModId(), dtsFiles); + } else if (source.getName().endsWith(".jar") || source.getName().endsWith(".zip")) { + scanJarForModDts(source, mod.getModId(), dtsFiles); + } + } + } catch (Throwable ignored) { + // Headless/non-FML environment: fall back to resource scanning. + } + return dtsFiles; + } + + static void sortDtsFiles(List dtsFiles) { + Collections.sort(dtsFiles, new DtsFileRefComparator()); + } + + static void logSummary(List dtsFiles) { + Map domainCounts = new LinkedHashMap<>(); + for (DtsFileRef ref : dtsFiles) { + domainCounts.put(ref.getDomain(), domainCounts.getOrDefault(ref.getDomain(), 0) + 1); + } +// System.out.println("[JSTypeRegistry] Found " + dtsFiles.size() + " .d.ts files across " + domainCounts.size() + " domains"); + for (Map.Entry entry : domainCounts.entrySet()) { +// System.out.println("[JSTypeRegistry] Domain " + entry.getKey() + ": " + entry.getValue() + " files"); + } + } + + private static void scanDirectoryForModDts(File baseDir, String modId, List dtsFiles) { + scanDirectoryForModDts(baseDir, baseDir, modId, dtsFiles); + } + + private static void scanDirectoryForModDts(File baseDir, File directory, String modId, List dtsFiles) { + File[] files = directory.listFiles(); + if (files == null) { + return; + } + for (File file : files) { + if (file.isDirectory()) { + scanDirectoryForModDts(baseDir, file, modId, dtsFiles); + continue; + } + if (!file.getName().endsWith(".d.ts")) { + continue; + } + String relativePath = baseDir.toURI().relativize(file.toURI()).getPath(); + if (relativePath == null) { + continue; + } + String normalized = relativePath.replace('\\', '/'); + Matcher matcher = MOD_DTS_PATH_PATTERN.matcher(normalized); + if (matcher.matches()) { + String domain = matcher.group(1); + String apiPath = matcher.group(2); + dtsFiles.add(DtsFileRef.forFile(modId, domain, apiPath, file)); + } + } + } + + private static void scanJarForModDts(File jarFile, String modId, List dtsFiles) { + try { + JarFile jar = new JarFile(jarFile); + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + Matcher matcher = MOD_DTS_PATH_PATTERN.matcher(entryName); + if (matcher.matches()) { + String domain = matcher.group(1); + String apiPath = matcher.group(2); + dtsFiles.add(DtsFileRef.forJar(modId, domain, apiPath, jarFile, entryName)); + } + } + jar.close(); + } catch (Exception e) { + System.err.println("[JSTypeRegistry] Error scanning mod jar for .d.ts files: " + e.getMessage()); + } + } + + static final class DtsFileRef { + private final String modId; + private final String domain; + private final String relativePath; + private final File file; + private final File jarFile; + private final String jarEntryName; + + private DtsFileRef(String modId, String domain, String relativePath, File file, File jarFile, String jarEntryName) { + this.modId = modId; + this.domain = domain; + this.relativePath = relativePath; + this.file = file; + this.jarFile = jarFile; + this.jarEntryName = jarEntryName; + } + + static DtsFileRef forFile(String modId, String domain, String relativePath, File file) { + return new DtsFileRef(modId, domain, relativePath, file, null, null); + } + + static DtsFileRef forJar(String modId, String domain, String relativePath, File jarFile, String jarEntryName) { + return new DtsFileRef(modId, domain, relativePath, null, jarFile, jarEntryName); + } + + InputStream openStream() throws IOException { + if (file != null) { + return new FileInputStream(file); + } + if (jarFile != null && jarEntryName != null) { + final JarFile jar = new JarFile(jarFile); + JarEntry entry = jar.getJarEntry(jarEntryName); + if (entry == null) { + jar.close(); + return null; + } + InputStream is = jar.getInputStream(entry); + return new FilterInputStream(is) { + @Override + public void close() throws IOException { + super.close(); + jar.close(); + } + }; + } + return null; + } + + String getDomain() { + return domain; + } + + String getRelativePath() { + return relativePath; + } + + String getOrigin() { + return modId + ":" + domain + ":" + relativePath; + } + } + + private static class DtsFileRefComparator implements Comparator { + @Override + public int compare(DtsFileRef a, DtsFileRef b) { + int domainCompare = Integer.compare(getDomainRank(a.getDomain()), getDomainRank(b.getDomain())); + if (domainCompare != 0) { + return domainCompare; + } + int domainNameCompare = a.getDomain().compareTo(b.getDomain()); + if (domainNameCompare != 0) { + return domainNameCompare; + } + int filePriorityCompare = Integer.compare(getFilePriority(a.getRelativePath()), getFilePriority(b.getRelativePath())); + if (filePriorityCompare != 0) { + return filePriorityCompare; + } + return a.getRelativePath().compareTo(b.getRelativePath()); + } + + private int getDomainRank(String domain) { + int idx = DOMAIN_PRIORITY.indexOf(domain); + return idx >= 0 ? idx : DOMAIN_PRIORITY.size(); + } + + private int getFilePriority(String relativePath) { + if (relativePath.endsWith("hooks.d.ts")) { + return 0; + } + if (relativePath.endsWith("index.d.ts")) { + return 1; + } + return 2; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSFieldInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSFieldInfo.java new file mode 100644 index 000000000..27e8c589c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSFieldInfo.java @@ -0,0 +1,120 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.GenericContext; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; +/** + * Represents a field/property in a TypeScript interface. + */ +public class JSFieldInfo { + + private final String name; + private final String type; // Raw type string for display + private TypeInfo typeInfo; // Resolved TypeInfo + private final boolean readonly; + private boolean isStatic; + private JSDocInfo jsDocInfo; + private JSTypeInfo containingType; // The type that contains this field + + public JSFieldInfo(String name, String type, boolean readonly) { + this.name = name; + this.type = type; + this.readonly = readonly; + } + + public JSFieldInfo setJsDocInfo(JSDocInfo jsDocInfo) { + this.jsDocInfo = jsDocInfo; + return this; + } + + public boolean isStatic() { return isStatic; } + + public JSFieldInfo setStatic(boolean isStatic) { + this.isStatic = isStatic; + return this; + } + + + /** + * Set the containing type (the JSTypeInfo that owns this field). + */ + public void setContainingType(JSTypeInfo containingType) { + this.containingType = containingType; + } + + public void setTypeInfo(TypeInfo typeInfo) { + this.typeInfo = typeInfo; + } + + /** + * Get the resolved type, with fallback resolution using type parameters. + * @param contextType The TypeInfo context for resolving type parameters + * @return The resolved TypeInfo for the field type + */ + public TypeInfo getResolvedType(TypeInfo contextType) { + TypeResolver resolver = TypeResolver.getInstance(); + + // Cache only the raw resolved type; substitutions depend on the receiver context. + TypeInfo resolved = typeInfo != null ? typeInfo : resolver.resolveJSType(type); + if (typeInfo == null) { + typeInfo = resolved; + } + + if (contextType != null) { + GenericContext ctx = GenericContext.forReceiver(contextType); + return ctx.substituteType(resolved, type, resolver); + } + + return resolved; + } + + // Getters + public String getName() { return name; } + public String getType() { return type; } + public TypeInfo getTypeInfo() { return typeInfo; } + public boolean isReadonly() { return readonly; } + public JSDocInfo getJsDocInfo() { return jsDocInfo; } + public JSTypeInfo getContainingType() { return containingType; } + + /** + * Get documentation string (backward compatibility). + * Extracts description from JSDocInfo if available. + */ + public String getDocumentation() { + return jsDocInfo != null ? jsDocInfo.getDescription() : null; + } + + /** + * Get display name - uses resolved TypeInfo display name if available, + * including generic type arguments like List. + */ + public String getDisplayType() { + if (typeInfo != null && typeInfo.isResolved()) { + return typeInfo.getDisplayName(); + } + return type; + } + + /** + * Build hover info HTML for this field. + */ + public String buildHoverInfo() { + StringBuilder sb = new StringBuilder(); + if (readonly) { + sb.append("readonly "); + } + sb.append("").append(name).append(": ").append(type).append(""); + + if (jsDocInfo != null && jsDocInfo.getDescription() != null && !jsDocInfo.getDescription().isEmpty()) { + sb.append("

").append(jsDocInfo.getDescription()); + } + + return sb.toString(); + } + + @Override + public String toString() { + return (readonly ? "readonly " : "") + name + ": " + type; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSMethodInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSMethodInfo.java new file mode 100644 index 000000000..4bca83dec --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSMethodInfo.java @@ -0,0 +1,205 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.GenericContext; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.util.*; + +/** + * Represents a method signature parsed from .d.ts files. + */ +public class JSMethodInfo { + + private final String name; + private final String returnType; // Raw type string for display, e.g., "number", "IEntity", "void" + private TypeInfo returnTypeInfo; // Resolved TypeInfo (set during Phase 2) + private final List parameters; + private boolean isStatic; + private JSDocInfo jsDocInfo; + private JSTypeInfo containingType; // The type that contains this method + + public JSMethodInfo(String name, String returnType, List parameters) { + this.name = name; + this.returnType = returnType; + this.parameters = parameters != null ? new ArrayList<>(parameters) : new ArrayList<>(); + } + + public JSMethodInfo setJsDocInfo(JSDocInfo jsDocInfo) { + this.jsDocInfo = jsDocInfo; + return this; + } + + public boolean isStatic() { return isStatic; } + + public JSMethodInfo setStatic(boolean isStatic) { + this.isStatic = isStatic; + return this; + } + + /** + * Set the resolved return type info (called during Phase 2 type resolution). + */ + public void setReturnTypeInfo(TypeInfo typeInfo) { + this.returnTypeInfo = typeInfo; + } + + /** + * Set the containing type (the JSTypeInfo that owns this method). + */ + public void setContainingType(JSTypeInfo containingType) { + this.containingType = containingType; + // Also set for all parameters + for (JSParameterInfo param : parameters) + param.setContainingMethod(this); + } + + /** + * Get the resolved return type, with type parameter substitution based on receiver context. + * + * For parameterized receivers like List, this will substitute type variables: + * - If return type is "T" and receiver is List, returns TypeInfo(String) + * - Handles nested generics like List> with proper substitution + * + * @param contextType The TypeInfo context for resolving type parameters (e.g., List to resolve E → String) + * @return The resolved TypeInfo for the return type, with type variables substituted + */ + public TypeInfo getResolvedReturnType(TypeInfo contextType) { + TypeResolver resolver = TypeResolver.getInstance(); + TypeInfo resolved = resolver.resolveJSType(returnType); + + if (contextType != null) { + GenericContext ctx = GenericContext.forReceiver(contextType); + resolved = ctx.substituteType(resolved, returnType, resolver); + } + + return resolved; + } + + // Getters + public String getName() { return name; } + public String getReturnType() { return returnType; } + public TypeInfo getReturnTypeInfo() { return returnTypeInfo; } + public List getParameters() { return parameters; } + public JSDocInfo getJsDocInfo() { return jsDocInfo; } + public int getParameterCount() { return parameters.size(); } + public JSTypeInfo getContainingType() { return containingType; } + + /** + * Get documentation string (backward compatibility). + * Extracts description from JSDocInfo if available. + */ + public String getDocumentation() { + return jsDocInfo != null ? jsDocInfo.getDescription() : null; + } + + /** + * Get a formatted signature string for display. + */ + public String getSignature() { + StringBuilder sb = new StringBuilder(); + sb.append(name).append("("); + for (int i = 0; i < parameters.size(); i++) { + if (i > 0) sb.append(", "); + JSParameterInfo param = parameters.get(i); + sb.append(param.getName()).append(": ").append(param.getType()); + } + sb.append("): ").append(returnType); + return sb.toString(); + } + + /** + * Build hover info HTML for this method. + */ + public String buildHoverInfo() { + StringBuilder sb = new StringBuilder(); + sb.append("").append(name).append("("); + for (int i = 0; i < parameters.size(); i++) { + if (i > 0) sb.append(", "); + JSParameterInfo param = parameters.get(i); + sb.append(param.getName()).append(": ").append(param.getType()).append(""); + } + sb.append("): ").append(returnType).append(""); + + if (jsDocInfo != null && jsDocInfo.getDescription() != null && !jsDocInfo.getDescription().isEmpty()) { + sb.append("

").append(jsDocInfo.getDescription()); + } + + return sb.toString(); + } + + @Override + public String toString() { + return getSignature(); + } + + /** + * Represents a parameter in a method signature. + */ + public static class JSParameterInfo { + private final String name; + private final String type; + private TypeInfo typeInfo; // Resolved TypeInfo (set during Phase 2) + private JSMethodInfo containingMethod; // The type that contains the method with this parameter + private boolean isVarArg = false; + + public JSParameterInfo(String name, String type) { + this.name = name; + this.type = type; + } + + public void setVarArg(boolean isVarArg) { this.isVarArg = isVarArg; } + public boolean isVarArg() { return isVarArg; } + + public void setContainingMethod(JSMethodInfo containingMethod) { + this.containingMethod = containingMethod; + } + + public void setTypeInfo(TypeInfo typeInfo) { + this.typeInfo = typeInfo; + } + + /** + * Get the resolved type, with type parameter substitution based on receiver context. + * + * For parameterized receivers like Consumer, this will substitute type variables: + * - If param type is "T" and receiver is Consumer, returns TypeInfo(IAction) + * + * @param contextType The TypeInfo context for resolving type parameters + * @return The resolved TypeInfo for the parameter type + */ + public TypeInfo getResolvedType(TypeInfo contextType) { + TypeResolver resolver = TypeResolver.getInstance(); + TypeInfo resolved = resolver.resolveJSType(type); + + if (contextType != null) { + GenericContext ctx = GenericContext.forReceiver(contextType); + resolved = ctx.substituteType(resolved, type, resolver); + } + + return resolved; + } + + public String getName() { return name; } + public String getType() { return type; } + public TypeInfo getTypeInfo() {return typeInfo;} + public JSMethodInfo getContainingMethod() {return containingMethod;} + + /** + * Get display name - uses resolved TypeInfo display name if available, + * including generic type arguments like List. + */ + public String getDisplayType() { + if (typeInfo != null && typeInfo.isResolved()) { + return typeInfo.getDisplayName(); + } + return type; + } + + @Override + public String toString() { + return name + ": " + type; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSScriptAnalyzer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSScriptAnalyzer.java new file mode 100644 index 000000000..0ebcce69f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSScriptAnalyzer.java @@ -0,0 +1,554 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import scala.annotation.meta.field; + +import java.util.*; +import java.util.regex.*; + +/** + * Analyzes JavaScript scripts to produce syntax highlighting marks and type information. + * Uses the JSTypeRegistry to resolve types and validate member access. + * + * @deprecated This class is deprecated. All JavaScript analysis is now handled by the + * unified pipeline in {@link ScriptDocument}. JavaScript and Java scripts now use the + * same methods and data structures: + *
    + *
  • {@link ScriptDocument#parseMethodDeclarations()} - for both Java methods and JS functions
  • + *
  • {@link ScriptDocument#parseLocalVariables()} - for both Java and JS local variables
  • + *
  • {@link ScriptDocument#parseGlobalFields()} - for both Java and JS global variables
  • + *
  • {@link ScriptDocument#buildMarks(List)} - for mark building (both languages)
  • + *
+ * Type information is available via the unified data structures: {@code getMethods()}, + * {@code getMethodLocals()}, and {@code getGlobalFields()}. + */ +@Deprecated +public class JSScriptAnalyzer { + + private final ScriptDocument document; + private final String text; + private final JSTypeRegistry registry; + + // Variable tracking: varName -> inferred type name + private final Map variableTypes = new HashMap<>(); + + // Function parameter types: funcName -> paramName -> typeName + private final Map> functionParams = new HashMap<>(); + + // Excluded ranges (strings, comments) + private final List excludedRanges = new ArrayList<>(); + + // Patterns + private static final Pattern STRING_PATTERN = Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'"); + private static final Pattern COMMENT_PATTERN = Pattern.compile("//.*?$|/\\*.*?\\*/", Pattern.MULTILINE | Pattern.DOTALL); + private static final Pattern FUNCTION_PATTERN = Pattern.compile("function\\s+(\\w+)\\s*\\(([^)]*)\\)"); + private static final Pattern VAR_DECL_PATTERN = Pattern.compile("(?:var|let|const)\\s+(\\w+)(?:\\s*=\\s*([^;]+))?"); + private static final Pattern ASSIGNMENT_PATTERN = Pattern.compile("(\\w+)\\s*=\\s*([^;]+)"); + private static final Pattern METHOD_CALL_PATTERN = Pattern.compile("(\\w+(?:\\.\\w+)*)\\s*\\("); + private static final Pattern MEMBER_ACCESS_PATTERN = Pattern.compile("(\\w+)(?:\\.(\\w+))+"); + private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b"); + + private static final Pattern JS_KEYWORD_PATTERN = Pattern.compile( + "\\b(function|var|let|const|if|else|for|while|do|switch|case|break|continue|return|" + + "try|catch|finally|throw|new|typeof|instanceof|in|of|this|null|undefined|true|false|" + + "class|extends|import|export|default|async|await|yield)\\b"); + + private static final Pattern NUMBER_PATTERN = Pattern.compile("\\b\\d+\\.?\\d*\\b"); + + public JSScriptAnalyzer(ScriptDocument document) { + this.document = document; + this.text = document.getText(); + this.registry = JSTypeRegistry.getInstance(); + // Ensure registry is initialized + if (!registry.isInitialized()) { + registry.initializeFromResources(); + } + } + + /** + * Analyze the script and produce marks. + */ + public List analyze() { + List marks = new ArrayList<>(); + + // First pass: find excluded regions + findExcludedRanges(); + + // Mark comments and strings + addPatternMarks(marks, COMMENT_PATTERN, TokenType.COMMENT); + addPatternMarks(marks, STRING_PATTERN, TokenType.STRING); + + // Mark keywords + addPatternMarks(marks, JS_KEYWORD_PATTERN, TokenType.KEYWORD); + + // Mark numbers + addPatternMarks(marks, NUMBER_PATTERN, TokenType.LITERAL); + + // Parse functions and infer parameter types from hooks + parseFunctions(marks); + + // Parse variable declarations + parseVariables(marks); + + // Mark member accesses with type validation + markMemberAccesses(marks); + + // Mark method calls + markMethodCalls(marks); + + // Mark standalone identifiers (parameters and variables in function bodies) + markIdentifiers(marks); + + return marks; + } + + /** + * Find strings and comments to exclude from analysis. + */ + private void findExcludedRanges() { + Matcher m = STRING_PATTERN.matcher(text); + while (m.find()) { + excludedRanges.add(new int[]{m.start(), m.end()}); + } + + m = COMMENT_PATTERN.matcher(text); + while (m.find()) { + excludedRanges.add(new int[]{m.start(), m.end()}); + } + } + + private boolean isExcluded(int pos) { + for (int[] range : excludedRanges) { + if (pos >= range[0] && pos < range[1]) return true; + } + return false; + } + + /** + * Parse function declarations and infer parameter types from hook signatures. + */ + private void parseFunctions(List marks) { + Matcher m = FUNCTION_PATTERN.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) continue; + + String funcName = m.group(1); + String params = m.group(2); + + // Mark function name + int nameStart = m.start(1); + int nameEnd = m.end(1); + + // Check if this is a known hook + if (registry.isHook(funcName)) { + // Create a unified MethodInfo for the hook + List sigs = registry.getHookSignatures(funcName); + if (!sigs.isEmpty()) { + JSTypeRegistry.HookSignature sig = sigs.get(0); + + // Create unified MethodInfo for hover info + TypeInfo paramTypeInfo = resolveJSType(sig.paramType); + List methodParams = new ArrayList<>(); + methodParams.add(FieldInfo.reflectionParam(sig.paramName, paramTypeInfo)); + + MethodInfo hookMethod = MethodInfo.declaration( + funcName, null, TypeInfo.fromPrimitive("void"), methodParams, + nameStart, nameStart, nameStart, -1, -1, 0, sig.doc + ); + + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_DECL, hookMethod)); + + // Infer parameter types from hook + if (!params.isEmpty()) { + // Parse parameter names from function + String[] paramNames = params.split(","); + if (paramNames.length > 0) { + String paramName = paramNames[0].trim(); + String paramType = sig.paramType; + + // Store in function params and variable types + Map funcParamMap = new HashMap<>(); + funcParamMap.put(paramName, paramType); + functionParams.put(funcName, funcParamMap); + variableTypes.put(paramName, paramType); + + // Mark the parameter with unified FieldInfo + int paramStart = m.start(2) + params.indexOf(paramName); + int paramEnd = paramStart + paramName.length(); + FieldInfo paramFieldInfo = FieldInfo.parameter( + paramName, paramTypeInfo, paramStart, hookMethod + ); + marks.add(new ScriptLine.Mark(paramStart, paramEnd, TokenType.PARAMETER, paramFieldInfo)); + } + } + } else { + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_DECL, funcName)); + } + } else { + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_DECL, funcName)); + } + } + } + + /** + * Parse variable declarations and infer types. + */ + private void parseVariables(List marks) { + Matcher m = VAR_DECL_PATTERN.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) continue; + + String varName = m.group(1); + String initializer = m.group(2); + + // Infer type from initializer + String inferredType = null; + if (initializer != null) { + inferredType = inferTypeFromExpression(initializer.trim()); + } + + if (inferredType != null) { + variableTypes.put(varName, inferredType); + } + + // Mark variable declaration with unified FieldInfo + int varStart = m.start(1); + int varEnd = m.end(1); + TypeInfo typeInfo = resolveJSType(inferredType != null ? inferredType : "any"); + FieldInfo varFieldInfo = FieldInfo.localField(varName, typeInfo, varStart, null); + marks.add(new ScriptLine.Mark(varStart, varEnd, TokenType.LOCAL_FIELD, varFieldInfo)); + } + } + + /** + * Infer type from an expression. + */ + private String inferTypeFromExpression(String expr) { + if (expr == null || expr.isEmpty()) return null; + + // String literal + if (expr.startsWith("\"") || expr.startsWith("'")) { + return "string"; + } + + // Number literal + if (expr.matches("\\d+\\.?\\d*")) { + return "number"; + } + + // Boolean literal + if (expr.equals("true") || expr.equals("false")) { + return "boolean"; + } + + // null/undefined + if (expr.equals("null")) return "null"; + if (expr.equals("undefined")) return "undefined"; + + // Array literal + if (expr.startsWith("[")) { + return "any[]"; + } + + // Object literal + if (expr.startsWith("{")) { + return "object"; + } + + // Method call: something.method() - infer from method return type + if (expr.contains(".") && expr.contains("(")) { + return inferTypeFromMethodCall(expr); + } + + // Variable reference + if (variableTypes.containsKey(expr)) { + return variableTypes.get(expr); + } + + return null; + } + + /** + * Infer type from a method call chain. + */ + private String inferTypeFromMethodCall(String expr) { + // Remove trailing parentheses and args for analysis + int parenIndex = expr.indexOf('('); + if (parenIndex > 0) { + expr = expr.substring(0, parenIndex); + } + + String[] parts = expr.split("\\."); + if (parts.length < 2) return null; + + // Start with the receiver type + String currentType = variableTypes.get(parts[0]); + if (currentType == null) return null; + + // Walk the chain + for (int i = 1; i < parts.length; i++) { + JSTypeInfo typeInfo = registry.getType(currentType); + if (typeInfo == null) return null; + + String member = parts[i]; + + // Check if it's a method + JSMethodInfo method = typeInfo.getMethod(member); + if (method != null) { + currentType = method.getReturnType(); + continue; + } + + // Check if it's a field + JSFieldInfo f = typeInfo.getField(member); + if (f != null) { + currentType = f.getType(); + continue; + } + + return null; // Unknown member + } + + return currentType; + } + + /** + * Mark member accesses (x.y.z) with type validation. + */ + private void markMemberAccesses(List marks) { + Matcher m = MEMBER_ACCESS_PATTERN.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) continue; + + String fullAccess = m.group(0); + String[] parts = fullAccess.split("\\."); + + if (parts.length < 2) continue; + + // Get receiver type + String receiverName = parts[0]; + String currentType = variableTypes.get(receiverName); + + int pos = m.start(); + + // Mark receiver with unified FieldInfo + if (currentType != null) { + TypeInfo unifiedType = resolveJSType(currentType); + FieldInfo receiverField = FieldInfo.localField(receiverName, unifiedType, pos, null); + marks.add(new ScriptLine.Mark(pos, pos + receiverName.length(), TokenType.LOCAL_FIELD, receiverField)); + } + + pos += receiverName.length() + 1; // +1 for the dot + + // Walk the chain and mark each member + for (int i = 1; i < parts.length; i++) { + String member = parts[i]; + int memberStart = pos; + int memberEnd = pos + member.length(); + + if (currentType != null) { + JSTypeInfo jsTypeInfo = registry.getType(currentType); + if (jsTypeInfo != null) { + TypeInfo unifiedContainingType = TypeInfo.fromJSTypeInfo(jsTypeInfo); + + // Check method first + JSMethodInfo jsMethod = jsTypeInfo.getMethod(member); + if (jsMethod != null) { + // Convert to unified MethodInfo + MethodInfo unifiedMethod = MethodInfo.fromJSMethod(jsMethod, unifiedContainingType); + marks.add(new ScriptLine.Mark(memberStart, memberEnd, TokenType.METHOD_CALL, unifiedMethod)); + currentType = jsMethod.getReturnType(); + } else { + // Check field + JSFieldInfo jsField = jsTypeInfo.getField(member); + if (jsField != null) { + // Convert to unified FieldInfo + FieldInfo unifiedField = FieldInfo.fromJSField(jsField, unifiedContainingType); + marks.add(new ScriptLine.Mark(memberStart, memberEnd, TokenType.GLOBAL_FIELD, unifiedField)); + currentType = jsField.getType(); + } else { + // Unknown member - mark as undefined + marks.add(new ScriptLine.Mark(memberStart, memberEnd, TokenType.UNDEFINED_VAR, + "Unknown member '" + member + "' on type " + jsTypeInfo.getFullName())); + currentType = null; + } + } + } else { + currentType = null; + } + } + + pos = memberEnd + 1; // +1 for the next dot + } + } + } + + /** + * Mark method calls. + */ + private void markMethodCalls(List marks) { + Matcher m = METHOD_CALL_PATTERN.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) continue; + + String callExpr = m.group(1); + if (!callExpr.contains(".")) { + // Simple function call + int nameStart = m.start(1); + int nameEnd = m.end(1); + + if (registry.isHook(callExpr)) { + // It's a known hook being called - create unified MethodInfo + List sigs = registry.getHookSignatures(callExpr); + if (!sigs.isEmpty()) { + JSTypeRegistry.HookSignature sig = sigs.get(0); + TypeInfo paramTypeInfo = resolveJSType(sig.paramType); + List methodParams = new ArrayList<>(); + methodParams.add(FieldInfo.reflectionParam(sig.paramName, paramTypeInfo)); + + MethodInfo hookMethod = MethodInfo.declaration( + callExpr, null, TypeInfo.fromPrimitive("void"), methodParams, + nameStart, nameStart, nameStart, -1, -1, 0, sig.doc + ); + marks.add(new ScriptLine.Mark(nameStart, nameEnd, TokenType.METHOD_CALL, hookMethod)); + } + } + } + // Chained calls are handled in markMemberAccesses + } + } + + /** + * Add pattern-based marks. + */ + private void addPatternMarks(List marks, Pattern pattern, TokenType type) { + Matcher m = pattern.matcher(text); + while (m.find()) { + marks.add(new ScriptLine.Mark(m.start(), m.end(), type)); + } + } + + /** + * Get the inferred type of a variable at a position. + */ + public String getVariableType(String varName) { + return variableTypes.get(varName); + } + + /** + * Get all inferred variable types. + */ + public Map getVariableTypes() { + return new HashMap<>(variableTypes); + } + + /** + * Resolves a JavaScript type name to a unified TypeInfo. + * Handles primitives, mapped types, and custom types from the registry. + */ + private TypeInfo resolveJSType(String jsTypeName) { + if (jsTypeName == null || jsTypeName.isEmpty() || "void".equals(jsTypeName)) { + return TypeInfo.fromPrimitive("void"); + } + + // Handle JS primitives + switch (jsTypeName) { + case "string": + return TypeInfo.fromClass(String.class); + case "number": + return TypeInfo.fromClass(double.class); + case "boolean": + return TypeInfo.fromClass(boolean.class); + case "any": + return TypeInfo.fromClass(Object.class); + case "void": + return TypeInfo.fromPrimitive("void"); + } + + // Handle array types + if (jsTypeName.endsWith("[]")) { + String elementType = jsTypeName.substring(0, jsTypeName.length() - 2); + TypeInfo elementTypeInfo = resolveJSType(elementType); + return TypeInfo.arrayOf(elementTypeInfo); + } + + // Try to resolve from the JS type registry + if (registry != null) { + JSTypeInfo jsTypeInfo = registry.getType(jsTypeName); + if (jsTypeInfo != null) { + return TypeInfo.fromJSTypeInfo(jsTypeInfo); + } + } + + // Fallback: unresolved type + return TypeInfo.unresolved(jsTypeName, jsTypeName); + } + + /** + * Mark all identifiers in the script - variables and parameters. + * This ensures consistent coloring for parameters throughout function bodies. + */ + private void markIdentifiers(List marks) { + // Build set of positions already marked + Set markedPositions = new HashSet<>(); + for (ScriptLine.Mark mark : marks) { + for (int i = mark.start; i < mark.end; i++) { + markedPositions.add(i); + } + } + + // Find all identifiers + Matcher matcher = IDENTIFIER_PATTERN.matcher(text); + while (matcher.find()) { + if (isExcluded(matcher.start())) { + continue; + } + + int start = matcher.start(); + int end = matcher.end(); + + // Skip if already marked + boolean alreadyMarked = false; + for (int i = start; i < end; i++) { + if (markedPositions.contains(i)) { + alreadyMarked = true; + break; + } + } + if (alreadyMarked) { + continue; + } + + String identifier = matcher.group(); + + // Check if it's a parameter + boolean isParameter = false; + for (Map params : functionParams.values()) { + if (params.containsKey(identifier)) { + isParameter = true; + break; + } + } + + if (isParameter) { + marks.add(new ScriptLine.Mark(start, end, TokenType.PARAMETER)); + // Mark this position as used + for (int i = start; i < end; i++) { + markedPositions.add(i); + } + } else if (variableTypes.containsKey(identifier)) { + // It's a local variable + marks.add(new ScriptLine.Mark(start, end, TokenType.LOCAL_FIELD)); + // Mark this position as used + for (int i = start; i < end; i++) { + markedPositions.add(i); + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeInfo.java new file mode 100644 index 000000000..a13c54ddb --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeInfo.java @@ -0,0 +1,286 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParamTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocReturnTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocTypeTag; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.util.*; + +/** + * Represents a TypeScript interface/type parsed from .d.ts files. + * This is the JS equivalent of TypeInfo for Java types. + */ +public class JSTypeInfo { + + private final String simpleName; // e.g., "InteractEvent" + private final String fullName; // e.g., "IPlayerEvent.InteractEvent" + private final String namespace; // e.g., "IPlayerEvent" (parent namespace, null for top-level) + + // Java fully-qualified name (e.g., "noppes.npcs.api.entity.IPlayer") + private String javaFqn; + + // Type parameters (generics) + private final List typeParams = new ArrayList<>(); + + // Members + private final Map methods = new LinkedHashMap<>(); + private final Map fields = new LinkedHashMap<>(); + + // Inheritance + private String extendsType; // The type this interface extends + private JSTypeInfo resolvedParent; // Resolved parent type (after registry is built) + + // Inner types (for namespaces) + private final Map innerTypes = new LinkedHashMap<>(); + private JSTypeInfo parentType; // The containing type (for inner types) + + // Documentation + private JSDocInfo jsDocInfo; + + public JSTypeInfo(String simpleName, String namespace) { + this.simpleName = simpleName; + this.namespace = namespace; + this.fullName = namespace != null ? namespace + "." + simpleName : simpleName; + } + + // Builder methods + public JSTypeInfo setExtends(String extendsType) { + this.extendsType = extendsType; + return this; + } + + public JSTypeInfo setJsDocInfo(JSDocInfo jsDocInfo) { + this.jsDocInfo = jsDocInfo; + return this; + } + + public JSTypeInfo setJavaFqn(String javaFqn) { + this.javaFqn = javaFqn; + return this; + } + + public void addMethod(JSMethodInfo method) { + method.setContainingType(this); + // Handle overloads - store with index if name already exists + String key = method.getName(); + if (methods.containsKey(key)) { + // Find next available key for overload + int index = 1; + while (methods.containsKey(key + "$" + index)) { + index++; + } + methods.put(key + "$" + index, method); + } else { + methods.put(key, method); + } + } + + public void addField(JSFieldInfo field) { + field.setContainingType(this); + fields.put(field.getName(), field); + } + + public void addInnerType(JSTypeInfo inner) { + inner.parentType = this; + innerTypes.put(inner.getSimpleName(), inner); + } + + public void setResolvedParent(JSTypeInfo parent) { + this.resolvedParent = parent; + } + + // Getters + public String getSimpleName() { return simpleName; } + public String getFullName() { return fullName; } + public String getNamespace() { return namespace; } + public String getJavaFqn() { return javaFqn; } + public String getExtendsType() { return extendsType; } + public JSTypeInfo getResolvedParent() { return resolvedParent; } + public JSDocInfo getJsDocInfo() { return jsDocInfo; } + public JSTypeInfo getParentType() { return parentType; } + public List getTypeParams() { return typeParams; } + + public Map getMethods() { return methods; } + public Map getFields() { return fields; } + public Map getInnerTypes() { return innerTypes; } + + /** + * Get the type parameter info for a given parameter name (e.g., "T"). + * @return TypeParamInfo or null if not found + */ + public TypeParamInfo getTypeParam(String name) { + for (TypeParamInfo param : typeParams) { + if (param.getName().equals(name)) { + return param; + } + } + return null; + } + + public void addTypeParam(TypeParamInfo param) { + typeParams.add(param); + } + + /** + * Resolve all type parameters for this type. + * Called during Phase 2 after all types are loaded into the registry. + */ + public void resolveTypeParameters() { + for (TypeParamInfo param : typeParams) { + param.resolveBoundType(); + } + } + + /** + * Resolve all member types (return types, field types, parameter types). + * Called during Phase 2 after all types are loaded into the registry. + * This resolves types like "Java.java.io.File" to proper TypeInfo objects. + */ + public void resolveMemberTypes() { + TypeResolver resolver = TypeResolver.getInstance(); + + // Resolve method return types and parameter types + for (JSMethodInfo method : methods.values()) { + TypeInfo returnTypeInfo = resolver.resolveJSType(method.getReturnType()); + method.setReturnTypeInfo(returnTypeInfo); + + // Resolve parameter types + for (JSMethodInfo.JSParameterInfo param : method.getParameters()) { + TypeInfo paramTypeInfo = resolver.resolveJSType(param.getType()); + param.setTypeInfo(paramTypeInfo); + } + } + + // Resolve field types + for (JSFieldInfo field : fields.values()) { + TypeInfo fieldTypeInfo = resolver.resolveJSType(field.getType()); + field.setTypeInfo(fieldTypeInfo); + } + } + + public void resolveJSDocTypes() { + TypeResolver resolver = TypeResolver.getInstance(); + + if (jsDocInfo != null) { + resolveJSDocInfoTypes(jsDocInfo, resolver); + } + + for (JSMethodInfo method : methods.values()) { + JSDocInfo methodDoc = method.getJsDocInfo(); + if (methodDoc != null) { + resolveJSDocInfoTypes(methodDoc, resolver); + } + } + + for (JSFieldInfo field : fields.values()) { + JSDocInfo fieldDoc = field.getJsDocInfo(); + if (fieldDoc != null) { + resolveJSDocInfoTypes(fieldDoc, resolver); + } + } + } + + private void resolveJSDocInfoTypes(JSDocInfo jsDoc, TypeResolver resolver) { + JSDocTypeTag typeTag = jsDoc.getTypeTag(); + if (typeTag != null && typeTag.hasType() && typeTag.getTypeInfo() == null) { + TypeInfo resolved = resolver.resolveJSType(typeTag.getTypeName()); + typeTag.setType(typeTag.getTypeName(), resolved, typeTag.getTypeStart(), typeTag.getTypeEnd()); + } + + for (JSDocParamTag paramTag : jsDoc.getParamTags()) { + if (paramTag.hasType() && paramTag.getTypeInfo() == null) { + TypeInfo resolved = resolver.resolveJSType(paramTag.getTypeName()); + paramTag.setType(paramTag.getTypeName(), resolved, paramTag.getTypeStart(), paramTag.getTypeEnd()); + } + } + + JSDocReturnTag returnTag = jsDoc.getReturnTag(); + if (returnTag != null && returnTag.hasType() && returnTag.getTypeInfo() == null) { + TypeInfo resolved = resolver.resolveJSType(returnTag.getTypeName()); + returnTag.setType(returnTag.getTypeName(), resolved, returnTag.getTypeStart(), returnTag.getTypeEnd()); + } + } + + + /** + * Get a method by name, including inherited methods. + */ + public JSMethodInfo getMethod(String name) { + JSMethodInfo method = methods.get(name); + if (method != null) return method; + + // Check parent + if (resolvedParent != null) { + return resolvedParent.getMethod(name); + } + return null; + } + + /** + * Get all methods with a given name (for overloads). + */ + public List getMethodOverloads(String name) { + List overloads = new ArrayList<>(); + + // Get from this type + if (methods.containsKey(name)) { + overloads.add(methods.get(name)); + } + // Get numbered overloads + int index = 1; + while (methods.containsKey(name + "$" + index)) { + overloads.add(methods.get(name + "$" + index)); + index++; + } + + // Get from parent + if (resolvedParent != null) { + overloads.addAll(resolvedParent.getMethodOverloads(name)); + } + + return overloads; + } + + /** + * Check if this type has a method (including inherited). + */ + public boolean hasMethod(String name) { + return getMethod(name) != null; + } + + /** + * Get a field by name, including inherited fields. + */ + public JSFieldInfo getField(String name) { + JSFieldInfo field = fields.get(name); + if (field != null) return field; + + // Check parent + if (resolvedParent != null) { + return resolvedParent.getField(name); + } + return null; + } + + /** + * Check if this type has a field (including inherited). + */ + public boolean hasField(String name) { + return getField(name) != null; + } + + /** + * Get an inner type by name. + */ + public JSTypeInfo getInnerType(String name) { + return innerTypes.get(name); + } + + @Override + public String toString() { + return "JSTypeInfo{" + fullName + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeRegistry.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeRegistry.java new file mode 100644 index 000000000..c08711051 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeRegistry.java @@ -0,0 +1,1199 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import net.minecraft.client.Minecraft; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.client.gui.util.script.interpreter.bridge.DtsJavaBridge; +import noppes.npcs.api.handler.IHookDefinition; +import noppes.npcs.controllers.ScriptHookController; + +import java.io.*; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * Central registry for all TypeScript types parsed from .d.ts files. + * Also manages hook function signatures and type aliases. + */ +public class JSTypeRegistry { + + private static JSTypeRegistry INSTANCE; + + // All registered types by full name (e.g., "IPlayerEvent.InteractEvent") + private final Map types = new LinkedHashMap<>(); + + // Registered types by Java fully-qualified name (e.g., "noppes.npcs.api.entity.IPlayer") + private final Map typesByJavaFqn = new LinkedHashMap<>(); + + // Type aliases (simple name -> full type name) + private final Map typeAliases = new HashMap<>(); + + // Type full name -> origin string (modId:domain:relativePath) + private final Map typeOrigins = new HashMap<>(); + + // Alias name -> origin string (modId:domain:relativePath) + private final Map aliasOrigins = new HashMap<>(); + + // Context-aware hook function signatures: namespace -> functionName -> list of signatures + // The namespace is the event interface name (e.g., "INpcEvent", "IPlayerEvent") + // This allows any mod to register hooks without modifying an enum + private final Map>> contextHooks = new LinkedHashMap<>(); + + // Legacy hook storage: functionName -> list of (paramName, paramType) pairs + // Kept for backward compatibility with code that doesn't use contexts + private final Map> hooks = new LinkedHashMap<>(); + + // Fallback namespace for hooks that don't match a specific context + private static final String GLOBAL_NAMESPACE = "Global"; + + // Global object instances: name -> type (e.g., "API" -> "AbstractNpcAPI") + // These are treated as instance objects, not static classes + private final Map globalEngineObjects = new LinkedHashMap<>(); + // Math / Number / Json / etc. built-in globals from ECMAScript 5.1 + private final Map globalEngineImports = new LinkedHashMap<>(); + // Top-level global functions from GlobalFunctions.d.ts (parseInt, parseFloat, isNaN, etc.) + private final Map globalEngineFunctions = new LinkedHashMap<>(); + + // Primitive types + private static final Set PRIMITIVES = new HashSet<>(Arrays.asList( + "number", "string", "boolean", "void", "any", "null", "undefined", "never", "object", + "byte", "short", "int", "integer", "long", "float", "double", "char", "bool" + )); + + private boolean initialized = false; + private boolean initializationAttempted = false; + private int lastSyncedHookRevision = -1; + + private String currentSource = null; + + public static JSTypeRegistry getInstance() { + if (INSTANCE == null) { + INSTANCE = new JSTypeRegistry(); + } + return INSTANCE; + } + + private JSTypeRegistry() {} + + /** + * Initialize the registry from the embedded resources. + * Recursively loads all .d.ts files from assets/customnpcs/api/ + */ + public void initializeFromResources() { + if (initialized || initializationAttempted) return; + initializationAttempted = true; + + try { + TypeScriptDefinitionParser parser = new TypeScriptDefinitionParser(this); + + List dtsFiles = DtsModScanner.collectDtsFilesFromMods(); + if (dtsFiles.isEmpty()) { + Set fallbackFiles = findAllDtsFilesInResources("assets/customnpcs/api"); + + // System.out.println("[JSTypeRegistry] Found " + fallbackFiles.size() + " .d.ts files in resources"); + + if (fallbackFiles.contains("hooks.d.ts")) { + loadResourceFile(parser, "hooks.d.ts"); + } + if (fallbackFiles.contains("index.d.ts")) { + loadResourceFile(parser, "index.d.ts"); + } + + for (String filePath : fallbackFiles) { + if (!filePath.equals("hooks.d.ts") && !filePath.equals("index.d.ts")) { + loadResourceFile(parser, filePath); + } + } + } else { + DtsModScanner.logSummary(dtsFiles); + loadDtsFiles(parser, dtsFiles); + } + + // Phase 2: Resolve all type parameters now that all types are loaded + resolveAllTypeParameters(); + + // Phase 2b: Resolve member types (return types, field types, param types) + resolveAllMemberTypes(); + + // Phase 2c: Resolve JSDoc types (@param, @return, @type type references) + resolveAllJSDocTypes(); + + resolveInheritance(); + registerEngineGlobalObjects(); + registerES5Builtins(); + + initialized = true; + // System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from resources"); + } catch (Exception e) { + System.err.println("[JSTypeRegistry] Failed to load type definitions from resources: " + e.getMessage()); + e.printStackTrace(); + } + } + + private void loadDtsFiles(TypeScriptDefinitionParser parser, List dtsFiles) { + DtsModScanner.sortDtsFiles(dtsFiles); + for (DtsModScanner.DtsFileRef ref : dtsFiles) { + try (InputStream is = ref.openStream()) { + if (is == null) { + continue; + } + String content = readFully(new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))); + setCurrentSource(ref.getOrigin()); + parser.parseDefinitionFile(content, ref.getRelativePath()); + } catch (Exception e) { + System.err.println("[JSTypeRegistry] Failed to load " + ref.getOrigin() + ": " + e.getMessage()); + } finally { + setCurrentSource(null); + } + } + } + + private String readFully(BufferedReader reader) throws IOException { + StringBuilder sb = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line).append("\n"); + } + return sb.toString(); + } + + /** + * Recursively find all .d.ts files in the resources directory. + * Similar to ClassIndex.addPackage, scans both file system and JAR resources. + * + * @param resourcePath The full resource path (e.g., "assets/customnpcs/api") + */ + private Set findAllDtsFilesInResources(String resourcePath) { + Set dtsFiles = new HashSet<>(); + + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Enumeration resources = classLoader.getResources(resourcePath); + + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + + if (resource.getProtocol().equals("file")) { + // Scan file system directory + File directory = new File(resource.getFile()); + scanDirectoryForDts(directory, "", dtsFiles); + } else if (resource.getProtocol().equals("jar")) { + // Scan JAR file + String jarPath = resource.getPath(); + if (jarPath.startsWith("file:")) { + jarPath = jarPath.substring(5); + } + int separatorIndex = jarPath.indexOf("!"); + if (separatorIndex != -1) { + jarPath = jarPath.substring(0, separatorIndex); + } + scanJarForDts(jarPath, resourcePath, dtsFiles); + } + } + } catch (Exception e) { + System.err.println("[JSTypeRegistry] Error scanning for .d.ts files: " + e.getMessage()); + } + + return dtsFiles; + } + + /** + * Recursively scan a file system directory for .d.ts files. + * + * @param directory The directory to scan + * @param currentPath The relative path from the base (used for building file paths) + * @param dtsFiles The set to collect .d.ts file paths + */ + private void scanDirectoryForDts(File directory, String currentPath, Set dtsFiles) { + if (!directory.exists() || !directory.isDirectory()) { + return; + } + + File[] files = directory.listFiles(); + if (files == null) { + return; + } + + for (File file : files) { + String fileName = file.getName(); + String filePath = currentPath.isEmpty() ? fileName : currentPath + "/" + fileName; + + if (file.isDirectory()) { + // Recursively scan subdirectory + scanDirectoryForDts(file, filePath, dtsFiles); + } else if (fileName.endsWith(".d.ts")) { + // Add .d.ts file path + dtsFiles.add(filePath); + } + } + } + + /** + * Scan a JAR file for .d.ts files in the specified resource path. + */ + private void scanJarForDts(String jarPath, String resourcePath, Set dtsFiles) { + try { + JarFile jarFile = new JarFile(jarPath); + Enumeration entries = jarFile.entries(); + + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + + // Check if entry is under our resource path and is a .d.ts file + if (entryName.startsWith(resourcePath + "/") && entryName.endsWith(".d.ts")) { + // Convert to relative path from resourcePath + String relativePath = entryName.substring(resourcePath.length() + 1); + dtsFiles.add(relativePath); + } + } + + jarFile.close(); + } catch (Exception e) { + System.err.println("[JSTypeRegistry] Error scanning JAR for .d.ts files: " + e.getMessage()); + } + } + + /** + * Load a specific .d.ts file from resources. + */ + private void loadResourceFile(TypeScriptDefinitionParser parser, String fileName) { + try { + ResourceLocation loc = new ResourceLocation("customnpcs", "api/" + fileName); + InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(loc).getInputStream(); + if (is != null) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { + StringBuilder sb = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line).append("\n"); + } + parser.parseDefinitionFile(sb.toString(), fileName); + } + } + } catch (Exception e) { + // File might not exist, that's ok + // System.out.println("[JSTypeRegistry] Could not load " + fileName + ": " + e.getMessage()); + } + } + + /** + * Initialize the registry from a directory containing .d.ts files. + */ + public void initializeFromDirectory(File directory) { + if (initialized) return; + + try { + TypeScriptDefinitionParser parser = new TypeScriptDefinitionParser(this); + parser.parseDirectory(directory); + resolveAllTypeParameters(); + resolveAllMemberTypes(); + resolveAllJSDocTypes(); + resolveInheritance(); + initialized = true; + // System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks"); + } catch (IOException e) { + System.err.println("[JSTypeRegistry] Failed to load type definitions: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Initialize the registry from a VSIX file. + */ + public void initializeFromVsix(File vsixFile) { + if (initialized) return; + + try { + TypeScriptDefinitionParser parser = new TypeScriptDefinitionParser(this); + parser.parseVsixArchive(vsixFile); + resolveAllTypeParameters(); + resolveAllMemberTypes(); + resolveAllJSDocTypes(); + resolveInheritance(); + initialized = true; + // System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from VSIX"); + } catch (IOException e) { + System.err.println("[JSTypeRegistry] Failed to load VSIX: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Register a type. + * If a type with matching javaFqn or fullName already exists, merges instead of discarding. + */ + public void registerType(JSTypeInfo type) { + String fullName = type.getFullName(); + String javaFqn = type.getJavaFqn(); + + JSTypeInfo existingType = null; + + if (javaFqn != null && !javaFqn.isEmpty()) { + existingType = typesByJavaFqn.get(javaFqn); + } + + if (existingType == null && types.containsKey(fullName)) { + existingType = types.get(fullName); + } + + if (existingType != null) { + mergeType(existingType, type, getCurrentSource()); + + // Preserve an addressable key for the incoming declared name. + // Some .d.ts parsing paths can encounter the same Java type via multiple textual names + // (e.g., due to nested namespaces). Even if we merge by @javaFqn, callers still expect + // lookups like "INpcEvent.DamagedEvent" to work. + if (!types.containsKey(fullName)) { + types.put(fullName, existingType); + typeOrigins.put(fullName, getCurrentSource()); + } + return; + } + + types.put(fullName, type); + typeOrigins.put(fullName, getCurrentSource()); + if (javaFqn != null && !javaFqn.isEmpty()) { + if (!typesByJavaFqn.containsKey(javaFqn)) { + typesByJavaFqn.put(javaFqn, type); + } else { + // System.out.println("[JSTypeRegistry] Duplicate javaFqn " + javaFqn + " from " + getCurrentSource()); + } + } + } + + /** + * Get a type by Java fully-qualified name. + */ + public JSTypeInfo getTypeByJavaFqn(String javaFqn) { + if (javaFqn == null || javaFqn.isEmpty()) return null; + return typesByJavaFqn.get(javaFqn); + } + + /** + * Register a type alias. + */ + public void registerTypeAlias(String alias, String fullType) { + if (typeAliases.containsKey(alias)) { + String existing = typeAliases.get(alias); + if (!Objects.equals(existing, fullType)) { + logAliasCollision(alias, existing, fullType, getCurrentSource()); + } + return; + } + typeAliases.put(alias, fullType); + aliasOrigins.put(alias, getCurrentSource()); + } + + /** + * Register a hook function signature with a namespace. + * + * @param namespace The event interface namespace (e.g., "INpcEvent", "IPlayerEvent") + * @param functionName The hook function name (e.g., "interact", "damaged") + * @param paramName The parameter name (e.g., "event") + * @param paramType The parameter type (e.g., "INpcEvent.InteractEvent") + */ + public void registerHook(String namespace, String functionName, String paramName, String paramType) { + HookSignature sig = new HookSignature(paramName, paramType, null, namespace); + + // Add to context-specific map + contextHooks.computeIfAbsent(namespace, k -> new LinkedHashMap<>()) + .computeIfAbsent(functionName, k -> new ArrayList<>()) + .add(sig); + + // Also add to legacy hooks map for backward compatibility + hooks.computeIfAbsent(functionName, k -> new ArrayList<>()).add(sig); + } + + /** + * Get a type by name (handles aliases and primitives). + */ + public JSTypeInfo getType(String name) { + return getType(name, new HashSet<>()); + } + + /** + * Internal method with cycle detection for type aliases. + */ + private JSTypeInfo getType(String name, Set visited) { + if (name == null || name.isEmpty()) return null; + + // Strip array brackets for lookup + String baseName = name.replace("[]", "").trim(); + + // Check if primitive + if (PRIMITIVES.contains(baseName)) { + return null; // Primitives don't have JSTypeInfo + } + + // Detect circular alias references + if (visited.contains(baseName)) { + // Circular alias detected - try direct type lookup as fallback + if (types.containsKey(baseName)) { + return types.get(baseName); + } + return null; + } + visited.add(baseName); + + // Direct lookup in types first (higher priority than aliases) + if (types.containsKey(baseName)) { + return types.get(baseName); + } + + // Check type aliases + if (typeAliases.containsKey(baseName)) { + String resolved = typeAliases.get(baseName); + // Don't follow alias if it resolves to itself + if (resolved.equals(baseName)) { + return null; + } + return getType(resolved, visited); + } + + // Check global engine imports (e.g., ES5.1 Math, JSON) before giving up + if (globalEngineImports.containsKey(baseName)){ + return globalEngineImports.get(baseName); + } + + // Try simple name lookup (for types like "IEntity" without namespace) + for (JSTypeInfo type : types.values()) { + if (type.getSimpleName().equals(baseName)) { + return type; + } + } + return null; + } + + /** + * Check if a type name is a known primitive. + */ + public boolean isPrimitive(String typeName) { + return PRIMITIVES.contains(typeName); + } + + /** + * Get hook signatures for a function name. + */ + public List getHookSignatures(String functionName) { + return hooks.getOrDefault(functionName, Collections.emptyList()); + } + + /** + * Check if a function name is a known hook. + */ + public boolean isHook(String functionName) { + return hooks.containsKey(functionName); + } + + /** + * Get the parameter type for a hook function. + * If multiple overloads exist, returns the first one. + */ + public String getHookParameterType(String functionName) { + List sigs = hooks.get(functionName); + if (sigs != null && !sigs.isEmpty()) { + return sigs.get(0).paramType; + } + return null; + } + + // ==================== Context-Aware Hook Methods ==================== + + /** + * Get hook signatures for a specific script context. + * Falls back to GLOBAL context if not found in the specified context. + * + * @param namespace The event interface namespace (e.g., "INpcEvent", "IPlayerEvent") + * @param functionName The hook function name + * @return List of hook signatures, or empty list if not found + */ + public List getHookSignatures(String namespace, String functionName) { + // First try the specific namespace + Map> namespaceMap = contextHooks.get(namespace); + if (namespaceMap != null) { + List sigs = namespaceMap.get(functionName); + if (sigs != null && !sigs.isEmpty()) { + return sigs; + } + } + + // Fall back to GLOBAL namespace + if (!GLOBAL_NAMESPACE.equals(namespace)) { + Map> globalMap = contextHooks.get(GLOBAL_NAMESPACE); + if (globalMap != null) { + List sigs = globalMap.get(functionName); + if (sigs != null && !sigs.isEmpty()) { + return sigs; + } + } + } + + return Collections.emptyList(); + } + + /** + * Check if a function name is a known hook in a specific namespace. + * + * @param namespace The event interface namespace + * @param functionName The hook function name + * @return true if the hook exists in this namespace or GLOBAL + */ + public boolean isHook(String namespace, String functionName) { + return !getHookSignatures(namespace, functionName).isEmpty(); + } + + /** + * Get the parameter type for a hook function in a specific namespace. + * Falls back to GLOBAL namespace if not found. + * + * @param namespace The event interface namespace + * @param functionName The hook function name + * @return The parameter type, or null if not found + */ + public String getHookParameterType(String namespace, String functionName) { + List sigs = getHookSignatures(namespace, functionName); + if (!sigs.isEmpty()) { + return sigs.get(0).paramType; + } + return null; + } + + /** + * Get all hook names for a specific namespace. + * + * @param namespace The event interface namespace + * @return Set of hook function names available in this namespace + */ + public Set getHookNames(String namespace) { + Set names = new HashSet<>(); + + // Add hooks from the specific namespace + Map> namespaceMap = contextHooks.get(namespace); + if (namespaceMap != null) { + names.addAll(namespaceMap.keySet()); + } + + // Also add GLOBAL hooks + if (!GLOBAL_NAMESPACE.equals(namespace)) { + Map> globalMap = contextHooks.get(GLOBAL_NAMESPACE); + if (globalMap != null) { + names.addAll(globalMap.keySet()); + } + } + + return names; + } + + /** + * Get all hooks organized by namespace. + * + * @return Map of namespace -> hookName -> signatures + */ + public Map>> getAllContextHooks() { + return Collections.unmodifiableMap(contextHooks); + } + + // ==================== MULTI-NAMESPACE LOOKUP (for ScriptContext) ==================== + + /** + * Get hook signatures by searching through multiple namespaces. + * This is used when a ScriptContext has multiple event types (e.g., Player has + * IPlayerEvent, IAnimationEvent, IPartyEvent, etc.) + * + * @param namespaces List of namespaces to search (in priority order) + * @param functionName The hook function name + * @return List of hook signatures from the first matching namespace, or empty list + */ + public List getHookSignatures(List namespaces, String functionName) { + // Search through all namespaces in order + for (String namespace : namespaces) { + Map> namespaceMap = contextHooks.get(namespace); + if (namespaceMap != null) { + List sigs = namespaceMap.get(functionName); + if (sigs != null && !sigs.isEmpty()) { + return sigs; + } + } + } + + // Fall back to GLOBAL namespace + Map> globalMap = contextHooks.get(GLOBAL_NAMESPACE); + if (globalMap != null) { + List sigs = globalMap.get(functionName); + if (sigs != null && !sigs.isEmpty()) { + return sigs; + } + } + + return Collections.emptyList(); + } + + /** + * Check if a function name is a known hook in any of the given namespaces. + * + * @param namespaces List of namespaces to search + * @param functionName The hook function name + * @return true if the hook exists in any namespace or GLOBAL + */ + public boolean isHook(List namespaces, String functionName) { + return !getHookSignatures(namespaces, functionName).isEmpty(); + } + + /** + * Get the parameter type for a hook function, searching through multiple namespaces. + * + * @param namespaces List of namespaces to search + * @param functionName The hook function name + * @return The parameter type, or null if not found + */ + public String getHookParameterType(List namespaces, String functionName) { + List sigs = getHookSignatures(namespaces, functionName); + if (!sigs.isEmpty()) { + return sigs.get(0).paramType; + } + return null; + } + + /** + * Get all hook names available in any of the given namespaces. + * + * @param namespaces List of namespaces to search + * @return Set of hook function names available in these namespaces + */ + public Set getHookNames(List namespaces) { + Set names = new HashSet<>(); + + // Add hooks from all specified namespaces + for (String namespace : namespaces) { + Map> namespaceMap = contextHooks.get(namespace); + if (namespaceMap != null) { + names.addAll(namespaceMap.keySet()); + } + } + + // Also add GLOBAL hooks + Map> globalMap = contextHooks.get(GLOBAL_NAMESPACE); + if (globalMap != null) { + names.addAll(globalMap.keySet()); + } + + return names; + } + + /** + * Resolve all type parameters for all types. + * Called after all .d.ts files are loaded (Phase 2). + * This ensures that type parameters can reference any type in the registry. + */ + public void resolveAllTypeParameters() { + for (JSTypeInfo type : types.values()) { + type.resolveTypeParameters(); + } + } + + /** + * Resolve all member types (return types, field types, parameter types) for all types. + * Called after resolveAllTypeParameters (Phase 2b). + * This resolves types like "Java.java.io.File" to proper TypeInfo objects. + */ + public void resolveAllMemberTypes() { + for (JSTypeInfo type : types.values()) + type.resolveMemberTypes(); + } + + public void resolveAllJSDocTypes() { + for (JSTypeInfo type : types.values()) + type.resolveJSDocTypes(); + } + + /** + * Resolve inheritance relationships between types. + * For each type, walks up the parent chain and resolves all ancestors. + * Efficient O(n) approach - each type's chain is walked once. + */ + public void resolveInheritance() { + for (JSTypeInfo type : types.values()) { + JSTypeInfo child = type; + while (child != null && child.getExtendsType() != null && child.getResolvedParent() == null) { + JSTypeInfo parent = getType(child.getExtendsType()); + if (parent != null) { + child.setResolvedParent(parent); + } + child = parent; + } + } + } + + /** + * Get all registered types. + */ + public Collection getAllTypes() { + return types.values(); + } + + /** + * Get all type names. + */ + public Set getTypeNames() { + return types.keySet(); + } + + /** + * Get all hook function names. + */ + public Set getHookNames() { + return hooks.keySet(); + } + + /** + * Get all registered hooks. + */ + public Map> getAllHooks() { + return hooks; + } + + /** + * Register a global object instance (like API, DBCAPI from NpcAPI.engineObjects). + * These are treated as instance objects, not static classes. + * @param name The global variable name (e.g., "API") + * @param typeName The type name (e.g., "AbstractNpcAPI") + */ + public void registerGlobalObject(String name, String typeName) { + globalEngineObjects.put(name, typeName); + } + + /** + * Get the type name for a global object. + * @param name The global variable name + * @return The type name, or null if not a registered global object + */ + public String getGlobalObjectType(String name) { + return globalEngineObjects.get(name); + } + + /** + * Check if a name is a registered global object instance. + */ + public boolean isGlobalObject(String name) { + return globalEngineObjects.containsKey(name); + } + + /** + * Get all registered global objects. + */ + public Map getGlobalEngineObjects() { + return Collections.unmodifiableMap(globalEngineObjects); + } + + /** + * Registers global objects from NpcAPI.engineObjects into JSTypeRegistry. + * This allows the IDE to recognize API, DBCAPI, etc. as instance objects with autocomplete. + */ + private void registerEngineGlobalObjects() { + Map engineObjects = new HashMap<>(NpcAPI.engineObjects); + engineObjects.put("API", NpcAPI.Instance()); //default API object + + if (engineObjects != null) { + for (Map.Entry entry : engineObjects.entrySet()) { + String name = entry.getKey(); // e.g., "API", "DBCAPI" + Object obj = entry.getValue(); // e.g., AbstractNpcAPI instance + + if (obj != null) { + // Get the actual class name + String concreteClassName = obj.getClass().getSimpleName(); + + // Map concrete implementation classes to their abstract interface names + // (because .d.ts files define the abstract interfaces, not the implementations) + String typeName = mapConcreteToAbstractClassName(concreteClassName); + + // Register as global object (instance, not static) + registerGlobalObject(name, typeName); + } + } + } + } + + /** + * Maps concrete implementation class names to their abstract interface names. + * For example: "NpcAPI" -> "AbstractNpcAPI", "DBCAPI" -> "AbstractDBCAPI" + */ + private String mapConcreteToAbstractClassName(String concreteClassName) { + // Check if the type exists in the registry as-is + if (types.containsKey(concreteClassName)) + return concreteClassName; + + // Try prepending "Abstract" if it doesn't exist + String abstractName = "Abstract" + concreteClassName; + if (types.containsKey(abstractName)) + return abstractName; + + // Default: return the original name + return concreteClassName; + } + + /** + * Register ECMAScript 5.1 global built-in objects so that expressions like + * `Math.floor(Math.random())`, `new Date()`, `Array.isArray(...)`, etc. + * resolve properly with type checking and autocomplete. + * + * These globals are parsed from .d.ts patch files under `patches/ecmascript/` + * and provide both static methods (e.g., Math.floor, Array.isArray, Object.keys) + * and instance members (e.g., date.getTime(), array.length, string.charAt). + */ + private void registerES5Builtins() { + // Singleton/namespace globals (accessed directly, not constructed) + registerGlobalIfTypeExists("Math", "Math"); + registerGlobalIfTypeExists("JSON", "JSON"); + + // Constructor globals (can be called with `new` or used for static methods) + registerGlobalIfTypeExists("Date", "Date"); + registerGlobalIfTypeExists("Array", "Array"); + registerGlobalIfTypeExists("Object", "Object"); + registerGlobalIfTypeExists("String", "String"); + registerGlobalIfTypeExists("Number", "Number"); + registerGlobalIfTypeExists("Boolean", "Boolean"); + registerGlobalIfTypeExists("RegExp", "RegExp"); + registerGlobalIfTypeExists("Error", "Error"); + + extractGlobalFunctions(); + } + + /** + * Registers a global object only if the target type is present in the registry. + * Silently skips if the .d.ts patch hasn't been loaded yet (e.g. in unit tests). + */ + private void registerGlobalIfTypeExists(String globalName, String typeName) { + // Remove the type since it's now accessed via the global import + if (types.containsKey(typeName)) { + globalEngineImports.put(globalName, types.remove(typeName)); + } + } + + /** + * Extract top-level global functions from the GlobalFunctions JSTypeInfo. + * Moves all methods into globalEngineFunctions and removes the GlobalFunctions + * type from the registry (it is not a constructable type). + */ + private void extractGlobalFunctions() { + JSTypeInfo globalFns = types.get("GlobalFunctions"); + if (globalFns == null) return; + + for (Map.Entry entry : globalFns.getMethods().entrySet()) { + String key = entry.getKey(); + // Strip overload suffix ($1, $2, …) to get base name + String baseName = key.contains("$") ? key.substring(0, key.indexOf('$')) : key; + // Keep the first overload per base name + globalEngineFunctions.putIfAbsent(baseName, entry.getValue()); + } + + // Remove GlobalFunctions from the main type registry — it is not a usable type name + types.remove("GlobalFunctions"); + } + + /** + * Get the type name for a global object. + * @param name The global variable name + * @return The type name, or null if not a registered global object + */ + public JSTypeInfo getGlobalImportType(String name) { + return globalEngineImports.get(name); + } + + /** + * Check if a name is a registered global object instance. + */ + public boolean isGlobalImport(String name) { + return globalEngineImports.containsKey(name); + } + + /** + * Get all registered global objects. + */ + public Map getGlobalEngineImports() { + return Collections.unmodifiableMap(globalEngineImports); + } + + /** + * Get JSMethodInfo for a global engine function by name (e.g., "parseInt"). + */ + public JSMethodInfo getGlobalEngineFunction(String name) { + return globalEngineFunctions.get(name); + } + + /** + * Check if a name is a registered global engine function. + */ + public boolean isGlobalEngineFunction(String name) { + return globalEngineFunctions.containsKey(name); + } + + /** + * Get all registered global engine functions (parseInt, parseFloat, isNaN, etc.). + */ + public Map getGlobalEngineFunctions() { + return Collections.unmodifiableMap(globalEngineFunctions); + } + /** + * Check if initialized. + */ + public boolean isInitialized() { + return initialized; + } + + /** + * Clear the registry (for reloading). + */ + public void clear() { + types.clear(); + typesByJavaFqn.clear(); + typeAliases.clear(); + typeOrigins.clear(); + aliasOrigins.clear(); + hooks.clear(); + contextHooks.clear(); + globalEngineObjects.clear(); + globalEngineImports.clear(); + globalEngineFunctions.clear(); + DtsJavaBridge.clearCache(); + initialized = false; + initializationAttempted = false; + currentSource = null; + lastSyncedHookRevision = -1; + } + + /** + * Sync hook signatures from ScriptHookController into this registry. + * Uses revision-gating so repeated calls are no-ops when nothing changed. + */ + public void syncHooksFromScriptHookControllerIfNeeded() { + try { + if (ScriptHookController.Instance == null) { + return; + } + + int currentRevision = ScriptHookController.Instance.getHookRevision(); + if (currentRevision == lastSyncedHookRevision) { + return; + } + + hooks.clear(); + contextHooks.clear(); + + Set seen = new HashSet<>(); + + String[] contexts = ScriptHookController.Instance.getContexts(); + if (contexts != null) { + for (String context : contexts) { + if (context == null || context.isEmpty()) { + continue; + } + List defs = ScriptHookController.Instance.getAllHookDefinitions(context); + if (defs == null || defs.isEmpty()) { + continue; + } + + for (IHookDefinition def : defs) { + if (def == null) { + continue; + } + String hookName = def.hookName(); + if (hookName == null || hookName.isEmpty()) { + continue; + } + + String usableTypeName = def.getUsableTypeName(); + String namespace; + String paramType; + + if (usableTypeName != null && usableTypeName.contains(".")) { + namespace = usableTypeName.substring(0, usableTypeName.indexOf('.')); + } else { + namespace = GLOBAL_NAMESPACE; + } + + paramType = usableTypeName != null ? usableTypeName : "any"; + + String[] paramNames = def.paramNames(); + String paramName = (paramNames != null && paramNames.length > 0 && paramNames[0] != null && !paramNames[0].isEmpty()) + ? paramNames[0] + : "event"; + + String dedupKey = namespace + "|" + hookName + "|" + paramType + "|" + paramName; + if (!seen.add(dedupKey)) { + continue; + } + registerHook(namespace, hookName, paramName, paramType); + } + } + } + + lastSyncedHookRevision = currentRevision; + } catch (Throwable t) { + System.err.println("[JSTypeRegistry] Failed to sync runtime hooks: " + t.getMessage()); + t.printStackTrace(); + } + } + + private void setCurrentSource(String source) { + currentSource = source; + } + + private String getCurrentSource() { + return currentSource == null ? "unknown" : currentSource; + } + + private void logTypeCollision(String fullName, String incomingSource) { + String existingSource = typeOrigins.getOrDefault(fullName, "unknown"); + // System.out.println("[JSTypeRegistry] Duplicate type " + fullName + " from " + incomingSource + " (kept " + existingSource + ")"); + } + + private void logAliasCollision(String alias, String existingType, String incomingType, String incomingSource) { + String existingSource = aliasOrigins.getOrDefault(alias, "unknown"); + // System.out.println("[JSTypeRegistry] Duplicate alias " + alias + " from " + incomingSource + " (kept " + existingSource + ")"); + // System.out.println("[JSTypeRegistry] Alias " + alias + " existing=" + existingType + " incoming=" + incomingType); + } + + /** + * Find the method key in a type's methods map that matches the given method name and parameter count. + * This handles overload keys (methodName, methodName$1, methodName$2, etc.) + * + * @param type The type to search in + * @param candidate The method name to search for + * @return The method key if found, or null if no match + */ + private String findOwnMethodKeyBySignature(JSTypeInfo type, JSMethodInfo candidate) { + Map methods = type.getMethods(); + String methodName = candidate.getName(); + + // Check direct key first + JSMethodInfo direct = methods.get(methodName); + if (direct != null && hasSameParameterSignature(direct, candidate)) { + return methodName; + } + + // Check overload keys: methodName$1, methodName$2, etc. + int index = 1; + String overloadKey = methodName + "$" + index; + while (methods.containsKey(overloadKey)) { + JSMethodInfo overload = methods.get(overloadKey); + if (hasSameParameterSignature(overload, candidate)) { + return overloadKey; + } + index++; + overloadKey = methodName + "$" + index; + } + + return null; // No match found + } + + private boolean hasSameParameterSignature(JSMethodInfo left, JSMethodInfo right) { + if (left == null || right == null) { + return false; + } + + if (left.getParameterCount() != right.getParameterCount()) { + return false; + } + + List leftParams = left.getParameters(); + List rightParams = right.getParameters(); + for (int i = 0; i < leftParams.size(); i++) { + String leftType = leftParams.get(i).getType(); + String rightType = rightParams.get(i).getType(); + if (!Objects.equals(leftType, rightType)) { + return false; + } + } + + return true; + } + + /** + * Merge an incoming type into an existing type. + * This allows addon mods to patch base mod types via .d.ts files. + * + * @param existing The existing type to merge into + * @param incoming The incoming type to merge from + * @param incomingSource The source of the incoming type (for logging) + */ + private void mergeType(JSTypeInfo existing, JSTypeInfo incoming, String incomingSource) { + int methodsMerged = 0; + int fieldsMerged = 0; + + // Merge methods (replace matching overloads by param count) + for (Map.Entry entry : incoming.getMethods().entrySet()) { + JSMethodInfo incomingMethod = entry.getValue(); + String methodName = incomingMethod.getName(); + String existingKey = findOwnMethodKeyBySignature(existing, incomingMethod); + if (existingKey != null) { + // Replace existing overload + existing.getMethods().put(existingKey, incomingMethod); + incomingMethod.setContainingType(existing); + methodsMerged++; + } else { + // Add as new overload + existing.addMethod(incomingMethod); + methodsMerged++; + } + } + + // Merge fields (replace by name) + for (Map.Entry entry : incoming.getFields().entrySet()) { + String fieldName = entry.getKey(); + JSFieldInfo incomingField = entry.getValue(); + existing.getFields().put(fieldName, incomingField); + incomingField.setContainingType(existing); + fieldsMerged++; + } + + // Merge metadata (fill gaps only - preserve existing non-null values) + if (existing.getJavaFqn() == null && incoming.getJavaFqn() != null) { + existing.setJavaFqn(incoming.getJavaFqn()); + } + if (existing.getJsDocInfo() == null && incoming.getJsDocInfo() != null) { + existing.setJsDocInfo(incoming.getJsDocInfo()); + } + if (existing.getExtendsType() == null && incoming.getExtendsType() != null) { + existing.setExtends(incoming.getExtendsType()); + } + + // Log merge details + // System.out.println("[JSTypeRegistry] Merged type " + existing.getFullName() + + // " with " + methodsMerged + " methods, " + fieldsMerged + + // " fields from " + incomingSource); + } + + /** + * Represents a hook function signature with its namespace. + */ + public static class HookSignature { + public final String paramName; + public final String paramType; + public final String doc; + public final String namespace; // The event interface namespace (e.g., "INpcEvent") + + public HookSignature(String paramName, String paramType) { + this(paramName, paramType, null, GLOBAL_NAMESPACE); + } + + public HookSignature(String paramName, String paramType, String doc) { + this(paramName, paramType, doc, GLOBAL_NAMESPACE); + } + + public HookSignature(String paramName, String paramType, String doc, String namespace) { + this.paramName = paramName; + this.paramType = paramType; + this.doc = doc; + this.namespace = namespace != null ? namespace : GLOBAL_NAMESPACE; + } + + @Override + public String toString() { + return paramName + ": " + paramType + " [" + namespace + "]"; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeParamInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeParamInfo.java new file mode 100644 index 000000000..d576c6a0c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeParamInfo.java @@ -0,0 +1,131 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Represents a generic type parameter like "T extends Entity" or "T extends Number & Comparable". + * Stores the parameter name and both the string representation (for deferred resolution) + * and the resolved TypeInfo for the bound. + * + * Multiple bounds (e.g., {@code >}) are supported: + * the primary bound is the first type after "extends", and additional bounds are + * interface types separated by "&". + */ +public class TypeParamInfo { + private final String name; // e.g., "T" + private final String boundType; // Simple name like "EntityPlayerMP" (may be null) + private final String fullBoundType; // Full name like "net.minecraft.entity.player.EntityPlayerMP" (may be null) + private TypeInfo boundTypeInfo; // Resolved TypeInfo for the primary bound (resolved in Phase 2) + + // Additional bounds from & syntax (e.g., Comparable in "T extends Number & Comparable") + private final List additionalBoundNames; + private final List additionalBoundTypes; + + /** + * Constructor for parse-time (Phase 1) - stores string names only. + */ + public TypeParamInfo(String name, String boundType, String fullBoundType) { + this.name = name; + this.boundType = boundType; + this.fullBoundType = fullBoundType; + this.boundTypeInfo = null; // Will be resolved later + this.additionalBoundNames = new ArrayList<>(); + this.additionalBoundTypes = new ArrayList<>(); + } + + public String getName() { return name; } + + public TypeInfo getBoundTypeInfo() { + return boundTypeInfo; + } + + public void setBoundTypeInfo(TypeInfo boundTypeInfo) { + this.boundTypeInfo = boundTypeInfo; + } + + /** + * Add an additional bound (from & syntax). + * @param boundName The simple name of the additional bound type + */ + public void addAdditionalBound(String boundName) { + additionalBoundNames.add(boundName); + } + + /** + * Add a resolved additional bound TypeInfo. + * @param typeInfo The resolved TypeInfo for an additional bound + */ + public void addAdditionalBoundType(TypeInfo typeInfo) { + additionalBoundTypes.add(typeInfo); + } + + /** + * Get the list of additional bound names (unresolved). + */ + public List getAdditionalBoundNames() { + return Collections.unmodifiableList(additionalBoundNames); + } + + /** + * Get the list of resolved additional bound TypeInfos. + */ + public List getAdditionalBoundTypes() { + return Collections.unmodifiableList(additionalBoundTypes); + } + + /** + * Check if this type parameter has additional bounds (& syntax). + */ + public boolean hasAdditionalBounds() { + return !additionalBoundNames.isEmpty(); + } + + /** + * Resolve the bound type using TypeResolver. + * Called during Phase 2 after all types are loaded. + */ + public void resolveBoundType() { + if (boundTypeInfo != null) + return; // Already resolved + + if (fullBoundType != null && !fullBoundType.isEmpty()) { + // Try to load the Java class using the full name + boundTypeInfo = TypeResolver.getInstance().resolveFullName(fullBoundType); + } else if (boundType != null && !boundType.isEmpty()) { + // Try to resolve using the simple name + boundTypeInfo = TypeResolver.getInstance().resolveJSType(boundType); + } + } + + /** + * Get display name for the bound type, including generic arguments. + */ + public String getBoundTypeName() { + if (boundTypeInfo == null) + return null; + return boundTypeInfo.getDisplayName(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(name); + if (boundTypeInfo != null) { + sb.append(" extends ").append(boundTypeInfo.getDisplayName()); + } else if (boundType != null || fullBoundType != null) { + sb.append(" extends ").append(boundType != null ? boundType : fullBoundType); + } + for (int i = 0; i < additionalBoundTypes.size(); i++) { + sb.append(" & ").append(additionalBoundTypes.get(i).getDisplayName()); + } + // Show unresolved additional bounds that don't have a resolved type yet + for (int i = additionalBoundTypes.size(); i < additionalBoundNames.size(); i++) { + sb.append(" & ").append(additionalBoundNames.get(i)); + } + return sb.toString(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeScriptDefinitionParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeScriptDefinitionParser.java new file mode 100644 index 000000000..9c82e63c4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeScriptDefinitionParser.java @@ -0,0 +1,728 @@ +package noppes.npcs.client.gui.util.script.interpreter.js_parser; + +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocTag; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeStringNormalizer; + +import java.io.*; +import java.util.*; +import java.util.regex.*; +import java.util.zip.*; + +/** + * Parses TypeScript definition files (.d.ts) to extract type information. + * Can read from individual files, directories, or .vsix archives. + */ +public class TypeScriptDefinitionParser { + + // Patterns for parsing .d.ts content + // Updated to capture generic type parameters like: export interface IEntity + private static final Pattern INTERFACE_PATTERN = Pattern.compile( + "export\\s+interface\\s+(\\w+)(?:<([^>]*)>)?(?:\\s+extends\\s+([^{]+?))?\\s*\\{"); + + // Pattern for nested interfaces without export keyword + private static final Pattern NESTED_INTERFACE_PATTERN = Pattern.compile( + "(?]*)>)?(?:\\s+extends\\s+([^{]+?))?\\s*\\{"); + + // Similar pattern for classes + private static final Pattern CLASS_PATTERN = Pattern.compile( + "export\\s+class\\s+(\\w+)(?:<([^>]*)>)?(?:\\s+extends\\s+([^{]+?))?\\s*\\{"); + + // Pattern to parse individual type parameters like: T extends EntityPlayerMP /* net.minecraft.entity.player.EntityPlayerMP */ + private static final Pattern TYPE_PARAM_PATTERN = Pattern.compile( + "(\\w+)(?:\\s+extends\\s+(\\w+)(?:\\s*/\\*\\s*([\\w.]+)\\s*\\*/)?)?"); + + // Match both "export namespace" and plain "namespace" (for declare global blocks) + private static final Pattern NAMESPACE_PATTERN = Pattern.compile( + "(?:export\\s+)?namespace\\s+(\\w+)\\s*\\{"); + + // Make semicolon optional for type aliases (TypeScript doesn't require them) + private static final Pattern TYPE_ALIAS_PATTERN = Pattern.compile( + "export\\s+type\\s+(\\w+)\\s*=\\s*([^;\\n]+);?"); + + private static final Pattern METHOD_PATTERN = Pattern.compile( + "(?m)^\\s*(static\\s+)?(\\w+)\\??\\s*\\((.*)\\)\\s*:\\s*([^;]+);", Pattern.MULTILINE); + + private static final Pattern FIELD_PATTERN = Pattern.compile( + "^\\s*(static\\s+)?(readonly\\s+)?(\\w+)\\??\\s*:\\s*([^;]+);", Pattern.MULTILINE); + + private static final Pattern GLOBAL_FUNCTION_PATTERN = Pattern.compile( + "function\\s+(\\w+)\\s*\\((.*)\\)\\s*:\\s*([^;]+);"); + + private static final Pattern GLOBAL_TYPE_ALIAS_PATTERN = Pattern.compile( + "type\\s+(\\w+)\\s*=\\s*import\\(['\"]([^'\"]+)['\"]\\)\\.([\\w.]+);"); + + // Pattern for context-namespaced hooks like: declare namespace INpcEvent { ... } + // Matches any "declare namespace {" where Name starts with I and contains Event, + // or any other namespace pattern used for hooks + private static final Pattern HOOKS_NAMESPACE_PATTERN = Pattern.compile( + "declare\\s+namespace\\s+(I\\w*Event|\\w+)\\s*\\{", Pattern.MULTILINE); + + private final JSTypeRegistry registry; + + public TypeScriptDefinitionParser(JSTypeRegistry registry) { + this.registry = registry; + } + + /** + * Parse all .d.ts files from a VSIX archive. + */ + public void parseVsixArchive(File vsixFile) throws IOException { + try (ZipFile zip = new ZipFile(vsixFile)) { + Enumeration entries = zip.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (entry.getName().endsWith(".d.ts")) { + try (InputStream is = zip.getInputStream(entry); + BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { + String content = readFully(reader); + String fileName = entry.getName(); + parseDefinitionFile(content, fileName); + } + } + } + } + } + + /** + * Parse all .d.ts files from a directory recursively. + */ + public void parseDirectory(File directory) throws IOException { + if (!directory.isDirectory()) { + throw new IllegalArgumentException("Not a directory: " + directory); + } + parseDirectoryRecursive(directory); + } + + private void parseDirectoryRecursive(File dir) throws IOException { + File[] files = dir.listFiles(); + if (files == null) return; + + for (File file : files) { + if (file.isDirectory()) { + parseDirectoryRecursive(file); + } else if (file.getName().endsWith(".d.ts")) { + parseFile(file); + } + } + } + + /** + * Parse a single .d.ts file. + */ + public void parseFile(File file) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + String content = readFully(reader); + parseDefinitionFile(content, file.getName()); + } + } + + /** + * Parse a .d.ts file content. + */ + public void parseDefinitionFile(String content, String fileName) { + // Special handling for hooks.d.ts - extract function signatures + if (fileName.contains("hooks.d.ts")) { + // Commented out as hooks are now parsed through ScriptHookController which is the universal source of truth for registered hooks. + // parseHooksFile(content); + return; + } + + // Special handling for index.d.ts - extract global type aliases + if (fileName.contains("index.d.ts")) { + parseIndexFile(content); + return; + } + + // Parse regular interface files + String packageName = derivePackageName(fileName); + parseInterfaceFile(content, null, packageName); + } + + /** + * Parse hooks.d.ts to extract function signatures for JS hooks. + * + * Hooks are organized by their parent event interface, with the interface name + * used directly as the namespace. Any mod can register its own event interfaces + * and they will be automatically parsed: + * + * declare namespace INpcEvent { + * function interact(event: INpcEvent.InteractEvent): void; + * function init(event: INpcEvent.InitEvent): void; + * } + * + * declare namespace IPlayerEvent { + * function interact(event: IPlayerEvent.InteractEvent): void; + * } + * + * declare namespace IDBCEvent { + * function customHook(event: IDBCEvent.CustomEvent): void; + * } + * + * The namespace name is stored as a string, allowing dynamic registration + * without requiring enum modifications. + */ + private void parseHooksFile(String content) { + // Parse namespaced hooks (e.g., declare namespace INpcEvent { ... }) + // The namespace name is used directly - any event interface can register hooks + Matcher namespaceMatcher = HOOKS_NAMESPACE_PATTERN.matcher(content); + while (namespaceMatcher.find()) { + String namespace = namespaceMatcher.group(1); // e.g., "INpcEvent", "IPlayerEvent", "IDBCEvent" + + // Find the body of this namespace + int bodyStart = namespaceMatcher.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd > bodyStart) { + String namespaceBody = content.substring(bodyStart, bodyEnd); + + // Parse functions within this namespace + Matcher funcMatcher = GLOBAL_FUNCTION_PATTERN.matcher(namespaceBody); + while (funcMatcher.find()) { + String funcName = funcMatcher.group(1); + String params = funcMatcher.group(2); + + // Parse parameter - format is "paramName: TypeName" + if (!params.isEmpty()) { + String[] parts = params.split(":\\s*", 2); + if (parts.length == 2) { + String paramName = parts[0].trim(); + String paramType = parts[1].trim(); + // Register hook with the namespace string directly + registry.registerHook(namespace, funcName, paramName, paramType); + } + } + } + } + } + } + + /** + * Parse index.d.ts to extract global type aliases. + */ + private void parseIndexFile(String content) { + Matcher m = GLOBAL_TYPE_ALIAS_PATTERN.matcher(content); + while (m.find()) { + String aliasName = m.group(1); + String importPath = m.group(2); + String typeName = m.group(3); + registry.registerTypeAlias(aliasName, typeName); + } + } + + /** + * Parse interface and class definitions from content. + */ + private void parseInterfaceFile(String content, String parentNamespace, String packageName) { + // IMPORTANT: + // Many generated .d.ts files declare nested exported interfaces inside `namespace X { ... }` blocks. + // If we scan `content` directly for `export interface` / `export class`, we'll accidentally treat + // those nested exports as top-level for the current `parentNamespace`. + // That pollutes the registry with incorrectly-scoped type names (e.g. "DamagedEvent" instead of + // "INpcEvent.DamagedEvent"), and later registry merges (by @javaFqn) can prevent the correctly + // namespaced key from ever being registered. + // + // To avoid this, we strip namespace blocks out of the scan input and then parse namespaces + // explicitly via the NAMESPACE_PATTERN recursion further below. + String scanContent = stripNamespaceBlocks(content); + + // Find exported interfaces + Matcher interfaceMatcher = INTERFACE_PATTERN.matcher(scanContent); + while (interfaceMatcher.find()) { + String interfaceName = interfaceMatcher.group(1); + String typeParamsStr = interfaceMatcher.group(2); // e.g., "T extends EntityPlayerMP /* net.minecraft.entity.player.EntityPlayerMP */" + String extendsClause = interfaceMatcher.group(3); + + JSTypeInfo typeInfo = new JSTypeInfo(interfaceName, parentNamespace); + + JSDocInfo jsDoc = extractJSDocBefore(content, interfaceMatcher.start()); + if (jsDoc != null) { + typeInfo.setJsDocInfo(jsDoc); + } + + String javaFqn = findJavaFqn(jsDoc, packageName, typeInfo.getFullName()); + if (javaFqn != null && !javaFqn.isEmpty()) { + typeInfo.setJavaFqn(javaFqn); + } + + // Parse type parameters + if (typeParamsStr != null && !typeParamsStr.isEmpty()) { + parseTypeParameters(typeParamsStr, typeInfo); + } + + if (extendsClause != null) { + // Handle multiple extends (e.g., "IEntityLivingBase, IAnimatable") + // Take the first one, stripping generics + String extendsType = extendsClause.trim(); + // Remove generic parameters like + extendsType = extendsType.replaceAll("<[^>]*>", ""); + // If multiple types (comma-separated), take the first one + if (extendsType.contains(",")) { + extendsType = extendsType.substring(0, extendsType.indexOf(',')).trim(); + } + // Clean up import() syntax if present + extendsType = cleanType(extendsType); + typeInfo.setExtends(extendsType); + } + + // Find the body of this interface + int bodyStart = interfaceMatcher.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd > bodyStart) { + String body = content.substring(bodyStart, bodyEnd); + parseInterfaceBody(body, typeInfo); + + // Parse nested interfaces and type aliases within this interface body + String fullNamespace = parentNamespace != null ? + parentNamespace + "." + interfaceName : interfaceName; + parseNestedTypes(body, fullNamespace, packageName); + } + + registry.registerType(typeInfo); + } + + // Find nested interfaces (without export keyword) + Matcher nestedInterfaceMatcher = NESTED_INTERFACE_PATTERN.matcher(scanContent); + while (nestedInterfaceMatcher.find()) { + String interfaceName = nestedInterfaceMatcher.group(1); + String typeParamsStr = nestedInterfaceMatcher.group(2); + String extendsClause = nestedInterfaceMatcher.group(3); + + JSTypeInfo typeInfo = new JSTypeInfo(interfaceName, parentNamespace); + + JSDocInfo jsDoc = extractJSDocBefore(content, nestedInterfaceMatcher.start()); + if (jsDoc != null) { + typeInfo.setJsDocInfo(jsDoc); + } + + // Parse type parameters + if (typeParamsStr != null && !typeParamsStr.isEmpty()) { + parseTypeParameters(typeParamsStr, typeInfo); + } + + if (extendsClause != null) { + String extendsType = extendsClause.trim(); + extendsType = extendsType.replaceAll("<[^>]*>", ""); + if (extendsType.contains(",")) { + extendsType = extendsType.substring(0, extendsType.indexOf(',')).trim(); + } + extendsType = cleanType(extendsType); + typeInfo.setExtends(extendsType); + } + + // Find the body of this nested interface + int bodyStart = nestedInterfaceMatcher.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd > bodyStart) { + String body = content.substring(bodyStart, bodyEnd); + parseInterfaceBody(body, typeInfo); + } + + registry.registerType(typeInfo); + } + + // Find classes (same logic as interfaces) + Matcher classMatcher = CLASS_PATTERN.matcher(scanContent); + while (classMatcher.find()) { + String className = classMatcher.group(1); + String typeParamsStr = classMatcher.group(2); + String extendsClause = classMatcher.group(3); + + JSTypeInfo typeInfo = new JSTypeInfo(className, parentNamespace); + + JSDocInfo jsDoc = extractJSDocBefore(content, classMatcher.start()); + if (jsDoc != null) { + typeInfo.setJsDocInfo(jsDoc); + } + + // Parse type parameters + if (typeParamsStr != null && !typeParamsStr.isEmpty()) { + parseTypeParameters(typeParamsStr, typeInfo); + } + + if (extendsClause != null) { + String extendsType = extendsClause.trim(); + extendsType = extendsType.replaceAll("<[^>]*>", ""); + if (extendsType.contains(",")) { + extendsType = extendsType.substring(0, extendsType.indexOf(',')).trim(); + } + extendsType = cleanType(extendsType); + typeInfo.setExtends(extendsType); + } + + // Find the body of this class + int bodyStart = classMatcher.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd > bodyStart) { + String body = content.substring(bodyStart, bodyEnd); + parseInterfaceBody(body, typeInfo); + } + + registry.registerType(typeInfo); + } + + // Find namespaces (which contain inner types) + Matcher namespaceMatcher = NAMESPACE_PATTERN.matcher(content); + while (namespaceMatcher.find()) { + String namespaceName = namespaceMatcher.group(1); + + // Find the body of this namespace + int bodyStart = namespaceMatcher.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd > bodyStart) { + String body = content.substring(bodyStart, bodyEnd); + + // Parse inner types with namespace prefix + // Namespaces contain exported types, so use parseInterfaceFile + String fullNamespace = parentNamespace != null ? + parentNamespace + "." + namespaceName : namespaceName; + parseInterfaceFile(body, fullNamespace, packageName); + // Don't call parseNestedTypes here - namespace members are all exported + // and will be caught by parseInterfaceFile's INTERFACE_PATTERN + } + } + + // Handle top-level type aliases + if (parentNamespace == null) { + parseTypeAliases(content, null); + } + } + + /** + * Strip namespace blocks from a file-level scan to avoid incorrectly capturing nested exports. + * + * This replaces the entire `namespace X { ... }` span (including braces) with whitespace so that + * match indices remain stable when we later slice `content` for bodies. + */ + private String stripNamespaceBlocks(String content) { + if (content == null || content.isEmpty()) { + return content; + } + + Matcher m = NAMESPACE_PATTERN.matcher(content); + if (!m.find()) { + return content; + } + + char[] chars = content.toCharArray(); + + int searchFrom = 0; + m.reset(); + while (m.find(searchFrom)) { + int start = m.start(); + int bodyStart = m.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd <= start) { + searchFrom = Math.max(m.end(), searchFrom + 1); + continue; + } + + int endExclusive = Math.min(chars.length, bodyEnd + 1); + for (int i = start; i < endExclusive; i++) { + chars[i] = ' '; + } + + searchFrom = endExclusive; + } + + return new String(chars); + } + + /** + * Parse type parameters from a string like "T extends EntityPlayerMP /* net.minecraft.entity.player.EntityPlayerMP *`/". + * Handles multiple parameters separated by commas. + * Stores strings only - resolution happens in Phase 2 after all types are loaded. + */ + private void parseTypeParameters(String typeParamsStr, JSTypeInfo typeInfo) { + // Split by comma, but be careful with nested generics (shouldn't happen at this level, but be safe) + String[] params = typeParamsStr.split(","); + for (String param : params) { + param = param.trim(); + if (param.isEmpty()) continue; + + Matcher m = TYPE_PARAM_PATTERN.matcher(param); + if (m.find()) { + String name = m.group(1); + String boundType = m.group(2); // Simple name like "EntityPlayerMP" + String fullBoundType = m.group(3); // Full name like "net.minecraft.entity.player.EntityPlayerMP" + + // Store strings only - resolution happens in Phase 2 + typeInfo.addTypeParam(new TypeParamInfo(name, boundType, fullBoundType)); + } + } + } + + /** + * Parse nested types (interfaces and type aliases) within a parent type or namespace. + */ + private void parseNestedTypes(String content, String namespace, String packageName) { + // Parse nested interfaces + Matcher nestedInterfaceMatcher = NESTED_INTERFACE_PATTERN.matcher(content); + while (nestedInterfaceMatcher.find()) { + String interfaceName = nestedInterfaceMatcher.group(1); + String typeParamsStr = nestedInterfaceMatcher.group(2); + String extendsClause = nestedInterfaceMatcher.group(3); + + JSTypeInfo typeInfo = new JSTypeInfo(interfaceName, namespace); + + JSDocInfo jsDoc = extractJSDocBefore(content, nestedInterfaceMatcher.start()); + if (jsDoc != null) { + typeInfo.setJsDocInfo(jsDoc); + } + + String javaFqn = findJavaFqn(jsDoc, packageName, typeInfo.getFullName()); + if (javaFqn != null && !javaFqn.isEmpty()) { + typeInfo.setJavaFqn(javaFqn); + } + + // Parse type parameters + if (typeParamsStr != null && !typeParamsStr.isEmpty()) { + parseTypeParameters(typeParamsStr, typeInfo); + } + + if (extendsClause != null) { + String extendsType = extendsClause.trim(); + extendsType = extendsType.replaceAll("<[^>]*>", ""); + if (extendsType.contains(",")) { + extendsType = extendsType.substring(0, extendsType.indexOf(',')).trim(); + } + extendsType = cleanType(extendsType); + typeInfo.setExtends(extendsType); + } + + // Find the body of this nested interface + int bodyStart = nestedInterfaceMatcher.end(); + int bodyEnd = findMatchingBrace(content, bodyStart - 1); + if (bodyEnd > bodyStart) { + String body = content.substring(bodyStart, bodyEnd); + parseInterfaceBody(body, typeInfo); + } + + registry.registerType(typeInfo); + } + + // Parse type aliases within this context + parseTypeAliases(content, namespace); + } + + private String findJavaFqn(JSDocInfo jsDoc, String packageName, String typeFullName) { + String tagged = extractJavaFqnFromJSDoc(jsDoc); + if (tagged != null && !tagged.isEmpty()) { + return tagged; + } + return buildJavaFqnFromPackage(packageName, typeFullName); + } + + private String extractJavaFqnFromJSDoc(JSDocInfo jsDoc) { + if (jsDoc == null) return null; + for (JSDocTag tag : jsDoc.getAllTags()) { + if (tag == null) continue; + if ("javaFqn".equals(tag.getTagName())) { + if (tag.getDescription() != null && !tag.getDescription().trim().isEmpty()) { + return tag.getDescription().trim(); + } + if (tag.getTypeName() != null && !tag.getTypeName().trim().isEmpty()) { + return tag.getTypeName().trim(); + } + } + } + return null; + } + + private String buildJavaFqnFromPackage(String packageName, String typeFullName) { + if (typeFullName == null || typeFullName.isEmpty()) return null; + if (packageName == null || packageName.isEmpty()) return null; + return packageName + "." + typeFullName; + } + + private String derivePackageName(String fileName) { + if (fileName == null || fileName.isEmpty()) return null; + String normalized = fileName.replace('\\', '/'); + if (normalized.endsWith(".d.ts")) { + normalized = normalized.substring(0, normalized.length() - 5); + } + int lastSlash = normalized.lastIndexOf('/'); + if (lastSlash < 0) return null; + String pkgPath = normalized.substring(0, lastSlash); + if (pkgPath.isEmpty()) return null; + return pkgPath.replace('/', '.'); + } + + /** + * Parse type aliases (export type X = Y). + */ + private void parseTypeAliases(String content, String namespace) { + Matcher m = TYPE_ALIAS_PATTERN.matcher(content); + while (m.find()) { + String aliasName = m.group(1); + String targetType = m.group(2).trim(); + + // Create a simple type that extends the target + JSTypeInfo typeInfo = new JSTypeInfo(aliasName, namespace); + typeInfo.setExtends(targetType); + registry.registerType(typeInfo); + } + } + + /** + * Parse the body of an interface to extract methods and fields. + */ + private void parseInterfaceBody(String body, JSTypeInfo typeInfo) { + // Parse methods + Matcher methodMatcher = METHOD_PATTERN.matcher(body); + while (methodMatcher.find()) { + boolean isStatic = methodMatcher.group(1) != null; + String methodName = methodMatcher.group(2); + String params = methodMatcher.group(3); + String returnType = cleanType(methodMatcher.group(4)); + + List parameters = parseParameters(params); + JSMethodInfo method = new JSMethodInfo(methodName, returnType, parameters); + method.setStatic(isStatic); + + JSDocInfo jsDoc = extractJSDocBefore(body, methodMatcher.start()); + if (jsDoc != null) { + method.setJsDocInfo(jsDoc); + } + + typeInfo.addMethod(method); + } + + // Parse fields (that aren't method signatures) + Matcher fieldMatcher = FIELD_PATTERN.matcher(body); + while (fieldMatcher.find()) { + boolean isStatic = fieldMatcher.group(1) != null; + String fieldName = fieldMatcher.group(3); + + // CNPC+ base event implementation CustomNPCsEvent exposes a public "API" field that + // ends up polluting autocomplete on every event via ICustomNPCsEvent inheritance. + // Keep parsing other fields, but skip this one. + if ("ICustomNPCsEvent".equals(typeInfo.getSimpleName()) && "API".equals(fieldName)) + continue; + + String fieldType = cleanType(fieldMatcher.group(4)); + boolean readonly = fieldMatcher.group(2) != null; + + JSFieldInfo field = new JSFieldInfo(fieldName, fieldType, readonly); + field.setStatic(isStatic); + + JSDocInfo jsDoc = extractJSDocBefore(body, fieldMatcher.start()); + if (jsDoc != null) { + field.setJsDocInfo(jsDoc); + } + + typeInfo.addField(field); + } + } + + /** + * Parse parameters string into list of parameter info. + */ + private List parseParameters(String params) { + List result = new ArrayList<>(); + if (params == null || params.trim().isEmpty()) { + return result; + } + + // Split by comma, but be careful of nested types like Map + List paramParts = splitParameters(params); + + for (String part : paramParts) { + part = part.trim(); + if (part.isEmpty()) continue; + + // Format: name: type or name?: type or ...name: type + int colonIndex = part.indexOf(':'); + if (colonIndex > 0) { + String name = part.substring(0, colonIndex).trim().replace("?", ""); + String type = cleanType(part.substring(colonIndex + 1).trim()); + boolean isVarArg = name.startsWith("..."); + if (isVarArg) { + name = name.substring(3).trim(); + // Varargs in TS are typed as arrays (e.g. ...codes: number[]) + // Strip the array wrapper to get the element type since isVarArg already implies array + if (type.endsWith("[]")) { + type = type.substring(0, type.length() - 2).trim(); + } else if (type.startsWith("Array<") && type.endsWith(">")) { + type = type.substring(6, type.length() - 1).trim(); + } + } + JSMethodInfo.JSParameterInfo param = new JSMethodInfo.JSParameterInfo(name, type); + param.setVarArg(isVarArg); + result.add(param); + } + } + + return result; + } + + /** + * Split parameters respecting nested angle brackets. + */ + private List splitParameters(String params) { + List result = new ArrayList<>(); + int depth = 0; + int start = 0; + + for (int i = 0; i < params.length(); i++) { + char c = params.charAt(i); + if (c == '<' || c == '(' || c == '[') { + depth++; + } else if (c == '>' || c == ')' || c == ']') { + depth--; + } else if (c == ',' && depth == 0) { + result.add(params.substring(start, i)); + start = i + 1; + } + } + + if (start < params.length()) { + result.add(params.substring(start)); + } + + return result; + } + + /** + * Clean up a type string (remove import() syntax, trim, etc.). + */ + private String cleanType(String type) { + if (type == null) return "any"; + return TypeStringNormalizer.stripImportTypeSyntax(type); + } + + /** + * Find the matching closing brace. + */ + private int findMatchingBrace(String text, int openBracePos) { + int depth = 1; + for (int i = openBracePos + 1; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '{') depth++; + else if (c == '}') { + depth--; + if (depth == 0) return i; + } + } + return -1; + } + + /** + * Read entire content from reader. + */ + private String readFully(BufferedReader reader) throws IOException { + StringBuilder sb = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line).append("\n"); + } + return sb.toString(); + } + + private JSDocInfo extractJSDocBefore(String content, int elementStart) { + String jsDocBlock = DTSJSDocParser.extractJSDocBefore(content, elementStart); + if (jsDocBlock != null) { + return DTSJSDocParser.parseJSDocBlock(jsDocBlock); + } + return null; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocInfo.java new file mode 100644 index 000000000..899239884 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocInfo.java @@ -0,0 +1,110 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Represents parsed JSDoc comment information. + * Captures @type, @param, @return, and other JSDoc tags with their type information. + */ +public class JSDocInfo { + + private final String rawComment; + private final int startOffset; + private final int endOffset; + + private JSDocTypeTag typeTag; + private final List paramTags = new ArrayList<>(); + private JSDocReturnTag returnTag; + private final List seeTags = new ArrayList<>(); + private String description; + private final List allTags = new ArrayList<>(); + + public JSDocInfo(String rawComment, int startOffset, int endOffset) { + this.rawComment = rawComment; + this.startOffset = startOffset; + this.endOffset = endOffset; + } + + public void setTypeTag(JSDocTypeTag typeTag) { + this.typeTag = typeTag; + allTags.add(typeTag); + } + + public void addParamTag(JSDocParamTag paramTag) { + this.paramTags.add(paramTag); + allTags.add(paramTag); + } + + public void setReturnTag(JSDocReturnTag returnTag) { + this.returnTag = returnTag; + allTags.add(returnTag); + } + + + public void addSeeTag(JSDocSeeTag seeTag) { + this.seeTags.add(seeTag); + allTags.add(seeTag); + } + + public void setDescription(String description) { + this.description = description; + } + + public void addTag(JSDocTag tag) { + allTags.add(tag); + } + + public String getRawComment() { return rawComment; } + public int getStartOffset() { return startOffset; } + public int getEndOffset() { return endOffset; } + public JSDocTypeTag getTypeTag() { return typeTag; } + public boolean hasTypeTag() { return typeTag != null; } + + public TypeInfo getDeclaredType() { + return typeTag != null ? typeTag.getTypeInfo() : null; + } + + public List getParamTags() { + return Collections.unmodifiableList(paramTags); + } + + public boolean hasParamTags() { return !paramTags.isEmpty(); } + + public JSDocParamTag getParamTag(String paramName) { + for (JSDocParamTag tag : paramTags) { + String tagName = tag.getParamName(); + if (tagName != null && tagName.equals(paramName)) { + return tag; + } + } + return null; + } + + public JSDocReturnTag getReturnTag() { return returnTag; } + public boolean hasReturnTag() { return returnTag != null; } + + public TypeInfo getReturnType() { + return returnTag != null ? returnTag.getTypeInfo() : null; + } + + public List getSeeTags() { return Collections.unmodifiableList(seeTags); } + public boolean hasSeeTags() { return !seeTags.isEmpty(); } + + public String getDescription() { return description; } + public List getAllTags() { return Collections.unmodifiableList(allTags); } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("JSDocInfo{"); + if (typeTag != null) sb.append("type=").append(typeTag.getTypeName()); + if (!paramTags.isEmpty()) sb.append(", params=").append(paramTags.size()); + if (returnTag != null) sb.append(", return=").append(returnTag.getTypeName()); + if (!seeTags.isEmpty()) sb.append(", see=").append(seeTags.size()); + sb.append("}"); + return sb.toString(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocParamTag.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocParamTag.java new file mode 100644 index 000000000..cdabdb717 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocParamTag.java @@ -0,0 +1,43 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +/** + * Represents an @param JSDoc tag. + * Used to declare the type and description of a function parameter. + * Example: @param {string} name - The name of the person + */ +public class JSDocParamTag extends JSDocTag { + + private final String paramName; + private final int paramNameStart; + private final int paramNameEnd; + + public JSDocParamTag(int atSignOffset, int tagNameStart, int tagNameEnd, + String paramName, int paramNameStart, int paramNameEnd) { + super("param", atSignOffset, tagNameStart, tagNameEnd); + this.paramName = paramName; + this.paramNameStart = paramNameStart; + this.paramNameEnd = paramNameEnd; + } + + public static JSDocParamTag create(int atSignOffset, int tagNameStart, int tagNameEnd, + String typeName, TypeInfo typeInfo, int typeStart, int typeEnd, + String paramName, int paramNameStart, int paramNameEnd, + String description) { + JSDocParamTag tag = new JSDocParamTag(atSignOffset, tagNameStart, tagNameEnd, + paramName, paramNameStart, paramNameEnd); + tag.setType(typeName, typeInfo, typeStart, typeEnd); + tag.setDescription(description); + return tag; + } + + public String getParamName() { return paramName; } + public int getParamNameStart() { return paramNameStart; } + public int getParamNameEnd() { return paramNameEnd; } + + @Override + public String toString() { + return "JSDocParamTag{@param " + (typeName != null ? "{" + typeName + "} " : "") + paramName + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocParser.java new file mode 100644 index 000000000..cbf8968ee --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocParser.java @@ -0,0 +1,330 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Parses JSDoc comments to extract type information. + * Handles @type, @param, @return/@returns tags. + */ +public class JSDocParser { + + private static final Pattern JSDOC_PATTERN = Pattern.compile( + "/\\*\\*([\\s\\S]*?)\\*/", Pattern.MULTILINE); + + private static final Pattern TYPE_TAG_PATTERN = Pattern.compile( + "^@(type)\\s*(?:\\{([^}]+)\\})?(?:\\s*-?\\s*(.*))?$", Pattern.CASE_INSENSITIVE); + + private static final Pattern PARAM_TAG_PATTERN = Pattern.compile( + "^@param\\s*(?:\\{([^}]+)\\})?\\s*(\\w+)?(?:\\s*-?\\s*(.*))?$", Pattern.CASE_INSENSITIVE); + + private static final Pattern RETURN_TAG_PATTERN = Pattern.compile( + "^@(returns?)\\s*(?:\\{([^}]+)\\})?(?:\\s*-?\\s*(.*))?$", Pattern.CASE_INSENSITIVE); + + private static final Pattern GENERIC_TAG_PATTERN = Pattern.compile( + "^@(\\w+)(?:\\s*\\{([^}]+)\\})?(?:\\s*-?\\s*(.*))?$", Pattern.CASE_INSENSITIVE); + + private final ScriptDocument document; + + public JSDocParser(ScriptDocument typeResolver) { + this.document = typeResolver; + } + + public JSDocInfo parse(String comment, int commentStart) { + if (comment == null || !comment.startsWith("/**")) { + return null; + } + + int commentEnd = commentStart + comment.length(); + JSDocInfo info = new JSDocInfo(comment, commentStart, commentEnd); + + String content = comment.substring(3); + if (content.endsWith("*/")) { + content = content.substring(0, content.length() - 2); + } + + int contentOffset = commentStart + 3; + + StringBuilder descriptionBuilder = new StringBuilder(); + boolean foundFirstTag = false; + JSDocTag lastTag = null; + + int position = 0; + while (position <= content.length()) { + int lineEnd = content.indexOf('\n', position); + if (lineEnd == -1) { + lineEnd = content.length(); + } + + String rawLine = content.substring(position, lineEnd); + if (rawLine.endsWith("\r")) { + rawLine = rawLine.substring(0, rawLine.length() - 1); + } + + CleanLine cleanLine = cleanLine(rawLine, contentOffset + position); + String line = cleanLine.text; + + if (line.startsWith("@")) { + foundFirstTag = true; + lastTag = parseTagLine(line, cleanLine.offset, info); + } else if (!foundFirstTag) { + if (line.isEmpty()) { + // Preserve blank lines as paragraph gaps (only if description has started) + if (descriptionBuilder.length() > 0) { + descriptionBuilder.append("\n"); + } + } else { + if (descriptionBuilder.length() > 0) { + descriptionBuilder.append("\n"); + } + descriptionBuilder.append(line); + } + } else if (lastTag != null && !line.isEmpty()) { + String existing = lastTag.getDescription(); + if (existing == null || existing.isEmpty()) { + lastTag.setDescription(line); + } else { + lastTag.setDescription(existing + "\n" + line); + } + } + + if (lineEnd == content.length()) { + break; + } + position = lineEnd + 1; + } + + if (descriptionBuilder.length() > 0) { + info.setDescription(descriptionBuilder.toString().trim()); + } + + return info; + } + + public JSDocInfo extractJSDocBefore(String source, int position) { + if (source == null || position <= 0) { + return null; + } + + int searchStart = Math.max(0, position - 1); + + while (searchStart > 0 && Character.isWhitespace(source.charAt(searchStart))) { + searchStart--; + } + + int endCommentPos = -1; + if (searchStart >= 1 && source.charAt(searchStart) == '/' && source.charAt(searchStart - 1) == '*') { + endCommentPos = searchStart; + } else if (searchStart >= 1 && source.charAt(searchStart - 1) == '/' && searchStart > 1 && source.charAt( + searchStart - 2) == '*') { + endCommentPos = searchStart - 1; + } + + if (endCommentPos < 0) { + return null; + } + + int startCommentPos = -1; + for (int i = endCommentPos - 1; i >= 2; i--) { + if (source.charAt(i) == '*' && source.charAt(i - 1) == '*' && source.charAt(i - 2) == '/') { + startCommentPos = i - 2; + break; + } + } + + if (startCommentPos < 0) { + return null; + } + + String comment = source.substring(startCommentPos, endCommentPos + 1); + return parse(comment, startCommentPos); + } + + private JSDocTag parseTagLine(String line, int lineOffset, JSDocInfo info) { + Matcher paramMatcher = PARAM_TAG_PATTERN.matcher(line); + if (paramMatcher.matches()) { + String typeName = paramMatcher.group(1); + String paramName = paramMatcher.group(2); + String description = normalizeDescription(paramMatcher.group(3)); + + int atSignOffset = lineOffset + paramMatcher.start(); + int tagNameStart = lineOffset + 1; + int tagNameEnd = tagNameStart + "param".length(); + + int typeStart = -1; + int typeEnd = -1; + TypeInfo typeInfo = null; + + if (typeName != null) { + typeName = typeName.trim(); + typeStart = lineOffset + paramMatcher.start(1); + typeEnd = lineOffset + paramMatcher.end(1); + typeInfo = resolveType(typeName); + } + + int paramNameStart = -1; + int paramNameEnd = -1; + if (paramName != null) { + paramNameStart = lineOffset + paramMatcher.start(2); + paramNameEnd = lineOffset + paramMatcher.end(2); + } + + JSDocParamTag tag = JSDocParamTag.create(atSignOffset, tagNameStart, tagNameEnd, + typeName, typeInfo, typeStart, typeEnd, + paramName, paramNameStart, paramNameEnd, + description); + info.addParamTag(tag); + return tag; + } + + Matcher returnMatcher = RETURN_TAG_PATTERN.matcher(line); + if (returnMatcher.matches()) { + String tagName = returnMatcher.group(1); + String typeName = returnMatcher.group(2); + String description = normalizeDescription(returnMatcher.group(3)); + + int atSignOffset = lineOffset + returnMatcher.start(); + int tagNameStart = lineOffset + returnMatcher.start(1); + int tagNameEnd = lineOffset + returnMatcher.end(1); + + int typeStart = -1; + int typeEnd = -1; + TypeInfo typeInfo = null; + + if (typeName != null) { + typeName = typeName.trim(); + typeStart = lineOffset + returnMatcher.start(2); + typeEnd = lineOffset + returnMatcher.end(2); + typeInfo = resolveType(typeName); + } + + JSDocReturnTag tag = JSDocReturnTag.create(tagName, atSignOffset, tagNameStart, tagNameEnd, + typeName, typeInfo, typeStart, typeEnd, + description); + info.setReturnTag(tag); + return tag; + } + + Matcher typeMatcher = TYPE_TAG_PATTERN.matcher(line); + if (typeMatcher.matches()) { + String typeName = typeMatcher.group(2); + String description = normalizeDescription(typeMatcher.group(3)); + + int atSignOffset = lineOffset + typeMatcher.start(); + int tagNameStart = lineOffset + typeMatcher.start(1); + int tagNameEnd = lineOffset + typeMatcher.end(1); + + int typeStart = -1; + int typeEnd = -1; + TypeInfo typeInfo = null; + + if (typeName != null) { + typeName = typeName.trim(); + typeStart = lineOffset + typeMatcher.start(2); + typeEnd = lineOffset + typeMatcher.end(2); + typeInfo = resolveType(typeName); + } + + JSDocTypeTag tag = JSDocTypeTag.create(atSignOffset, tagNameStart, tagNameEnd, + typeName, typeInfo, typeStart, typeEnd, description); + info.setTypeTag(tag); + return tag; + } + + Matcher genericMatcher = GENERIC_TAG_PATTERN.matcher(line); + if (genericMatcher.matches()) { + String tagName = genericMatcher.group(1); + String typeName = genericMatcher.group(2); + String description = normalizeDescription(genericMatcher.group(3)); + + int atSignOffset = lineOffset + genericMatcher.start(); + int tagNameStart = lineOffset + genericMatcher.start(1); + int tagNameEnd = lineOffset + genericMatcher.end(1); + + JSDocTag tag = new JSDocTag(tagName, atSignOffset, tagNameStart, tagNameEnd); + + if (typeName != null) { + typeName = typeName.trim(); + int typeStart = lineOffset + genericMatcher.start(2); + int typeEnd = lineOffset + genericMatcher.end(2); + TypeInfo typeInfo = resolveType(typeName); + tag.setType(typeName, typeInfo, typeStart, typeEnd); + } + + if (description != null && !description.isEmpty()) { + tag.setDescription(description); + } + + info.addTag(tag); + return tag; + } + + return null; + } + + private String normalizeDescription(String description) { + if (description == null) { + return null; + } + String trimmed = description.trim(); + return trimmed.isEmpty() ? null : trimmed; + } + + private CleanLine cleanLine(String line, int lineStartOffset) { + int index = 0; + while (index < line.length() && Character.isWhitespace(line.charAt(index))) { + index++; + } + + if (index + 2 < line.length() && line.startsWith("/**", index)) { + index += 3; + while (index < line.length() && Character.isWhitespace(line.charAt(index))) { + index++; + } + } + + if (index < line.length() && line.charAt(index) == '*') { + index++; + if (index < line.length() && line.charAt(index) == ' ') { + index++; + } + } + + String cleaned = line.substring(index); + int end = cleaned.length(); + while (end > 0 && Character.isWhitespace(cleaned.charAt(end - 1))) { + end--; + } + cleaned = cleaned.substring(0, end); + + return new CleanLine(cleaned, lineStartOffset + index); + } + + private TypeInfo resolveType(String typeName) { + return document.resolveType(typeName); + } + + private static class CleanLine { + private final String text; + private final int offset; + + private CleanLine(String text, int offset) { + this.text = text; + this.offset = offset; + } + } + + public static List findAllJSDocComments(String source) { + List positions = new ArrayList<>(); + Matcher m = JSDOC_PATTERN.matcher(source); + while (m.find()) { + positions.add(new int[]{m.start(), m.end()}); + } + return positions; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocReturnTag.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocReturnTag.java new file mode 100644 index 000000000..0f5fca416 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocReturnTag.java @@ -0,0 +1,29 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +/** + * Represents an @return or @returns JSDoc tag. + * Used to declare the return type of a function. + * Example: @return {number} The calculated result + */ +public class JSDocReturnTag extends JSDocTag { + + public JSDocReturnTag(String tagName, int atSignOffset, int tagNameStart, int tagNameEnd) { + super(tagName, atSignOffset, tagNameStart, tagNameEnd); + } + + public static JSDocReturnTag create(String tagName, int atSignOffset, int tagNameStart, int tagNameEnd, + String typeName, TypeInfo typeInfo, int typeStart, int typeEnd, + String description) { + JSDocReturnTag tag = new JSDocReturnTag(tagName, atSignOffset, tagNameStart, tagNameEnd); + tag.setType(typeName, typeInfo, typeStart, typeEnd); + tag.setDescription(description); + return tag; + } + + @Override + public String toString() { + return "JSDocReturnTag{@" + tagName + " " + (typeName != null ? "{" + typeName + "}" : "") + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocSeeTag.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocSeeTag.java new file mode 100644 index 000000000..028023c6e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocSeeTag.java @@ -0,0 +1,75 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +public class JSDocSeeTag extends JSDocTag { + + private final String reference; + private String url; + private String linkText; + + public JSDocSeeTag(String tagName, int atSignOffset, int tagNameStart, int tagNameEnd, String reference) { + super(tagName, atSignOffset, tagNameStart, tagNameEnd); + this.reference = reference; + this.setDescription(reference); + parseReference(reference); + } + + public static JSDocSeeTag create(String tagName, int atSignOffset, int tagNameStart, int tagNameEnd, + String reference) { + return new JSDocSeeTag(tagName, atSignOffset, tagNameStart, tagNameEnd, reference); + } + + public static JSDocSeeTag createSimple(String reference) { + return new JSDocSeeTag("see", -1, -1, -1, reference); + } + + private void parseReference(String ref) { + if (ref == null) return; + + if (ref.contains(""); + int textEnd = ref.indexOf(""); + if (textStart != -1 && textEnd != -1 && textStart < textEnd) { + this.linkText = ref.substring(textStart + 1, textEnd); + } + } else if (ref.contains("{@link")) { + int linkStart = ref.indexOf("{@link"); + int linkEnd = ref.indexOf("}", linkStart); + if (linkStart != -1 && linkEnd != -1) { + this.linkText = ref.substring(linkStart + 6, linkEnd).trim(); + } + } + } + + public String getReference() { + return reference; + } + + public String getUrl() { + return url; + } + + public boolean hasUrl() { + return url != null && !url.isEmpty(); + } + + public String getLinkText() { + return linkText; + } + + public boolean hasLinkText() { + return linkText != null && !linkText.isEmpty(); + } + + @Override + public String toString() { + return "JSDocSeeTag{@see " + reference + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocTag.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocTag.java new file mode 100644 index 000000000..82fd1edbe --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocTag.java @@ -0,0 +1,55 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +/** + * Base class for JSDoc tags. + * Each tag stores its position information for syntax highlighting. + */ +public class JSDocTag { + + protected final String tagName; + protected final int atSignOffset; + protected final int tagNameStart; + protected final int tagNameEnd; + + protected String typeName; + protected TypeInfo typeInfo; + protected int typeStart = -1; + protected int typeEnd = -1; + protected String description; + + public JSDocTag(String tagName, int atSignOffset, int tagNameStart, int tagNameEnd) { + this.tagName = tagName; + this.atSignOffset = atSignOffset; + this.tagNameStart = tagNameStart; + this.tagNameEnd = tagNameEnd; + } + + public void setType(String typeName, TypeInfo typeInfo, int typeStart, int typeEnd) { + this.typeName = typeName; + this.typeInfo = typeInfo; + this.typeStart = typeStart; + this.typeEnd = typeEnd; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTagName() { return tagName; } + public int getAtSignOffset() { return atSignOffset; } + public int getTagNameStart() { return tagNameStart; } + public int getTagNameEnd() { return tagNameEnd; } + public String getTypeName() { return typeName; } + public TypeInfo getTypeInfo() { return typeInfo; } + public boolean hasType() { return typeName != null && !typeName.isEmpty(); } + public int getTypeStart() { return typeStart; } + public int getTypeEnd() { return typeEnd; } + public String getDescription() { return description; } + + @Override + public String toString() { + return "JSDocTag{@" + tagName + (typeName != null ? " {" + typeName + "}" : "") + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocTypeTag.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocTypeTag.java new file mode 100644 index 000000000..1f27f6667 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/jsdoc/JSDocTypeTag.java @@ -0,0 +1,28 @@ +package noppes.npcs.client.gui.util.script.interpreter.jsdoc; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +/** + * Represents an @type JSDoc tag. + * Used to declare the type of a variable. + * Example: @type {string} + */ +public class JSDocTypeTag extends JSDocTag { + + public JSDocTypeTag(int atSignOffset, int tagNameStart, int tagNameEnd) { + super("type", atSignOffset, tagNameStart, tagNameEnd); + } + + public static JSDocTypeTag create(int atSignOffset, int tagNameStart, int tagNameEnd, String typeName, + TypeInfo typeInfo, int typeStart, int typeEnd, String description) { + JSDocTypeTag tag = new JSDocTypeTag(atSignOffset, tagNameStart, tagNameEnd); + tag.setType(typeName, typeInfo, typeStart, typeEnd); + tag.setDescription(description); + return tag; + } + + @Override + public String toString() { + return "JSDocTypeTag{@type " + (typeName != null ? "{" + typeName + "}" : "") + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodCallInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodCallInfo.java new file mode 100644 index 000000000..1a744d215 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodCallInfo.java @@ -0,0 +1,472 @@ +package noppes.npcs.client.gui.util.script.interpreter.method; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.token.Token; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Stores information about a method call for argument validation. + * This includes the method name, the arguments passed, and validation results. + */ +public class MethodCallInfo { + + /** + * Represents a single argument in a method call. + */ + public static class Argument { + private final String text; // The text of the argument expression + private final int startOffset; // Start position in source + private final int endOffset; // End position in source + private final TypeInfo resolvedType; // The resolved type of the argument (null if unresolved) + private final boolean valid; // Whether this arg matches the expected parameter type + private final String errorMessage; // Error message if invalid + + public Argument(String text, int startOffset, int endOffset, TypeInfo resolvedType, + boolean valid, String errorMessage) { + this.text = text; + this.startOffset = startOffset; + this.endOffset = endOffset; + this.resolvedType = resolvedType; + this.valid = valid; + this.errorMessage = errorMessage; + } + + public String getText() { + return text; + } + + public int getStartOffset() { + return startOffset; + } + + public int getEndOffset() { + return endOffset; + } + + public TypeInfo getResolvedType() { + return resolvedType; + } + + public boolean isValid() { + return valid; + } + + public String getErrorMessage() { + return errorMessage; + } + + public boolean equals(Token t) { + return text.equals(t.getText()) && + startOffset == t.getGlobalStart() && + endOffset == t.getGlobalEnd(); + } + + @Override + public String toString() { + return "Arg{" + text + " [" + startOffset + "-" + endOffset + "]" + + (resolvedType != null ? " :" + resolvedType.getSimpleName() : "") + + (valid ? "" : " INVALID: " + errorMessage) + "}"; + } + } + /** + * Validation error type. + */ + public enum ErrorType { + NONE, + WRONG_ARG_COUNT, // Number of args doesn't match any overload + WRONG_ARG_TYPE, // Specific argument has wrong type + STATIC_ACCESS_ERROR, // Trying to call instance method statically or vice versa + RETURN_TYPE_MISMATCH, // Return type doesn't match expected type (e.g., assignment LHS) + UNRESOLVED_METHOD, // Method doesn't exist + UNRESOLVED_RECEIVER // Can't resolve the receiver type + } + + private final String methodName; + private final int methodNameStart; // Position of method name + private final int methodNameEnd; + private final int openParenOffset; // Position of '(' + private final int closeParenOffset; // Position of ')' + private final List arguments; + private final TypeInfo receiverType; // The type on which this method is called (null for standalone) + private final MethodInfo resolvedMethod; // The resolved method (null if unresolved) + private final boolean isStaticAccess; // True if this is Class.method() style access + private TypeInfo expectedType; // Expected return type (from assignment LHS, etc.) + + private ErrorType errorType = ErrorType.NONE; + private String errorMessage; + private int errorArgIndex = -1; // Index of the problematic argument (for WRONG_ARG_TYPE) + private List argumentTypeErrors = new ArrayList<>(); + + private boolean isConstructor; + + // For Java.type() ClassTypeInfo constructor access + // i.e var IntArray = Java.type("int[]"); var array = new IntArray() + public boolean isClassTypeAccess; + + public MethodCallInfo(String methodName, int methodNameStart, int methodNameEnd, + int openParenOffset, int closeParenOffset, + List arguments, TypeInfo receiverType, + MethodInfo resolvedMethod) { + this(methodName, methodNameStart, methodNameEnd, openParenOffset, closeParenOffset, + arguments, receiverType, resolvedMethod, false); + } + + public MethodCallInfo(String methodName, int methodNameStart, int methodNameEnd, + int openParenOffset, int closeParenOffset, + List arguments, TypeInfo receiverType, + MethodInfo resolvedMethod, boolean isStaticAccess) { + this.methodName = methodName; + this.methodNameStart = methodNameStart; + this.methodNameEnd = methodNameEnd; + this.openParenOffset = openParenOffset; + this.closeParenOffset = closeParenOffset; + this.arguments = arguments != null ? new ArrayList<>(arguments) : new ArrayList<>(); + this.receiverType = receiverType; + this.resolvedMethod = resolvedMethod; + this.isStaticAccess = isStaticAccess; + } + + /** + * Factory method to create a MethodCallInfo for a constructor call. + * Constructors are represented as method calls where the type itself is the receiver. + */ + public static MethodCallInfo constructor(TypeInfo typeInfo, MethodInfo constructor, + int typeNameStart, int typeNameEnd, + int openParenOffset, int closeParenOffset, + List arguments) { + return new MethodCallInfo( + typeInfo.getSimpleName(), // Constructor name is the type name + typeNameStart, + typeNameEnd, + openParenOffset, + closeParenOffset, + arguments, + typeInfo, // The type itself is the receiver + constructor, // The constructor MethodInfo + false // Constructors are not static access + ).setConstructor(true); + } + + // Getters + public String getMethodName() { + return methodName; + } + + public int getMethodNameStart() { + return methodNameStart; + } + + public int getMethodNameEnd() { + return methodNameEnd; + } + + public int getOpenParenOffset() { + return openParenOffset; + } + + public int getCloseParenOffset() { + return closeParenOffset; + } + + public List getArguments() { + return Collections.unmodifiableList(arguments); + } + + public int getArgumentCount() { + return arguments.size(); + } + + public TypeInfo getReceiverType() { + return receiverType; + } + + public MethodInfo getResolvedMethod() { + return resolvedMethod; + } + + public boolean isStaticAccess() { + return isStaticAccess; + } + + public TypeInfo getExpectedType() { + return expectedType; + } + + public void setExpectedType(TypeInfo expectedType) { + this.expectedType = expectedType; + } + + // Dynamically resolved return type (e.g., for Java.type() which returns ClassTypeInfo) + private TypeInfo resolvedReturnType; + + /** + * Get the resolved return type of this method call. + * This may differ from resolvedMethod.getReturnType() for methods with dynamic return types. + * @return The resolved return type, or the method's declared return type if not dynamically resolved + */ + public TypeInfo getResolvedReturnType() { + if (resolvedReturnType != null) { + return resolvedReturnType; + } + return resolvedMethod != null ? resolvedMethod.getReturnType() : null; + } + + /** + * Set a dynamically resolved return type. + * Used for methods like Java.type() where the return type depends on the arguments. + */ + public void setResolvedReturnType(TypeInfo returnType) { + this.resolvedReturnType = returnType; + } + + public boolean isConstructor() { + return isConstructor; + } + + public MethodCallInfo setConstructor(boolean isConstructor) { + this.isConstructor = isConstructor; + return this; + } + + public ErrorType getErrorType() { + return errorType; + } + + public String getErrorMessage() { + return errorMessage; + } + + /** + * Get the full span of the method call including parentheses. + * Used for underlining the entire call on arg count errors. + */ + public int getFullCallStart() { + return methodNameStart; + } + + public int getFullCallEnd() { + return closeParenOffset + 1; + } + + /** + * Check if this method call has any validation errors. + */ + public boolean hasError() { + return errorType != ErrorType.NONE; + } + + /** + * Check if this is an arg count error (underline whole call). + */ + public boolean hasArgCountError() { + return errorType == ErrorType.WRONG_ARG_COUNT; + } + + /** + * Check if this is an arg type error (underline specific arg). + */ + public boolean hasArgTypeError() { + return !this.argumentTypeErrors.isEmpty(); + } + + + /** + * Check if this is a static access error (underline method name). + */ + public boolean hasStaticAccessError() { + return errorType == ErrorType.STATIC_ACCESS_ERROR; + } + + /** + * Check if this is a return type mismatch error. + */ + public boolean hasReturnTypeMismatch() { + return errorType == ErrorType.RETURN_TYPE_MISMATCH; + } + + // Setters for validation results + public void setError(ErrorType type, String message) { + this.errorType = type; + this.errorMessage = message; + } + + public void setArgTypeError(int argIndex, String message) { + this.argumentTypeErrors.add(new ArgumentTypeError(arguments.get(argIndex), argIndex, message)); + } + + public List getArgumentTypeErrors() { + return argumentTypeErrors; + } + + public class ArgumentTypeError { + private ErrorType type = ErrorType.WRONG_ARG_TYPE; + private final Argument arg; + private final int argIndex; + private final String message; + + public ArgumentTypeError(Argument arg, int argIndex, String message) { + this.arg = arg; + this.argIndex = argIndex; + this.message = message; + } + + public int getArgIndex() { + return argIndex; + } + + public String getMessage() { + return message; + } + + public Argument getArg() { + return arg; + } + } + + /** + * Validate this method call against the resolved method signature. + * Sets error information if validation fails. + */ + public void validate() { + if (isConstructor) { + if (resolvedMethod == null) { + // Don't report missing JS constructors as unresolved method error, since they may be created dynamically at runtime + boolean isJSType = receiverType != null && receiverType.isJSType(); + if (!isJSType && !isClassTypeAccess) { + if (receiverType != null && receiverType.hasConstructors()) { + setError(ErrorType.WRONG_ARG_COUNT, + "No constructor in '" + receiverType.getSimpleName() + "' matches " + arguments.size() + " argument(s)"); + } else { + setError(ErrorType.UNRESOLVED_METHOD, + "Cannot resolve constructor for '" + methodName + "'"); + } + } + } else if (receiverType != null) { + List cParams = resolvedMethod.getParameters(); + boolean ctorVarArg = !cParams.isEmpty() && cParams.get(cParams.size() - 1).isVarArg(); + boolean ctorCountOk = ctorVarArg + ? arguments.size() >= cParams.size() - 1 + : arguments.size() == resolvedMethod.getParameterCount(); + if (ctorCountOk) validateArgTypeError(); + } + return; + } + + // Check static/instance access (skip for constructors) + // NO LONGER CHECKED HERE, BUT DIRECTLY AT MARK CREATION + if (!isConstructor && isStaticAccess && !resolvedMethod.isStatic()) { + setError(ErrorType.STATIC_ACCESS_ERROR, + "Cannot call instance method '" + methodName + "' on a class type"); + return; + } + + List params = resolvedMethod.getParameters(); + int expectedCount = params.size(); + int actualCount = arguments.size(); + boolean isVarArgMethod = expectedCount > 0 && params.get(expectedCount - 1).isVarArg(); + + // Check arg count + if (isVarArgMethod) { + if (actualCount < expectedCount - 1) { + setError(ErrorType.WRONG_ARG_COUNT, + "Expected at least " + (expectedCount - 1) + " argument(s) but got " + actualCount); + return; + } + } else { + if (actualCount != expectedCount) { + setError(ErrorType.WRONG_ARG_COUNT, + "Expected " + expectedCount + " argument(s) but got " + actualCount); + return; + } + } + + // Check each argument type + validateArgTypeError(); + + // Check return type compatibility with expected type (e.g., assignment LHS) + // ALREADY CHECKED AT AssignmentInfo LEVEL + if (expectedType != null && resolvedMethod != null) { + TypeInfo returnType = resolvedMethod.getReturnType(); + if (returnType != null && !TypeChecker.isTypeCompatible(expectedType, returnType)) { + // setError(ErrorType.RETURN_TYPE_MISMATCH, + // "Required type: " + expectedType.getSimpleName() + ", Provided: " + returnType.getSimpleName()); + } + } + } + + public void validateArgTypeError() { + List params = resolvedMethod.getParameters(); + int paramCount = params.size(); + boolean isVarArgMethod = paramCount > 0 && params.get(paramCount - 1).isVarArg(); + + for (int i = 0; i < arguments.size(); i++) { + Argument arg = arguments.get(i); + + // Surface argument-level errors (e.g., SAM conflict, ambiguous overload, bare method in Java) + if (!arg.isValid() && arg.getErrorMessage() != null) { + setArgTypeError(i, arg.getErrorMessage()); + continue; // Skip remaining checks for this argument + } + + // Varargs: all args at index >= (paramCount-1) map to the element type of the last param + FieldInfo para; + TypeInfo paramType; + if (isVarArgMethod && i >= paramCount - 1) { + para = params.get(paramCount - 1); + TypeInfo arrType = para.getTypeInfo(); + paramType = (arrType != null && arrType.isArray()) ? arrType.getElementType() : arrType; + } else { + para = params.get(i); + paramType = para.getTypeInfo(); + } + + TypeInfo argType = arg.getResolvedType(); + if (argType != null && paramType != null) { + if (!TypeChecker.isTypeCompatible(paramType, argType)) { + setArgTypeError(i, "Expected " + getTypeDisplayName(paramType) + + " but got " + getTypeDisplayName(argType)); + } + } else if (paramType == null) { + setArgTypeError(i, "Parameter type of '" + para.getName() + "' is unresolved"); + } else if (argType == null) { + setArgTypeError(i, "Cannot resolve type of argument '" + arg.getText() + "'"); + } + } + } + + /** + * in error "Expect T but got String", if T has a resolved bound aka "int" show it instead of T to avoid confusion. + * So the error would be "Expect int but got String" + */ + public static String getTypeDisplayName(TypeInfo type) { + if(type.isTypeParameter()) { + TypeInfo bound = type.getBoundType(); + if (bound != null) + return bound.getDisplayName(); + } + + return type.getDisplayName(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("MethodCallInfo{"); + sb.append(methodName).append("("); + for (int i = 0; i < arguments.size(); i++) { + if (i > 0) + sb.append(", "); + sb.append(arguments.get(i).getText()); + } + sb.append(")"); + if (hasError()) { + sb.append(" ERROR: ").append(errorType).append(" - ").append(errorMessage); + } + sb.append("}"); + return sb.toString(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodInfo.java new file mode 100644 index 000000000..12ba570d3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodInfo.java @@ -0,0 +1,775 @@ +package noppes.npcs.client.gui.util.script.interpreter.method; + +import noppes.npcs.client.gui.util.script.interpreter.*; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.bridge.DtsJavaBridge; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSMethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.GenericContext; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import noppes.npcs.client.gui.util.script.interpreter.type.GenericParameterAdapter; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * Metadata for a method declaration or method call. + * Tracks method name, parameters, return type, and containing class. + * + *

This class delegates to helper classes for specific functionality:

+ *
    + *
  • {@link ControlFlowAnalyzer} - Control flow analysis for missing return detection
  • + *
  • {@link CodeParser} - Code parsing utilities (brace matching, comment removal)
  • + *
  • {@link TypeChecker} - Type compatibility checking
  • + *
+ */ +public final class MethodInfo { + + /** + * Validation error types for method declarations. + */ + public enum ErrorType { + NONE, + MISSING_RETURN, // Non-void method missing return statement, + INTERFACE_METHOD_BODY, // Interface method has a body + MISSING_BODY, // Non-void method missing return statement + RETURN_TYPE_MISMATCH, // Return statement type doesn't match method return type + VOID_METHOD_RETURNS_VALUE, // Void method returns a value + DUPLICATE_METHOD, // Method with same signature already defined in scope + DUPLICATE_PARAMETER, // Two parameters have the same name + PARAMETER_UNDEFINED, // Parameter type cannot be resolved + SAM_TYPE_INCOMPATIBLE // Explicit param type incompatible with SAM context + } + + private final String name; + private final TypeInfo returnType; + private final TypeInfo containingType; // The class/interface that owns this method + private final List parameters; + private final int fullDeclarationOffset; // Start of full declaration (including modifiers), -1 for external + private final int typeOffset; // Start of return type + private final int nameOffset; // Start of method name + private final int bodyStart; // Start of method body (after {) + private final int bodyEnd; // End of method body (before }) + private final boolean resolved; + private final boolean isDeclaration; // true if this is a declaration, false if it's a call + private final int modifiers; // Java Modifier flags (e.g., Modifier.PUBLIC | Modifier.STATIC) + private final String documentation; // Javadoc/comment documentation for this method + private JSDocInfo jsDocInfo; // Parsed JSDoc info for this method (may be null) + private final java.lang.reflect.Method javaMethod; // The Java reflection Method, if this was created from reflection + + // Error tracking for method declarations + private ErrorType errorType = ErrorType.NONE; + private String errorMessage; + private List parameterErrors = new ArrayList<>(); + private List returnStatementErrors = new ArrayList<>(); + + // ==================== OVERRIDE/IMPLEMENTS TRACKING ==================== + + /** + * The type containing the method that this method overrides (the super class). + * Null if this method doesn't override anything. + */ + private TypeInfo overridesFrom; + + /** + * The type containing the interface method that this method implements. + * Null if this method doesn't implement an interface method. + */ + private TypeInfo implementsFrom; + + private MethodInfo(String name, TypeInfo returnType, TypeInfo containingType, + List parameters, int fullDeclarationOffset, int typeOffset, int nameOffset, + int bodyStart, int bodyEnd, boolean resolved, boolean isDeclaration, + int modifiers, String documentation, java.lang.reflect.Method javaMethod) { + this.name = name; + this.returnType = returnType; + this.containingType = containingType; + this.parameters = parameters != null ? new ArrayList<>(parameters) : new ArrayList<>(); + this.fullDeclarationOffset = fullDeclarationOffset; + this.typeOffset = typeOffset; + this.nameOffset = nameOffset; + this.bodyStart = bodyStart; + this.bodyEnd = bodyEnd; + this.resolved = resolved; + this.isDeclaration = isDeclaration; + this.modifiers = modifiers; + this.documentation = documentation; + this.javaMethod = javaMethod; + } + + public static MethodInfo declaration(String name, TypeInfo containingType, TypeInfo returnType, List params, + int fullDeclOffset, int typeOffset, int nameOffset, + int bodyStart, int bodyEnd, int modifiers, String documentation) { + return new MethodInfo(name, returnType, containingType, params, fullDeclOffset, typeOffset, nameOffset, bodyStart, bodyEnd, true, true, modifiers, documentation, null); + } + + public static MethodInfo call(String name, TypeInfo containingType, int paramCount) { + boolean resolved = containingType != null && containingType.isResolved() && + containingType.hasMethod(name); + List params = new ArrayList<>(); + for (int i = 0; i < paramCount; i++) { + params.add(FieldInfo.unresolved("arg" + i, FieldInfo.Scope.PARAMETER)); + } + return new MethodInfo(name, null, containingType, params, -1, -1, -1, -1, -1, resolved, false, 0, null, null); + } + + public static MethodInfo unresolvedCall(String name, int paramCount) { + List params = new ArrayList<>(); + for (int i = 0; i < paramCount; i++) { + params.add(FieldInfo.unresolved("arg" + i, FieldInfo.Scope.PARAMETER)); + } + return new MethodInfo(name, null, null, params, -1, -1, -1, -1, -1, false, false, 0, null, null); + } + + /** + * Create a MethodInfo for a synthetic/external method. + * Used for built-in types like Nashorn's Java object. + */ + public static MethodInfo external(String name, TypeInfo returnType, TypeInfo containingType, + List params, int modifiers, String documentation) { + return new MethodInfo(name, returnType, containingType, params, -1, -1, -1, -1, -1, true, false, modifiers, documentation, null); + } + + /** + * Create a MethodInfo from reflection data. + * Used when resolving method calls on known types. + * Preserves generic type information from reflection. + */ + public static MethodInfo fromReflection(Method method, TypeInfo containingType) { + String name = method.getName(); + // Use getGenericReturnType() to preserve generic information like List + TypeInfo returnType = TypeInfo.fromGenericType(method.getGenericReturnType()); + if (returnType == null) { + returnType = TypeInfo.fromClass(method.getReturnType()); + } + int modifiers = method.getModifiers(); + + // Try to find matching JSMethodInfo to bridge parameter names/docs and allow return overrides + JSMethodInfo jsMethod = DtsJavaBridge.findMatchingMethod(method, containingType); + if (jsMethod != null) { + // If .d.ts provides a more specific return type, use it for editor typing. + // (e.g., .d.ts override like IDBCPlayer -> IDBCAddon in npcdbc). + TypeInfo overrideReturnType = DtsJavaBridge.resolveReturnTypeOverride(method, containingType, jsMethod); + if (overrideReturnType != null && overrideReturnType.getJavaClass() != null) { + Class reflectedReturn = method.getReturnType(); + Class overrideClass = overrideReturnType.getJavaClass(); + if (reflectedReturn.isAssignableFrom(overrideClass)) { + if (reflectedReturn != overrideClass) { + returnType = overrideReturnType; +// System.out.println("[DtsJavaBridge] Overrode return type for " +// + method.getDeclaringClass().getName() + "." + name +// + "(" + method.getParameterCount() + ") from " +// + reflectedReturn.getName() + " to " + overrideClass.getName()); + } + } + } + } + + // If the receiver is parameterized (e.g., List), substitute class type variables (E -> String) + GenericContext receiverCtx = null; + if (GenericContext.hasGenerics(containingType)) { + receiverCtx = GenericContext.forReceiver(containingType); + returnType = receiverCtx.substitute(returnType); + } + + List params = new ArrayList<>(); + // Use getGenericParameterTypes() to preserve generic information + java.lang.reflect.Type[] genericParamTypes = method.getGenericParameterTypes(); + List jsParams = jsMethod != null ? jsMethod.getParameters() : null; + for (int i = 0; i < genericParamTypes.length; i++) { + TypeInfo paramType = TypeInfo.fromGenericType(genericParamTypes[i]); + if (paramType == null) { + paramType = TypeInfo.fromClass(method.getParameterTypes()[i]); + } + + if (receiverCtx != null) + paramType = receiverCtx.substitute(paramType); + + // Adapt Object params to receiver generic type args (e.g., Map.get(Object) -> Map.get(K)) + TypeInfo adapted = GenericParameterAdapter.adaptParameterType(method, containingType, i, paramType); + if (adapted != null) { + paramType = adapted; + } + String paramName = "arg" + i; + if (jsParams != null && i < jsParams.size()) { + String jsName = jsParams.get(i).getName(); + if (jsName != null && !jsName.isEmpty()) { + paramName = jsName; + } + } + + FieldInfo fieldInfo = FieldInfo.reflectionParam(paramName, paramType); + boolean isVarArg = method.isVarArgs() && i == genericParamTypes.length - 1; + if (jsParams != null && i < jsParams.size()) { + isVarArg = isVarArg || jsParams.get(i).isVarArg(); + } + fieldInfo.setVarArg(isVarArg); + params.add(fieldInfo); + } + + String documentation = null; + JSDocInfo jsDocInfo = null; + if (jsMethod != null) { + jsDocInfo = jsMethod.getJsDocInfo(); + String jsDocDesc = jsDocInfo != null ? jsDocInfo.getDescription() : null; + documentation = jsDocDesc != null ? jsDocDesc : jsMethod.getDocumentation(); + } + + MethodInfo methodInfo = new MethodInfo(name, returnType, containingType, params, -1, -1, -1, -1, -1, true, false, modifiers, documentation, method); + if (jsDocInfo != null) { + methodInfo.setJSDocInfo(jsDocInfo); + } + return methodInfo; + } + + /** + * Create a MethodInfo from a Constructor via reflection. + * Used when resolving constructor calls on external types. + * Preserves generic type information for constructor parameters. + */ + public static MethodInfo fromReflectionConstructor(Constructor constructor, TypeInfo containingType) { + String name = containingType.getSimpleName(); // Constructor name is the type name + TypeInfo returnType = containingType; // Constructor "returns" an instance of the type + int modifiers = constructor.getModifiers(); + + List params = new ArrayList<>(); + // Use getGenericParameterTypes() to preserve generic information + java.lang.reflect.Type[] genericParamTypes = constructor.getGenericParameterTypes(); + for (int i = 0; i < genericParamTypes.length; i++) { + TypeInfo paramType = TypeInfo.fromGenericType(genericParamTypes[i]); + if (paramType == null) { + paramType = TypeInfo.fromClass(constructor.getParameterTypes()[i]); + } + FieldInfo fieldInfo = FieldInfo.reflectionParam("arg" + i, paramType); + fieldInfo.setVarArg(constructor.isVarArgs() && i == genericParamTypes.length - 1); + params.add(fieldInfo); + } + + return new MethodInfo(name, returnType, containingType, params, -1, -1, -1, -1, -1, true, true, modifiers, null, null); + } + + /** + * Create a MethodInfo from a JSMethodInfo (parsed from .d.ts files). + * Used when resolving method calls on JavaScript types. + * + * @param jsMethod The JavaScript method info from the type registry + * @param containingType The TypeInfo that owns this method + * @return A MethodInfo representing the JavaScript method + */ + public static MethodInfo fromJSMethod(JSMethodInfo jsMethod, TypeInfo containingType) { + String name = jsMethod.getName(); + + // Use the new getResolvedReturnType method + TypeInfo returnType = jsMethod.getResolvedReturnType(containingType); + + // Convert JS parameters to FieldInfo + List params = new ArrayList<>(); + List jsParams = jsMethod.getParameters(); + + for (JSMethodInfo.JSParameterInfo param : jsParams) { + String paramName = param.getName(); + + // Use the new getResolvedType method + TypeInfo paramType = param.getResolvedType(containingType); + + FieldInfo fieldInfo = FieldInfo.reflectionParam(paramName, paramType); + fieldInfo.setVarArg(param.isVarArg()); + params.add(fieldInfo); + } + + // JS methods are always public (no access modifiers in .d.ts) + int modifiers = Modifier.PUBLIC; + if (jsMethod.isStatic()) { + modifiers |= Modifier.STATIC; + } + + // Use the documentation from the method if available + JSDocInfo jsDocInfo = jsMethod.getJsDocInfo(); + String jsDocDesc = jsDocInfo != null ? jsDocInfo.getDescription() : null; + String documentation = jsDocDesc != null ? jsDocDesc : jsMethod.getDocumentation(); + + MethodInfo methodInfo = new MethodInfo(name, returnType, containingType, params, -1, -1, -1, -1, -1, true, + false, modifiers, documentation, null); + methodInfo.setJSDocInfo(jsDocInfo); + return methodInfo; + } + + + + // Getters + public String getName() { return name; } + public TypeInfo getReturnType() { return returnType; } + public TypeInfo getContainingType() { return containingType; } + public List getParameters() { return Collections.unmodifiableList(parameters); } + public int getParameterCount() { return parameters.size(); } + public Method getJavaMethod() { return javaMethod; } + /** @deprecated Use getTypeOffset() or getNameOffset() instead */ + @Deprecated + public int getDeclarationOffset() { return typeOffset; } + public int getFullDeclarationOffset() { return fullDeclarationOffset; } + public int getTypeOffset() { return typeOffset; } + public int getNameOffset() { return nameOffset; } + public int getBodyStart() { return bodyStart; } + public int getBodyEnd() { return bodyEnd; } + public boolean isResolved() { return resolved; } + public boolean isDeclaration() { return isDeclaration; } + public boolean isCall() { return !isDeclaration; } + public int getModifiers() { return modifiers; } + public boolean isStatic() { return Modifier.isStatic(modifiers); } + public boolean isFinal() { return Modifier.isFinal(modifiers); } + public boolean isAbstract() { return Modifier.isAbstract(modifiers); } + public boolean isSynchronized() { return Modifier.isSynchronized(modifiers); } + public boolean isNative() { return Modifier.isNative(modifiers); } + public boolean isPublic() { return Modifier.isPublic(modifiers); } + public boolean isPrivate() { return Modifier.isPrivate(modifiers); } + public boolean isProtected() { return Modifier.isProtected(modifiers); } + public String getDocumentation() { return documentation; } + public JSDocInfo getJSDocInfo() { return jsDocInfo; } + public void setJSDocInfo(JSDocInfo jsDocInfo) { this.jsDocInfo = jsDocInfo; } + + // ==================== OVERRIDE/IMPLEMENTS GETTERS/SETTERS ==================== + + /** + * Check if this method overrides a parent class method. + */ + public boolean isOverride() { return overridesFrom != null; } + + /** + * Get the type containing the method this overrides. + * @return The parent class TypeInfo, or null if not an override + */ + public TypeInfo getOverridesFrom() { return overridesFrom; } + + /** + * Mark this method as overriding a parent class method. + * @param parentType The type containing the overridden method + */ + public void setOverridesFrom(TypeInfo parentType) { this.overridesFrom = parentType; } + + /** + * Check if this method implements an interface method. + */ + public boolean isImplements() { return implementsFrom != null; } + + /** + * Get the interface containing the method this implements. + * @return The interface TypeInfo, or null if not implementing + */ + public TypeInfo getImplementsFrom() { return implementsFrom; } + + /** + * Mark this method as implementing an interface method. + * @param interfaceType The interface containing the implemented method + */ + public void setImplementsFrom(TypeInfo interfaceType) { this.implementsFrom = interfaceType; } + + /** + * Check if this method either overrides or implements something. + */ + public boolean hasInheritanceMarker() { return isOverride() || isImplements(); } + + /** + * Create a copy of this method with all type variables substituted using the given context. + * Applies substitution to both the return type and every parameter type recursively. + * + * Used when a generic type is parameterized (e.g., {@code Box}) and its raw methods + * (declared with type variables like T) need to reflect the concrete type arguments. + * + * Example: for {@code class Box { T get(); }}, calling this on the raw {@code get() → T} + * with a context binding {@code T → String} produces {@code get() → String}. + * + * @param context the generic context containing type variable bindings; if null, returns {@code this} unchanged + * @return a new MethodInfo with substituted types, or {@code this} if context is null + */ + public MethodInfo substituteTypeParams(GenericContext context) { + if (context == null) { + return this; + } + TypeInfo subReturnType = context.substitute(returnType); + List subParams = new ArrayList<>(parameters.size()); + for (FieldInfo param : parameters) { + subParams.add(param.substituteTypeParams(context)); + } + MethodInfo result = new MethodInfo(name, subReturnType, containingType, subParams, + fullDeclarationOffset, typeOffset, nameOffset, bodyStart, bodyEnd, + resolved, isDeclaration, modifiers, documentation, javaMethod); + result.jsDocInfo = this.jsDocInfo; + result.overridesFrom = this.overridesFrom; + result.implementsFrom = this.implementsFrom; + return result; + } + + /** + * Check if a position is inside this method's body. + */ + public boolean containsPosition(int position) { + return position >= bodyStart && position < bodyEnd; + } + + /** + * Get the end of the method declaration (closing paren position). + * This is used for error highlighting of duplicate methods. + */ + public int getDeclarationEnd() { + // The declaration ends just before the opening brace + // We find the closing paren by searching backwards from bodyStart + return bodyStart > 0 ? bodyStart - 1 : nameOffset + name.length(); + } + + /** + * Check if this method has a parameter with the given name. + */ + public boolean hasParameter(String paramName) { + for (FieldInfo p : parameters) { + if (p.getName().equals(paramName)) { + return true; + } + } + return false; + } + + /** + * Get parameter info by name. + */ + public FieldInfo getParameter(String paramName) { + for (FieldInfo p : parameters) { + if (p.getName().equals(paramName)) { + return p; + } + } + return null; + } + + /** + * Get method signature for duplicate detection. + * Signature = name + parameter types (ignoring parameter names). + */ + public MethodSignature cachedSignature; + + public MethodSignature getSignature() { + if (cachedSignature == null) { + List paramTypes = new ArrayList<>(); + for (FieldInfo param : parameters) + paramTypes.add(param.getTypeInfo()); + cachedSignature = new MethodSignature(name, paramTypes); + } + return cachedSignature; + } + + /** + * Get the appropriate TokenType for highlighting this method. + */ + public TokenType getTokenType() { + if (isDeclaration) { + return TokenType.METHOD_DECL; + } + return resolved ? TokenType.METHOD_CALL : TokenType.DEFAULT; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("MethodInfo{"); + sb.append(name).append("("); + for (int i = 0; i < parameters.size(); i++) { + if (i > 0) sb.append(", "); + sb.append(parameters.get(i).getName()); + } + sb.append(")"); + if (returnType != null) { + sb.append(" -> ").append(returnType.getSimpleName()); + } + sb.append(", ").append(isDeclaration ? "decl" : "call"); + sb.append(", ").append(resolved ? "resolved" : "unresolved"); + sb.append("}"); + return sb.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MethodInfo that = (MethodInfo) o; + return name.equals(that.name) && parameters.size() == that.parameters.size(); + } + + @Override + public int hashCode() { + return name.hashCode() * 31 + parameters.size(); + } + + // ==================== ERROR HANDLING ==================== + + /** + * Represents an error with a specific parameter. + */ + public static class ParameterError { + private final FieldInfo parameter; + private final int paramIndex; + private final ErrorType errorType; + private final String message; + + public ParameterError(FieldInfo parameter, int paramIndex, ErrorType errorType, String message) { + this.parameter = parameter; + this.paramIndex = paramIndex; + this.errorType = errorType; + this.message = message; + } + + public FieldInfo getParameter() { return parameter; } + public int getParamIndex() { return paramIndex; } + public ErrorType getErrorType() { return errorType; } + public String getMessage() { return message; } + } + + /** + * Represents an error with a return statement (type mismatch). + */ + public static class ReturnStatementError { + private final int startOffset; // Start of "return" keyword (absolute position) + private final int endOffset; // End of return statement (after semicolon) + private final String message; + private final TypeInfo expectedType; + private final TypeInfo actualType; + + public ReturnStatementError(int startOffset, int endOffset, String message, TypeInfo expectedType, TypeInfo actualType) { + this.startOffset = startOffset; + this.endOffset = endOffset; + this.message = message; + this.expectedType = expectedType; + this.actualType = actualType; + } + + public int getStartOffset() { return startOffset; } + public int getEndOffset() { return endOffset; } + public String getMessage() { return message; } + public TypeInfo getExpectedType() { return expectedType; } + public TypeInfo getActualType() { return actualType; } + } + + /** + * Check if this method declaration has any errors. + */ + public boolean hasError() { + return errorType != ErrorType.NONE || !parameterErrors.isEmpty() || !returnStatementErrors.isEmpty(); + } + + /** + * Check if this has a missing return error. + */ + public boolean hasMissingReturnError() { + return errorType == ErrorType.MISSING_RETURN; + } + + /** + * Check if this has parameter errors. + */ + public boolean hasParameterErrors() { + return !parameterErrors.isEmpty(); + } + + /** + * Check if this has return statement type errors. + */ + public boolean hasReturnStatementErrors() { + return !returnStatementErrors.isEmpty(); + } + + public ErrorType getErrorType() { return errorType; } + public String getErrorMessage() { return errorMessage; } + public List getParameterErrors() { return Collections.unmodifiableList(parameterErrors); } + public List getReturnStatementErrors() { return Collections.unmodifiableList(returnStatementErrors); } + + /** + * Set the main error for this method. + */ + public void setError(ErrorType type, String message) { + this.errorType = type; + this.errorMessage = message; + } + + /** + * Add a parameter-specific error. + */ + public void addParameterError(FieldInfo param, int index, ErrorType type, String message) { + parameterErrors.add(new ParameterError(param, index, type, message)); + } + + public void addSamTypeError(int paramIndex, TypeInfo expectedSamType, TypeInfo actualDeclaredType) { + if (paramIndex < 0 || paramIndex >= parameters.size()) { + return; + } + FieldInfo param = parameters.get(paramIndex); + String message = "Explicit type '" + actualDeclaredType.getSimpleName() + + "' is incompatible with SAM parameter type '" + expectedSamType.getSimpleName() + "'"; + parameterErrors.add(new ParameterError(param, paramIndex, ErrorType.SAM_TYPE_INCOMPATIBLE, message)); + } + + /** + * Add a return statement error. + */ + public void addReturnStatementError(int startOffset, int endOffset, String message, TypeInfo expectedType, TypeInfo actualType) { + returnStatementErrors.add(new ReturnStatementError(startOffset, endOffset, message, expectedType, actualType)); + } + + /** + * Functional interface for type resolution callback. + */ + @FunctionalInterface + public interface TypeResolver { + TypeInfo resolveExpression(String expression, int position); + } + + + /** + * Validate this method declaration with type resolution for return statements. + * Checks for parameter errors, missing return statements, and return type mismatches. + * + * @param methodBodyText The text content of the method body (between { and }) + * @param typeResolver Optional callback to resolve expression types (for return type checking) + */ + public void validate(String methodBodyText, boolean hasBody, TypeResolver typeResolver) { + if (!isDeclaration) return; + + // Don't error if return type unresolved + if(returnType != null && !returnType.isResolved()) + return; + + // Validate parameters + validateParameters(); + boolean interfaceMember = containingType != null && containingType.isInterface(); + if (hasBody && (interfaceMember || isAbstract() || isNative())) { + setError(MethodInfo.ErrorType.INTERFACE_METHOD_BODY, "Interface or abstract methods cannot have a body"); + return; + } + + //No need to check for return types/statements + if(interfaceMember) + return; + + //If no body and not interface or abstract/native + if (bodyStart == bodyEnd && !isAbstract() && !isNative()) { + setError(ErrorType.MISSING_BODY, "Method must have a body or be declared abstract/native."); + return; + } + + // Validate return statement types FIRST if we have a type resolver + // This ensures type errors are shown even if there's also a missing return + if (typeResolver != null) { + validateReturnTypes(methodBodyText, typeResolver); + } + + // Validate return statement for non-void methods + // This may set the main error, but return type errors are already recorded + validateReturnStatement(methodBodyText); + } + + /** + * Check for duplicate and unresolved parameters. + */ + private void validateParameters() { + Set seenNames = new HashSet<>(); + + for (int i = 0; i < parameters.size(); i++) { + FieldInfo param = parameters.get(i); + String paramName = param.getName(); + + // Check for duplicate parameter names + if (seenNames.contains(paramName)) { + addParameterError(param, i, ErrorType.DUPLICATE_PARAMETER, + "Duplicate parameter name '" + paramName + "'"); + } else { + seenNames.add(paramName); + } + + // Check for unresolved parameter types + TypeInfo paramType = param.getTypeInfo(); + if (paramType == null || !paramType.isResolved()) { + String typeName = paramType != null ? paramType.getDisplayName() : "unknown"; + addParameterError(param, i, ErrorType.PARAMETER_UNDEFINED, + "Cannot resolve parameter type '" + typeName + "'"); + } + } + } + + /** + * Validate that a non-void method has a guaranteed return statement. + * Delegates to {@link ControlFlowAnalyzer} for control flow analysis. + */ + private void validateReturnStatement(String bodyText) { + if (bodyText == null || bodyText.isEmpty()) return; + + // void methods don't need return statements + if (TypeChecker.isVoidType(returnType)) return; + + // Abstract/native methods don't have bodies + if (isAbstract() || isNative()) return; + + // Check if the method has a guaranteed return using the control flow analyzer + if (!ControlFlowAnalyzer.hasGuaranteedReturn(bodyText)) { + setError(ErrorType.MISSING_RETURN, "Missing return statement"); + } + } + + /** + * Validate that all return statements have compatible types. + * Delegates to {@link CodeParser} for parsing and {@link TypeChecker} for type checks. + */ + private void validateReturnTypes(String bodyText, TypeResolver typeResolver) { + if (bodyText == null || bodyText.isEmpty()) return; + + boolean isVoid = TypeChecker.isVoidType(returnType); + String expectedTypeName = isVoid ? "void" : returnType.getDisplayName(); + + // Remove comments but keep strings (we need accurate positions) + String cleanBody = CodeParser.removeComments(bodyText); + + // Find all return statements + int pos = 0; + while (pos < cleanBody.length()) { + // Look for "return" keyword + int returnPos = CodeParser.findReturnKeyword(cleanBody, pos); + if (returnPos < 0) break; + + // Find the semicolon ending this return statement + int semiPos = CodeParser.findReturnSemicolon(cleanBody, returnPos + 6); + if (semiPos < 0) { + pos = returnPos + 6; + continue; + } + + // Extract the return expression + String returnExpr = cleanBody.substring(returnPos + 6, semiPos).trim(); + + // Calculate absolute position (bodyStart + 1 is after the opening brace) + int absoluteReturnStart = bodyStart + 1 + returnPos; + int absoluteSemiEnd = bodyStart + 1 + semiPos + 1; // +1 to include semicolon + + // Check void method returning a value + if (isVoid && !returnExpr.isEmpty()) { + String message = "Cannot return a value from a method with void result type"; + addReturnStatementError(absoluteReturnStart, absoluteSemiEnd, message, returnType, null); + } + // Check non-void method return type compatibility + else if (!isVoid && !returnExpr.isEmpty() && typeResolver != null) { + // Resolve the expression type + TypeInfo actualType = typeResolver.resolveExpression(returnExpr, absoluteReturnStart); + + // Check type compatibility + if (!TypeChecker.isTypeCompatible(returnType, actualType)) { + String actualTypeName = actualType != null ? actualType.getSimpleName() : "null"; + String message = "Incompatible types.\nRequired: " + expectedTypeName + "\nFound: " + actualTypeName; + addReturnStatementError(absoluteReturnStart, absoluteSemiEnd, message, returnType, actualType); + } + } + + pos = semiPos + 1; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodSignature.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodSignature.java new file mode 100644 index 000000000..5cde0ac63 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodSignature.java @@ -0,0 +1,95 @@ +package noppes.npcs.client.gui.util.script.interpreter.method; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a method signature for robust comparison. + * Compares method name and parameter types as structured data, not as strings. + */ +public final class MethodSignature { + private final String methodName; + private final List parameterTypes; + + public MethodSignature(String methodName, List parameterTypes) { + this.methodName = methodName; + this.parameterTypes = new ArrayList<>(parameterTypes); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof MethodSignature)) + return false; + + MethodSignature other = (MethodSignature) obj; + + // Compare method names + if (!this.methodName.equals(other.methodName)) + return false; + + // Compare parameter count + if (this.parameterTypes.size() != other.parameterTypes.size()) + return false; + + // Compare each parameter type + for (int i = 0; i < this.parameterTypes.size(); i++) { + TypeInfo thisType = this.parameterTypes.get(i); + TypeInfo otherType = other.parameterTypes.get(i); + + // Both null = equal + if (thisType == null && otherType == null) + continue; + + // One null, one not = not equal + if (thisType == null || otherType == null) + return false; + + // Compare full type names + if (!thisType.getFullName().equals(otherType.getFullName())) + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = methodName.hashCode(); + for (TypeInfo paramType : parameterTypes) { + result = 31 * result + (paramType != null ? paramType.getFullName().hashCode() : 0); + } + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(methodName); + sb.append("("); + for (int i = 0; i < parameterTypes.size(); i++) { + if (i > 0) + sb.append(", "); + TypeInfo type = parameterTypes.get(i); + sb.append(type != null ? type.getFullName() : "?"); + } + sb.append(")"); + return sb.toString(); + } + + public static String asString(Method javaMethod) { + StringBuilder sig = new StringBuilder(javaMethod.getName()); + sig.append("("); + Class[] paramTypes = javaMethod.getParameterTypes(); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) + sig.append(", "); + sig.append(paramTypes[i].getSimpleName()); + } + sig.append(")"); + return sig.toString(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/package-info.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/package-info.java new file mode 100644 index 000000000..0fe302521 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/package-info.java @@ -0,0 +1,102 @@ +/** + *

Interpreter Package - Java Syntax Highlighting System

+ * + *

This package provides a clean, modular rewrite of the JavaTextContainer + * syntax highlighting system. It replaces the original implementation with + * well-structured, atomic classes that work together like LEGO pieces.

+ * + *

Architecture Overview

+ * + *
+ * ┌─────────────────────────────────────────────────────────────────┐
+ * │                    ScriptTextContainer                          │
+ * │  (Compatibility adapter extending JavaTextContainer)            │
+ * │  - USE_NEW_INTERPRETER flag to toggle between systems           │
+ * │  - Produces JavaTextContainer.LineData/Token for GUI compat     │
+ * └───────────────────────┬─────────────────────────────────────────┘
+ *                         │
+ *                         ▼
+ * ┌─────────────────────────────────────────────────────────────────┐
+ * │                     ScriptDocument                              │
+ * │  (Main document container - replaces JavaTextContainer core)    │
+ * │                                                                 │
+ * │  7-Phase Tokenization Pipeline:                                 │
+ * │  1. findExcludedRanges() - strings/comments                     │
+ * │  2. parseImports() - import statements                          │
+ * │  3. parseStructure() - methods, fields                          │
+ * │  4. buildMarks() - all highlighting marks                       │
+ * │  5. resolveConflicts() - priority-based resolution              │
+ * │  6. buildTokens() - convert marks to tokens per line            │
+ * │  7. computeIndentGuides() - visual indent guides                │
+ * └───────────────────────┬─────────────────────────────────────────┘
+ *                         │
+ *                         ▼
+ * ┌─────────────────────────────────────────────────────────────────┐
+ * │                      ScriptLine                                 │
+ * │  (Line container with token management and rendering)           │
+ * │  - Token list with navigation                                   │
+ * │  - Indent guides                                                │
+ * │  - drawString() with color codes                                │
+ * │  - drawStringHex() for direct hex color rendering               │
+ * └───────────────────────┬─────────────────────────────────────────┘
+ *                         │
+ *                         ▼
+ * ┌─────────────────────────────────────────────────────────────────┐
+ * │                        Token                                    │
+ * │  (Atomic token unit with type-specific metadata)                │
+ * │  - Text, start/end offsets                                      │
+ * │  - TokenType (with hex color and priority)                      │
+ * │  - prev()/next() navigation                                     │
+ * │  - Type-specific metadata: TypeInfo, FieldInfo, MethodInfo      │
+ * └─────────────────────────────────────────────────────────────────┘
+ * 
+ * + *

Supporting Classes

+ * + *
    + *
  • TokenType - Enum with hex colors and priorities for all token types
  • + *
  • TypeInfo - Immutable type metadata (class/interface/enum)
  • + *
  • TypeResolver - Class resolution with caching (replaces ClassPathFinder)
  • + *
  • ImportData - Import statement tracking with resolution status
  • + *
  • FieldInfo - Field/variable metadata with scope (global/local/parameter)
  • + *
  • MethodInfo - Method declaration/call metadata with parameters
  • + *
+ * + *

Key Improvements Over Original

+ * + *
    + *
  1. Single-pass tokenization - 7 distinct phases vs multiple loops
  2. + *
  3. Token navigation - prev()/next() methods for easy traversal
  4. + *
  5. Type-specific metadata - Rich information attached to tokens
  6. + *
  7. Hex color support - Direct RGB colors in addition to MC color codes
  8. + *
  9. Clean separation - Each class has one responsibility
  10. + *
  11. Immutable data - TypeInfo, FieldInfo, MethodInfo are immutable
  12. + *
  13. Feature toggle - USE_NEW_INTERPRETER flag for safe rollback
  14. + *
+ * + *

Usage

+ * + *
{@code
+ * // The new system is automatically used via ScriptTextContainer
+ * // To disable and use original JavaTextContainer:
+ * ScriptTextContainer.USE_NEW_INTERPRETER = false;
+ * 
+ * // To access the underlying ScriptDocument:
+ * ScriptTextContainer container = (ScriptTextContainer) textArea.getContainer();
+ * ScriptDocument doc = container.getDocument();
+ * 
+ * // Token navigation example:
+ * for (ScriptLine line : doc.getLines()) {
+ *     for (Token token : line.getTokens()) {
+ *         Token next = token.next();
+ *         Token prev = token.prev();
+ *     }
+ * }
+ * }
+ * + * @since 2.0 + * @see ScriptTextContainer + * @see ScriptDocument + * @see Token + */ +package noppes.npcs.client.gui.util.script.interpreter; diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/ScriptColorScheme.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/ScriptColorScheme.java new file mode 100644 index 000000000..f5d6a9cb9 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/ScriptColorScheme.java @@ -0,0 +1,270 @@ +package noppes.npcs.client.gui.util.script.interpreter.token; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.minecraft.client.resources.IResource; +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.LogWriter; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * Manages reloadable style overrides (color, bold, italic) for {@link TokenType}, + * plus editor background/gutter/scrollbar colors via {@link BackgroundStyleEntry}. + *

+ * Priority is always determined internally by {@link TokenType#getPriority()} ()} + * and is never exposed to or loaded from user-facing JSON files. + *

+ * Loaded from {@code assets/customnpcs/colorscheme/script_editor_scheme.json} on resource reload. + * Styles are cached in a flat array indexed by {@link TokenType#ordinal()} for zero-cost lookups. + */ +public final class ScriptColorScheme { + + // Volatile array reference swapped atomically — all tokens update at once + static volatile StyleEntry[] styles = buildDefaults(); + + // Background/gutter/scrollbar colors — volatile for same atomic-swap pattern + private static volatile BackgroundStyleEntry background = BackgroundStyleEntry.DEFAULT; + + private ScriptColorScheme() {} + + /** Returns the current background style (never null). */ + public static BackgroundStyleEntry getBackgroundStyle() { + return background; + } + + /** + * Reload the color scheme from the resource pack's JSON file. + * Uses {@code getAllResources()} to find the highest-priority version + * (the last entry in the list, which is the latest resource pack override). + * Falls back to defaults if the file is missing or malformed. + */ + public static void reloadColorScheme(IResourceManager resourceManager) { + ResourceLocation loc = new ResourceLocation("customnpcs", "colorscheme/script_editor_scheme.json"); + try { + List resources = resourceManager.getAllResources(loc); + IResource top = resources.get(resources.size() - 1); + + try (InputStream is = top.getInputStream(); + InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { + loadFromJson(reader); + LogWriter.info("[ColorScheme] Loaded script_editor_scheme.json successfully"); + logLoadedSample(); + } + } catch (FileNotFoundException e) { + LogWriter.info("[ColorScheme] No script_editor_scheme.json found, using defaults"); + resetToDefaults(); + } catch (Exception e) { + LogWriter.error("[ColorScheme] Failed to load script_editor_scheme.json: " + e.getMessage()); + resetToDefaults(); + } + } + + private static void logLoadedSample() { + StyleEntry[] current = styles; + TokenType[] samples = { TokenType.COMMENT, TokenType.KEYWORD, TokenType.STRING, TokenType.METHOD_CALL, TokenType.DEFAULT }; + for (TokenType tt : samples) { + StyleEntry e = current[tt.ordinal()]; + LogWriter.info("[ColorScheme] " + tt.name() + " -> color=#" + String.format("%08X", e.hexColor) + + ", bold=" + e.bold + ", italic=" + e.italic); + } + + BackgroundStyleEntry bg = background; + LogWriter.info("[ColorScheme] background -> bg=#" + String.format("%08X", bg.getBackgroundColor()) + + ", gutter=#" + String.format("%08X", bg.getGutterColor())); + } + + /** + * Parse a color scheme JSON and install it as the active scheme. + * Expected format: {@code { "TOKEN_NAME": { "color": "#RRGGBB", "bold": bool, "italic": bool }, ... }} + * Missing properties per token fall back to the enum default. Parse errors are logged per-token. + */ + public static void loadFromJson(Reader reader) { + try { + JsonParser parser = new JsonParser(); + JsonElement root = parser.parse(reader); + if (!root.isJsonObject()) { + LogWriter.error("[ColorScheme] script_editor_scheme.json root is not a JSON object, using defaults"); + return; + } + + JsonObject obj = root.getAsJsonObject(); + + background = parseBackground(obj); + + TokenType[] all = TokenType.values(); + StyleEntry[] next = new StyleEntry[all.length]; + for (TokenType tt : all) { + next[tt.ordinal()] = parseEntry(obj, tt); + } + styles = next; + } catch (Exception e) { + LogWriter.error("[ColorScheme] Failed to parse script_editor_scheme.json, using defaults: " + e.getMessage()); + } + } + + public static void resetToDefaults() { + styles = buildDefaults(); + background = BackgroundStyleEntry.DEFAULT; + } + + private static StyleEntry parseEntry(JsonObject root, TokenType tt) { + if (!root.has(tt.name())) { + return defaultEntry(tt); + } + try { + JsonElement elem = root.get(tt.name()); + if (!elem.isJsonObject()) { + LogWriter.error("[ColorScheme] Entry for " + tt.name() + " is not an object, skipping"); + return defaultEntry(tt); + } + JsonObject entry = elem.getAsJsonObject(); + + int defaultColor = tt.getDefaultHexColor(); + if ((defaultColor & 0xFF000000) == 0) { + defaultColor |= 0xFF000000; + } + + int color = entry.has("color") + ? parseColor(entry.get("color"), defaultColor, tt.name()) + : defaultColor; + boolean bold = entry.has("bold") ? entry.get("bold").getAsBoolean() : tt.getDefaultBold(); + boolean italic = entry.has("italic") ? entry.get("italic").getAsBoolean() : tt.getDefaultItalic(); + + return new StyleEntry(color, bold, italic); + } catch (Exception e) { + LogWriter.error("[ColorScheme] Error parsing token " + tt.name() + ", using defaults: " + e.getMessage()); + return defaultEntry(tt); + } + } + + private static StyleEntry defaultEntry(TokenType tt) { + int color = tt.getDefaultHexColor(); + if ((color & 0xFF000000) == 0) { + color |= 0xFF000000; + } + return new StyleEntry(color, tt.getDefaultBold(), tt.getDefaultItalic()); + } + + private static BackgroundStyleEntry parseBackground(JsonObject root) { + if (!root.has("background")) { + return BackgroundStyleEntry.DEFAULT; + } + try { + JsonElement elem = root.get("background"); + if (!elem.isJsonObject()) { + LogWriter.error("[ColorScheme] 'background' is not an object, using defaults"); + return BackgroundStyleEntry.DEFAULT; + } + JsonObject bg = elem.getAsJsonObject(); + BackgroundStyleEntry d = BackgroundStyleEntry.DEFAULT; + + int backgroundColor = bg.has("backgroundColor") ? parseColor(bg.get("backgroundColor"), d.getBackgroundColor(), "background.backgroundColor") : d.getBackgroundColor(); + int gutterColor = bg.has("gutterColor") ? parseColor(bg.get("gutterColor"), d.getGutterColor(), "background.gutterColor") : d.getGutterColor(); + int gutterSeparatorColor = bg.has("gutterSeparatorColor") ? parseColor(bg.get("gutterSeparatorColor"), d.getGutterSeparatorColor(), "background.gutterSeparatorColor") : d.getGutterSeparatorColor(); + int lineNumberColor = bg.has("lineNumberColor") ? parseColor(bg.get("lineNumberColor"), d.getLineNumberColor(), "background.lineNumberColor") : d.getLineNumberColor(); + int lineNumberActiveColor = bg.has("lineNumberActiveColor") ? parseColor(bg.get("lineNumberActiveColor"), d.getLineNumberActiveColor(), "background.lineNumberActiveColor") : d.getLineNumberActiveColor(); + int scrollbarColor = bg.has("scrollbarColor") ? parseColor(bg.get("scrollbarColor"), d.getScrollbarColor(), "background.scrollbarColor") : d.getScrollbarColor(); + int borderColor = bg.has("borderColor") ? parseColor(bg.get("borderColor"), d.getBorderColor(), "background.borderColor") : d.getBorderColor(); + int caretColor = bg.has("caretColor") ? parseColor(bg.get("caretColor"), d.getCaretColor(), "background.caretColor") : d.getCaretColor(); + + return new BackgroundStyleEntry(backgroundColor, gutterColor, gutterSeparatorColor, + lineNumberColor, lineNumberActiveColor, scrollbarColor, borderColor, caretColor); + } catch (Exception e) { + LogWriter.error("[ColorScheme] Error parsing 'background', using defaults: " + e.getMessage()); + return BackgroundStyleEntry.DEFAULT; + } + } + + private static StyleEntry[] buildDefaults() { + TokenType[] all = TokenType.values(); + StyleEntry[] defaults = new StyleEntry[all.length]; + for (TokenType tt : all) { + defaults[tt.ordinal()] = defaultEntry(tt); + } + return defaults; + } + + private static int parseColor(JsonElement element, int fallback, String tokenName) { + try { + if (element.isJsonPrimitive()) { + if (element.getAsJsonPrimitive().isString()) { + String s = element.getAsString().trim(); + if (s.startsWith("#")) { + s = s.substring(1); + } + int color = (int) Long.parseLong(s, 16); + if (s.length() <= 6) { + color |= 0xFF000000; + } + return color; + } else if (element.getAsJsonPrimitive().isNumber()) { + return element.getAsInt(); + } + } + } catch (NumberFormatException e) { + LogWriter.error("[ColorScheme] Invalid color for " + tokenName + ": " + element + ", using default"); + } + return fallback; + } + + static final class StyleEntry { + final int hexColor; + final boolean bold; + final boolean italic; + + StyleEntry(int hexColor, boolean bold, boolean italic) { + this.hexColor = hexColor; + this.bold = bold; + this.italic = italic; + } + } + + public static final class BackgroundStyleEntry { + static final BackgroundStyleEntry DEFAULT = new BackgroundStyleEntry( + 0xff000000, // backgroundColor (text viewport) + 0xff000000, // gutterColor (line-number gutter) + 0xff3c3f41, // gutterSeparatorColor + 0xFF606366, // lineNumberColor (inactive) + 0xFFb9c7d6, // lineNumberActiveColor (current line) + 0xFFe0e0e0, // scrollbarColor + 0xffa0a0a0, // borderColor (outer border) + 0xffffffff // caretColor (cursor) + ); + + private final int backgroundColor; + private final int gutterColor; + private final int gutterSeparatorColor; + private final int lineNumberColor; + private final int lineNumberActiveColor; + private final int scrollbarColor; + private final int borderColor; + private final int caretColor; + + BackgroundStyleEntry(int backgroundColor, int gutterColor, int gutterSeparatorColor, + int lineNumberColor, int lineNumberActiveColor, + int scrollbarColor, int borderColor, int caretColor) { + this.backgroundColor = backgroundColor; + this.gutterColor = gutterColor; + this.gutterSeparatorColor = gutterSeparatorColor; + this.lineNumberColor = lineNumberColor; + this.lineNumberActiveColor = lineNumberActiveColor; + this.scrollbarColor = scrollbarColor; + this.borderColor = borderColor; + this.caretColor = caretColor; + } + + public int getBackgroundColor() { return backgroundColor; } + public int getGutterColor() { return gutterColor; } + public int getGutterSeparatorColor() { return gutterSeparatorColor; } + public int getLineNumberColor() { return lineNumberColor; } + public int getLineNumberActiveColor() { return lineNumberActiveColor; } + public int getScrollbarColor() { return scrollbarColor; } + public int getBorderColor() { return borderColor; } + public int getCaretColor() { return caretColor; } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/Token.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/Token.java new file mode 100644 index 000000000..7e12ee0c4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/Token.java @@ -0,0 +1,278 @@ +package noppes.npcs.client.gui.util.script.interpreter.token; + +import noppes.npcs.client.gui.util.script.interpreter.type.ImportData; +import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; + +/** + * Represents a single token in the source code with its type and metadata. + * Tokens are the atomic units of the syntax highlighting system. + * + * Each token knows: + * - Its text content + * - Its position in the global source + * - Its type (for coloring) + * - Type-specific metadata (resolved class info, declaration info, etc.) + */ +public class Token { + + private final String text; + private final int globalStart; // start offset in the full document + private final int globalEnd; // end offset in the full document + private TokenType type; + + // Optional metadata based on token type + private TypeInfo typeInfo; // For class references, type declarations + private FieldInfo fieldInfo; // For field references + private MethodInfo methodInfo; // For method calls/declarations + private MethodCallInfo methodCallInfo; // For method calls with argument info + private ImportData importData; // For import statements + private FieldAccessInfo fieldAccessInfo; //For fields like Minecraft.getMinecraft.thePlayer + private TokenErrorMessage errorMessage; + + + // Navigation - set by ScriptLine + private Token prev; + private Token next; + private ScriptLine parentLine; + + public Token(String text, int globalStart, int globalEnd, TokenType type) { + this.text = text; + this.globalStart = globalStart; + this.globalEnd = globalEnd; + this.type = type; + } + + // ==================== FACTORY METHODS ==================== + + public static Token defaultToken(String text, int start, int end) { + return new Token(text, start, end, TokenType.DEFAULT); + } + + public static Token keyword(String text, int start, int end) { + return new Token(text, start, end, TokenType.KEYWORD); + } + + public static Token comment(String text, int start, int end) { + return new Token(text, start, end, TokenType.COMMENT); + } + + public static Token string(String text, int start, int end) { + return new Token(text, start, end, TokenType.STRING); + } + + public static Token literal(String text, int start, int end) { + return new Token(text, start, end, TokenType.LITERAL); + } + + public static Token typeReference(String text, int start, int end, TypeInfo info) { + Token t = new Token(text, start, end, info != null ? info.getTokenType() : TokenType.TYPE_DECL); + t.typeInfo = info; + return t; + } + + public static Token methodDecl(String text, int start, int end, MethodInfo info) { + Token t = new Token(text, start, end, TokenType.METHOD_DECL); + t.methodInfo = info; + return t; + } + + public static Token methodCall(String text, int start, int end, MethodInfo info, boolean resolved) { + Token t = new Token(text, start, end, resolved ? TokenType.METHOD_CALL : TokenType.DEFAULT); + t.methodInfo = info; + return t; + } + + public static Token globalField(String text, int start, int end, FieldInfo info) { + Token t = new Token(text, start, end, TokenType.GLOBAL_FIELD); + t.fieldInfo = info; + return t; + } + + public static Token localField(String text, int start, int end, FieldInfo info) { + Token t = new Token(text, start, end, TokenType.LOCAL_FIELD); + t.fieldInfo = info; + return t; + } + + public static Token parameter(String text, int start, int end, FieldInfo info) { + Token t = new Token(text, start, end, TokenType.PARAMETER); + t.fieldInfo = info; + return t; + } + + public static Token undefined(String text, int start, int end) { + return new Token(text, start, end, TokenType.UNDEFINED_VAR); + } + + // ==================== GETTERS ==================== + + public String getText() { return text; } + public int getGlobalStart() { return globalStart; } + public int getGlobalEnd() { return globalEnd; } + public int getLength() { return globalEnd - globalStart; } + public TokenType getType() { return type; } + public TypeInfo getTypeInfo() { return typeInfo; } + public FieldInfo getFieldInfo() { return fieldInfo; } + public MethodInfo getMethodInfo() { return methodInfo; } + public MethodCallInfo getMethodCallInfo() { return methodCallInfo; } + public FieldAccessInfo getFieldAccessInfo() { return fieldAccessInfo; } + public ImportData getImportData() { return importData; } + public TokenErrorMessage getErrorMessage() { return errorMessage; } + public ScriptLine getParentLine() { return parentLine; } + + // ==================== SETTERS ==================== + + public void setType(TokenType type) { this.type = type; } + public void setTypeInfo(TypeInfo info) { this.typeInfo = info; } + public void setFieldInfo(FieldInfo info) { this.fieldInfo = info; } + public void setFieldAccessInfo(FieldAccessInfo info) { this.fieldAccessInfo = info; } + public void setMethodInfo(MethodInfo info) { this.methodInfo = info; } + public void setMethodCallInfo(MethodCallInfo info) { this.methodCallInfo = info; } + public void setImportData(ImportData data) { this.importData = data; } + public void setErrorMessage(TokenErrorMessage message) { this.errorMessage = message; } + + public void setParentLine(ScriptLine line) { this.parentLine = line; } + public void setPrev(Token prev) { this.prev = prev; } + public void setNext(Token next) { this.next = next; } + + // ==================== NAVIGATION ==================== + + /** + * Get the previous token (may be on a previous line). + */ + public Token prev() { + if (prev != null) return prev; + if (parentLine == null) return null; + + ScriptLine prevLine = parentLine.prev(); + while (prevLine != null) { + Token last = prevLine.getLastToken(); + if (last != null) return last; + prevLine = prevLine.prev(); + } + return null; + } + + /** + * Get the next token (may be on a following line). + */ + public Token next() { + if (next != null) return next; + if (parentLine == null) return null; + + ScriptLine nextLine = parentLine.next(); + while (nextLine != null) { + Token first = nextLine.getFirstToken(); + if (first != null) return first; + nextLine = nextLine.next(); + } + return null; + } + + /** + * Get the previous token on the same line only. + */ + public Token prevOnLine() { + return prev; + } + + /** + * Get the next token on the same line only. + */ + public Token nextOnLine() { + return next; + } + + // ==================== TYPE CHECKS ==================== + + public boolean isKeyword() { + return type == TokenType.KEYWORD; + } + + public boolean isTypeReference() { + return type == TokenType.TYPE_DECL || type == TokenType.IMPORTED_CLASS || + type == TokenType.CLASS_DECL || type == TokenType.INTERFACE_DECL || + type == TokenType.ENUM_DECL; + } + + public boolean isEnumConstant() { + return type == TokenType.ENUM_CONSTANT; + } + public boolean isResolved() { + if (typeInfo != null) return typeInfo.isResolved(); + if (fieldInfo != null) return fieldInfo.isResolved(); + if (methodInfo != null) return methodInfo.isResolved(); + return type != TokenType.UNDEFINED_VAR; + } + + public boolean isIdentifier() { + if (text.isEmpty()) return false; + char first = text.charAt(0); + return Character.isJavaIdentifierStart(first); + } + + public boolean startsWithUpperCase() { + return !text.isEmpty() && Character.isUpperCase(text.charAt(0)); + } + + public boolean isMethodCall() { + return type == TokenType.METHOD_CALL || + (type == TokenType.DEFAULT && methodInfo != null); + } + + public boolean isField() { + return type == TokenType.GLOBAL_FIELD || type == TokenType.LOCAL_FIELD || + type == TokenType.PARAMETER || type == TokenType.STATIC_FINAL_FIELD || + type == TokenType.ENUM_CONSTANT; + } + + // ==================== RENDERING ==================== + + /** + * Get the hex color for this token. + */ + public int getHexColor() { + return type.getHexColor(); + } + + /** + * Get the Minecraft color code character. + */ + public char getColorCode() { + return type.toColorCode(); + } + + /** + * Get the Minecraft style prefix for this token (bold/italic codes). + * Returns empty string if no style, otherwise §l for bold, §o for italic, or both. + */ + public String getStylePrefix() { + StringBuilder sb = new StringBuilder(); + if (type.isBold()) sb.append('\u00A7').append('l'); + if (type.isItalic()) sb.append('\u00A7').append('o'); + return sb.toString(); + } + + /** + * Get the java.awt.Font style bitmask for this token. + * Returns a combination of {@link java.awt.Font#PLAIN}, {@link java.awt.Font#BOLD}, + * and {@link java.awt.Font#ITALIC}. + */ + public int getFontStyle() { + int style = java.awt.Font.PLAIN; + if (type.isBold()) style |= java.awt.Font.BOLD; + if (type.isItalic()) style |= java.awt.Font.ITALIC; + return style; + } + + @Override + public String toString() { + return "Token{'" + text + "', " + type + ", [" + globalStart + "-" + globalEnd + "]}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenErrorMessage.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenErrorMessage.java new file mode 100644 index 000000000..7b5115eb2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenErrorMessage.java @@ -0,0 +1,23 @@ +package noppes.npcs.client.gui.util.script.interpreter.token; + +public class TokenErrorMessage { + private final String message; + public boolean clearOtherErrors; + + public TokenErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public static TokenErrorMessage from(String message) { + return new TokenErrorMessage(message); + } + + public TokenErrorMessage clearOtherErrors() { + this.clearOtherErrors = true; + return this; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenType.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenType.java new file mode 100644 index 000000000..e5bd1f244 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenType.java @@ -0,0 +1,166 @@ +package noppes.npcs.client.gui.util.script.interpreter.token; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +/** + * Defines all token types for syntax highlighting with hex colors and priorities. + * Priority determines which token type wins when marks overlap. + * Higher priority = wins conflicts. + *

+ * Priority is defined exclusively by the enum and never stored elsewhere. + * Visual style properties (color, bold, italic) can be overridden at runtime + * via {@link ScriptColorScheme}. The enum constructor values serve as compile-time defaults. + */ +public enum TokenType { + // Comments and strings have highest priority - they override everything inside them + COMMENT(0xFF777777, 140), + STRING(0xFF17C6A3, 130), + + // JSDoc elements - lower priority but will fill gaps left by fragmented comment marking + JSDOC_TAG(0xFF8E8070, 125,true, true), // @param, @type, @return etc. (gold/orange) + JSDOC_TYPE(0xFF9A8C7C, 124), // {TypeName} in JSDoc (aqua like types) + + UNUSED_IMPORT(0xFF666666, 119), // unused import statements (gray) + + // Keywords and modifiers + KEYWORD(0xFFFF5555, 100,true, false), // control flow: if, else, for, while, etc. + + // Type declarations and references + INTERFACE_DECL(0xFF80F2F6, 85), // interface names (aqua) + ENUM_DECL(0xFFFF55FF, 85), // enum names (magenta) + ENUM_CONSTANT(0xFF55FFFF, 84, true, true), // enum constant values (blue, bold+italic) - like IntelliJ + CLASS_DECL(0xFF00AAAA, 85), // class names in declarations + IMPORTED_CLASS(0xFF00AAAA, 75), // imported class usages + GENERIC_TYPE_PARAM(0xFF00FA9A, 76), // generic type parameters like T, E, K, V (light green) + TYPE_DECL(0xFF00AAAA, 70), // package paths, type references + + // Methods + METHOD_DECL(0xFF00AA00, 60), // method declarations (green) + METHOD_CALL(0xFF55FF55, 50), // method calls (bright green) + + // Variables and fields + UNDEFINED_VAR(0xFFAA0000, 20), // unresolved variables (dark red) - high priority + PARAMETER(0xFF5555FF, 36), // method parameters (blue) + GLOBAL_FIELD(0xFF55FFFF, 35), // class-level fields (aqua) + LOCAL_FIELD(0xFFFFFF55, 25), // local variables (yellow) + STATIC_FINAL_FIELD(0xFFFF55FF, 36, true, true), // static final fields (magenta, italic) + + // Literals + LITERAL(0xFF79C0FF, 40), // numeric and boolean literals + + // Default + VARIABLE(0xFFFFFFFF, 30), // generic variables + DEFAULT(0xFFFFFFFF, 0); // default text color (white) + + private final int defaultHexColor; + private final int priority; + private final boolean defaultBold; + private final boolean defaultItalic; + + TokenType(int hexColor, int priority) { + this(hexColor, priority, false, false); + } + + TokenType(int hexColor, int priority, boolean bold, boolean italic) { + this.defaultHexColor = hexColor; + this.priority = priority; + this.defaultBold = bold; + this.defaultItalic = italic; + } + + public int getHexColor() { + return ScriptColorScheme.styles[ordinal()].hexColor; + } + + public int getPriority() { + return priority; + } + + public boolean isBold() { + return ScriptColorScheme.styles[ordinal()].bold; + } + + public boolean isItalic() { + return ScriptColorScheme.styles[ordinal()].italic; + } + + int getDefaultHexColor() { + return defaultHexColor; + } + + boolean getDefaultBold() { + return defaultBold; + } + + boolean getDefaultItalic() { + return defaultItalic; + } + + public static TokenType getByType(TypeInfo typeInfo) { + if (typeInfo == null || !typeInfo.isResolved()) + return TokenType.UNDEFINED_VAR; + + if ("any".equals(typeInfo.getFullName())) + return TokenType.KEYWORD; + + // Use the TypeInfo's own token type, which handles ScriptTypeInfo correctly + return typeInfo.getTokenType(); + } + + public static int getColor(TypeInfo typeInfo) { + return getByType(typeInfo).getHexColor(); + } + + public static int getPackageColor(){ + return IMPORTED_CLASS.getHexColor(); + } + /** + * Convert this token type to a Minecraft color code character. + * Used for backward compatibility with the existing rendering system. + */ + public char toColorCode() { + switch (this) { + case COMMENT: + case LITERAL: + case UNUSED_IMPORT: + return '7'; // gray + case STRING: + return '5'; // purple + case JSDOC_TAG: + return '6'; // gold + case JSDOC_TYPE: + return '3'; // dark aqua (like types) + case KEYWORD: + return 'c'; // red + case ENUM_DECL: + case STATIC_FINAL_FIELD: + return 'd'; // magenta + case ENUM_CONSTANT: + return '9'; // blue (same as PARAMETER) + case INTERFACE_DECL: + case GLOBAL_FIELD: + return 'b'; // aqua + case GENERIC_TYPE_PARAM: + return 'a'; // green (distinct from class types) + case CLASS_DECL: + case IMPORTED_CLASS: + case TYPE_DECL: + return '3'; // dark aqua + case METHOD_DECL: + return '2'; // dark green + case METHOD_CALL: + return 'a'; // green + case LOCAL_FIELD: + return 'e'; // yellow + case PARAMETER: + return '9'; // blue + case UNDEFINED_VAR: + return '4'; // dark red + case VARIABLE: + case DEFAULT: + default: + return 'f'; // white + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/CLASSINDEX_USAGE.txt b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/CLASSINDEX_USAGE.txt new file mode 100644 index 000000000..2adbda50f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/CLASSINDEX_USAGE.txt @@ -0,0 +1,20 @@ +/** + * Example Usage of ClassIndex: + * + * 1. Add a single class: + * ClassIndex.getInstance().addClass(EntityPlayer.class); + * + * 2. Add an entire package recursively: + * ClassIndex.getInstance().addPackage("net.minecraft.entity.player"); + * This will scan and add ALL classes in that package and subpackages. + * + * 3. Find classes by prefix: + * List matches = ClassIndex.getInstance().findByPrefix("Entity", 50); + * // Returns fully-qualified names like "net.minecraft.entity.Entity", etc. + * + * Benefits: + * - No more manual string pairs! Just pass Class objects. + * - Simple name and package are extracted automatically via reflection. + * - Can scan entire package trees recursively with one call. + * - Cleaner, more maintainable, and easier to extend. + */ diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ClassIndex.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ClassIndex.java new file mode 100644 index 000000000..694dd40d1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ClassIndex.java @@ -0,0 +1,326 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import java.io.File; +import java.net.URL; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * Index of Java classes for autocomplete suggestions. + * Uses reflection to automatically extract class names and packages. + * Supports multiple classes with the same simple name (e.g., java.util.Date and java.sql.Date). + */ +public class ClassIndex { + private static ClassIndex instance; + + // Map simple names to multiple classes (handles name collisions) + private final Map>> simpleNameToClasses = new LinkedHashMap<>(); + private final Set> registeredClasses = new HashSet<>(); + + private ClassIndex() { + // Initialize with common classes + initializeCommonClasses(); + } + + public static ClassIndex getInstance() { + if (instance == null) { + instance = new ClassIndex(); + } + return instance; + } + + public static void init(){ + getInstance(); + } + /** + * Register a single class by its Class object. + * The simple name and full name are extracted via reflection. + * Supports multiple classes with the same simple name. + */ + public void addClass(Class clazz) { + if (clazz == null) return; + + // Check if already registered using the Class object itself + if (registeredClasses.contains(clazz)) { + return; // Already registered + } + + registeredClasses.add(clazz); + String simpleName = clazz.getSimpleName(); + + // Only add if simple name is not empty (avoid inner classes with $ in name) + if (!simpleName.isEmpty() && !simpleName.contains("$")) { + // Add to list of classes with this simple name + simpleNameToClasses.computeIfAbsent(simpleName, k -> new ArrayList<>()).add(clazz); + } + } + + /** + * Register all classes in a package and all subpackages recursively. + * Uses ClassLoader to scan the classpath. + */ + public void addPackage(String packageName) { + addPackage(packageName, new String[0]); + } + + /** + * Register all classes in a package and all subpackages recursively, + * excluding specified packages. + * Uses ClassLoader to scan the classpath. + * + * @param packageName The base package to scan + * @param excludedPackages Array of package names to exclude (including their subpackages) + */ + public void addPackage(String packageName, String... excludedPackages) { + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + String path = packageName.replace('.', '/'); + Enumeration resources = classLoader.getResources(path); + + Set classNames = new HashSet<>(); + Set excludedPrefixes = new HashSet<>(); + + // Prepare excluded package prefixes for matching + for (String excluded : excludedPackages) { + if (excluded != null && !excluded.isEmpty()) { + excludedPrefixes.add(excluded + "."); + } + } + + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + + if (resource.getProtocol().equals("file")) { + // Scan directory + File directory = new File(resource.getFile()); + scanDirectory(directory, packageName, classNames, excludedPrefixes); + } else if (resource.getProtocol().equals("jar")) { + // Scan JAR file + String jarPath = resource.getPath(); + if (jarPath.startsWith("file:")) { + jarPath = jarPath.substring(5); + } + int separatorIndex = jarPath.indexOf("!"); + if (separatorIndex != -1) { + jarPath = jarPath.substring(0, separatorIndex); + } + scanJar(jarPath, packageName, classNames, excludedPrefixes); + } + } + + // Load all discovered classes + for (String className : classNames) { + try { + Class clazz = Class.forName(className, false, classLoader); + addClass(clazz); + } catch (ClassNotFoundException | NoClassDefFoundError | ExceptionInInitializerError e) { + // Skip classes that can't be loaded + } + } + } catch (Exception e) { + // Silently fail - package might not exist + } + } + + private void scanDirectory(File directory, String packageName, Set classNames) { + scanDirectory(directory, packageName, classNames, new HashSet<>()); + } + + private void scanDirectory(File directory, String packageName, Set classNames, Set excludedPrefixes) { + if (!directory.exists() || !directory.isDirectory()) { + return; + } + + // Check if this package is excluded + for (String excludedPrefix : excludedPrefixes) { + if ((packageName + ".").startsWith(excludedPrefix) || packageName.equals(excludedPrefix.substring(0, excludedPrefix.length() - 1))) { + return; // Skip excluded package + } + } + + File[] files = directory.listFiles(); + if (files == null) { + return; + } + + for (File file : files) { + String fileName = file.getName(); + + if (file.isDirectory()) { + // Recursively scan subdirectory + scanDirectory(file, packageName + "." + fileName, classNames, excludedPrefixes); + } else if (fileName.endsWith(".class")) { + // Add class name + String className = packageName + "." + fileName.substring(0, fileName.length() - 6); + classNames.add(className); + } + } + } + + private void scanJar(String jarPath, String packageName, Set classNames) { + scanJar(jarPath, packageName, classNames, new HashSet<>()); + } + + private void scanJar(String jarPath, String packageName, Set classNames, Set excludedPrefixes) { + try { + JarFile jarFile = new JarFile(jarPath); + Enumeration entries = jarFile.entries(); + String packagePath = packageName.replace('.', '/'); + + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + + if (entryName.startsWith(packagePath) && entryName.endsWith(".class")) { + // Convert path to class name + String className = entryName + .substring(0, entryName.length() - 6) + .replace('/', '.'); + + // Check if this class is in an excluded package + boolean excluded = false; + for (String excludedPrefix : excludedPrefixes) { + if ((className + ".").startsWith(excludedPrefix) || + className.startsWith(excludedPrefix.substring(0, excludedPrefix.length() - 1) + ".")) { + excluded = true; + break; + } + } + + if (!excluded) { + classNames.add(className); + } + } + } + + jarFile.close(); + } catch (Exception e) { + // Silently fail + } + } + + /** + * Find all classes whose simple name starts with the given prefix (case-insensitive). + * Returns fully-qualified class names for all matches, including multiple classes with the same simple name. + */ + public List findByPrefix(String prefix, int maxResults) { + List results = new ArrayList<>(); + String lowerPrefix = prefix.toLowerCase(); + + for (Map.Entry>> entry : simpleNameToClasses.entrySet()) { + if (entry.getKey().toLowerCase().startsWith(lowerPrefix)) { + // Add all classes with this simple name + for (Class clazz : entry.getValue()) { + results.add(clazz.getName()); + + if (maxResults != -1 && results.size() >= maxResults) { + return results; + } + } + } + } + + return results; + } + + /** + * Initialize the index with commonly used Java, Minecraft, and NPC classes. + */ + private void initializeCommonClasses() { + // Java standard library + addClass(String.class); + addClass(Integer.class); + addClass(Double.class); + addClass(Float.class); + addClass(Long.class); + addClass(Boolean.class); + addClass(Character.class); + addClass(Byte.class); + addClass(Short.class); + addClass(Object.class); + addClass(Math.class); + addClass(System.class); + addClass(Thread.class); + addClass(Runnable.class); + addClass(Exception.class); + addClass(RuntimeException.class); + addClass(Error.class); + addClass(Throwable.class); + + // Java collections + addClass(List.class); + addClass(ArrayList.class); + addClass(LinkedList.class); + addClass(Set.class); + addClass(HashSet.class); + addClass(LinkedHashSet.class); + addClass(TreeSet.class); + addClass(Map.class); + addClass(HashMap.class); + addClass(LinkedHashMap.class); + addClass(TreeMap.class); + addClass(Collection.class); + addClass(Iterator.class); + addClass(Comparator.class); + addClass(Collections.class); + addClass(Arrays.class); + addClass(Queue.class); + addClass(Deque.class); + addClass(Stack.class); + addClass(Vector.class); + addClass(Hashtable.class); + + // Java I/O + addClass(java.io.File.class); + addClass(java.io.InputStream.class); + addClass(java.io.OutputStream.class); + addClass(java.io.Reader.class); + addClass(java.io.Writer.class); + addClass(java.io.BufferedReader.class); + addClass(java.io.BufferedWriter.class); + addClass(java.io.FileReader.class); + addClass(java.io.FileWriter.class); + addClass(java.io.IOException.class); + + // Java utilities + addClass(java.util.Random.class); + addClass(java.util.Date.class); + addClass(java.util.Calendar.class); + addClass(java.util.UUID.class); + addClass(java.util.regex.Pattern.class); + addClass(java.util.regex.Matcher.class); + addPackage("java.util.function"); + + // Now add common Minecraft/Forge/NPC packages + addPackage("net.minecraft.entity"); + addPackage("net.minecraft.item"); + addPackage("net.minecraft.block"); + addPackage("net.minecraft.world"); + addPackage("net.minecraft.util"); + addPackage("net.minecraft.nbt"); + addPackage("net.minecraft.potion"); + addPackage("net.minecraft.enchantment"); + addPackage("net.minecraft.inventory"); + addPackage("net.minecraft.tileentity"); + addPackage("net.minecraft.command"); + addPackage("net.minecraft.client"); + + // Forge + addPackage("net.minecraftforge.common"); + addPackage("net.minecraftforge.event"); + addPackage("net.minecraftforge.fml.common"); + + // CustomNPCs + addPackage("noppes.npcs"); + + // DBC (if available) + try { + addPackage("JinRyuu.JRMCore"); + addPackage("JinRyuu.DragonBC"); + addPackage("kamkeel.npcdbc"); + } catch (Exception e) { + // DBC might not be available + } + } +} \ No newline at end of file diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ClassTypeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ClassTypeInfo.java new file mode 100644 index 000000000..ab0888d5d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ClassTypeInfo.java @@ -0,0 +1,158 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Represents a reference to a Java Class itself (not an instance). + * Used for patterns like: var File = Java.type("java.io.File"); + * + * When you have a ClassTypeInfo: + * - Accessing members should show ONLY static members (File.listRoots()) + * - Using 'new' should return an instance of the wrapped class (new File("path")) + * - Calling .constructor(...) should return an instance of the wrapped class + * + * This is distinct from a regular TypeInfo which represents an instance of that type. + */ +public class ClassTypeInfo extends TypeInfo { + + private final TypeInfo instanceType; // The type you get when you do 'new' on this class + private List constructorMethod; + private List classField; + + /** + * Create a ClassTypeInfo wrapping a Java class. + * + * @param javaClass The Java class this represents (e.g., java.io.File.class) + */ + public ClassTypeInfo(Class javaClass) { + super( + javaClass.getSimpleName(), + javaClass.getName(), + javaClass.getPackage() != null ? javaClass.getPackage().getName() : "", + javaClass.isInterface() ? Kind.INTERFACE : (javaClass.isEnum() ? Kind.ENUM : Kind.CLASS), + javaClass, + true, + null, + true // subclass marker + ); + this.instanceType = TypeInfo.fromClass(javaClass); + } + + /** + * Create a ClassTypeInfo from an existing TypeInfo. + */ + public ClassTypeInfo(TypeInfo instanceType) { + super( + instanceType.getSimpleName(), + instanceType.getFullName(), + instanceType.getPackageName(), + instanceType.getKind(), + instanceType.getJavaClass(), + instanceType.isResolved(), + instanceType.getEnclosingType(), + true // subclass marker + ); + this.instanceType = instanceType; + } + + /** + * Returns true - this TypeInfo represents a class reference, not an instance. + */ + @Override + public boolean isClassReference() { + return true; + } + + /** + * Get the TypeInfo for instances of this class. + * This is what you get when you call 'new' on this class. + */ + public TypeInfo getInstanceType() { + return instanceType; + } + + @Override + public List getSyntheticMethods() { + List base = super.getSyntheticMethods(); + + // if (constructorMethod == null) { + constructorMethod = buildConstructorMethod(); + //} + + if (constructorMethod.isEmpty()) { + return base; + } + + List merged = new ArrayList<>(base.size() + constructorMethod.size()); + merged.addAll(base); + merged.addAll(constructorMethod); + return merged; + } + + @Override + public List getSyntheticFields() { + List base = super.getSyntheticFields(); + + if (classField == null) { + classField = buildClassField(); + } + + if (classField.isEmpty()) { + return base; + } + + List merged = new ArrayList<>(base.size() + classField.size()); + merged.addAll(base); + merged.addAll(classField); + return merged; + } + + private List buildConstructorMethod() { + if (instanceType == null) { + return Collections.emptyList(); + } + + FieldInfo argsParam = FieldInfo.parameter("args", TypeInfo.OBJECT, -1, null); + argsParam.setVarArg(true); + + List params = new ArrayList<>(); + params.add(argsParam); + + MethodInfo ctor = MethodInfo.external( + "constructor", + instanceType, + this, + params, + Modifier.PUBLIC | Modifier.STATIC, + "Creates a new instance of " + instanceType.getSimpleName() + ".\n\n" + + "Equivalent to using the 'new' operator on this class reference." + ); + + return Collections.singletonList(ctor); + } + + private List buildClassField() { + if (getJavaClass() == null) { + return Collections.emptyList(); + } + try { + TypeInfo classType = TypeInfo.fromClass(Class.class).parameterize(instanceType); + FieldInfo classField = FieldInfo.external("class", classType, + "The Class object for " + getSimpleName(), Modifier.PUBLIC | Modifier.STATIC); + return Collections.singletonList(classField); + } catch (Exception e) { + return Collections.emptyList(); + } + } + + @Override + public String toString() { + return "Class<" + getSimpleName() + ">"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericContext.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericContext.java new file mode 100644 index 000000000..455e8c6b3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericContext.java @@ -0,0 +1,323 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Single source of truth for generic type variable substitution. + * + * Resolves type parameters (T, E, K, V...) to concrete types using: + * 1. Applied type arguments (e.g., List<String> binds E → String) — priority + * 2. Declared bounds fallback (e.g., <T extends Entity> binds T → Entity) — fallback + * + * Usage patterns: + * - {@link #forReceiver(TypeInfo)} — build context from a parameterized receiver type + * - {@link #fromBindings(List, List)} — build context from explicit params/args (anti-recursion safe) + * - {@link #substitute(TypeInfo)} — instance method with two-tier resolution + */ +public final class GenericContext { + + /** Singleton context for types with no generic parameters. Used to avoid object allocation. */ + private static final GenericContext EMPTY = new GenericContext(new HashMap<>(), new HashMap<>()); + + /** + * Map of type variable names to their applied type arguments. + * For example, in List<String>, this contains E -> TypeInfo.STRING. + * Applied bindings take precedence over bound fallbacks. + */ + private final Map appliedBindings; + + /** + * Map of type variable names to their declared upper bounds. + * For example, in <T extends Entity>, this contains T -> TypeInfo(Entity). + * Used as fallback when no applied argument exists. + */ + private final Map boundFallbacks; + + private GenericContext(Map appliedBindings, Map boundFallbacks) { + this.appliedBindings = appliedBindings != null ? appliedBindings : new HashMap<>(); + this.boundFallbacks = boundFallbacks != null ? boundFallbacks : new HashMap<>(); + } + + /** + * Create a GenericContext directly from declared type parameters and applied type arguments. + * + * Unlike {@link #forReceiver(TypeInfo)}, this does NOT introspect a TypeInfo, so it cannot + * trigger recursive parameterization. Use this inside {@code parameterize()} implementations + * to avoid the cycle: parameterize → forReceiver → substitute → parameterize. + * + * @param declaredParams the declared type parameters (e.g., [T, E]) + * @param appliedArgs the applied type arguments (e.g., [String, Integer]) + * @return a context mapping param names to applied args (with bound fallbacks for unmatched params) + */ + public static GenericContext fromBindings(List declaredParams, List appliedArgs) { + if (declaredParams == null || declaredParams.isEmpty()) { + return EMPTY; + } + + Map applied = new HashMap<>(); + if (appliedArgs != null) { + int count = Math.min(declaredParams.size(), appliedArgs.size()); + for (int i = 0; i < count; i++) { + TypeParamInfo declared = declaredParams.get(i); + TypeInfo arg = appliedArgs.get(i); + if (declared == null || declared.getName() == null || declared.getName().isEmpty() || arg == null) { + continue; + } + applied.put(declared.getName(), arg); + } + } + + Map bounds = new HashMap<>(); + for (TypeParamInfo declared : declaredParams) { + if (declared == null) continue; + String name = declared.getName(); + if (name == null || name.isEmpty()) continue; + TypeInfo tp = TypeInfo.typeParameter(name, declared); + TypeInfo effectiveBound = tp.getBoundType(); + bounds.put(name, effectiveBound != null ? effectiveBound : TypeInfo.OBJECT); + } + + return new GenericContext(applied, bounds); + } + + /** + * Create a GenericContext for a receiver type. + * + * Fast path: returns singleton EMPTY for non-generic types (no allocation overhead). + * Slow path: builds maps from type parameters and applied arguments for generic types. + * + * @param receiverType the type to extract generic bindings from (e.g., List<String>, DAO<T extends Entity>) + * @return a context with applied bindings and bound fallbacks, or EMPTY singleton if receiverType is not generic + */ + public static GenericContext forReceiver(TypeInfo receiverType) { + // Special edge case: Array.d.ts JS type, bind T to element type so Array methods resolve correctly + if (receiverType != null && receiverType.isArray() && receiverType.getElementType() != null) { + Map applied = new HashMap<>(); + applied.put("T", receiverType.getElementType()); + return new GenericContext(applied, new HashMap<>()); + } + + // Fast path: return singleton for non-generic types + if (receiverType == null || !hasGenerics(receiverType)) { + return EMPTY; + } + + TypeInfo rawType = receiverType.getRawType(); + List declaredParams = rawType != null ? rawType.getTypeParams() : null; + List appliedArgs = receiverType.getAppliedTypeArgs(); + + Map applied = new HashMap<>(); + if (declaredParams != null && appliedArgs != null) { + int count = Math.min(declaredParams.size(), appliedArgs.size()); + for (int i = 0; i < count; i++) { + TypeParamInfo declared = declaredParams.get(i); + TypeInfo arg = appliedArgs.get(i); + if (declared == null || declared.getName() == null || declared.getName().isEmpty() || arg == null) { + continue; + } + applied.put(declared.getName(), arg); + } + } + + Map bounds = new HashMap<>(); + if (declaredParams != null) { + for (TypeParamInfo declared : declaredParams) { + if (declared == null) continue; + String name = declared.getName(); + if (name == null || name.isEmpty()) continue; + TypeInfo tp = TypeInfo.typeParameter(name, declared); + TypeInfo effectiveBound = tp.getBoundType(); + bounds.put(name, effectiveBound != null ? effectiveBound : TypeInfo.OBJECT); + } + } + + return new GenericContext(applied, bounds); + } + + /** + * Check if a type has generics that need substitution. + * + * Returns true if: + * - Type is parameterized (e.g., List<String>) + * - Type's raw form differs from the type itself + * - Type has declared type parameters + * + * @param type the type to check + * @return true if this type contains generic information that may need substitution + */ + public static boolean hasGenerics(TypeInfo type) { + return type.isParameterized() || + type.getRawType() != type || + (type.getTypeParams() != null && !type.getTypeParams().isEmpty()); + } + + /** + * Resolve a type variable to its bound or applied type. + * + * Prefers applied bindings (e.g., E -> String in List<String>) over declared bounds. + * Falls back to bounds (e.g., T -> Entity in <T extends Entity>) if no applied argument exists. + * Returns null if the variable is not found in either map. + * + * @param name the type variable name (e.g., "T", "E", "K") + * @return the resolved TypeInfo, or null if variable not found + */ + public TypeInfo resolveTypeVariable(String name) { + if (name == null || name.isEmpty()) { + return null; + } + + TypeInfo applied = appliedBindings.get(name); + if (applied != null) { + return applied; + } + + return boundFallbacks.get(name); + } + + /** + * Substitute type variables in a TypeInfo recursively. + * + * Handles: + * - Direct type variables (unresolved types representing T, E, etc.) + * - Parameterized types (recursively substitutes inside type arguments) + * - Array types (substitutes the element type, preserves array dimensions) + * + * @param type the type to substitute (may contain type variables) + * @return the substituted type, or the original type if no substitutions apply + */ + public TypeInfo substitute(TypeInfo type) { + if (type == null) { + return null; + } + + // Direct type variable substitution. + // Handles unresolved types (Java reflection path) and TypeInfo.typeParameter() (script-defined path). + if (!type.isResolved() || type.isTypeParameter()) { + String lookupKey = type.isTypeParameter() ? type.getTypeParameterName() : type.getSimpleName(); + TypeInfo substitution = resolveTypeVariable(lookupKey); + if (substitution != null) { + return substitution; + } + } + + // Parameterized types: substitute inside args. + if (type.isParameterized()) { + List originalArgs = type.getAppliedTypeArgs(); + List substitutedArgs = new ArrayList<>(originalArgs.size()); + boolean changed = false; + + for (TypeInfo arg : originalArgs) { + TypeInfo substitutedArg = substitute(arg); + substitutedArgs.add(substitutedArg); + if (substitutedArg != arg) { + changed = true; + } + } + + if (changed) { + return type.getRawType().parameterize(substitutedArgs); + } + } + + // Array wrapper types are represented by a display-name suffix; we can still substitute + // a plain "T[]" by looking up "T". + String simple = type.getSimpleName(); + if (simple != null && simple.endsWith("[]")) { + TypeStringNormalizer.ArraySplit split = TypeStringNormalizer.splitArraySuffixes(simple); + String elementName = split.base; + int dims = split.dimensions; + TypeInfo elementSub = resolveTypeVariable(elementName); + if (elementSub != null) { + TypeInfo result = elementSub; + for (int i = 0; i < dims; i++) { + result = TypeInfo.arrayOf(result); + } + return result; + } + } + + return type; + } + + /** + * Substitute type variables in a type string. + * + * Attempts substitution in this order: + * 1. Normalize the string (strip imports, pick union branch, remove nullable suffix, split arrays) + * 2. Try direct type variable lookup (e.g., "T" -> resolved Entity) + * 3. Fall back to full type resolution with substitution applied + * + * @param typeString the type expression as a string (e.g., "T", "T[]", "List<T>") + * @param resolver optional TypeResolver for fallback resolution; if null, returns null on failure + * @return the substituted type, or null if resolution fails + */ + public TypeInfo substituteString(String typeString, TypeResolver resolver) { + if (typeString == null || typeString.trim().isEmpty()) { + return null; + } + + String normalized = TypeStringNormalizer.stripImportTypeSyntax(typeString); + normalized = TypeStringNormalizer.pickPreferredUnionBranch(normalized); + normalized = TypeStringNormalizer.stripNullableSuffix(normalized); + + TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalized); + String baseExpr = arraySplit.base; + int dims = arraySplit.dimensions; + + String bareBase = GenericTypeParser.stripGenerics(baseExpr); + TypeInfo direct = resolveTypeVariable(bareBase); + if (direct != null) { + TypeInfo result = direct; + for (int i = 0; i < dims; i++) { + result = TypeInfo.arrayOf(result); + } + return result; + } + + if (resolver == null) { + return null; + } + TypeInfo resolved = resolver.resolveJSType(typeString); + return substitute(resolved); + } + + /** + * Substitute type variables in a resolved type, with string fallback. + * + * Two-phase approach: + * 1. Try substituting the resolved type directly + * 2. If that fails, attempt substitution via the raw string as fallback + * + * This handles edge cases where the TypeInfo doesn't capture enough information + * to do proper substitution (e.g., union types, complex generics). + * + * @param resolvedType a TypeInfo that has already been resolved (may still contain type variables) + * @param rawTypeString the original type string before resolution (for fallback) + * @param resolver optional TypeResolver for string-based fallback resolution + * @return the substituted type, or the best attempt if full substitution fails + */ + public TypeInfo substituteType(TypeInfo resolvedType, String rawTypeString, TypeResolver resolver) { + if (resolvedType == null) { + return null; + } + + TypeInfo substituted = substitute(resolvedType); + if (substituted != null && substituted.isResolved()) { + return substituted; + } + + if (rawTypeString != null && !rawTypeString.trim().isEmpty()) { + TypeInfo fromString = substituteString(rawTypeString, resolver); + if (fromString != null && fromString.isResolved()) { + return fromString; + } + } + + return substituted; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericParameterAdapter.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericParameterAdapter.java new file mode 100644 index 000000000..cda297a4c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericParameterAdapter.java @@ -0,0 +1,171 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentMap; + +/** + * Adapts {@code Object}-typed method parameters to the receiver's generic type arguments + * for editor display (autocomplete/hover). + *

+ * Java collections use {@code Object} in certain method signatures for backward-compatibility + * (e.g., {@code Map.get(Object)} instead of {@code Map.get(K)}). This adapter maps those + * {@code Object} parameters back to the appropriate generic type argument when the receiver + * is parameterized (e.g., {@code Map}). + *

+ * Design rules: + *

    + *
  • Only contract-level checks using {@code java.util.Map}, {@code java.util.Collection}, + * {@code java.util.List} assignability — never concrete classes like HashMap/ArrayList.
  • + *
  • Only adapts when the reflected parameter type is exactly {@code java.lang.Object} + * AND the receiver is parameterized with applied type args.
  • + *
  • Table-driven: each rule is a {@link Rule} record in a static list.
  • + *
+ */ +public final class GenericParameterAdapter { + + // ==================== Rule Model ==================== + + /** + * A single adaptation rule. + * + * @see #RULES + */ + private static final class Rule { + /** The contract interface (e.g., {@code java.util.Map}). */ + final Class contractType; + /** Method name to match. */ + final String methodName; + /** Total parameter count the method must have. */ + final int paramCount; + /** The parameter index to adapt (0-based). */ + final int paramIndex; + /** Index into the receiver's applied type args (0-based). 0=K/E, 1=V, etc. */ + final int typeArgIndex; + + Rule(Class contractType, String methodName, int paramCount, int paramIndex, int typeArgIndex) { + this.contractType = contractType; + this.methodName = methodName; + this.paramCount = paramCount; + this.paramIndex = paramIndex; + this.typeArgIndex = typeArgIndex; + } + } + + // ==================== Rule Table ==================== + + private static final List RULES; + + static { + List rules = new ArrayList<>(); + + // Map + rules.add(new Rule(java.util.Map.class, "get", 1, 0, 0)); + rules.add(new Rule(java.util.Map.class, "containsKey", 1, 0, 0)); + rules.add(new Rule(java.util.Map.class, "containsValue", 1, 0, 1)); + rules.add(new Rule(java.util.Map.class, "remove", 1, 0, 0)); + rules.add(new Rule(java.util.Map.class, "remove", 2, 0, 0)); + rules.add(new Rule(java.util.Map.class, "remove", 2, 1, 1)); + rules.add(new Rule(java.util.Map.class, "getOrDefault", 2, 0, 0)); + + // ConcurrentMap (get/containsKey/containsValue inherited from Map above) + rules.add(new Rule(java.util.concurrent.ConcurrentMap.class, "remove", 2, 0, 0)); + rules.add(new Rule(java.util.concurrent.ConcurrentMap.class, "remove", 2, 1, 1)); + rules.add(new Rule(java.util.concurrent.ConcurrentMap.class, "getOrDefault", 2, 0, 0)); + + // Collection + rules.add(new Rule(java.util.Collection.class, "contains", 1, 0, 0)); + rules.add(new Rule(java.util.Collection.class, "remove", 1, 0, 0)); + + // List (contains/remove covered by Collection above) + rules.add(new Rule(java.util.List.class, "indexOf", 1, 0, 0)); + rules.add(new Rule(java.util.List.class, "lastIndexOf", 1, 0, 0)); + + // Set (contains/remove covered by Collection above) + + // Deque + rules.add(new Rule(java.util.Deque.class, "contains", 1, 0, 0)); + rules.add(new Rule(java.util.Deque.class, "remove", 1, 0, 0)); + rules.add(new Rule(java.util.Deque.class, "removeFirstOccurrence", 1, 0, 0)); + rules.add(new Rule(java.util.Deque.class, "removeLastOccurrence", 1, 0, 0)); + + // BlockingQueue (contains/remove covered by Collection above) + rules.add(new Rule(java.util.concurrent.BlockingQueue.class, "remove", 1, 0, 0)); + rules.add(new Rule(java.util.concurrent.BlockingQueue.class, "contains", 1, 0, 0)); + + // BlockingDeque + rules.add(new Rule(java.util.concurrent.BlockingDeque.class, "remove", 1, 0, 0)); + rules.add(new Rule(java.util.concurrent.BlockingDeque.class, "contains", 1, 0, 0)); + rules.add(new Rule(java.util.concurrent.BlockingDeque.class, "removeFirstOccurrence", 1, 0, 0)); + rules.add(new Rule(java.util.concurrent.BlockingDeque.class, "removeLastOccurrence", 1, 0, 0)); + + RULES = Collections.unmodifiableList(rules); + } + + // ==================== Public API ==================== + + /** + * Attempt to adapt a parameter type from {@code Object} to the receiver's generic type argument. + *

+ * Returns the adapted {@link TypeInfo} if all conditions are met: + *

    + *
  1. The receiver is parameterized and has applied type args.
  2. + *
  3. The parameter's current type is exactly {@code java.lang.Object}.
  4. + *
  5. A matching rule exists in the rule table.
  6. + *
  7. The rule's required type arg index is within bounds.
  8. + *
+ * Otherwise returns {@code null} (meaning: keep the original type). + * + * @param method the reflected Java method + * @param receiverType the parameterized receiver TypeInfo (e.g., {@code Map}) + * @param paramIndex the index of the parameter being checked + * @param currentType the current TypeInfo for that parameter (after normal substitution) + * @return adapted TypeInfo, or {@code null} if no adaptation applies + */ + public static TypeInfo adaptParameterType(Method method, TypeInfo receiverType, + int paramIndex, TypeInfo currentType) { + // Guard: only adapt Object params on parameterized receivers + if (receiverType == null || !receiverType.isParameterized()) { + return null; + } + if (currentType == null || currentType.getJavaClass() != Object.class) { + return null; + } + + List appliedArgs = receiverType.getAppliedTypeArgs(); + if (appliedArgs == null || appliedArgs.isEmpty()) { + return null; + } + + // Determine the declaring class of the method + Class declaringClass = method.getDeclaringClass(); + String methodName = method.getName(); + int paramCount = method.getParameterCount(); + + // Scan rules for a match + for (Rule rule : RULES) { + if (rule.paramIndex != paramIndex) continue; + if (rule.paramCount != paramCount) continue; + if (!rule.methodName.equals(methodName)) continue; + if (!rule.contractType.isAssignableFrom(declaringClass)) continue; + + // Rule matches — check if the type arg index is within bounds + if (rule.typeArgIndex < appliedArgs.size()) { + TypeInfo adapted = appliedArgs.get(rule.typeArgIndex); + if (adapted != null && adapted.isResolved()) { + return adapted; + } + } + } + + return null; + } + + private GenericParameterAdapter() { + // Utility class — no instantiation + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericTypeParser.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericTypeParser.java new file mode 100644 index 000000000..727c85388 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericTypeParser.java @@ -0,0 +1,325 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import java.util.ArrayList; +import java.util.List; + +/** + * Parser for generic type expressions with nested type arguments. + * + * Handles type expressions like: + * - Simple types: "String", "IPlayer" + * - Qualified names: "java.util.List", "IPlayerEvent.InteractEvent" + * - Single generic: "List", "Consumer" + * - Multiple generics: "Map" + * - Nested generics: "List>" + * + * Note: union/nullability/array semantics are handled by higher-level resolvers. + * This parser only consumes suffix tokens where needed to correctly delimit type arguments. + * + * This parser produces a ParsedType tree that can be resolved into parameterized TypeInfo instances. + */ +public class GenericTypeParser { + + /** + * Represents a parsed type expression with potential generic arguments. + */ + public static class ParsedType { + /** The base type name (may be qualified, e.g., "java.util.List" or "IPlayer") */ + public final String baseName; + + /** The applied type arguments (for generics like List), each is itself a ParsedType */ + public final List typeArgs; + + /** The original raw string before parsing */ + public final String rawString; + + public ParsedType(String baseName, List typeArgs, String rawString) { + this.baseName = baseName; + this.typeArgs = typeArgs != null ? typeArgs : new ArrayList<>(); + this.rawString = rawString; + } + + /** + * Check if this parsed type has generic arguments. + */ + public boolean hasTypeArgs() { + return !typeArgs.isEmpty(); + } + + /** + * Get display string for debugging. + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(baseName); + if (!typeArgs.isEmpty()) { + sb.append("<"); + for (int i = 0; i < typeArgs.size(); i++) { + if (i > 0) sb.append(", "); + sb.append(typeArgs.get(i).toString()); + } + sb.append(">"); + } + return sb.toString(); + } + } + + /** + * Parse a type expression string into a ParsedType tree. + * + * @param typeExpr The type expression to parse (e.g., "List>[]") + * @return The parsed type, or null if parsing fails + */ + public static ParsedType parse(String typeExpr) { + if (typeExpr == null || typeExpr.isEmpty()) { + return null; + } + + String expr = typeExpr.trim(); + + // Now parse the base type with potential generic arguments + ParseResult result = parseTypeWithGenerics(expr, 0); + if (result == null || result.type == null) { + // Fallback: treat entire expression as a simple type + return new ParsedType(expr, null, typeExpr); + } + + return result.type; + } + + /** + * Internal result class for recursive parsing. + */ + private static class ParseResult { + final ParsedType type; + final int endIndex; // position after this type in the string + + ParseResult(ParsedType type, int endIndex) { + this.type = type; + this.endIndex = endIndex; + } + } + + /** + * Parse a type expression starting at the given index, handling nested generics. + * Returns the parsed type and the index after this type expression. + */ + private static ParseResult parseTypeWithGenerics(String expr, int startIndex) { + int i = startIndex; + int len = expr.length(); + + // Skip leading whitespace + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + if (i >= len) { + return null; + } + + // Read the base type name (can include dots for qualified names) + StringBuilder baseNameBuilder = new StringBuilder(); + while (i < len) { + char c = expr.charAt(i); + if (Character.isJavaIdentifierPart(c) || c == '.') { + baseNameBuilder.append(c); + i++; + } else { + break; + } + } + String baseName = baseNameBuilder.toString().trim(); + + if (baseName.isEmpty()) { + return null; + } + + // Remove trailing dots if any + while (baseName.endsWith(".")) { + baseName = baseName.substring(0, baseName.length() - 1); + } + + // Skip whitespace before potential < + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + // Check for generic arguments + List typeArgs = new ArrayList<>(); + if (i < len && expr.charAt(i) == '<') { + i++; // Skip '<' + + // Parse type arguments (comma-separated, handling nested <>) + while (i < len) { + // Skip whitespace + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + if (i >= len) break; + + char c = expr.charAt(i); + if (c == '>') { + i++; // Skip '>' + break; + } + + if (c == ',') { + i++; // Skip ',' + continue; + } + + // Parse a type argument (may itself have generics) + ParseResult argResult = parseTypeArgument(expr, i); + if (argResult != null && argResult.type != null) { + typeArgs.add(argResult.type); + i = argResult.endIndex; + } else { + // Skip forward until the next ',' or '>' at the current nesting level. + i = skipToNextTypeArgDelimiter(expr, i); + } + } + } + + ParsedType type = new ParsedType(baseName, typeArgs, expr.substring(startIndex, i)); + return new ParseResult(type, i); + } + + /** + * Skip forward until we hit ',' or '>' that would delimit a type argument. + * This prevents producing spurious additional type args when encountering unsupported syntax. + */ + private static int skipToNextTypeArgDelimiter(String expr, int startIndex) { + int i = startIndex; + int depth = 0; + boolean inString = false; + char stringChar = 0; + while (i < expr.length()) { + char c = expr.charAt(i); + if (inString) { + if (c == stringChar && (i == 0 || expr.charAt(i - 1) != '\\')) { + inString = false; + } + i++; + continue; + } + + if (c == '\'' || c == '"') { + inString = true; + stringChar = c; + i++; + continue; + } + + if (c == '<' || c == '(' || c == '[') { + depth++; + } else if (c == '>' || c == ')' || c == ']') { + if (depth > 0) { + depth--; + } else if (c == '>') { + return i; // Let caller handle closing '>' + } + } else if ((c == ',' || c == '>') && depth == 0) { + return i; + } + i++; + } + return i; + } + + /** + * Parse a single type argument, which may include nested generics and array suffixes. + */ + private static ParseResult parseTypeArgument(String expr, int startIndex) { + int i = startIndex; + int len = expr.length(); + + // Skip leading whitespace + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + if (i >= len) { + return null; + } + + // Check for wildcard (? extends X, ? super X, or just ?) + if (expr.charAt(i) == '?') { + i++; + // Skip whitespace + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + // Check for "extends" or "super" + if (i < len && expr.substring(i).startsWith("extends ")) { + i += 8; // Skip "extends " + // Parse the bound type + ParseResult boundResult = parseTypeWithGenerics(expr, i); + if (boundResult != null) { + return boundResult; + } + } else if (i < len && expr.substring(i).startsWith("super ")) { + i += 6; // Skip "super " + // Parse the bound type + ParseResult boundResult = parseTypeWithGenerics(expr, i); + if (boundResult != null) { + return boundResult; + } + } + // Plain wildcard, treat as Object + return new ParseResult(new ParsedType("Object", null, "?"), i); + } + + // Parse regular type with potential generics + ParseResult typeResult = parseTypeWithGenerics(expr, i); + if (typeResult == null) { + return null; + } + + i = typeResult.endIndex; + ParsedType baseType = typeResult.type; + + // Skip whitespace + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + + // Consume array suffixes / nullable suffix so the caller can correctly find delimiters. + while (i + 1 < len && expr.charAt(i) == '[' && expr.charAt(i + 1) == ']') { + i += 2; + while (i < len && Character.isWhitespace(expr.charAt(i))) { + i++; + } + } + if (i < len && expr.charAt(i) == '?') { + i++; + } + + // Preserve the full raw substring (including suffixes) for higher-level resolvers. + if (i != typeResult.endIndex) { + return new ParseResult(new ParsedType(baseType.baseName, baseType.typeArgs, expr.substring(startIndex, i)), i); + } + + return new ParseResult(baseType, i); + } + + /** + * Convenience method to check if a type string contains generic arguments. + */ + public static boolean hasGenerics(String typeExpr) { + return typeExpr != null && typeExpr.contains("<") && typeExpr.contains(">"); + } + + /** + * Strip generic arguments from a type string (for base type lookup). + * Example: "List" -> "List" + */ + public static String stripGenerics(String typeExpr) { + if (typeExpr == null) return null; + int idx = typeExpr.indexOf('<'); + if (idx > 0) { + return typeExpr.substring(0, idx).trim(); + } + return typeExpr; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ImportData.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ImportData.java new file mode 100644 index 000000000..cda544a98 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ImportData.java @@ -0,0 +1,183 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.token.Token; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Represents a single import statement with all its metadata. + * Tracks the full import path, resolution status, source positions, and references. + */ +public final class ImportData { + + private final String fullPath; // e.g., "java.util.List" or "kamkeel.npcdbc.api.*" + private final String simpleName; // e.g., "List" or null for wildcard + private final boolean isWildcard; // true if ends with .* + private final boolean isStatic; // true if 'import static' + private final int startOffset; // start of 'import' keyword in source + private final int endOffset; // end of import statement (before or at semicolon) + private final int pathStartOffset; // start of the package.Class path + private final int pathEndOffset; // end of the package.Class path (before .*) + + private TypeInfo resolvedType; // null if wildcard or unresolved + private boolean resolved; // whether resolution was attempted and succeeded + + // Track usage count (simpler than tracking individual tokens) + private int usageCount = 0; + + // Track all tokens that reference this import (optional, for detailed analysis) + private final List referencingTokens = new ArrayList<>(); + + public ImportData(String fullPath, String simpleName, boolean isWildcard, boolean isStatic, + int startOffset, int endOffset, int pathStartOffset, int pathEndOffset) { + this.fullPath = fullPath; + this.simpleName = simpleName; + this.isWildcard = isWildcard; + this.isStatic = isStatic; + this.startOffset = startOffset; + this.endOffset = endOffset; + this.pathStartOffset = pathStartOffset; + this.pathEndOffset = pathEndOffset; + this.resolved = false; + } + + // Getters + public String getFullPath() { return fullPath; } + public String getSimpleName() { return simpleName; } + public boolean isWildcard() { return isWildcard; } + public boolean isStatic() { return isStatic; } + public int getStartOffset() { return startOffset; } + public int getEndOffset() { return endOffset; } + public int getPathStartOffset() { return pathStartOffset; } + public int getPathEndOffset() { return pathEndOffset; } + public TypeInfo getResolvedType() { return resolvedType; } + public boolean isResolved() { return resolved; } + + /** + * Set the resolved type information. + */ + public void setResolvedType(TypeInfo typeInfo) { + this.resolvedType = typeInfo; + this.resolved = typeInfo != null && typeInfo.isResolved(); + } + + /** + * Mark this import as resolved (for wildcard imports where we confirm the package exists). + */ + public void markResolved(boolean resolved) { + this.resolved = resolved; + } + + // ==================== REFERENCE TRACKING ==================== + + /** + * Increment the usage count for this import. + * Called during type resolution when this import is used. + */ + public void incrementUsage() { + usageCount++; + } + + /** + * Add a token that references this import. + * Called when a token is created that uses this import's type. + */ + public void addReference(Token token) { + if (token != null && !referencingTokens.contains(token)) { + referencingTokens.add(token); + } + } + + /** + * Get all tokens that reference this import. + */ + public List getReferencingTokens() { + return Collections.unmodifiableList(referencingTokens); + } + + /** + * Check if this import is used (has any references or usages). + */ + public boolean isUsed() { + return usageCount > 0 || !referencingTokens.isEmpty(); + } + + /** + * Get the usage count for this import. + */ + public int getUsageCount() { + return usageCount; + } + + /** + * Get the number of references to this import. + */ + public int getReferenceCount() { + return referencingTokens.size(); + } + + /** + * Clear all references and reset usage count (used when re-tokenizing). + */ + public void clearReferences() { + referencingTokens.clear(); + usageCount = 0; + } + + /** + * Get the package portion of the import path. + * For "java.util.List" returns "java.util" + * For wildcards like "java.util.*" returns "java.util" + */ + public String getPackagePortion() { + if (isWildcard) { + return fullPath; + } + int lastDot = fullPath.lastIndexOf('.'); + return lastDot > 0 ? fullPath.substring(0, lastDot) : ""; + } + + /** + * Get all segments of the import path. + */ + public String[] getPathSegments() { + return fullPath.split("\\."); + } + + /** + * Check if this import could provide the given simple class name. + * For wildcard imports, always returns true (might provide any class). + * For specific imports, checks if the simple name matches. + */ + public boolean couldProvide(String className) { + if (isWildcard) { + return true; + } + return className.equals(simpleName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("import "); + if (isStatic) sb.append("static "); + sb.append(fullPath); + if (isWildcard) sb.append(".*"); + sb.append(" [").append(resolved ? "resolved" : "unresolved").append("]"); + return sb.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ImportData that = (ImportData) o; + return fullPath.equals(that.fullPath) && isWildcard == that.isWildcard && isStatic == that.isStatic; + } + + @Override + public int hashCode() { + return fullPath.hashCode() * 31 + (isWildcard ? 1 : 0) + (isStatic ? 2 : 0); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/IntersectionTypeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/IntersectionTypeInfo.java new file mode 100644 index 000000000..74e039559 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/IntersectionTypeInfo.java @@ -0,0 +1,160 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Represents an intersection type from multiple bounds on a type parameter. + * For example, {@code >} creates an intersection + * of Number and Comparable. + * + *

The primary bound determines the display name and main type identity. + * Member lookup (hasMethod, getMethodInfo, hasField, getFieldInfo, getAllMethodOverloads) + * delegates to ALL constituent types, so methods from any bound are accessible.

+ * + *

This is used by {@link GenericContext} when building bound fallbacks for type + * parameters with additional interface bounds.

+ */ +public class IntersectionTypeInfo extends TypeInfo { + + /** The primary (first) bound type — used for display and as the "main" type. */ + private final TypeInfo primaryBound; + + /** Additional interface bounds (everything after {@code &}). */ + private final List additionalBounds; + + private IntersectionTypeInfo(TypeInfo primaryBound, List additionalBounds) { + super(primaryBound.getSimpleName(), primaryBound.getFullName(), "", + primaryBound.getKind(), primaryBound.getJavaClass(), true, null, true); + this.primaryBound = primaryBound; + this.additionalBounds = additionalBounds; + } + + /** + * Create an intersection type from a primary bound and additional interface bounds. + * If there are no additional bounds, returns the primary bound directly (no wrapper). + * + * @param primary the primary (first) bound type + * @param additional the additional interface bounds (may be empty) + * @return an IntersectionTypeInfo if there are additional bounds, otherwise the primary itself + */ + public static TypeInfo of(TypeInfo primary, List additional) { + if (additional == null || additional.isEmpty()) { + return primary; + } + return new IntersectionTypeInfo(primary, new ArrayList<>(additional)); + } + + @Override + public boolean hasMethod(String methodName) { + if (primaryBound.hasMethod(methodName)) return true; + for (TypeInfo bound : additionalBounds) { + if (bound.hasMethod(methodName)) return true; + } + return false; + } + + @Override + public boolean hasMethod(String methodName, int paramCount) { + if (primaryBound.hasMethod(methodName, paramCount)) return true; + for (TypeInfo bound : additionalBounds) { + if (bound.hasMethod(methodName, paramCount)) return true; + } + return false; + } + + @Override + public MethodInfo getMethodInfo(String methodName) { + MethodInfo m = primaryBound.getMethodInfo(methodName); + if (m != null) return m; + for (TypeInfo bound : additionalBounds) { + m = bound.getMethodInfo(methodName); + if (m != null) return m; + } + return null; + } + + @Override + public List getAllMethodOverloads(String methodName) { + Set seen = new LinkedHashSet<>(); + seen.addAll(primaryBound.getAllMethodOverloads(methodName)); + for (TypeInfo bound : additionalBounds) { + seen.addAll(bound.getAllMethodOverloads(methodName)); + } + return new ArrayList<>(seen); + } + + @Override + public MethodInfo getBestMethodOverload(String methodName, TypeInfo[] argTypes) { + MethodInfo m = primaryBound.getBestMethodOverload(methodName, argTypes); + if (m != null) return m; + for (TypeInfo bound : additionalBounds) { + m = bound.getBestMethodOverload(methodName, argTypes); + if (m != null) return m; + } + return null; + } + + @Override + public MethodInfo getBestMethodOverload(String methodName, TypeInfo expectedReturnType) { + MethodInfo m = primaryBound.getBestMethodOverload(methodName, expectedReturnType); + if (m != null) return m; + for (TypeInfo bound : additionalBounds) { + m = bound.getBestMethodOverload(methodName, expectedReturnType); + if (m != null) return m; + } + return null; + } + + @Override + public boolean hasField(String fieldName) { + if (primaryBound.hasField(fieldName)) return true; + for (TypeInfo bound : additionalBounds) { + if (bound.hasField(fieldName)) return true; + } + return false; + } + + @Override + public FieldInfo getFieldInfo(String fieldName) { + FieldInfo f = primaryBound.getFieldInfo(fieldName); + if (f != null) return f; + for (TypeInfo bound : additionalBounds) { + f = bound.getFieldInfo(fieldName); + if (f != null) return f; + } + return null; + } + + public TypeInfo getPrimaryBound() { + return primaryBound; + } + + public List getAdditionalBounds() { + return new ArrayList<>(additionalBounds); + } + + @Override + public String getDisplayName() { + StringBuilder sb = new StringBuilder(primaryBound.getDisplayName()); + for (TypeInfo bound : additionalBounds) { + sb.append(" & ").append(bound.getDisplayName()); + } + return sb.toString(); + } + + @Override + public boolean isResolved() { + return true; + } + + @Override + public String toString() { + return "IntersectionTypeInfo{" + getDisplayName() + "}"; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/NashornBuiltins.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/NashornBuiltins.java new file mode 100644 index 000000000..962b5b11a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/NashornBuiltins.java @@ -0,0 +1,282 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticMethod; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticParameter; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticTypeBuilder; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticType; + +import java.util.*; + +/** + * Registry for Nashorn built-in types and global functions. + * + *

Nashorn provides several built-in objects and functions:

+ *
    + *
  • Java - Object for Java interop: type(), extend(), from(), to()
  • + *
  • Packages - Root of package hierarchy for accessing Java packages
  • + *
  • JavaImporter - Creates scope with imported Java packages
  • + *
  • print() - Global print function
  • + *
  • load() - Load and execute a script
  • + *
+ */ +public class NashornBuiltins { + + private static NashornBuiltins instance; + + private final Map builtinTypes = new LinkedHashMap<>(); + private final Map globalFunctions = new LinkedHashMap<>(); + + private NashornBuiltins() { + initializeBuiltins(); + } + + public static NashornBuiltins getInstance() { + if (instance == null) { + instance = new NashornBuiltins(); + } + return instance; + } + + private void initializeBuiltins() { + // ==================== Java object ==================== + SyntheticType javaType = new SyntheticTypeBuilder("Java") + .documentation("Nashorn's Java interop object for accessing Java types and utilities.") + + .addMethod("type") + .parameter("className", "String", "Fully-qualified Java class name") + .returns("java.lang.Class") + .returnsResolved(args -> { + if (args != null && args.length > 0 && args[0] != null) { + String className = args[0]; + // Remove quotes if present + if (className.startsWith("\"") && className.endsWith("\"")) { + className = className.substring(1, className.length() - 1); + } else if (className.startsWith("'") && className.endsWith("'")) { + className = className.substring(1, className.length() - 1); + } + // Try to load the class + TypeInfo resolved = TypeResolver.getInstance().resolve(className); + if (resolved != null && resolved.isResolved()) { + return new ClassTypeInfo(resolved); + } + } + return null; + }) + .documentation("Loads a Java class by its fully-qualified name.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "var File = Java.type(\"java.io.File\");\n" + + "var file = new File(\"path/to/file\");\n" + + "```\n\n" + + "@param className The fully-qualified Java class name\n" + + "@returns The Java class reference (use with 'new' to create instances)") + .done() + + .addMethod("extend") + .parameter("type", "java.lang.Class", "Java class or interface to extend/implement") + .returns("java.lang.Class") + .documentation("Creates a subclass or implementation of a Java class or interface.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "var MyRunnable = Java.extend(Java.type(\"java.lang.Runnable\"), {\n" + + " run: function() {\n" + + " print(\"Running!\");\n" + + " }\n" + + "});\n" + + "```\n\n" + + "@param type The Java class or interface to extend\n" + + "@returns A new class that extends/implements the given type") + .done() + + .addMethod("from") + .parameter("javaArray", "Object", "A Java array or Collection") + .returns("Object[]") + .documentation("Converts a Java array or Collection to a JavaScript array.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "var jsList = Java.from(javaArrayList);\n" + + "jsList.forEach(function(item) { print(item); });\n" + + "```\n\n" + + "@param javaArray A Java array or java.util.Collection\n" + + "@returns A JavaScript array containing the elements") + .done() + + .addMethod("to") + .parameter("jsArray", "Object[]", "A JavaScript array") + .parameter("javaType", "Class", "The target Java array type") + .returns("Object") + .documentation("Converts a JavaScript array to a Java array of the specified type.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "var jsArray = [1, 2, 3];\n" + + "var intArray = Java.to(jsArray, \"int[]\");\n" + + "```\n\n" + + "@param jsArray A JavaScript array\n" + + "@param javaType The target Java array type (e.g., \"int[]\", \"java.lang.String[]\")\n" + + "@returns A Java array of the specified type") + .done() + + .addMethod("super") + .parameter("object", "Object", "A Java object created via Java.extend()") + .returns("Object") + .documentation("Gets a reference to the super class for calling super methods.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "var MyList = Java.extend(Java.type(\"java.util.ArrayList\"), {\n" + + " add: function(e) {\n" + + " print(\"Adding: \" + e);\n" + + " return Java.super(this).add(e);\n" + + " }\n" + + "});\n" + + "```\n\n" + + "@param object An extended Java object\n" + + "@returns A reference to call super methods") + .done() + + .addMethod("synchronized") + .parameter("func", "java.util.function.Function", "The function to synchronize") + .parameter("lock", "Object", "The object to synchronize on") + .returns("java.util.function.Function") + .documentation("Wraps a function to execute synchronized on a given object.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "var syncFunc = Java.synchronized(function() {\n" + + " // Thread-safe code here\n" + + "}, lockObject);\n" + + "```\n\n" + + "@param func The function to synchronize\n" + + "@param lock The object to use as the monitor\n" + + "@returns A synchronized version of the function") + .done() + + .build(); + builtinTypes.put("Java", javaType); + + // ==================== Global print function ==================== + SyntheticType printFunc = new SyntheticTypeBuilder("print") + .addMethod("print") + .parameter("message", "Object", "The message to print") + .returns("void") + .documentation("Prints a message to standard output.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "print(\"Hello, world!\");\n" + + "print(myObject);\n" + + "```") + .done() + .build(); + globalFunctions.put("print", printFunc.getMethod("print")); + + // ==================== Global load function ==================== + SyntheticType loadFunc = new SyntheticTypeBuilder("load") + .addMethod("load") + .parameter("script", "String", "Path or URL to the script") + .returns("Object") + .documentation("Loads and executes a script file or URL.\n\n" + + "**Usage:**\n" + + "```javascript\n" + + "load(\"./myScript.js\");\n" + + "load(\"http://example.com/script.js\");\n" + + "```\n\n" + + "@param script Path to a local script or URL\n" + + "@returns The result of the script execution") + .done() + .build(); + globalFunctions.put("load", loadFunc.getMethod("load")); + } + + /** + * Get a built-in type by name. + * @param name The type name (e.g., "Java") + * @return The SyntheticType or null if not found + */ + public SyntheticType getBuiltinType(String name) { + return builtinTypes.get(name); + } + + /** + * Check if a name is a built-in type. + */ + public boolean isBuiltinType(String name) { + return builtinTypes.containsKey(name); + } + + /** + * Get a global function by name. + */ + public SyntheticMethod getGlobalFunction(String name) { + return globalFunctions.get(name); + } + + /** + * Check if a name is a global function. + */ + public boolean isGlobalFunction(String name) { + return globalFunctions.containsKey(name); + } + + /** + * Get all built-in type names. + */ + public Set getBuiltinTypeNames() { + return Collections.unmodifiableSet(builtinTypes.keySet()); + } + + /** + * Get all global function names. + */ + public Set getGlobalFunctionNames() { + return Collections.unmodifiableSet(globalFunctions.keySet()); + } + + /** + * Get all built-in types. + */ + public Collection getAllBuiltinTypes() { + return Collections.unmodifiableCollection(builtinTypes.values()); + } + + /** + * Get all global functions as SyntheticTypes. + * Each function is wrapped in its own SyntheticType for the registry. + */ + public Map getAllGlobalFunctions() { + Map result = new LinkedHashMap<>(); + + // Wrap each global function in a minimal SyntheticType + for (Map.Entry entry : globalFunctions.entrySet()) { + String name = entry.getKey(); + SyntheticMethod method = entry.getValue(); + + // Create a synthetic type that just contains this one global function + SyntheticTypeBuilder builder = new SyntheticTypeBuilder(name); + builder.documentation("Global " + name + " function"); + + // Add the method + SyntheticTypeBuilder.MethodBuilder methodBuilder = builder.addMethod(name); + for (SyntheticParameter param : method.parameters) { + methodBuilder.parameter(param.name, param.typeName, param.documentation); + } + methodBuilder.returns(method.returnType); + if (method.documentation != null && !method.documentation.isEmpty()) { + methodBuilder.documentation(method.documentation); + } + methodBuilder.done(); + + result.put(name, builder.build()); + } + + return result; + } + + /** + * Resolve the return type of Java.type() given the class name argument. + */ + public TypeInfo resolveJavaType(String className) { + SyntheticType javaBuiltin = builtinTypes.get("Java"); + if (javaBuiltin != null) { + return javaBuiltin.resolveMethodReturnType("type", new String[]{className}); + } + return null; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/OverloadSelector.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/OverloadSelector.java new file mode 100644 index 000000000..6400a3f9d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/OverloadSelector.java @@ -0,0 +1,319 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; + +import java.util.List; + +/** + * Helper class for selecting the best method overload from a list of candidates. + * + * This encapsulates the scoring-based overload selection logic that considers: + * - Exact type matches + * - Numeric promotion compatibility + * - Arity (parameter count) matching + * - Varargs handling + * - Unknown (null) argument types + * + * Lower scores indicate better matches. + */ +public class OverloadSelector { + + // Scoring constants + private static final int ARITY_MISMATCH_BASE = 10000; + private static final int VARARGS_PENALTY = 50; + private static final int UNKNOWN_TYPE_PENALTY = 10; + private static final int COMPATIBLE_TYPE_PENALTY = 5; + private static final int INCOMPATIBLE_TYPE_PENALTY = 100; + + /** + * Select the best overload from a list of candidates based on argument types. + * + * Selection phases: + * 1. Exact match (all types match exactly) + * 2. Numeric promotion match (all args can promote to common param type) + * 3. Scoring-based selection (handles unknown types, varargs, etc.) + * + * @param overloads List of candidate method overloads + * @param argTypes Array of argument types (may contain nulls for unknown types) + * @return The best matching overload, or the first overload if no good match found + */ + public static MethodInfo selectBestOverload(List overloads, TypeInfo[] argTypes) { + if (overloads == null || overloads.isEmpty()) return null; + + int argCount = (argTypes == null) ? 0 : argTypes.length; + + // Fast path: If no arguments provided, try to find zero-arg method + if (argCount == 0) { + for (MethodInfo method : overloads) { + if (method.getParameterCount() == 0) { + return method; + } + } + // Fall back to closest arity + return selectClosestArity(overloads, 0); + } + + // Check if all arg types are known (non-null) + boolean allArgsKnown = true; + for (TypeInfo argType : argTypes) { + if (argType == null) { + allArgsKnown = false; + break; + } + } + + // Phase 1: Try exact match (only when all args known) + if (allArgsKnown) { + MethodInfo exactMatch = findExactMatch(overloads, argTypes, argCount); + if (exactMatch != null) return exactMatch; + } + + // Phase 2: Try numeric promotion match (only when all args known) + if (allArgsKnown) { + MethodInfo numericMatch = findNumericPromotionMatch(overloads, argTypes, argCount); + if (numericMatch != null) return numericMatch; + } + + // Phase 3: Scoring-based selection with arity-first preference + // This handles unknown (null) arg types gracefully and prefers fixed-arity over varargs + return scoringBasedSelection(overloads, argTypes, argCount); + } + + /** + * Find an overload with exact type match for all arguments. + */ + private static MethodInfo findExactMatch(List overloads, TypeInfo[] argTypes, int argCount) { + for (MethodInfo method : overloads) { + if (method.getParameterCount() == argCount) { + boolean exactMatch = true; + List params = method.getParameters(); + for (int i = 0; i < argCount; i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + TypeInfo argType = argTypes[i]; + if (paramType == null || !paramType.equals(argType)) { + exactMatch = false; + break; + } + } + if (exactMatch) return method; + } + } + return null; + } + + /** + * Find an overload where all numeric arguments can promote to a common parameter type. + * Prefers narrower numeric types (e.g., int over long over double). + */ + private static MethodInfo findNumericPromotionMatch(List overloads, TypeInfo[] argTypes, int argCount) { + MethodInfo bestNumericMatch = null; + int bestNumericRank = Integer.MAX_VALUE; + + for (MethodInfo method : overloads) { + if (method.getParameterCount() == argCount) { + List params = method.getParameters(); + + // Check if all parameters and arguments are numeric primitives + boolean allNumeric = true; + for (int i = 0; i < argCount; i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + TypeInfo argType = argTypes[i]; + if (paramType == null || + !TypeChecker.isNumericPrimitive(paramType) || !TypeChecker.isNumericPrimitive(argType)) { + allNumeric = false; + break; + } + } + + if (allNumeric) { + // Check if all parameters are the same numeric type + TypeInfo commonParamType = params.get(0).getTypeInfo(); + boolean allParamsSame = true; + for (int i = 1; i < params.size(); i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + if (!paramType.equals(commonParamType)) { + allParamsSame = false; + break; + } + } + + // If all parameters are the same numeric type, check if args can promote to it + if (allParamsSame) { + boolean canPromote = true; + for (int i = 0; i < argCount; i++) { + if (!TypeChecker.canPromoteNumeric(argTypes[i], commonParamType)) { + canPromote = false; + break; + } + } + + // If all args can promote, check if this is the narrowest match so far + if (canPromote) { + int paramRank = TypeChecker.getNumericRank(commonParamType.getJavaClass()); + if (paramRank < bestNumericRank) { + bestNumericRank = paramRank; + bestNumericMatch = method; + } + } + } + } + } + } + + return bestNumericMatch; + } + + /** + * Use scoring to select the best overload when exact/numeric matches don't apply. + */ + private static MethodInfo scoringBasedSelection(List overloads, TypeInfo[] argTypes, int argCount) { + MethodInfo bestCandidate = null; + int bestScore = Integer.MAX_VALUE; + + for (MethodInfo method : overloads) { + int score = scoreOverload(method, argTypes, argCount); + if (score < bestScore) { + bestScore = score; + bestCandidate = method; + } + } + + return (bestCandidate != null) ? bestCandidate : overloads.get(0); + } + + /** + * Score an overload for matching against provided arguments. + * Lower score = better match. + * + * Scoring priorities: + * - Arity mismatch: +10000 + |paramCount - argCount| + * - Varargs penalty: +1000 + * - Unknown arg type (null): +10 per arg + * - Compatible but not exact: +5 per arg + * - Incompatible type: +100 per arg + * - Exact type match: +0 per arg + * + * @param method The method overload to score + * @param argTypes Array of argument types (may contain nulls) + * @param argCount Number of arguments + * @return Score (lower is better) + */ + public static int scoreOverload(MethodInfo method, TypeInfo[] argTypes, int argCount) { + int score = 0; + int paramCount = method.getParameterCount(); + + // Check if method is varargs + boolean isVarArgs = false; + java.lang.reflect.Method javaMethod = method.getJavaMethod(); + if (javaMethod != null) { + isVarArgs = javaMethod.isVarArgs(); + } else { + // JS methods from .d.ts have no backing Java method; vararg info lives on the last FieldInfo + List checkParams = method.getParameters(); + if (!checkParams.isEmpty()) { + isVarArgs = checkParams.get(checkParams.size() - 1).isVarArg(); + } + } + + // Determine arity applicability + boolean arityApplicable; + if (isVarArgs) { + // Varargs methods accept argCount >= paramCount - 1 + // (the varargs array can be empty or have multiple elements) + arityApplicable = argCount >= paramCount - 1; + } else { + arityApplicable = paramCount == argCount; + } + + if (!arityApplicable) { + // Large penalty for arity mismatch, plus distance to encourage closest match + score += ARITY_MISMATCH_BASE + Math.abs(paramCount - argCount); + } + + // Varargs penalty (fixed-arity preferred over varargs when both apply) + if (isVarArgs) { + score += VARARGS_PENALTY; + } + + // Score each argument's type compatibility + List params = method.getParameters(); + int paramsToCheck = Math.min(argCount, paramCount); + + for (int i = 0; i < paramsToCheck; i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + TypeInfo argType = (argTypes != null && i < argTypes.length) ? argTypes[i] : null; + + if (argType == null) { + // Unknown arg type - don't disqualify, but add penalty + score += UNKNOWN_TYPE_PENALTY; + } else if (paramType == null) { + // Unknown param type - add penalty + score += UNKNOWN_TYPE_PENALTY; + } else if (paramType.equals(argType)) { + // Exact match - no penalty + score += 0; + } else if (TypeChecker.isTypeCompatible(paramType, argType)) { + // Compatible but not exact + score += COMPATIBLE_TYPE_PENALTY; + } else { + // Incompatible type + score += INCOMPATIBLE_TYPE_PENALTY; + } + } + + // For vararg methods, also score extra args (index >= paramCount) against the element type + if (isVarArgs && argCount > paramCount && !params.isEmpty()) { + TypeInfo varargElemType = params.get(paramCount - 1).getTypeInfo(); + for (int i = paramCount; i < argCount; i++) { + TypeInfo argType = (argTypes != null && i < argTypes.length) ? argTypes[i] : null; + if (argType == null || varargElemType == null) { + score += UNKNOWN_TYPE_PENALTY; + } else if (varargElemType.equals(argType)) { + // exact match + } else if (TypeChecker.isTypeCompatible(varargElemType, argType)) { + score += COMPATIBLE_TYPE_PENALTY; + } else { + score += INCOMPATIBLE_TYPE_PENALTY; + } + } + } + + // Penalize extra args that don't match params (for non-varargs) + if (!isVarArgs && argCount > paramCount) { + score += (argCount - paramCount) * INCOMPATIBLE_TYPE_PENALTY; + } + + return score; + } + + /** + * Select the overload with closest arity to the target. + * Tie-breaker: lower parameter count wins. + * + * @param overloads List of candidate overloads + * @param targetArity The desired number of parameters + * @return The overload with closest arity, or first overload if list is empty + */ + public static MethodInfo selectClosestArity(List overloads, int targetArity) { + if (overloads == null || overloads.isEmpty()) return null; + + MethodInfo best = null; + int bestDistance = Integer.MAX_VALUE; + int bestParamCount = Integer.MAX_VALUE; + + for (MethodInfo method : overloads) { + int paramCount = method.getParameterCount(); + int distance = Math.abs(paramCount - targetArity); + + // Prefer smaller distance; tie-break by lower paramCount + if (distance < bestDistance || (distance == bestDistance && paramCount < bestParamCount)) { + best = method; + bestDistance = distance; + bestParamCount = paramCount; + } + } + + return (best != null) ? best : overloads.get(0); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ScriptTypeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ScriptTypeInfo.java new file mode 100644 index 000000000..b40c17bf9 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ScriptTypeInfo.java @@ -0,0 +1,1081 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodSignature; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Represents a type defined within the script itself (not from Java classpath). + * This handles classes, interfaces, and enums declared in the user's script. + * + * Unlike TypeInfo which wraps a Java Class, ScriptTypeInfo stores all metadata + * about fields, methods, and other type information parsed from the script. + */ +public class ScriptTypeInfo extends TypeInfo { + + private final String scriptClassName; + private final int declarationOffset; + private final int bodyStart; + private final int bodyEnd; + private final int modifiers; // Java reflection modifiers (public, static, final, etc.) + + // Script-defined members + private final Map fields = new HashMap<>(); + private final Map> methods = new HashMap<>(); // name -> list of overloads + private final List constructors = new ArrayList<>(); // List of constructors + private final List innerClasses = new ArrayList<>(); + + // Enum constants (for enum types only) - name -> EnumConstantInfo + private final Map enumConstants = new HashMap<>(); + + // Generic type parameters declared on this type (e.g., , , ) + private final List declaredTypeParams = new ArrayList<>(); + + // Recursion guard: tracks ScriptTypeInfo instances currently being parameterized on this thread + // to break the cycle: parameterize → substitute → parameterize (self-referential types) + private static final ThreadLocal> PARAMETERIZING = + ThreadLocal.withInitial(HashSet::new); + + // Parent class reference (for inner class resolution) + private ScriptTypeInfo outerClass; + + // ==================== INHERITANCE ==================== + + /** + * The parent/super class for this type (from "extends ParentClass"). + * Can be a resolved TypeInfo or ScriptTypeInfo, or unresolved TypeInfo if the parent is not found. + * Null if this type doesn't extend anything (or extends Object implicitly). + */ + private TypeInfo superClass; + + /** + * The raw string name of the super class as written in the script (e.g., "ParentClass"). + * Stored for display purposes even when the type couldn't be resolved. + */ + private String superClassName; + + /** + * All implemented interfaces (from "implements Interface1, Interface2, ..."). + * Each can be resolved or unresolved. The list order matches the declaration order. + */ + private final List implementedInterfaces = new ArrayList<>(); + + /** + * The raw string names of implemented interfaces as written in the script. + * Stored for display purposes even when types couldn't be resolved. + */ + private final List implementedInterfaceNames = new ArrayList<>(); + + private ScriptTypeInfo(String simpleName, String fullName, Kind kind, + int declarationOffset, int bodyStart, int bodyEnd, int modifiers) { + super(simpleName, fullName, "", kind, null, true, null, true); + this.scriptClassName = simpleName; + this.declarationOffset = declarationOffset; + this.bodyStart = bodyStart; + this.bodyEnd = bodyEnd; + this.modifiers = modifiers; + } + + // Factory method + public static ScriptTypeInfo create(String simpleName, Kind kind, + int declarationOffset, int bodyStart, int bodyEnd, int modifiers) { + return new ScriptTypeInfo(simpleName, simpleName, kind, declarationOffset, bodyStart, bodyEnd, modifiers); + } + + public static ScriptTypeInfo createInner(String simpleName, Kind kind, ScriptTypeInfo outer, + int declarationOffset, int bodyStart, int bodyEnd, int modifiers) { + String fullName = outer.getFullName() + "$" + simpleName; + ScriptTypeInfo inner = new ScriptTypeInfo(simpleName, fullName, kind, declarationOffset, bodyStart, bodyEnd, modifiers); + inner.outerClass = outer; + outer.innerClasses.add(inner); + return inner; + } + + // Getters + public String getScriptClassName() { return scriptClassName; } + public int getDeclarationOffset() { return declarationOffset; } + public int getBodyStart() { return bodyStart; } + public int getBodyEnd() { return bodyEnd; } + public int getModifiers() { return modifiers; } + public ScriptTypeInfo getOuterClass() { return outerClass; } + public List getInnerClasses() { return innerClasses; } + + // ==================== GENERIC TYPE PARAMETERS ==================== + + public void addDeclaredTypeParam(TypeParamInfo param) { + declaredTypeParams.add(param); + } + + public List getDeclaredTypeParams() { + return declaredTypeParams; + } + + public TypeParamInfo getDeclaredTypeParam(String name) { + for (TypeParamInfo param : declaredTypeParams) { + if (param.getName().equals(name)) { + return param; + } + } + return null; + } + + public boolean hasDeclaredTypeParams() { + return !declaredTypeParams.isEmpty(); + } + + @Override + public List getTypeParams() { + if (!declaredTypeParams.isEmpty()) { + return declaredTypeParams; + } + return super.getTypeParams(); + } + + @Override + public TypeParamInfo getTypeParam(String name) { + TypeParamInfo param = getDeclaredTypeParam(name); + if (param != null) { + return param; + } + return super.getTypeParam(name); + } + + @Override + public TypeInfo parameterize(List typeArgs) { + if (typeArgs == null || typeArgs.isEmpty()) return this; + + Set active = PARAMETERIZING.get(); + if (!active.add(this)) { + return super.parameterize(typeArgs); + } + + try { + ScriptTypeInfo result = new ScriptTypeInfo(getSimpleName(), getFullName(), getKind(), + declarationOffset, bodyStart, bodyEnd, modifiers); + result.setRawType(this); + result.setAppliedTypeArgs(typeArgs); + result.superClass = this.superClass; + result.superClassName = this.superClassName; + result.implementedInterfaces.addAll(this.implementedInterfaces); + result.implementedInterfaceNames.addAll(this.implementedInterfaceNames); + result.declaredTypeParams.addAll(this.declaredTypeParams); + result.outerClass = this.outerClass; + // Use fromBindings instead of forReceiver to avoid infinite recursion: + // forReceiver(result) → substitute() → parameterize() → forReceiver() → ... + GenericContext ctx = GenericContext.fromBindings(this.declaredTypeParams, typeArgs); + + // Parameterize methods, constructors, and fields with the generic context of this type. + for (Map.Entry> entry : this.methods.entrySet()) { + List substituted = new ArrayList<>(); + for (MethodInfo m : entry.getValue()) substituted.add(m.substituteTypeParams(ctx)); + result.methods.put(entry.getKey(), substituted); + } + for (MethodInfo ctor : this.constructors) { + result.constructors.add(ctor.substituteTypeParams(ctx)); + } + for (Map.Entry entry : this.fields.entrySet()) { + result.fields.put(entry.getKey(), entry.getValue().substituteTypeParams(ctx)); + } + return result; + } finally { + active.remove(this); + } + } + + // ==================== INHERITANCE ==================== + + /** + * Get the super class (from "extends"). Can be resolved or unresolved. + * @return The parent class TypeInfo, or null if no extends clause + */ + public TypeInfo getSuperClass() { return superClass; } + + /** + * Get the raw super class name as written in the script. + * @return The super class name string, or null if no extends clause + */ + public String getSuperClassName() { return superClassName; } + + /** + * Set the super class info. Call this after resolving types. + * @param superClass The resolved or unresolved TypeInfo for the parent class + * @param superClassName The raw class name as written in the script + */ + public void setSuperClass(TypeInfo superClass, String superClassName) { + this.superClass = superClass; + this.superClassName = superClassName; + } + + /** + * Check if this type has a super class (extends something). + */ + public boolean hasSuperClass() { return superClass != null || superClassName != null; } + + /** + * Get all implemented interfaces. Each can be resolved or unresolved. + * @return Unmodifiable list of implemented interface TypeInfos + */ + public List getImplementedInterfaces() { + return new ArrayList<>(implementedInterfaces); + } + + /** + * Get the raw interface names as written in the script. + * @return Unmodifiable list of interface name strings + */ + public List getImplementedInterfaceNames() { + return new ArrayList<>(implementedInterfaceNames); + } + + /** + * Add an implemented interface. Call this after resolving types. + * @param interfaceType The resolved or unresolved TypeInfo for the interface + * @param interfaceName The raw interface name as written in the script + */ + public void addImplementedInterface(TypeInfo interfaceType, String interfaceName) { + implementedInterfaces.add(interfaceType); + implementedInterfaceNames.add(interfaceName); + } + + /** + * Check if this type implements any interfaces. + */ + public boolean hasImplementedInterfaces() { return !implementedInterfaces.isEmpty(); } + + /** + * Check if this type implements a specific interface (by simple name). + */ + public boolean implementsInterface(String interfaceName) { + for (String name : implementedInterfaceNames) { + if (name.equals(interfaceName)) return true; + } + for (TypeInfo ti : implementedInterfaces) { + if (ti.getSimpleName().equals(interfaceName)) return true; + } + return false; + } + + /** + * Check if a position is inside this type's body. + */ + public boolean containsPosition(int position) { + return position >= bodyStart && position < bodyEnd; + } + + // ==================== FIELD MANAGEMENT ==================== + + public void addField(FieldInfo field) { + fields.put(field.getName(), field); + } + + @Override + public boolean hasField(String fieldName) { + if (fields.containsKey(fieldName)) + return true; + + if (enumConstants.containsKey(fieldName)) + return true; + + for (FieldInfo f : getSyntheticFields()) + if (f.getName().equals(fieldName)) + return true; + + return false; + } + + @Override + public FieldInfo getFieldInfo(String fieldName) { + if (fields.containsKey(fieldName)) + return fields.get(fieldName); + + if (enumConstants.containsKey(fieldName)) { + EnumConstantInfo enumConst = enumConstants.get(fieldName); + if (enumConst != null) + return enumConst.getFieldInfo(); + } + + for (FieldInfo f : getSyntheticFields()) + if (f.getName().equals(fieldName)) + return f; + + return null; + } + + public Map getFields() { + return new HashMap<>(fields); + } + + // ==================== ENUM CONSTANT MANAGEMENT ==================== + + /** + * Add an enum constant to this enum type. + * Only valid for enum types. + */ + public void addEnumConstant(EnumConstantInfo constant) { + if (isEnum()) { + enumConstants.put(constant.getFieldInfo().getName(), constant); + } + } + + /** + * Check if this enum has a constant with the given name. + */ + public boolean hasEnumConstant(String constantName) { + return enumConstants.containsKey(constantName); + } + + /** + * Get an enum constant by name. + */ + public EnumConstantInfo getEnumConstant(String constantName) { + return enumConstants.get(constantName); + } + + /** + * Get all enum constants. + */ + @Override + public Map getEnumConstants() { + return new HashMap<>(enumConstants); + } + + /** + * Check if this is an enum type and has any constants. + */ + public boolean hasEnumConstants() { + return isEnum() && !enumConstants.isEmpty(); + } + + // ==================== METHOD MANAGEMENT ==================== + + public void addMethod(MethodInfo method) { + methods.computeIfAbsent(method.getName(), k -> new ArrayList<>()).add(method); + } + + @Override + public boolean hasMethod(String methodName) { + if (methods.containsKey(methodName)) + return true; + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + return true; + return false; + } + + @Override + public boolean hasMethod(String methodName, int paramCount) { + List overloads = methods.get(methodName); + if (overloads != null) { + for (MethodInfo m : overloads) { + if (m.getParameterCount() == paramCount) { + return true; + } + } + } + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName) && m.getParameterCount() == paramCount) + return true; + return false; + } + + @Override + public MethodInfo getMethodInfo(String methodName) { + List overloads = methods.get(methodName); + if (overloads != null && !overloads.isEmpty()) + return overloads.get(0); + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + return m; + return null; + } + + /** + * Get all method overloads with the given name. + */ + @Override + public List getAllMethodOverloads(String methodName) { + List result = new ArrayList<>(methods.getOrDefault(methodName, Collections.emptyList())); + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + result.add(m); + return result; + } + + /** + * Get a method with specific parameter count. + */ + public MethodInfo getMethodWithParamCount(String methodName, int paramCount) { + List overloads = methods.get(methodName); + if (overloads == null) return null; + for (MethodInfo m : overloads) { + if (m.getParameterCount() == paramCount) { + return m; + } + } + return null; + } + + public Map> getMethods() { + return new HashMap<>(methods); + } + + public List getAllMethodsFlat() { + List allMethods = new ArrayList<>(); + for (List overloads : methods.values()) { + allMethods.addAll(overloads); + } + return allMethods; + } + + @Override + public List getAllMethods() { + List result = getAllMethodsFlat(); + result.addAll(getSyntheticMethods()); + return result; + } + + @Override + public List getAllFields() { + List result = new ArrayList<>(getFields().values()); + result.addAll(getSyntheticFields()); + return result; + } + + @Override + public List getAllNestedTypes() { + return new ArrayList<>(innerClasses); + } + + // ==================== CONSTRUCTOR MANAGEMENT ==================== + + public void addConstructor(MethodInfo constructor) { + constructors.add(constructor); + } + + @Override + public List getConstructors() { + return new ArrayList<>(constructors); + } + + @Override + public boolean hasConstructors() { + return !constructors.isEmpty(); + } + + /** + * Find the best matching constructor for the given argument count. + * Returns null if no constructor matches. + */ + @Override + public MethodInfo findConstructor(int argCount) { + for (MethodInfo constructor : constructors) { + if (constructor.getParameterCount() == argCount) { + return constructor; + } + } + return null; + } + + public MethodInfo findConstructor(TypeInfo[] argTypes) { + for (MethodInfo constructor : constructors) { + if (constructor.getParameterCount() == argTypes.length) { + boolean match = true; + List params = constructor.getParameters(); + for (int i = 0; i < argTypes.length; i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + if (!TypeChecker.isTypeCompatible(paramType, argTypes[i])) { + match = false; + break; + } + } + if (match) + return constructor; + } + } + return null; + } + + // ==================== INHERITANCE HIERARCHY SEARCH ==================== + + /** + * Check if this type or any of its parent classes has a field with the given name. + * This recursively searches up the inheritance tree. + */ + public boolean hasFieldInHierarchy(String fieldName) { + // Check this class first + if (hasField(fieldName)) { + return true; + } + + // Check parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) superClass).hasFieldInHierarchy(fieldName); + } else { + // For Java classes, hasField already checks inheritance via reflection + return superClass.hasField(fieldName); + } + } + + return false; + } + + /** + * Get field info from this type or any of its parent classes. + * This recursively searches up the inheritance tree. + */ + public FieldInfo getFieldInfoInHierarchy(String fieldName) { + // Check this class first + FieldInfo field = getFieldInfo(fieldName); + if (field != null) { + return field; + } + + // Check parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) superClass).getFieldInfoInHierarchy(fieldName); + } else { + // For Java classes, getFieldInfo already checks inheritance via reflection + return superClass.getFieldInfo(fieldName); + } + } + + return null; + } + + /** + * Check if this type or any of its parent classes has a method with the given name. + * This recursively searches up the inheritance tree. + */ + public boolean hasMethodInHierarchy(String methodName) { + // Check this class first + if (hasMethod(methodName)) { + return true; + } + + // Check parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) superClass).hasMethodInHierarchy(methodName); + } else { + // For Java classes, hasMethod already checks inheritance via reflection + return superClass.hasMethod(methodName); + } + } + + return false; + } + + /** + * Check if this type or any of its parent classes has a method with the given name and parameter count. + * This recursively searches up the inheritance tree. + */ + public boolean hasMethodInHierarchy(String methodName, int paramCount) { + // Check this class first + if (hasMethod(methodName, paramCount)) { + return true; + } + + // Check parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) superClass).hasMethodInHierarchy(methodName, paramCount); + } else { + // For Java classes, hasMethod already checks inheritance via reflection + return superClass.hasMethod(methodName, paramCount); + } + } + + return false; + } + + /** + * Get method info from this type or any of its parent classes. + * This recursively searches up the inheritance tree. + */ + public MethodInfo getMethodInfoInHierarchy(String methodName) { + // Check this class first + MethodInfo method = getMethodInfo(methodName); + if (method != null) { + return method; + } + + // Check parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) superClass).getMethodInfoInHierarchy(methodName); + } else { + // For Java classes, getMethodInfo already checks inheritance via reflection + return superClass.getMethodInfo(methodName); + } + } + + return null; + } + + /** + * Get method info with specific parameter count from this type or any of its parent classes. + * This recursively searches up the inheritance tree. + */ + public MethodInfo getMethodWithParamCountInHierarchy(String methodName, int paramCount) { + // Check this class first + MethodInfo method = getMethodWithParamCount(methodName, paramCount); + if (method != null) { + return method; + } + + // Check parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + return ((ScriptTypeInfo) superClass).getMethodWithParamCountInHierarchy(methodName, paramCount); + } else { + // For Java classes, reflection already handles inheritance + // We need to manually search for matching method + List overloads = superClass.getAllMethodOverloads(methodName); + for (MethodInfo m : overloads) { + if (m.getParameterCount() == paramCount) { + return m; + } + } + } + } + + return null; + } + + /** + * Get all method overloads with the given name from this type or any of its parent classes. + * This recursively searches up the inheritance tree and returns all matching overloads. + */ + public List getAllMethodOverloadsInHierarchy(String methodName) { + List result = new ArrayList<>(); + + // Get overloads from this class + result.addAll(getAllMethodOverloads(methodName)); + + // Get overloads from parent class recursively + if (superClass != null && superClass.isResolved()) { + if (superClass instanceof ScriptTypeInfo) { + result.addAll(((ScriptTypeInfo) superClass).getAllMethodOverloadsInHierarchy(methodName)); + } else { + // For Java classes, getAllMethodOverloads already checks inheritance via reflection + result.addAll(superClass.getAllMethodOverloads(methodName)); + } + } + + return result; + } + + /** + * Override getBestMethodOverload to search the inheritance hierarchy. + * This ensures that method overload resolution considers parent class methods. + */ + @Override + public MethodInfo getBestMethodOverload(String methodName, TypeInfo[] argTypes) { + // Get all overloads from this class and parent classes + List allOverloads = getAllMethodOverloadsInHierarchy(methodName); + if (allOverloads.isEmpty()) + return null; + + // If no arguments provided, try to find zero-arg method + if (argTypes == null || argTypes.length == 0) { + for (MethodInfo method : allOverloads) { + if (method.getParameterCount() == 0) { + return method; + } + } + // Fall back to first overload if no zero-arg found + return allOverloads.get(0); + } + + // Phase 1: Try exact match + for (MethodInfo method : allOverloads) { + if (method.getParameterCount() == argTypes.length) { + boolean exactMatch = true; + List params = method.getParameters(); + for (int i = 0; i < argTypes.length; i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + TypeInfo argType = argTypes[i]; + if (paramType == null || argType == null || !paramType.equals(argType)) { + exactMatch = false; + break; + } + } + if (exactMatch) + return method; + } + } + + // Phase 2: Try compatible type match (assignability) + for (MethodInfo method : allOverloads) { + if (method.getParameterCount() == argTypes.length) { + boolean compatible = true; + List params = method.getParameters(); + for (int i = 0; i < argTypes.length; i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + TypeInfo argType = argTypes[i]; + if (paramType == null || argType == null) { + continue; // Allow null types (unresolved) + } + // Check if argType can be assigned to paramType + if (!noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker.isTypeCompatible(paramType, + argType)) { + compatible = false; + break; + } + } + if (compatible) + return method; + } + } + + // Phase 3: Fall back to first overload with matching parameter count + for (MethodInfo method : allOverloads) { + if (method.getParameterCount() == argTypes.length) { + return method; + } + } + + // No match found, return first overload + return allOverloads.get(0); + } + + /** + * Override getBestMethodOverload with return type expectation to search the inheritance hierarchy. + */ + @Override + public MethodInfo getBestMethodOverload(String methodName, TypeInfo expectedReturnType) { + List allOverloads = getAllMethodOverloadsInHierarchy(methodName); + if (allOverloads.isEmpty()) + return null; + + // If no expected return type, return first overload + if (expectedReturnType == null) { + return allOverloads.get(0); + } + + // First pass: look for return type compatible overload + for (MethodInfo method : allOverloads) { + TypeInfo returnType = method.getReturnType(); + if (returnType != null && noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker.isTypeCompatible( + expectedReturnType, returnType)) { + return method; + } + } + // Second pass: return any overload (first one) + return allOverloads.get(0); + } + + // ==================== INNER CLASS LOOKUP ==================== + + /** + * Get the dot-separated display name for this type. + * Top-level: "MyClass" + * Inner: "Outer.Inner" + * Deeply nested: "Outer.Middle.Inner" + * + * This is what users write in type annotations and what resolveType() should accept. + * Recursively walks the outerClass chain to build the full user-facing qualified name. + */ + public String getDotSeparatedName() { + if (outerClass == null) { + return getSimpleName(); + } + // Recurse up the nesting hierarchy: each level prepends "Parent." to the name + return outerClass.getDotSeparatedName() + "." + getSimpleName(); + } + + /** + * Find an inner class by name. + */ + public ScriptTypeInfo getInnerClass(String name) { + for (ScriptTypeInfo inner : innerClasses) { + if (inner.getSimpleName().equals(name)) { + return inner; + } + } + return null; + } + + // Script types are always considered resolved since they're defined in the script + @Override + public boolean isResolved() { + return true; + } + + // Script types don't have a Java class + @Override + public Class getJavaClass() { + return null; + } + + @Override + public String toString() { + return "ScriptTypeInfo{" + scriptClassName + ", " + getKind() + + ", fields=" + fields.size() + ", methods=" + methods.size() + "}"; + } + + // ==================== ERROR HANDLING ==================== + + /** + * Error types for ScriptTypeInfo validation. + */ + public enum ErrorType { + NONE, + MISSING_INTERFACE_METHOD, // Class doesn't implement all interface methods + MISSING_CONSTRUCTOR_MATCH, // Class extends parent but has no matching constructor + UNRESOLVED_PARENT, // Parent class cannot be resolved + UNRESOLVED_INTERFACE // Implemented interface cannot be resolved + } + + /** + * Represents a missing interface method error. + */ + + // Error tracking + private ErrorType errorType = ErrorType.NONE; + private String errorMessage; + private final List missingMethodErrors = new ArrayList<>(); + private final List constructorMismatchErrors = new ArrayList<>(); + + // Error getters + public ErrorType getErrorType() { return errorType; } + public String getErrorMessage() { return errorMessage; } + public boolean hasError() { return errorType != ErrorType.NONE || !missingMethodErrors.isEmpty() || !constructorMismatchErrors.isEmpty(); } + public List getMissingMethodErrors() { return new ArrayList<>(missingMethodErrors); } + public List getConstructorMismatchErrors() { return new ArrayList<>(constructorMismatchErrors); } + + /** + * Set a general error on this type. + */ + public void setError(ErrorType type, String message) { + this.errorType = type; + this.errorMessage = message; + } + + /** + * Add a missing interface method error. + */ + public void addMissingMethodError(TypeInfo interfaceType, String signature) { + missingMethodErrors.add(new MissingMethodError(interfaceType, signature)); + } + + /** + * Add a constructor mismatch error. + */ + public void addConstructorMismatchError(TypeInfo parentType, String parentConstructorSignature) { + constructorMismatchErrors.add(new ConstructorMismatchError(parentType, parentConstructorSignature)); + } + + /** + * Clear all errors on this type. + */ + public void clearErrors() { + errorType = ErrorType.NONE; + errorMessage = null; + missingMethodErrors.clear(); + constructorMismatchErrors.clear(); + } + + public static class MissingMethodError { + private final TypeInfo interfaceType; + private final String signature; + + public MissingMethodError(TypeInfo interfaceType, String signature) { + this.interfaceType = interfaceType; + this.signature = signature; + } + + public String getMessage() { + return "Class must implement method '" + signature + "' from interface " + interfaceType.getSimpleName(); + } + } + + /** + * Represents a constructor mismatch error. + */ + public static class ConstructorMismatchError { + private final TypeInfo parentType; + private final String parentConstructorSignature; + + public ConstructorMismatchError(TypeInfo parentType, String parentConstructorSignature) { + this.parentType = parentType; + this.parentConstructorSignature = parentConstructorSignature; + } + + public String getMessage() { + return "Class extends " + parentType.getSimpleName() + " but has no constructor matching " + parentConstructorSignature; + } + } + + // ==================== VALIDATION ==================== + + /** + * Validate this script type for missing interface methods and constructor matching. + */ + @Override + public void validate() { + // Check that extending class has a matching constructor + if (hasSuperClass()) { + TypeInfo superClass = getSuperClass(); + if (superClass == null || !superClass.isResolved()) { + setError(ErrorType.UNRESOLVED_PARENT, + "Cannot resolve parent class " + getSuperClassName()); + } else { + validateConstructorChain(superClass); + } + } + + // Skip validation for interfaces - they don't implement methods + if (getKind() == Kind.INTERFACE) + return; + + // Check that all interface methods are implemented + if (hasImplementedInterfaces()) { + for (TypeInfo iface : getImplementedInterfaces()) { + if (iface == null || !iface.isResolved()) { + // Mark unresolved interface error + setError(ErrorType.UNRESOLVED_INTERFACE, "Cannot resolve interface"); + continue; + } + validateInterfaceImplementation(iface); + } + } + } + + /** + * Validate that this script type implements all methods from an interface. + */ + private void validateInterfaceImplementation(TypeInfo iface) { + // Handle Java interfaces + Class javaClass = iface.getJavaClass(); + if (javaClass != null && javaClass.isInterface()) { + try { + for (Method javaMethod : javaClass.getMethods()) { + // Skip static and default methods + if (Modifier.isStatic(javaMethod.getModifiers())) + continue; + + // Check if this type has a matching method + String methodName = javaMethod.getName(); + int paramCount = javaMethod.getParameterCount(); + + boolean found = false; + List overloads = getAllMethodOverloads(methodName); + for (MethodInfo method : overloads) { + if (parameterTypesMatch(method, javaMethod)) { + found = true; + break; + } + } + + //Limit to one error at a time to not spam all missing methods + if (!found && missingMethodErrors.isEmpty()) + addMissingMethodError(iface, MethodSignature.asString(javaMethod)); + } + } catch (Exception e) { + } + return; + } + + // Handle script-defined interfaces (ScriptType) + if (iface instanceof ScriptTypeInfo) { + ScriptTypeInfo ifaceType = (ScriptTypeInfo) iface; + + // Check all methods declared in the interface + for (MethodInfo ifaceMethod : ifaceType.getAllMethodsFlat()) { + MethodSignature ifaceSignature = ifaceMethod.getSignature(); + String methodName = ifaceMethod.getName(); + + boolean found = false; + List overloads = getAllMethodOverloads(methodName); + for (MethodInfo method : overloads) { + if (method.getSignature().equals(ifaceSignature)) { + found = true; + break; + } + } + + //Limit to one error at a time to not spam all missing methods + if (!found && missingMethodErrors.isEmpty()) + addMissingMethodError(iface, ifaceSignature.toString()); + } + } + } + + /** + * Validate that this script type has a constructor compatible with its parent class. + * This checks that for each parent constructor, there's a matching constructor in the child. + */ + private void validateConstructorChain(TypeInfo superClass) { + // If no constructors defined in script type, it has an implicit default constructor + // Check if parent has a no-arg constructor + if (!hasConstructors()) { + if (superClass instanceof ScriptTypeInfo) { + ScriptTypeInfo parentScript = (ScriptTypeInfo) superClass; + if (!parentScript.isInterface() && (!parentScript.hasConstructors() || parentScript.findConstructor(0) != null)) { + addConstructorMismatchError(superClass, superClass.getSimpleName()); + } + } else { + Class javaClass = superClass.getJavaClass(); + if (javaClass != null && !javaClass.isInterface()) { + try { + for (java.lang.reflect.Constructor ctor : javaClass.getConstructors()) { + if (ctor.getParameterCount() == 0) { + addConstructorMismatchError(superClass, superClass.getSimpleName()); + break; + } + } + } catch (Exception e) { + // Security error + } + } + } + + } + // If script type has constructors, we'd need to check super() calls - that's more complex + // For now, we just validate the implicit default constructor case + } + + /** + * Check if a MethodInfo's parameter types match a Java reflection Method's parameter types. + */ + private boolean parameterTypesMatch(MethodInfo methodInfo, Method javaMethod) { + List params = methodInfo.getParameters(); + Class[] javaParams = javaMethod.getParameterTypes(); + + if (params.size() != javaParams.length) + return false; + + for (int i = 0; i < params.size(); i++) { + TypeInfo paramType = params.get(i).getTypeInfo(); + if (paramType == null) + continue; // Unresolved param, skip check + + Class javaParamClass = javaParams[i]; + String javaParamName = javaParamClass.getName(); + + // Compare type names + if (!paramType.getFullName().equals(javaParamName) && + !paramType.getSimpleName().equals(javaParamClass.getSimpleName())) { + return false; + } + } + + return true; + } +} \ No newline at end of file diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeChecker.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeChecker.java new file mode 100644 index 000000000..2e4a52b15 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeChecker.java @@ -0,0 +1,660 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.HashSet; +import java.util.Set; + +/** + * Utility class for checking type compatibility between types. + * Handles primitive widening conversions, boxing/unboxing, and inheritance. + */ +public final class TypeChecker { + + private TypeChecker() {} // Utility class + + private static boolean CURRENT_JAVASCRIPT_MODE; + + public static void enterTypeCheckingContext(boolean javaScriptMode) { + CURRENT_JAVASCRIPT_MODE = javaScriptMode; + } + + static boolean isJavaScriptMode() { + return CURRENT_JAVASCRIPT_MODE; + } + + /** + * Check if the actual type is compatible with (assignable to) the expected type. + * @param expected The expected/target type + * @param actual The actual/source type + * @return true if actual can be assigned to expected + */ + public static boolean isTypeCompatible(TypeInfo expected, TypeInfo actual) { + if (expected == null) return true; // void can accept anything (shouldn't happen) + if (actual == null) return true; // Can't verify, assume compatible + + // Exact match by reference equality + if(expected.equals(actual)) return true; + + // Handle array types: compatible if element types are compatible + if (expected.isArray() && actual.isArray()) { + TypeInfo expectedElement = expected.getElementType(); + TypeInfo actualElement = actual.getElementType(); + if (expectedElement != null && actualElement != null) + return isTypeCompatible(expectedElement, actualElement); + } + + // Script method reference placeholder: only compatible with functional interface params. + // Used to help overload selection choose SAM overloads in JavaScript. + if ("__script_method_ref__".equals(actual.getFullName())) { + return expected.isFunctionalInterface(); + } + + // Handle "any" type - universally compatible (JavaScript/TypeScript) + if ("any".equals(expected.getFullName()) || "any".equals(actual.getFullName())) { + return true; + } + + if (isJavaScriptMode()) { + // Treat java.lang.Object as "any", universally compatible + if ("Object".equals(expected.getSimpleName()) || "Object".equals(actual.getSimpleName()) ) + return true; + + // Treat String as universally compatible, since JavaScript string literals can be assigned to String + // parameters and String is commonly used as a catch-all type in JS APIs + if("String".equals(expected.getSimpleName())) + return true; + } + + // Handle null literal - null is compatible with any reference type (non-primitive) + if ("".equals(actual.getFullName())) { + Class expectedClass = expected.getJavaClass(); + if (expectedClass != null && !expectedClass.isPrimitive() || "".equals(expected.getFullName())) { + return true; // null can be assigned to any reference type and null + } + // null cannot be assigned to primitive types + return false; + } + + String expectedName = expected.getSimpleName(); + String actualName = actual.getSimpleName(); + + if (expectedName == null || actualName == null) return true; + + + // Primitive widening conversions + if ("number".equals(expectedName) && isNumericType(actualName)) { + return true; + } + if ("number".equals(actualName) && isNumericType(expectedName)) { + return true; + } + if (isNumericType(expectedName) && isNumericType(actualName)) { + if (isJavaScriptMode()) return true; + return canWiden(actualName, expectedName); + } + + // JS/.d.ts type compatibility (check inheritance chain from actual -> parent) + if (expected.isJSType() && actual.isJSType()) { + if (isJSTypeAssignableFrom(expected.getJSTypeInfo(), actual.getJSTypeInfo())) { + return true; + } + } + + // Same-name match: handles ScriptTypeInfo, non-Java types, and same-class Java types. + // Must run before isAssignableFrom so type arg checking isn't skipped for same-class pairs. + if (expected.getFullName().equals(actual.getFullName())) { + if (expected.isParameterized() && actual.isParameterized()) { + return areTypeArgumentsCompatible(expected, actual); + } + return true; + } + + // ScriptTypeInfo inheritance: actual is a script-defined type that may extend/implement expected. + // ScriptTypeInfo.getJavaClass() returns null, so the Java isAssignableFrom gate below won't fire. + if (actual instanceof ScriptTypeInfo) { + if (isScriptTypeAssignableTo((ScriptTypeInfo) actual, expected)) { + return true; + } + } + + // Object type compatibility (check inheritance) + if (expected.getJavaClass() != null && actual.getJavaClass() != null) { + Class expectedClass = expected.getJavaClass(); + Class actualClass = actual.getJavaClass(); + + // Direct assignability + if (expectedClass.isAssignableFrom(actualClass)) { + return true; + } + + // Primitive widening with Class objects + if (isPrimitiveWidening(actualClass, expectedClass)) { + return true; + } + + // Boxing/unboxing compatibility + if (isBoxingCompatible(actualClass, expectedClass)) { + return true; + } + } + + // Allow boxed/unboxed conversions by name + if (isPrimitiveOrWrapper(expectedName) && isPrimitiveOrWrapper(actualName)) { + return getUnboxedName(expectedName).equals(getUnboxedName(actualName)); + } + + return false; + } + + /** + * Check assignability for JS/.d.ts types by walking the resolved parent chain. + */ + private static boolean isJSTypeAssignableFrom(JSTypeInfo expected, JSTypeInfo actual) { + if (expected == null || actual == null) { + return false; + } + + Set visited = new HashSet<>(); + JSTypeInfo current = actual; + while (current != null) { + String currentFullName = current.getFullName(); + if (currentFullName == null || !visited.add(currentFullName)) { + break; + } + + if (expected.getFullName() != null && expected.getFullName().equals(currentFullName)) { + return true; + } + + current = current.getResolvedParent(); + } + + return false; + } + + /** + * Check assignability for ScriptTypeInfo by iteratively walking the extends/implements chain. + * Handles both direct and indirect inheritance (A extends B extends C implements D). + */ + private static boolean isScriptTypeAssignableTo(ScriptTypeInfo actual, TypeInfo expected) { + String expectedFull = expected.getFullName(); + String expectedSimple = expected.getSimpleName(); + + Deque worklist = new ArrayDeque<>(); + worklist.add(actual); + + while (!worklist.isEmpty()) { + TypeInfo current = worklist.poll(); + if (current == null || !current.isResolved()) continue; + + String currentFull = current.getFullName(); + if (currentFull != null) { + if (expectedFull != null && expectedFull.equals(currentFull)) return true; + if (expectedSimple != null && expectedSimple.equals(current.getSimpleName())) return true; + } + + if (current instanceof ScriptTypeInfo) { + ScriptTypeInfo scriptCurrent = (ScriptTypeInfo) current; + TypeInfo superClass = scriptCurrent.getSuperClass(); + if (superClass != null) { + worklist.add(superClass); + } + for (TypeInfo iface : scriptCurrent.getImplementedInterfaces()) { + worklist.add(iface); + } + } else if (current.getJavaClass() != null && expected.getJavaClass() != null) { + if (expected.getJavaClass().isAssignableFrom(current.getJavaClass())) { + return true; + } + } + } + + return false; + } + + private static boolean areTypeArgumentsCompatible(TypeInfo expected, TypeInfo actual) { + java.util.List expectedArgs = expected.getAppliedTypeArgs(); + java.util.List actualArgs = actual.getAppliedTypeArgs(); + + // Actual has no type args — it's a raw type being assigned to a parameterized type. + // In Java this is always valid (unchecked warning, not an error). + if (actualArgs.isEmpty()) { + return true; + } + + // If all of actual's type args are unresolved type parameters (e.g., Box + // from diamond "new Box<>()"), treat as raw/inferred — always compatible. + boolean allActualAreTypeParams = true; + for (TypeInfo actualArg : actualArgs) { + if (!actualArg.isTypeParameter()) { + allActualAreTypeParams = false; + break; + } + } + if (allActualAreTypeParams) { + return true; + } + + for (int i = 0; i < expectedArgs.size(); i++) { + TypeInfo expectedArg = expectedArgs.get(i); + TypeInfo actualArg = actualArgs.get(i); + + if (expectedArg.isTypeParameter() || actualArg.isTypeParameter()) { + continue; + } + + if (!isTypeCompatible(expectedArg, actualArg) && !isTypeCompatible(actualArg, expectedArg)) { + return false; + } + } + + return true; + } + + /** + * Check if the type is a numeric type (including wrappers). + */ + public static boolean isNumericType(String typeName) { + switch (typeName) { + case "number": + case "byte": case "Byte": + case "short": case "Short": + case "int": case "Integer": + case "long": case "Long": + case "float": case "Float": + case "double": case "Double": + case "char": case "Character": + return true; + default: + return false; + } + } + + /** + * Check if a primitive type can be widened to another type. + * Follows Java's widening primitive conversion rules. + */ + public static boolean canWiden(String from, String to) { + int fromRank = getNumericRank(from); + int toRank = getNumericRank(to); + return fromRank <= toRank; + } + + /** + * Get the numeric rank for primitive widening conversion. + * Higher rank can accept lower ranks. + */ + public static int getNumericRank(String typeName) { + switch (getUnboxedName(typeName)) { + case "byte": return 1; + case "short": case "char": return 2; + case "int": return 3; + case "long": return 4; + case "float": return 5; + case "number": + case "double": return 6; + default: return 0; + } + } + + /** + * Check if a type is a numeric primitive (byte, short, int, long, float, double) + */ + public static boolean isNumericPrimitive(TypeInfo type) { + if (type == null || type.getJavaClass() == null) return false; + Class cls = type.getJavaClass(); + return cls == byte.class || cls == Byte.class || + cls == short.class || cls == Short.class || + cls == int.class || cls == Integer.class || + cls == long.class || cls == Long.class || + cls == float.class || cls == Float.class || + cls == double.class || cls == Double.class; + } + + /** + * Check if a numeric type can be promoted to a target numeric type. + * Follows Java's numeric promotion hierarchy: byte -> short -> int -> long -> float -> double + */ + public static boolean canPromoteNumeric(TypeInfo from, TypeInfo to) { + if (from == null || to == null || from.getJavaClass() == null || to.getJavaClass() == null) return false; + + Class fromClass = from.getJavaClass(); + Class toClass = to.getJavaClass(); + + // Unbox if necessary + if (fromClass == Byte.class) fromClass = byte.class; + if (fromClass == Short.class) fromClass = short.class; + if (fromClass == Integer.class) fromClass = int.class; + if (fromClass == Long.class) fromClass = long.class; + if (fromClass == Float.class) fromClass = float.class; + if (fromClass == Double.class) fromClass = double.class; + + if (toClass == Byte.class) toClass = byte.class; + if (toClass == Short.class) toClass = short.class; + if (toClass == Integer.class) toClass = int.class; + if (toClass == Long.class) toClass = long.class; + if (toClass == Float.class) toClass = float.class; + if (toClass == Double.class) toClass = double.class; + + // Get numeric ranks (higher = wider type) + int fromRank = getNumericRank(fromClass); + int toRank = getNumericRank(toClass); + + return fromRank >= 0 && toRank >= 0 && fromRank <= toRank; + } + + /** + * Get the numeric rank for promotion hierarchy. + * byte=0, short=1, int=2, long=3, float=4, double=5 + */ + public static int getNumericRank(Class cls) { + if (cls == byte.class) return 0; + if (cls == short.class) return 1; + if (cls == int.class) return 2; + if (cls == long.class) return 3; + if (cls == float.class) return 4; + if (cls == double.class) return 5; + return -1; + } + + + /** + * Check if the type name is a primitive or its wrapper type. + */ + public static boolean isPrimitiveOrWrapper(String typeName) { + switch (typeName) { + case "byte": case "Byte": + case "short": case "Short": + case "int": case "Integer": + case "long": case "Long": + case "float": case "Float": + case "double": case "Double": + case "char": case "Character": + case "boolean": case "Boolean": + return true; + default: + return false; + } + } + + /** + * Get the primitive type name from a wrapper type name. + * Returns the input unchanged if already primitive or not a wrapper. + */ + public static String getUnboxedName(String typeName) { + switch (typeName) { + case "Byte": return "byte"; + case "Short": return "short"; + case "Integer": return "int"; + case "Long": return "long"; + case "Float": return "float"; + case "Double": return "double"; + case "Character": return "char"; + case "Boolean": return "boolean"; + default: return typeName; + } + } + + /** + * Get the wrapper type name from a primitive type name. + * Returns the input unchanged if already a wrapper or not a primitive. + */ + public static String getBoxedName(String typeName) { + switch (typeName) { + case "byte": return "Byte"; + case "short": return "Short"; + case "int": return "Integer"; + case "long": return "Long"; + case "float": return "Float"; + case "double": return "Double"; + case "char": return "Character"; + case "boolean": return "Boolean"; + default: return typeName; + } + } + + /** + * Check if the type name represents a void type. + */ + public static boolean isVoidType(String typeName) { + return typeName == null || typeName.equals("void") || typeName.equals("Void"); + } + + /** + * Check if the type represents a void type. + */ + public static boolean isVoidType(TypeInfo type) { + if (type == null) return true; + return isVoidType(type.getSimpleName()); + } + + /** + * Check for primitive widening conversions. + * byte -> short -> int -> long -> float -> double + * char -> int -> long -> float -> double + */ + private static boolean isPrimitiveWidening(Class from, Class to) { + if (!from.isPrimitive() || !to.isPrimitive()) { + return false; + } + + if (from == byte.class) { + return to == short.class || to == int.class || to == long.class || + to == float.class || to == double.class; + } + if (from == short.class || from == char.class) { + return to == int.class || to == long.class || to == float.class || to == double.class; + } + if (from == int.class) { + return to == long.class || to == float.class || to == double.class; + } + if (from == long.class) { + return to == float.class || to == double.class; + } + if (from == float.class) { + return to == double.class; + } + return false; + } + + /** + * Check for boxing/unboxing compatibility. + */ + private static boolean isBoxingCompatible(Class from, Class to) { + if (from.isPrimitive()) { + Class wrapper = getWrapperClassInternal(from); + if (wrapper != null && to.isAssignableFrom(wrapper)) { + return true; + } + } + if (to.isPrimitive()) { + Class wrapper = getWrapperClassInternal(to); + if (wrapper != null && wrapper.isAssignableFrom(from)) { + return true; + } + } + return false; + } + + /** + * Get the wrapper class for a primitive type. + */ + private static Class getWrapperClassInternal(Class primitive) { + if (primitive == boolean.class) return Boolean.class; + if (primitive == byte.class) return Byte.class; + if (primitive == char.class) return Character.class; + if (primitive == short.class) return Short.class; + if (primitive == int.class) return Integer.class; + if (primitive == long.class) return Long.class; + if (primitive == float.class) return Float.class; + if (primitive == double.class) return Double.class; + return null; + } + + /** + * Attempt to narrow an integer literal to byte, short, or char when the + * expected type requires it. The expression resolver normally infers integer + * literals as {@code int}; this helper allows callers to re-type a literal + * when {@code ExpressionTypeResolver.CURRENT_EXPECTED_TYPE} is set (e.g. + * method-argument second pass or assignment RHS). + * + *

Supported literal formats:

+ *
    + *
  • Decimal: {@code 42}, {@code -128}, {@code +127}
  • + *
  • Hexadecimal: {@code 0xFF}, {@code 0XAB}
  • + *
  • Binary: {@code 0b1010}, {@code 0B1111_0000}
  • + *
  • Underscores as digit separators: {@code 1_000}
  • + *
  • Optional trailing {@code l}/{@code L} suffix (stripped before parsing)
  • + *
+ * + *

Range checks:

+ *
    + *
  • byte: [-128 .. 127]
  • + *
  • short: [-32768 .. 32767]
  • + *
  • char: [0 .. 65535]
  • + *
+ * + * @param literalText the raw text of the integer literal (e.g. {@code "0xFF"}) + * @param expectedType the target type at the call/assignment site + * @return a {@link TypeInfo} for the narrowed primitive type, or {@code null} + * if the expected type is not byte/short/char, the literal is not a + * valid integer, or the value falls outside the target range + */ + public static TypeInfo narrowLiteralToExpectedType(String literalText, TypeInfo expectedType) { + if (literalText == null || literalText.isEmpty() || expectedType == null) { + return null; + } + + // Determine the narrowing target from the expected type + String expectedSimple = expectedType.getSimpleName(); + if (expectedSimple == null) { + return null; + } + String unboxed = getUnboxedName(expectedSimple); + if (!"byte".equals(unboxed) && !"short".equals(unboxed) && !"char".equals(unboxed)) { + return null; // Only narrow to byte, short, or char + } + + // Parse the literal value + Long value = parseIntegerLiteral(literalText); + if (value == null) { + return null; + } + + // Range check for the target type + long v = value; + switch (unboxed) { + case "byte": + if (v < -128 || v > 127) return null; + break; + case "short": + if (v < -32768 || v > 32767) return null; + break; + case "char": + if (v < 0 || v > 65535) return null; + break; + default: + return null; + } + + return TypeInfo.fromPrimitive(unboxed); + } + + /** + * Parse an integer literal string into a {@code Long} value. + * Supports decimal, hexadecimal (0x/0X), and binary (0b/0B) formats, + * optional leading sign (+/-), underscores as digit separators, + * and an optional trailing l/L suffix. + * + * @param text the raw literal text + * @return the parsed value, or {@code null} on parse failure + */ + private static Long parseIntegerLiteral(String text) { + String s = text.trim(); + if (s.isEmpty()) { + return null; + } + + // Determine sign + boolean negative = false; + if (s.charAt(0) == '-') { + negative = true; + s = s.substring(1); + } else if (s.charAt(0) == '+') { + s = s.substring(1); + } + + if (s.isEmpty()) { + return null; + } + + // Strip optional trailing l/L suffix + if (s.charAt(s.length() - 1) == 'l' || s.charAt(s.length() - 1) == 'L') { + s = s.substring(0, s.length() - 1); + } + + if (s.isEmpty()) { + return null; + } + + // Remove underscores (Java digit separators) + s = s.replace("_", ""); + if (s.isEmpty()) { + return null; + } + + try { + long value; + if (s.length() > 2 && s.charAt(0) == '0' && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { + // Hexadecimal + value = Long.parseUnsignedLong(s.substring(2), 16); + } else if (s.length() > 2 && s.charAt(0) == '0' && (s.charAt(1) == 'b' || s.charAt(1) == 'B')) { + // Binary + value = Long.parseUnsignedLong(s.substring(2), 2); + } else { + // Decimal + value = Long.parseLong(s); + } + return negative ? -value : value; + } catch (NumberFormatException e) { + return null; + } + } + + public static String[] getJavaKeywords() { + String[] keywords = { + "if", "else", "for", "while", "do", "switch", "case", "break", "continue", + "return", "try", "catch", "finally", "throw", "throws", "new", "this", "super", + "true", "false", "null", "instanceof", "import", "class", "interface", "enum", + "extends", "implements", "public", "private", "protected", "static", "final", + "abstract", "synchronized", "volatile", "transient", "native", "void", + "boolean", "byte", "short", "int", "long", "float", "double", "char" + }; + return keywords; + } + + public static String[] getJavaScriptKeywords() { + String[] keywords = { + "function", "var", "let", "const", "if", "else", "for", "while", "do", + "switch", "case", "break", "continue", "return", "try", "catch", "finally", + "throw", "delete", "new", "typeof", "instanceof", "in", "of", "this", "null", + "undefined", "true", "false", "async", "await", "yield", "class", "extends", + "import", "export", "default" + }; + + + return keywords; + } + + public static boolean isJavaScriptKeyword(String keyword) { + for (String k : getJavaScriptKeywords()) { + if (k.equals(keyword)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java new file mode 100644 index 000000000..df406ebba --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java @@ -0,0 +1,1610 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.ObjectLiteralParser; +import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSFieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSMethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodSignature; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; + +import java.lang.reflect.*; +import java.util.*; +import java.util.function.Supplier; + +/** + * Represents resolved type information for a class/interface/enum. + * + * This is the unified type system that supports: + * - Java types (via Class reflection) + * - Script-defined types (via ScriptTypeInfo subclass) + * - JavaScript/TypeScript types (via JSTypeInfo bridge) + * + * For JavaScript types, the jsTypeInfo field holds the parsed .d.ts data, + * and methods like hasMethod/getMethodInfo delegate to it. + */ +public class TypeInfo { + + public enum Kind { + CLASS, + INTERFACE, + ENUM, + UNKNOWN + } + + /** + * Singleton constant for the void type. + */ + public static final TypeInfo VOID = fromPrimitive("void"); + + public static final TypeInfo BOOLEAN = fromPrimitive("boolean"); + + public static final TypeInfo STRING = TypeInfo.fromClass(String.class); + static TypeInfo jsString = null; + + public static final TypeInfo OBJECT = TypeInfo.fromClass(Object.class); + static TypeInfo jsObject = null; + + public static TypeInfo string() { + return TypeChecker.isJavaScriptMode() && jsString != null ? jsString : STRING; + } + + public static TypeInfo object() { + return TypeChecker.isJavaScriptMode() && jsObject != null ? jsObject : OBJECT; + } + + public static final TypeInfo NULL = TypeInfo.unresolved("null", ""); + + /** + * Singleton constant for the "any" type (used in JavaScript/TypeScript). + * The "any" type is universally compatible - it can be assigned to anything + * and anything can be assigned to it. + */ + public static final TypeInfo ANY = new TypeInfo("any", "any", "", Kind.CLASS, null, true, null).setPrimitive(true); + public static final TypeInfo NUMBER = new TypeInfo("number", "number", "", Kind.CLASS, double.class, true, null).setPrimitive(true); + + public static final Supplier OBJECT_LITERAL = () -> new TypeInfo("ObjectLiteral", "ObjectLiteral", "", + Kind.CLASS, null, true, null); + + + private final String simpleName; // e.g., "List", "ColorType" + private final String fullName; // e.g., "java.util.List", "kamkeel...IOverlay$ColorType" + private final String packageName; // e.g., "java.util", "kamkeel.npcdbc.api.client.overlay" + private final Kind kind; // CLASS, INTERFACE, ENUM + private final Class javaClass; // The actual resolved Java class (null if unresolved or JS type) + private final boolean resolved; // Whether this type was successfully resolved + private final TypeInfo enclosingType; // For inner classes, the outer type (null if top-level) + + private boolean isPrimitive; // Whether this is a primitive type (e.g., int, boolean) + private boolean isObjectLiteral; + private String typeParameterName; // Non-null if this TypeInfo represents a type parameter (e.g., "T") + private TypeInfo boundType; // For type parameters with bounds, stores the bound for resolution + + // JavaScript/TypeScript type info (for types from .d.ts files) + private final JSTypeInfo jsTypeInfo; // The JS type info (null if Java type) + + // Declared type parameters (generics definition, e.g., "T extends Entity" on interface List) + private final List typeParams = new ArrayList<>(); + + // Applied type arguments (concrete types provided for generics, e.g., in Map) + // These are TypeInfo instances that can themselves be parameterized for nested generics + private List appliedTypeArgs = new ArrayList<>(); + + // For parameterized types, the raw/base type (e.g., List for List) + // Null for non-parameterized types + private TypeInfo rawType; + + // For array types, the element type (e.g., IItemStack for IItemStack[]) + // Null for non-array types + private final TypeInfo elementType; + + // Synthetic members injected at construction time (e.g. array built-ins: length, clone) + private final List syntheticFields = new ArrayList<>(); + private final List syntheticMethods = new ArrayList<>(); + + // Documentation (script-defined types) + private JSDocInfo jsDocInfo; + + // SAM (Single Abstract Method) caching for functional interface detection + private MethodInfo cachedSAM; + private boolean samCacheResolved = false; + + private TypeInfo(String simpleName, String fullName, String packageName, + Kind kind, Class javaClass, boolean resolved, TypeInfo enclosingType) { + this(simpleName, fullName, packageName, kind, javaClass, resolved, enclosingType, null, null, null, null); + } + + private TypeInfo(String simpleName, String fullName, String packageName, + Kind kind, Class javaClass, boolean resolved, TypeInfo enclosingType, + JSTypeInfo jsTypeInfo) { + this(simpleName, fullName, packageName, kind, javaClass, resolved, enclosingType, jsTypeInfo, null, null, null); + } + + private TypeInfo(String simpleName, String fullName, String packageName, + Kind kind, Class javaClass, boolean resolved, TypeInfo enclosingType, + JSTypeInfo jsTypeInfo, TypeInfo rawType, List appliedTypeArgs, TypeInfo elementType) { + this.simpleName = simpleName; + this.fullName = fullName; + this.packageName = packageName; + this.kind = kind; + this.javaClass = javaClass; + this.resolved = resolved; + this.enclosingType = enclosingType; + this.jsTypeInfo = jsTypeInfo; + this.rawType = rawType; + this.elementType = elementType; + if (appliedTypeArgs != null) { + this.appliedTypeArgs.addAll(appliedTypeArgs); + } + } + + // Protected constructor for subclasses (like ScriptTypeInfo) + protected TypeInfo(String simpleName, String fullName, String packageName, + Kind kind, Class javaClass, boolean resolved, TypeInfo enclosingType, + @SuppressWarnings("unused") boolean subclass) { + this.simpleName = simpleName; + this.fullName = fullName; + this.packageName = packageName; + this.kind = kind; + this.javaClass = javaClass; + this.resolved = resolved; + this.enclosingType = enclosingType; + this.jsTypeInfo = null; + this.rawType = null; + this.elementType = null; + } + + // Factory methods + public static TypeInfo resolved(String simpleName, String fullName, String packageName, + Kind kind, Class javaClass) { + return new TypeInfo(simpleName, fullName, packageName, kind, javaClass, true, null); + } + + public static TypeInfo resolvedInner(String simpleName, String fullName, String packageName, + Kind kind, Class javaClass, TypeInfo enclosing) { + return new TypeInfo(simpleName, fullName, packageName, kind, javaClass, true, enclosing); + } + + public static TypeInfo unresolved(String simpleName, String fullPath) { + int lastDot = fullPath.lastIndexOf('.'); + String pkg = lastDot > 0 ? fullPath.substring(0, lastDot) : ""; + return new TypeInfo(simpleName, fullPath, pkg, Kind.UNKNOWN, null, false, null); + } + + /** + * Create a TypeInfo representing an unbounded type parameter (e.g., {@code T} in {@code class Box}). + * Uses Object.class for member lookup (erasure semantics) but displays as the parameter name. + */ + public static TypeInfo typeParameter(String paramName) { + TypeInfo ti = new TypeInfo(paramName, paramName, "", Kind.CLASS, Object.class, true, null); + ti.typeParameterName = paramName; + return ti; + } + + /** + * Create a TypeInfo representing a bounded type parameter (e.g., {@code T extends Entity}). + * Keeps the type parameter's own identity (paramName as simpleName/fullName) but stores the + * bound separately for display. Uses the bound's javaClass/kind for member resolution (erasure semantics). + */ + public static TypeInfo typeParameter(String paramName, TypeInfo boundType) { + Class javaClass = (boundType != null && boundType.javaClass != null) ? boundType.javaClass : Object.class; + Kind kind = (boundType != null) ? boundType.kind : Kind.CLASS; + + if (boundType instanceof IntersectionTypeInfo) { + final IntersectionTypeInfo intersection = (IntersectionTypeInfo) boundType; + TypeInfo ti = new TypeInfo(paramName, paramName, "", kind, javaClass, true, null) { + @Override + public List getAllMethods() { + List result = new ArrayList<>(super.getAllMethods()); + for (TypeInfo bound : intersection.getAdditionalBounds()) + result.addAll(bound.getAllMethods()); + + return result; + } + @Override + public List getAllFields() { + List result = new ArrayList<>(super.getAllFields()); + for (TypeInfo bound : intersection.getAdditionalBounds()) + result.addAll(bound.getAllFields()); + + return result; + } + }; + ti.typeParameterName = paramName; + ti.boundType = boundType; + return ti; + } + + TypeInfo ti = new TypeInfo(paramName, paramName, "", kind, javaClass, true, null); + ti.typeParameterName = paramName; + ti.boundType = boundType; + return ti; + } + + /** + * Create a TypeInfo representing a bounded type parameter from a {@link TypeParamInfo}. + * This is the single point of control for creating type parameter TypeInfos with bound handling. + * + *

If the TypeParamInfo has additional bounds (e.g., {@code T extends Number & Comparable}), + * an {@link IntersectionTypeInfo} is created internally to represent the combined bound. + * This centralizes intersection creation so no caller needs to call {@code IntersectionTypeInfo.of()} directly.

+ * + * @param paramName the type parameter name (e.g., "T") + * @param typeParam the TypeParamInfo containing bound information + * @return a TypeInfo tagged as a type parameter with the effective bound + */ + public static TypeInfo typeParameter(String paramName, TypeParamInfo typeParam) { + if (typeParam == null) { + return typeParameter(paramName); + } + TypeInfo primaryBound = typeParam.getBoundTypeInfo(); + if (primaryBound == null) { + typeParam.resolveBoundType(); + primaryBound = typeParam.getBoundTypeInfo(); + } + + TypeInfo effectiveBound; + if (primaryBound != null && primaryBound.isResolved()) { + List additionalBounds = typeParam.getAdditionalBoundTypes(); + if (additionalBounds != null && !additionalBounds.isEmpty()) { + effectiveBound = IntersectionTypeInfo.of(primaryBound, additionalBounds); + } else { + effectiveBound = primaryBound; + } + } else { + effectiveBound = null; + } + return typeParameter(paramName, effectiveBound); + } + + public boolean isTypeParameter() { + return typeParameterName != null; + } + + public String getTypeParameterName() { + return typeParameterName; + } + + public TypeInfo getBoundType() { + return boundType; + } + + public static TypeInfo fromClass(Class clazz) { + if (clazz == null) return null; + + Kind kind; + if (clazz.isInterface()) { + kind = Kind.INTERFACE; + } else if (clazz.isEnum()) { + kind = Kind.ENUM; + } else { + kind = Kind.CLASS; + } + + String fullName = clazz.getName(); + String simpleName = clazz.getSimpleName(); + Package pkg = clazz.getPackage(); + String packageName = ""; + if (pkg != null) { + packageName = pkg.getName(); + } else if (!fullName.equals(simpleName)) { + int lastDot = fullName.lastIndexOf('.'); + if (lastDot > 0) { + packageName = fullName.substring(0, lastDot); + } + } + + TypeInfo enclosing = null; + if (clazz.getEnclosingClass() != null) { + enclosing = fromClass(clazz.getEnclosingClass()); + } + + if (clazz.isArray()) { + return arrayOf(fromClass(clazz.getComponentType())); + } + + return new TypeInfo(simpleName, fullName, packageName, kind, clazz, true, enclosing); + } + + /** + * Create a TypeInfo from a generic java.lang.reflect.Type. + * This preserves generic type arguments from reflection APIs like + * Method.getGenericReturnType() and Field.getGenericType(). + * + * Examples: + * - List -> TypeInfo(List) with appliedTypeArgs=[TypeInfo(String)] + * - Map -> TypeInfo(Map) with appliedTypeArgs=[TypeInfo(String), TypeInfo(Integer)] + * - T (type variable) -> TypeInfo representing the type variable name + * + * @param type The generic type from reflection + * @return A TypeInfo preserving the generic structure, or null if type is null + */ + public static TypeInfo fromGenericType(Type type) { + return fromGenericType(type, new HashSet>()); + } + + /** + * @param resolving type variables whose bounds are currently being expanded, so a + * self-referential bound such as {@code E extends Enum} terminates + */ + private static TypeInfo fromGenericType(Type type, Set> resolving) { + if (type == null) return null; + + if (type instanceof Class) { + // Plain class - no generic info + return fromClass((Class) type); + } + + if (type instanceof ParameterizedType) { + // Generic type like List + ParameterizedType paramType = (ParameterizedType) type; + Type rawType = paramType.getRawType(); + + if (!(rawType instanceof Class)) { + // Edge case - should not happen normally + return rawType != null ? fromGenericType(rawType, resolving) : null; + } + + // Get the raw type as TypeInfo + TypeInfo rawTypeInfo = fromClass((Class) rawType); + + // Recursively convert type arguments + Type[] typeArgs = paramType.getActualTypeArguments(); + List appliedArgs = new ArrayList<>(typeArgs.length); + for (Type arg : typeArgs) { + TypeInfo argInfo = fromGenericType(arg, resolving); + if (argInfo != null) { + appliedArgs.add(argInfo); + } + } + + // Return a parameterized TypeInfo + if (!appliedArgs.isEmpty()) { + return rawTypeInfo.parameterize(appliedArgs); + } + return rawTypeInfo; + } + + if (type instanceof GenericArrayType) { + // Array of generic type, e.g. T[] or List[] + GenericArrayType arrayType = (GenericArrayType) type; + TypeInfo elementType = fromGenericType(arrayType.getGenericComponentType(), resolving); + if (elementType != null) { + return arrayOf(elementType); + } + return fromClass(Object[].class); + } + + if (type instanceof TypeVariable) { + TypeVariable typeVar = (TypeVariable) type; + String varName = typeVar.getName(); + // Already expanding this variable - emit it unbounded rather than recursing forever + if (!resolving.add(typeVar)) { + return TypeInfo.typeParameter(varName); + } + try { + // Check for bounds - if bounded, create typeParameter with bound + Type[] bounds = typeVar.getBounds(); + if (bounds != null && bounds.length > 0 && bounds[0] != Object.class) { + return TypeInfo.typeParameter(varName, fromGenericType(bounds[0], resolving)); + } + return TypeInfo.typeParameter(varName); + } finally { + resolving.remove(typeVar); + } + } + + if (type instanceof WildcardType) { + // Wildcard like ? or ? extends Number or ? super Integer + WildcardType wildcard = (WildcardType) type; + Type[] upperBounds = wildcard.getUpperBounds(); + + // Use the upper bound if available (most useful for ? extends T) + if (upperBounds.length > 0 && upperBounds[0] != Object.class) { + return fromGenericType(upperBounds[0], resolving); + } + + // For ? super T or plain ?, just use Object + return fromClass(Object.class); + } + + // Unknown type - shouldn't happen in practice + return null; + } + + /** + * Create a TypeInfo for a primitive type. + */ + public static TypeInfo fromPrimitive(String typeName) { + Class primitiveClass = null; + switch (typeName) { + case "boolean": primitiveClass = boolean.class; break; + case "byte": primitiveClass = byte.class; break; + case "char": primitiveClass = char.class; break; + case "short": primitiveClass = short.class; break; + case "int": primitiveClass = int.class; break; + case "long": primitiveClass = long.class; break; + case "float": primitiveClass = float.class; break; + case "double": primitiveClass = double.class; break; + case "void": primitiveClass = void.class; break; + } + return new TypeInfo(typeName, typeName, "", Kind.CLASS, primitiveClass, true, null).setPrimitive(true); + } + + /** + * Create a TypeInfo from a JavaScript/TypeScript type. + * This bridges JS types parsed from .d.ts files into the unified type system. + * + * @param jsType The parsed JS type info + * @return A TypeInfo wrapping the JS type + */ + public static TypeInfo fromJSTypeInfo(JSTypeInfo jsType) { + if (jsType == null) return null; + + String syntheticDisplayName = ObjectLiteralParser.getSyntheticObjectLiteralDisplayName(jsType); + if (syntheticDisplayName != null) { + return new TypeInfo(syntheticDisplayName, jsType.getFullName(), "", + Kind.INTERFACE, null, true, null, jsType); + } + + String simpleName = jsType.getSimpleName(); + String fullName = jsType.getFullName(); + String namespace = jsType.getNamespace(); + + // JS interfaces are always Kind.INTERFACE + return new TypeInfo(simpleName, fullName, namespace != null ? namespace : "", + Kind.INTERFACE, null, true, null, jsType); + } + + public static TypeInfo objectLiteral(List properties) { + TypeInfo t = OBJECT_LITERAL.get(); + t.isObjectLiteral = true; + if (properties != null) { + for (ObjectLiteralParser.ObjectLiteralProperty p : properties) { + TypeInfo vt = (p.valueType != null) ? p.valueType : TypeInfo.ANY; + if (p.isCallable()) { + ObjectLiteralParser.CallableInfo ci = p.callableInfo; + t.syntheticFields.add(FieldInfo.external(p.keyName, TypeInfo.ANY, null, Modifier.PUBLIC)); + TypeInfo returnType = ci.returnsThis() ? t : ci.returnType; + if (returnType == null) { + returnType = t; + } + List params = new ArrayList<>(); + for (String paramName : ci.parameterNames) { + params.add(FieldInfo.external(paramName, TypeInfo.ANY, null, Modifier.PUBLIC)); + } + t.syntheticMethods.add(MethodInfo.external(p.keyName, returnType, t, + params, Modifier.PUBLIC, null)); + } else { + t.syntheticFields.add(FieldInfo.external(p.keyName, vt, null, Modifier.PUBLIC)); + } + } + } + return t; + } + + public void addSyntheticField(String name, TypeInfo type) { + syntheticFields.add(FieldInfo.external(name, type, null, Modifier.PUBLIC)); + } + + public void removeSyntheticField(String name) { + syntheticFields.removeIf(f -> f.getName().equals(name)); + } + + public void addSyntheticMethod(String name, TypeInfo returnType, List params) { + syntheticMethods.add(MethodInfo.external(name, returnType, this, + params != null ? params : Collections.emptyList(), Modifier.PUBLIC, null)); + } + + public void removeSyntheticMethod(String name) { + syntheticMethods.removeIf(m -> m.getName().equals(name)); + } + + public static void injectJSMembers(TypeInfo target, JSTypeInfo jsExtensions) { + for (JSFieldInfo jsField : jsExtensions.getFields().values()) + target.syntheticFields.add(FieldInfo.fromJSField(jsField, target)); + for (JSMethodInfo jsMethod : jsExtensions.getMethods().values()) + target.syntheticMethods.add(MethodInfo.fromJSMethod(jsMethod, target)); + } + + public List getSyntheticMethods() { + // Merge .d.ts methods for arrays in JS + if (isArray() && TypeChecker.isJavaScriptMode()) { + JSTypeInfo arrayType = JSTypeRegistry.getInstance().getType("Array"); + if (arrayType == null) { + return syntheticMethods; + } + + Map merged = new LinkedHashMap<>(); + for (MethodInfo method : syntheticMethods) { + merged.put(method.getSignature(), method); + } + + for (JSMethodInfo jsMethod : arrayType.getMethods().values()) { + if (jsMethod.isStatic()) { + continue; + } + MethodInfo method = MethodInfo.fromJSMethod(jsMethod, this); + merged.putIfAbsent(method.getSignature(), method); + } + + return new ArrayList<>(merged.values()); + } + + return syntheticMethods; + } + + public List getSyntheticFields() { + return syntheticFields; + } + + /** + * Create an array type wrapping the given element type. + * + * @param elementType The type of elements in the array + * @return A TypeInfo representing the array type + */ + public static TypeInfo arrayOf(TypeInfo elementType) { + if (elementType == null) { + return fromClass(Object[].class); + } + + // Preserve generic display in arrays (e.g., List[]) and keep JS namespace display. + String simpleName = elementType.getDisplayName() + "[]"; + String fullName = elementType.getDisplayNameFull() + "[]"; + String pkg = elementType.getPackageName(); + + // Try to get the actual array class if we have a Java class + Class arrayClass = null; + if (elementType.getJavaClass() != null) { + try { + arrayClass = java.lang.reflect.Array.newInstance(elementType.getJavaClass(), 0).getClass(); + } catch (Exception e) { + // Fallback to Object array if we can't create the specific array type + } + } + TypeInfo arr = new TypeInfo(simpleName, fullName, pkg, elementType.kind, arrayClass, elementType.isResolved(), + null, null, null, null, elementType); + arr.setPrimitive(elementType.isPrimitive()); + arr.syntheticFields.add(FieldInfo.external("length", TypeInfo.fromPrimitive("int"), null, + Modifier.PUBLIC | Modifier.FINAL)); + arr.syntheticMethods.add(MethodInfo.external("clone", arr, null, + Collections.emptyList(), Modifier.PUBLIC, null)); + + arr.typeParameterName = elementType.typeParameterName; + if (elementType.boundType != null) + arr.boundType = arrayOf(elementType.boundType); + return arr; + } + + /** + * Check if this is a JavaScript type (backed by JSTypeInfo). + */ + public boolean isJSType() { + return jsTypeInfo != null; + } + + public boolean isSyntheticObjectLiteralType() { + return isObjectLiteral; + } + + /** + * Get the underlying JSTypeInfo if this is a JS type. + */ + public JSTypeInfo getJSTypeInfo() { + return jsTypeInfo; + } + + public JSDocInfo getJSDocInfo() { + if (jsDocInfo != null) { + return jsDocInfo; + } + return jsTypeInfo != null ? jsTypeInfo.getJsDocInfo() : null; + } + + public void setJSDocInfo(JSDocInfo jsDocInfo) { this.jsDocInfo = jsDocInfo; } + + // Getters + public String getSimpleName() { return simpleName; } + public String getFullName() { return fullName; } + public String getPackageName() { return packageName; } + public Kind getKind() { return kind; } + public Class getJavaClass() { return javaClass; } + public boolean isResolved() { return resolved; } + public TypeInfo getEnclosingType() { return enclosingType; } + public boolean isInnerClass() { return enclosingType != null; } + public boolean isInterface() {return kind == Kind.INTERFACE;} + public boolean isEnum() {return kind == Kind.ENUM;} + public boolean isClass() {return kind == Kind.CLASS;} + public boolean isPrimitive() {return this.isPrimitive || javaClass != null && javaClass.isPrimitive();} + private TypeInfo setPrimitive(boolean value) { this.isPrimitive = value; return this;} + + // ==================== Applied Type Arguments (Parameterized Types) ==================== + + /** + * Check if this type is parameterized (has applied type arguments). + * For example, List is parameterized, but List is not. + */ + public boolean isParameterized() { + return !appliedTypeArgs.isEmpty(); + } + + /** + * Get the raw/base type if this is parameterized. + * For List, returns the TypeInfo for List. + * For non-parameterized types, returns this. + */ + public TypeInfo getRawType() { + return rawType != null ? rawType : this; + } + + public TypeInfo getElementType() { + return elementType; + } + + public boolean isArray() { + return elementType != null || (javaClass != null && javaClass.isArray()); + } + + /** + * Get the applied type arguments. + * For List, returns [TypeInfo(String)]. + * For Map, returns [TypeInfo(String), TypeInfo(Integer)]. + * For nested generics like List>, the Map TypeInfo itself has appliedTypeArgs. + */ + public List getAppliedTypeArgs() { + return appliedTypeArgs; + } + + protected void setRawType(TypeInfo rawType) { + this.rawType = rawType; + } + + protected void setAppliedTypeArgs(List args) { + this.appliedTypeArgs = new ArrayList<>(args); + } + + /** + * Create a parameterized version of this type with the given type arguments. + * For example, calling parameterize([TypeInfo(String)]) on List returns List. + * + * @param typeArgs The type arguments to apply + * @return A new parameterized TypeInfo + */ + public TypeInfo parameterize(List typeArgs) { + if (typeArgs == null || typeArgs.isEmpty()) { + return this; + } + + // Keep base names stable for logic (constructor names, lookups, etc.). + // Generic arguments are tracked via appliedTypeArgs and rendered via getDisplayName*(). + TypeInfo raw = getRawType(); + return new TypeInfo(raw.simpleName, raw.fullName, raw.packageName, raw.kind, raw.javaClass, + raw.resolved, raw.enclosingType, raw.jsTypeInfo, raw, typeArgs, null); + } + + /** + * Create a parameterized version of this type with a single type argument. + */ + public TypeInfo parameterize(TypeInfo typeArg) { + if (typeArg == null) { + return this; + } + List args = new ArrayList<>(); + args.add(typeArg); + return parameterize(args); + } + + /** + * Build the generic type arguments string like "". + * @param typeArgs The type arguments + * @param useFullNames Whether to use full names (for fullName) or simple names (for simpleName) + */ + private static String buildTypeArgsString(List typeArgs, boolean useFullNames) { + if (typeArgs == null || typeArgs.isEmpty()) { + return ""; + } + StringBuilder sb = new StringBuilder("<"); + for (int i = 0; i < typeArgs.size(); i++) { + if (i > 0) sb.append(", "); + TypeInfo arg = typeArgs.get(i); + sb.append(useFullNames ? arg.getDisplayNameFull() : arg.getDisplayNameSimple()); + } + sb.append(">"); + return sb.toString(); + } + + /** + * Get the canonical display name for this type, including generic arguments. + * This is the preferred method for UI display (hover, autocomplete, etc.). + * + * For Java types: uses simple name + generics (e.g., "List") + * For JS types: uses full name + generics (e.g., "IPlayerEvent.InteractEvent") + * For arrays: includes "[]" suffix + * For nested generics: recursively builds (e.g., "List>") + */ + public String getDisplayName() { + // Use full name for JS types, simple name for Java + return isJSType() ? getDisplayNameFull() : getDisplayNameSimple(); + } + + /** + * Get display name using simple names for all types. + * Example: "Map" instead of "java.util.Map" + */ + public String getDisplayNameSimple() { + if (appliedTypeArgs.isEmpty()) { + return simpleName; + } + + String baseName = rawType != null ? rawType.getSimpleName() : simpleName; + return baseName + buildTypeArgsString(appliedTypeArgs, false); + } + + /** + * Get display name using full qualified names. + * Example: "java.util.Map" + */ + public String getDisplayNameFull() { + if (appliedTypeArgs.isEmpty()) { + return fullName; + } + // For full display, use the raw type's full name + the args with their display names + String baseName = rawType != null ? rawType.getFullName() : fullName; + return baseName + buildTypeArgsString(appliedTypeArgs, true); + } + + /** + * Returns true if this TypeInfo represents a Class reference (not an instance). + * For example, Java.type("java.io.File") returns a Class reference. + * Override in ClassTypeInfo to return true. + */ + public boolean isClassReference() { return false; } + + /** + * Get the appropriate TokenType for highlighting this type. + */ + public TokenType getTokenType() { + if (!resolved) + return TokenType.UNDEFINED_VAR; + if (isTypeParameter()) + return TokenType.GENERIC_TYPE_PARAM; + if(isPrimitive()) + return TokenType.KEYWORD; + + switch (kind) { + case INTERFACE: + return TokenType.INTERFACE_DECL; + case ENUM: + return TokenType.ENUM_DECL; + case CLASS: + default: + return TokenType.IMPORTED_CLASS; + } + } + + /** + * Returns all public instance members of this type for autocomplete/resolution. + * Override in subclasses to extend or replace the default Java reflection path. + */ + public List getAllMethods() { + if (javaClass != null) { + // Java reflection path: enumerate public methods + synthetics + List result = new ArrayList<>(); + try { + for (java.lang.reflect.Method m : javaClass.getMethods()) { + try { + result.add(MethodInfo.fromReflection(m, this)); + } catch (Exception e) { + // Skip individual methods that fail (e.g., linkage errors on obscure return types) + } + } + } catch (Exception ignored) {} + result.addAll(getSyntheticMethods()); + return result; + } + + // javaClass == null: check rawType, jsTypeInfo, synthetics in priority order + if (rawType != null && rawType != this) { + List rawMethods = rawType.getAllMethods(); + if (!rawMethods.isEmpty() && isParameterized()) { + GenericContext ctx = GenericContext.forReceiver(this); + List substituted = new ArrayList<>(rawMethods.size()); + for (MethodInfo m : rawMethods) { + substituted.add(m.substituteTypeParams(ctx)); + } + return substituted; + } + return rawMethods; + } + + // No javaClass, no rawType — collect from jsTypeInfo and synthetics + List result = new ArrayList<>(); + if (jsTypeInfo != null) { + for (JSMethodInfo m : jsTypeInfo.getMethods().values()) { + result.add(MethodInfo.fromJSMethod(m, this)); + } + } + result.addAll(getSyntheticMethods()); + return result; + } + + public List getAllFields() { + if (javaClass != null) { + // Java reflection path: enumerate public fields + synthetics + List result = new ArrayList<>(); + try { + for (java.lang.reflect.Field f : javaClass.getFields()) { + try { + result.add(FieldInfo.fromReflection(f, this)); + } catch (Exception e) { + // Skip individual fields that fail rather than losing ALL fields. + } + } + } catch (Exception ignored) {} + result.addAll(getSyntheticFields()); + return result; + } + + // javaClass == null: check rawType, jsTypeInfo, synthetics in priority order + if (rawType != null && rawType != this) { + List rawFields = rawType.getAllFields(); + if (!rawFields.isEmpty() && isParameterized()) { + GenericContext ctx = GenericContext.forReceiver(this); + List substituted = new ArrayList<>(rawFields.size()); + for (FieldInfo f : rawFields) { + substituted.add(f.substituteTypeParams(ctx)); + } + return substituted; + } + return rawFields; + } + + // No javaClass, no rawType — collect from jsTypeInfo and synthetics + List result = new ArrayList<>(); + if (jsTypeInfo != null) { + for (JSFieldInfo f : jsTypeInfo.getFields().values()) { + result.add(FieldInfo.fromJSField(f, this)); + } + } + result.addAll(getSyntheticFields()); + return result; + } + + /** + * Returns all public nested types (inner classes/interfaces/enums) of this type. + * Uses reflection to discover nested types from the Java class, filters to public only, + * converts internal '$' separators to '.' for name resolution, and resolves each via TypeResolver. + * + * Override in subclasses (e.g., ScriptTypeInfo) to return script-defined inner classes. + * + * @return List of resolved nested TypeInfo instances (may be empty, never null) + */ + public List getAllNestedTypes() { + if (javaClass != null) { + List result = new ArrayList<>(); + try { + for (Class nested : javaClass.getDeclaredClasses()) { + if (!Modifier.isPublic(nested.getModifiers())) { + continue; + } + // Convert JVM internal '$' separator to '.' for TypeResolver lookup + String nestedFullName = nested.getName().replace('$', '.'); + TypeInfo nestedType = TypeResolver.getInstance().resolveFullName(nestedFullName); + if (nestedType != null && nestedType.isResolved()) { + result.add(nestedType); + } + } + } catch (SecurityException ignored) { + // Some runtimes may restrict getDeclaredClasses() + } + return result; + } + + if (rawType != null && rawType != this) { + return rawType.getAllNestedTypes(); + } + + // No javaClass, no rawType — check jsTypeInfo for inner types + if (jsTypeInfo != null) { + Map innerTypes = jsTypeInfo.getInnerTypes(); + if (!innerTypes.isEmpty()) { + List result = new ArrayList<>(innerTypes.size()); + for (JSTypeInfo inner : innerTypes.values()) { + TypeInfo ti = TypeInfo.fromJSTypeInfo(inner); + if (ti != null) { + result.add(ti); + } + } + return result; + } + } + return Collections.emptyList(); + } + + /** + * Check if this type has a method with the given name. + */ + public boolean hasMethod(String methodName) { + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + return true; + // Check JS type first + if (jsTypeInfo != null) { + if (jsTypeInfo.hasMethod(methodName)) return true; + } else if (javaClass != null) { + try { + for (java.lang.reflect.Method m : javaClass.getMethods()) { + if (m.getName().equals(methodName)) return true; + } + } catch (Exception e) { + // Security or linkage error + } + } else if (rawType != null && rawType != this) { + return rawType.hasMethod(methodName); + } + + TypeInfo obj = TypeInfo.object(); + if (obj != this) return obj.hasMethod(methodName); + return false; + } + + /** + * Check if this type has a method with the given name and parameter count. + */ + public boolean hasMethod(String methodName, int paramCount) { + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName) && m.getParameterCount() == paramCount) + return true; + // Check JS type first + if (jsTypeInfo != null) { + List overloads = jsTypeInfo.getMethodOverloads(methodName); + for (JSMethodInfo m : overloads) { + if (m.getParameterCount() == paramCount) return true; + } + } else if (javaClass != null) { + try { + for (java.lang.reflect.Method m : javaClass.getMethods()) { + if (m.getName().equals(methodName) && m.getParameterCount() == paramCount) return true; + } + } catch (Exception e) { + // Security or linkage error + } + } else if (rawType != null && rawType != this) { + return rawType.hasMethod(methodName, paramCount); + } + TypeInfo obj = TypeInfo.object(); + if (obj != this) return obj.hasMethod(methodName); + return false; + } + + /** + * Check if this type has constructors. + * Override in ScriptTypeInfo for script-defined types. + */ + public boolean hasConstructors() { + if (javaClass != null) { + try { + return javaClass.getConstructors().length > 0; + } catch (Exception e) { + return false; + } + } + if (rawType != null && rawType != this) return rawType.hasConstructors(); + return false; + } + + /** + * Get the constructors for this type. + * Override in ScriptTypeInfo for script-defined types. + */ + public List getConstructors() { + List result = new ArrayList<>(); + if (javaClass != null) { + try { + java.lang.reflect.Constructor[] constructors = javaClass.getConstructors(); + for (java.lang.reflect.Constructor ctor : constructors) { + result.add(MethodInfo.fromReflectionConstructor(ctor, this)); + } + } catch (Exception e) { + // Security or linkage error + } + return result; + } + if (rawType != null && rawType != this) return rawType.getConstructors(); + return result; + } + + /** + * Find the best matching constructor for the given argument count. + * Override in ScriptTypeInfo for script-defined types. + */ + public MethodInfo findConstructor(int argCount) { + if (javaClass != null) { + try { + Constructor[] constructors = javaClass.getConstructors(); + for (Constructor ctor : constructors) { + if (ctor.getParameterCount() == argCount) { + return MethodInfo.fromReflectionConstructor(ctor, this); + } + } + } catch (Exception e) { + // Security or linkage error + } + return null; + } + if (rawType != null && rawType != this) return rawType.findConstructor(argCount); + return null; + } + + public MethodInfo findConstructor(TypeInfo[] argTypes) { + if (javaClass != null) { + try { + Constructor[] constructors = javaClass.getConstructors(); + for (Constructor ctor : constructors) { + if (ctor.getParameterCount() == argTypes.length) { + Class[] paramTypes = ctor.getParameterTypes(); + boolean match = true; + for (int i = 0; i < argTypes.length; i++) { + TypeInfo paramTypeInfo = TypeInfo.fromClass(paramTypes[i]); + if (!TypeChecker.isTypeCompatible(paramTypeInfo, argTypes[i])) { + match = false; + break; + } + } + if (match) { + return MethodInfo.fromReflectionConstructor(ctor, this); + } + } + } + } catch (Exception e) { + // Security or linkage error + } + return null; + } + if (rawType != null && rawType != this) return rawType.findConstructor(argTypes); + return null; + } + + /** + * Check if this type has a field with the given name. + */ + public boolean hasField(String fieldName) { + for (FieldInfo f : syntheticFields) if (f.getName().equals(fieldName)) return true; + // Check JS type first + if (jsTypeInfo != null) { + return jsTypeInfo.hasField(fieldName); + } + + if (javaClass != null) { + try { + for (java.lang.reflect.Field f : javaClass.getFields()) { + if (f.getName().equals(fieldName)) { + return true; + } + } + } catch (Exception e) { + // Security or linkage error + } + return false; + } + if (rawType != null && rawType != this) return rawType.hasField(fieldName); + return false; + } + + /** + * Returns all enum constants for this type as a name-to-EnumConstantInfo map. + * For Java enum types, builds the map via reflection. For script-defined enums, + * ScriptTypeInfo overrides this to return its stored constants directly. + * + * @return Map of constant name to EnumConstantInfo (empty if not an enum or no constants) + */ + public Map getEnumConstants() { + if (javaClass == null || !javaClass.isEnum()) { + if (rawType != null && rawType != this) { + return rawType.getEnumConstants(); + } + return Collections.emptyMap(); + } + Map result = new LinkedHashMap<>(); + try { + Object[] constants = javaClass.getEnumConstants(); + for (Object constant : constants) { + String name = constant.toString(); + result.put(name, EnumConstantInfo.fromReflection(name, this, null)); + } + } catch (Exception e) { + // Security or linkage error — return whatever we have so far + } + return result; + } + + public boolean hasEnumConstant(String constantName) { + if (javaClass != null && javaClass.isEnum()) { + try { + Object[] constants = javaClass.getEnumConstants(); + for (Object constant : constants) { + if (constant.toString().equals(constantName)) + return true; + } + } catch (Exception e) { + // Security or linkage error + } + return false; + } + if (rawType != null && rawType != this) return rawType.hasEnumConstant(constantName); + return false; + } + + /** + * Get an enum constant by name. + */ + public EnumConstantInfo getEnumConstant(String constantName) { + if (javaClass != null && javaClass.isEnum()) { + try { + Object[] constants = javaClass.getEnumConstants(); + for (Object constant : constants) { + if (constant.toString().equals(constantName)) + return EnumConstantInfo.fromReflection(constantName, this, null); + } + } catch (Exception e) { + // Security or linkage error + } + return null; + } + if (rawType != null && rawType != this) return rawType.getEnumConstant(constantName); + return null; + } + + /** + * Get MethodInfo for a method by name. Returns null if not found. + * Creates a synthetic MethodInfo based on reflection data or JS type data. + */ + public MethodInfo getMethodInfo(String methodName) { + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + return m; + if (jsTypeInfo != null) { + JSMethodInfo jsMethod = jsTypeInfo.getMethod(methodName); + if (jsMethod != null) return MethodInfo.fromJSMethod(jsMethod, this); + } else if (javaClass != null) { + try { + for (java.lang.reflect.Method m : javaClass.getMethods()) { + if (m.getName().equals(methodName)) return MethodInfo.fromReflection(m, this); + } + } catch (Exception e) { + // Security or linkage error + } + } else if (rawType != null && rawType != this) { + MethodInfo rawMethod = rawType.getMethodInfo(methodName); + if (rawMethod != null && isParameterized()) { + GenericContext ctx = GenericContext.forReceiver(this); + return rawMethod.substituteTypeParams(ctx); + } + return rawMethod; + } + TypeInfo obj = TypeInfo.object(); + if (obj != this) return obj.getMethodInfo(methodName); + return null; + } + + /** + * Get all MethodInfo overloads for a method by name. + * Returns an empty list if not found. + */ + public java.util.List getAllMethodOverloads(String methodName) { + java.util.List overloads = new java.util.ArrayList<>(); + + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + overloads.add(m); + if (!overloads.isEmpty()) return overloads; + + // Check JS type first + if (jsTypeInfo != null) { + for (JSMethodInfo jsMethod : jsTypeInfo.getMethodOverloads(methodName)) { + // Type parameter resolution now happens inside fromJSMethod using this TypeInfo + overloads.add(MethodInfo.fromJSMethod(jsMethod, this)); + } + if (!overloads.isEmpty()) return overloads; + } else if (javaClass != null) { + try { + for (java.lang.reflect.Method m : javaClass.getMethods()) { + if (m.getName().equals(methodName)) { + overloads.add(MethodInfo.fromReflection(m, this)); + } + } + } catch (Exception e) { + // Security or linkage error + } + if (!overloads.isEmpty()) return overloads; + } else if (rawType != null && rawType != this) { + java.util.List rawOverloads = rawType.getAllMethodOverloads(methodName); + if (!rawOverloads.isEmpty() && isParameterized()) { + GenericContext ctx = GenericContext.forReceiver(this); + for (MethodInfo m : rawOverloads) { + overloads.add(m.substituteTypeParams(ctx)); + } + return overloads; + } + return rawOverloads; + } + TypeInfo obj = TypeInfo.object(); + if (obj != this) return obj.getAllMethodOverloads(methodName); + return overloads; + } + + /** + * Find the best matching method overload considering return type. + * First tries to find a match with compatible return type, then falls back to any match. + * + * @param methodName The name of the method + * @param expectedReturnType The expected return type (can be null) + * @return The best matching MethodInfo, or null if not found + */ + public MethodInfo getBestMethodOverload(String methodName, TypeInfo expectedReturnType) { + java.util.List overloads = getAllMethodOverloads(methodName); + if (overloads.isEmpty()) return null; + + // If no expected return type, return first overload + if (expectedReturnType == null) { + return overloads.get(0); + } + + // First pass: look for return type compatible overload + for (MethodInfo method : overloads) { + TypeInfo returnType = method.getReturnType(); + if (returnType != null && TypeChecker.isTypeCompatible(expectedReturnType, returnType)) { + return method; + } + } + // Second pass: return any overload (first one) + return overloads.get(0); + } + + /** + * Find the best matching method overload based on argument types. + * Uses Java's method resolution rules: exact match, then numeric promotion, then widening conversion, then autoboxing. + * + * @param methodName The name of the method + * @param argTypes The types of the arguments being passed + * @return The best matching MethodInfo, or null if not found + */ + public MethodInfo getBestMethodOverload(String methodName, TypeInfo[] argTypes) { + for (MethodInfo m : getSyntheticMethods()) + if (m.getName().equals(methodName)) + return m; + java.util.List overloads = getAllMethodOverloads(methodName); + if (overloads.isEmpty()) return null; + return OverloadSelector.selectBestOverload(overloads, argTypes); + } + + /** + * Get FieldInfo for a field by name. Returns null if not found. + * Creates a synthetic FieldInfo based on reflection data or JS type data. + */ + public FieldInfo getFieldInfo(String fieldName) { + for (FieldInfo f : syntheticFields) if (f.getName().equals(fieldName)) return f; + // Check JS type first + if (jsTypeInfo != null) { + JSFieldInfo jsField = jsTypeInfo.getField(fieldName); + if (jsField != null) { + return FieldInfo.fromJSField(jsField, this); + } + return null; + } + + if (javaClass != null) { + try { + for (java.lang.reflect.Field f : javaClass.getFields()) { + if (f.getName().equals(fieldName)) { + return FieldInfo.fromReflection(f, this); + } + } + } catch (Exception e) { + // Security or linkage error + } + return null; + } + if (rawType != null && rawType != this) { + FieldInfo rawField = rawType.getFieldInfo(fieldName); + if (rawField != null && isParameterized()) { + GenericContext ctx = GenericContext.forReceiver(this); + return rawField.substituteTypeParams(ctx); + } + return rawField; + } + return null; + } + + /** + * Validate this type. Default implementation does nothing (for Java types). + * Override in ScriptTypeInfo to validate script-defined types. + */ + public void validate() { + // Default: no validation for Java types + } + + // ==================== Functional Interface (SAM) Detection ==================== + + /** + * Determine whether this type is a functional interface and return its single abstract method (SAM). + * + * For Java reflection types (javaClass != null): + * - Must be an interface + * - Collects all public methods from javaClass.getMethods() + * - Filters out: static methods, default methods, and Object methods + * - If exactly one abstract instance method remains, returns it as a MethodInfo + * + * For script-defined interfaces (ScriptTypeInfo with kind == INTERFACE): + * - Identifies abstract methods (methods without body) + * - If exactly one exists, returns it as a MethodInfo + * + * @return MethodInfo for the single abstract method, or null if not a functional interface + */ + public MethodInfo getSingleAbstractMethod() { + // Return cached result if already resolved + if (samCacheResolved) { + return cachedSAM; + } + + // Mark as resolved to prevent re-computation + samCacheResolved = true; + + try { + // Handle Java reflection types + if (javaClass != null) { + // Only interfaces can be functional interfaces (for simplicity) + if (!javaClass.isInterface()) { + cachedSAM = null; + return null; + } + + // Collect all public methods + java.lang.reflect.Method[] methods = javaClass.getMethods(); + java.lang.reflect.Method singleAbstractMethod = null; + + for (java.lang.reflect.Method method : methods) { + int modifiers = method.getModifiers(); + + // Skip static methods + if (java.lang.reflect.Modifier.isStatic(modifiers)) { + continue; + } + + // Skip default methods (Java 8+) + if (method.isDefault()) { + continue; + } + + // Skip methods inherited from Object + String methodName = method.getName(); + if (isObjectMethod(methodName, method.getParameterCount())) { + continue; + } + + // This is an abstract instance method + if (singleAbstractMethod != null) { + // More than one abstract method - not a functional interface + cachedSAM = null; + return null; + } + + singleAbstractMethod = method; + } + + // If exactly one abstract method found, create MethodInfo with generic substitution + if (singleAbstractMethod != null) { + cachedSAM = MethodInfo.fromReflection(singleAbstractMethod, this); + return cachedSAM; + } + + cachedSAM = null; + return null; + } + + // Handle script-defined interfaces + if (this instanceof ScriptTypeInfo) { + ScriptTypeInfo scriptType = (ScriptTypeInfo) this; + + // Only check interfaces + if (scriptType.getKind() != Kind.INTERFACE) { + cachedSAM = null; + return null; + } + + // Find all abstract methods (methods without body) + // For script-defined interfaces, all declared methods are implicitly abstract + java.util.List allMethods = scriptType.getAllMethodsFlat(); + + if (allMethods.size() == 1) { + // Exactly one method - it's the SAM + cachedSAM = allMethods.get(0); + return cachedSAM; + } else if (allMethods.size() > 1) { + // More than one method - not a functional interface + cachedSAM = null; + return null; + } + + cachedSAM = null; + return null; + } + + // Not a functional interface — try rawType for parameterized script types + if (rawType != null && rawType != this) { + MethodInfo rawSAM = rawType.getSingleAbstractMethod(); + if (rawSAM != null && isParameterized()) { + GenericContext ctx = GenericContext.forReceiver(this); + cachedSAM = rawSAM.substituteTypeParams(ctx); + return cachedSAM; + } + cachedSAM = rawSAM; + return cachedSAM; + } + cachedSAM = null; + return null; + + } catch (Exception e) { + // Any reflection or security error - treat as not a functional interface + cachedSAM = null; + return null; + } + } + + /** + * Check if this type is a functional interface (has a single abstract method). + * + * @return true if this is a functional interface, false otherwise + */ + public boolean isFunctionalInterface() { + return getSingleAbstractMethod() != null; + } + + /** + * Helper method to check if a method is inherited from java.lang.Object. + * These methods don't count toward the SAM requirement. + * + * @param methodName The name of the method + * @param paramCount The number of parameters + * @return true if this is an Object method + */ + private boolean isObjectMethod(String methodName, int paramCount) { + switch (methodName) { + case "equals": + return paramCount == 1; + case "hashCode": + case "toString": + case "getClass": + case "notify": + case "notifyAll": + return paramCount == 0; + case "wait": + // wait() has overloads with 0, 1, and 2 parameters + return paramCount == 0 || paramCount == 1 || paramCount == 2; + default: + return false; + } + } + + // ==================== Type Parameter Methods ==================== + + /** + * Add a type parameter to this type. + * Used during parsing/construction of types with generics. + */ + public void addTypeParam(TypeParamInfo param) { + // If this is a JS type, delegate to JSTypeInfo + if (jsTypeInfo != null) { + jsTypeInfo.addTypeParam(param); + } else { + typeParams.add(param); + } + } + + /** + * Get all type parameters for this type. + * @return List of type parameters (empty if none) + */ + public List getTypeParams() { + // If this is a JS type, delegate to JSTypeInfo + if (jsTypeInfo != null) { + return jsTypeInfo.getTypeParams(); + } + + // For Java reflection types, lazily expose declared generic parameters (e.g., List, Map) + if (javaClass != null && typeParams.isEmpty()) { + try { + TypeVariable[] vars = javaClass.getTypeParameters(); + for (TypeVariable v : vars) { + if (v == null) continue; + String n = v.getName(); + if (n == null || n.isEmpty()) continue; + typeParams.add(new TypeParamInfo(n, null, null)); + } + } catch (Exception ignored) { + // Best-effort only; leave typeParams empty. + } + } + return typeParams; + } + + /** + * Resolve all type parameters for this type. + * Called during Phase 2 after all types are loaded into the registry. + */ + public void resolveTypeParameters() { + // If this is a JS type, delegate to JSTypeInfo + if (jsTypeInfo != null) { + jsTypeInfo.resolveTypeParameters(); + } else { + for (TypeParamInfo param : typeParams) { + param.resolveBoundType(); + } + } + } + + /** + * Get the type parameter info for a given parameter name (e.g., "T"). + * @return TypeParamInfo or null if not found + */ + public TypeParamInfo getTypeParam(String name) { + // If this is a JS type, delegate to JSTypeInfo + if (jsTypeInfo != null) { + return jsTypeInfo.getTypeParam(name); + } + + for (TypeParamInfo param : typeParams) { + if (param.getName().equals(name)) { + return param; + } + } + return null; + } + + @Override + public String toString() { + return "TypeInfo{" + fullName + ", " + kind + ", resolved=" + resolved + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof TypeInfo)) + return false; + TypeInfo other = (TypeInfo) o; + + if (!fullName.equals(other.fullName)) + return false; + + if (typeParameterName != null || other.typeParameterName != null) { + if (!Objects.equals(typeParameterName, other.typeParameterName)) + return false; + if (!Objects.equals(boundType, other.boundType)) + return false; + } + + if(!appliedTypeArgs.equals(other.appliedTypeArgs)) + return false; + + if (!Objects.equals(elementType, other.elementType)) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = fullName.hashCode(); + if (typeParameterName != null) + result = 31 * result + typeParameterName.hashCode(); + if (elementType != null) + result = 31 * result + elementType.hashCode(); + return result; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeResolver.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeResolver.java new file mode 100644 index 000000000..de626e96d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeResolver.java @@ -0,0 +1,1009 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.PackageFinder; +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeRegistry; +import noppes.npcs.client.gui.util.script.interpreter.token.TokenType; +import noppes.npcs.client.gui.util.script.interpreter.type.synthetic.SyntheticType; + +import java.util.*; + +/** + * Unified type resolver for both Java and JavaScript/TypeScript types. + * Serves as the single front-end for all type resolution needs. + * + * For Java: Uses reflection and import resolution + * For JavaScript: Delegates to JSTypeRegistry for .d.ts defined types + * + * This is the ONLY class that should be used for type resolution. + */ +public class TypeResolver { + + // Cache: fully-qualified class name -> TypeInfo + private final Map typeCache = new HashMap<>(); + + // Cache: Java types that have been enriched with JS members from .d.ts types (e.g., String, Object) + private final Map jsMergeCache = new HashMap<>(); + + // Cache: validated package paths + private final Set validPackages = new HashSet<>(); + + // JavaScript type registry (lazily initialized) + private JSTypeRegistry jsTypeRegistry; + + // Synthetic type registry (e.g., Nashorn built-ins) + private final Map syntheticTypes = new LinkedHashMap<>(); + + // Auto-imported java.lang classes + public static final Set JAVA_LANG_CLASSES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "Object", "String", "Class", "System", "Math", "Integer", "Double", "Float", "Long", "Short", "Byte", + "Character", "Boolean", "Number", "Void", "Thread", "Runnable", "Exception", "RuntimeException", + "Error", "Throwable", "StringBuilder", "StringBuffer", "Enum", "Comparable", "Iterable", + "CharSequence", "Cloneable", "Process", "ProcessBuilder", "Runtime", "SecurityManager", + "ClassLoader", "Package", "ArithmeticException", "ArrayIndexOutOfBoundsException", + "ClassCastException", "IllegalArgumentException", "IllegalStateException", + "IndexOutOfBoundsException", "NullPointerException", "NumberFormatException", + "UnsupportedOperationException", "AssertionError", "OutOfMemoryError", "StackOverflowError" + ))); + + // JavaScript primitive type mappings + private static final Map JS_PRIMITIVE_TO_JAVA = new HashMap<>(); + static { + JS_PRIMITIVE_TO_JAVA.put("string", "String"); + JS_PRIMITIVE_TO_JAVA.put("number", "double"); + JS_PRIMITIVE_TO_JAVA.put("boolean", "boolean"); + JS_PRIMITIVE_TO_JAVA.put("any", "Object"); + JS_PRIMITIVE_TO_JAVA.put("void", "void"); + JS_PRIMITIVE_TO_JAVA.put("null", "null"); + JS_PRIMITIVE_TO_JAVA.put("undefined", "void"); + JS_PRIMITIVE_TO_JAVA.put("object", "Object"); + } + + // Singleton instance for global caching (optional - can also use per-document instances) + private static TypeResolver instance; + + public static TypeResolver getInstance() { + if (instance == null) { + instance = new TypeResolver(); + } + return instance; + } + + public TypeResolver() { + // Pre-register common packages + validPackages.add("java"); + validPackages.add("java.lang"); + validPackages.add("java.util"); + validPackages.add("java.io"); + + // Initialize built-in synthetic types + initializeSyntheticTypes(); + } + + /** + * Initialize built-in synthetic types (e.g., Nashorn built-ins). + */ + private void initializeSyntheticTypes() { + // Register all Nashorn built-in types (Java, etc.) + for (SyntheticType type : NashornBuiltins.getInstance().getAllBuiltinTypes()) { + syntheticTypes.put(type.getName(), type); + } + + // Register all Nashorn global functions (print, load, etc.) + Map nashornGlobals = NashornBuiltins.getInstance().getAllGlobalFunctions(); + syntheticTypes.putAll(nashornGlobals); + } + + // ==================== SYNTHETIC TYPE REGISTRY ==================== + + /** + * Register a synthetic type for use in scripts. + * @param name The type name (e.g., "Java", "MyCustomType") + * @param type The synthetic type definition + */ + public void registerSyntheticType(String name, SyntheticType type) { + syntheticTypes.put(name, type); + } + + /** + * Check if a name is a known synthetic type. + * @param name The type name to check + * @return true if the name is a registered synthetic type + */ + public boolean isSyntheticType(String name) { + return syntheticTypes.containsKey(name); + } + + /** + * Get a synthetic type by name. + * @param name The type name + * @return The synthetic type, or null if not found + */ + public SyntheticType getSyntheticType(String name) { + return syntheticTypes.get(name); + } + + /** + * Get all registered synthetic types. + * @return Collection of all synthetic types + */ + public Collection getAllSyntheticTypes() { + return syntheticTypes.values(); + } + + // ==================== JS TYPE REGISTRY ACCESS ==================== + + /** + * Get the JS type registry, initializing it if needed. + */ + public JSTypeRegistry getJSTypeRegistry() { + if (jsTypeRegistry == null) { + jsTypeRegistry = JSTypeRegistry.getInstance(); + if (!jsTypeRegistry.isInitialized()) { + jsTypeRegistry.initializeFromResources(); + } + jsTypeRegistry.syncHooksFromScriptHookControllerIfNeeded(); + } + return jsTypeRegistry; + } + + /** + * Check if a function name is a known JS hook. + */ + public boolean isJSHook(String functionName) { + return getJSTypeRegistry().isHook(functionName); + } + + /** + * Get the parameter type for a JS hook function. + */ + public String getJSHookParameterType(String functionName) { + return getJSTypeRegistry().getHookParameterType(functionName); + } + + /** + * Get hook signatures for a JS function. + */ + public List getJSHookSignatures(String functionName) { + return getJSTypeRegistry().getHookSignatures(functionName); + } + + // ==================== CONTEXT-AWARE HOOK METHODS ==================== + + /** + * Check if a function name is a known JS hook in a specific script context. + * Falls back to GLOBAL context if not found in the specified context. + * + * @param namespace The event interface namespace (e.g., "INpcEvent", "IPlayerEvent") + * @param functionName The function name to check + * @return true if it's a known hook in this namespace + */ + public boolean isJSHook(String namespace, String functionName) { + return getJSTypeRegistry().isHook(namespace, functionName); + } + + /** + * Get the parameter type for a JS hook function in a specific namespace. + * Falls back to "Global" namespace if not found in the specified namespace. + * + * @param namespace The event interface namespace (e.g., "INpcEvent", "IPlayerEvent") + * @param functionName The hook function name + * @return The parameter type, or null if not a hook + */ + public String getJSHookParameterType(String namespace, String functionName) { + return getJSTypeRegistry().getHookParameterType(namespace, functionName); + } + + /** + * Get hook signatures for a JS function in a specific namespace. + * Falls back to "Global" namespace if not found in the specified namespace. + * + * @param namespace The event interface namespace (e.g., "INpcEvent", "IPlayerEvent") + * @param functionName The hook function name + * @return List of hook signatures + */ + public List getJSHookSignatures(String namespace, String functionName) { + return getJSTypeRegistry().getHookSignatures(namespace, functionName); + } + + /** + * Get all hook names available in a specific namespace. + * + * @param namespace The event interface namespace + * @return Set of hook function names + */ + public Set getJSHookNames(String namespace) { + return getJSTypeRegistry().getHookNames(namespace); + } + + // ==================== MULTI-NAMESPACE HOOK METHODS ==================== + + /** + * Check if a function name is a known JS hook in any of the provided namespaces. + * Checks namespaces in order, returning true on first match. + * Falls back to GLOBAL namespace if not found in any specified namespace. + * + * @param namespaces The list of event interface namespaces to search (e.g., ["IPlayerEvent", "IAnimationEvent"]) + * @param functionName The function name to check + * @return true if it's a known hook in any of the namespaces + */ + public boolean isJSHook(List namespaces, String functionName) { + return getJSTypeRegistry().isHook(namespaces, functionName); + } + + /** + * Get the parameter type for a JS hook function, searching multiple namespaces. + * Checks namespaces in order, returning the first match found. + * Falls back to "Global" namespace if not found in any specified namespace. + * + * @param namespaces The list of event interface namespaces to search + * @param functionName The hook function name + * @return The parameter type, or null if not a hook + */ + public String getJSHookParameterType(List namespaces, String functionName) { + return getJSTypeRegistry().getHookParameterType(namespaces, functionName); + } + + /** + * Get hook signatures for a JS function, searching multiple namespaces. + * Checks namespaces in order, returning signatures from the first matching namespace. + * Falls back to "Global" namespace if not found in any specified namespace. + * + * @param namespaces The list of event interface namespaces to search + * @param functionName The hook function name + * @return List of hook signatures + */ + public List getJSHookSignatures(List namespaces, String functionName) { + return getJSTypeRegistry().getHookSignatures(namespaces, functionName); + } + + /** + * Get all hook names available in any of the provided namespaces. + * Combines hook names from all specified namespaces. + * + * @param namespaces The list of event interface namespaces + * @return Combined set of hook function names from all namespaces + */ + public Set getJSHookNames(List namespaces) { + return getJSTypeRegistry().getHookNames(namespaces); + } + + // ==================== CACHE MANAGEMENT ==================== + + /** + * Clear all caches. Call when imports change significantly. + */ + public void clearCache() { + typeCache.clear(); + validPackages.clear(); + // Re-add common packages + validPackages.add("java"); + validPackages.add("java.lang"); + validPackages.add("java.util"); + validPackages.add("java.io"); + } + + // ==================== UNIFIED TYPE RESOLUTION ==================== + + /** + * General-purpose type resolution. + * Tries JS types first, then falls back to Java types. + * + * @param typeName The type name (can be simple or fully-qualified) + * @return TypeInfo for the resolved type, or null if not found + */ + public TypeInfo resolve(String typeName) { + if (typeName == null || typeName.isEmpty()) { + return null; + } + + // Try JS resolution first (handles primitives, .d.ts types) + TypeInfo jsType = resolveJSType(typeName); + if (jsType != null && jsType.isResolved()) { + return jsType; + } + + // Try full name resolution + TypeInfo fullType = resolveFullName(typeName); + if (fullType != null && fullType.isResolved()) { + return fullType; + } + + // Return unresolved or null + return jsType; // Will be unresolved TypeInfo or null + } + + /** + * Resolve a type name for JavaScript context. + * Handles JS primitives, .d.ts types, and falls back to Java types. + * NOW preserves generic type arguments in the returned TypeInfo. + * + * @param jsTypeName The JS type name (e.g., "IPlayer", "string", "List", "Map") + * @return TypeInfo for the resolved type, or unresolved TypeInfo if not found + */ + public TypeInfo resolveJSType(String jsTypeName) { + if (jsTypeName == null || jsTypeName.isEmpty()) { + return TypeInfo.fromPrimitive("void"); + } + + // Normalize import() references first. + String normalized = TypeStringNormalizer.stripImportTypeSyntax(jsTypeName); + if (normalized == null || normalized.isEmpty()) { + return TypeInfo.fromPrimitive("void"); + } + + // Unions: pick a single "best" branch for resolution (prefer non-nullish). + normalized = TypeStringNormalizer.pickPreferredUnionBranch(normalized); + + // Nullable: treat Foo? as Foo | null (for resolution purposes this means "resolve Foo"). + normalized = TypeStringNormalizer.stripNullableSuffix(normalized); + + // Arrays: handled here, not in the generics structural parser. + TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(normalized); + String baseExpr = arraySplit.base; + int arrayDims = arraySplit.dimensions; + + if (baseExpr == null || baseExpr.isEmpty()) { + return TypeInfo.unresolved(jsTypeName, jsTypeName); + } + + TypeInfo resolved = null; + // Fast path: no generics - skip expensive parsing + if (!baseExpr.contains("<")) { + resolved = resolveBaseType(baseExpr); + } else { + // Slow path: parse and resolve into a TypeInfo, preserving generic arguments. + GenericTypeParser.ParsedType parsed = GenericTypeParser.parse(baseExpr); + if (parsed != null) { + // Resolve the base type (without generics) + TypeInfo baseType = resolveBaseType(parsed.baseName); + + // If we have type arguments, resolve them (allowing each arg to have its own arrays/unions/etc). + if (parsed.hasTypeArgs() && baseType != null && baseType.isResolved()) { + List resolvedArgs = new ArrayList<>(); + for (GenericTypeParser.ParsedType argParsed : parsed.typeArgs) { + if (argParsed == null) { + resolvedArgs.add(TypeInfo.ANY); + continue; + } + TypeInfo argType = resolveJSType(argParsed.rawString); + resolvedArgs.add(argType != null ? argType : TypeInfo.unresolved(argParsed.baseName, + argParsed.baseName)); + } + if (!resolvedArgs.isEmpty()) { + baseType = baseType.parameterize(resolvedArgs); + } + } + resolved = baseType != null ? baseType : TypeInfo.unresolved(parsed.baseName, parsed.rawString); + } else + resolved = resolveBaseType(baseExpr); + } + + if (resolved == null) { + resolved = TypeInfo.unresolved(baseExpr, jsTypeName); + } + + for (int i = 0; i < arrayDims; i++) { + resolved = TypeInfo.arrayOf(resolved); + } + + return resolved; + } + + /** + * Resolve a base type name (without generics) to a TypeInfo. + * This handles primitives, synthetic types, JS registry types, and Java types. + */ + private TypeInfo resolveBaseType(String baseName) { + if (baseName == null || baseName.isEmpty()) { + return null; + } + + // Primitives + if (TypeResolver.isPrimitiveType(baseName)) { + return TypeInfo.fromPrimitive(baseName); + } + + // Handle "Java." prefix - convert to actual Java type + if (baseName.startsWith("Java.")) { + baseName = baseName.substring(5); + } + + // Check synthetic types (Nashorn built-ins, custom types, etc.) + if (isSyntheticType(baseName)) { + SyntheticType syntheticType = getSyntheticType(baseName); + return syntheticType.getTypeInfo(); + } + + // Check JS type registry + // Before primitive mapping, to allow .d.ts types to override primitive names for ECMAScript 5.1 globals (e.g., "String" in JS is not the same as "String" in Java)) + JSTypeInfo jsTypeInfo = getJSTypeRegistry().getType(baseName); + if (jsTypeInfo != null) { + TypeInfo merged = tryMergeJSWithJava(baseName, jsTypeInfo); + if (merged != null) return merged; + return TypeInfo.fromJSTypeInfo(jsTypeInfo); + } + + // Check primitives and common types + switch (baseName.toLowerCase()) { + case "string": + return TypeInfo.STRING; + case "number": + case "int": + case "integer": + return TypeInfo.NUMBER; + case "boolean": + case "bool": + return TypeInfo.BOOLEAN; + case "void": + return TypeInfo.VOID; + case "any": + case "object": + case "*": + return TypeInfo.ANY; + } + + // Fall back to Java type resolution + TypeInfo javaType = resolveFullName(baseName); + if (javaType != null && javaType.isResolved()) { + return javaType; + } + + // Unresolved + return TypeInfo.unresolved(baseName, baseName); + } + + private static TypeInfo getJSJavaMergeBase(String baseName) { + switch (baseName) { + case "String": + return TypeInfo.STRING; + case "Object": + return TypeInfo.OBJECT; + default: + return null; + } + } + + public JSTypeInfo findJSTypeForJavaClass(Class javaClass) { + if (javaClass == null) return null; + String simpleName = javaClass.getSimpleName(); + if (getJSJavaMergeBase(simpleName) != null) { + return getJSTypeRegistry().getType(simpleName); + } + return getJSTypeRegistry().getTypeByJavaFqn(javaClass.getName()); + } + + /** + * For certain core types (e.g., String, Object), we want to merge JS type info from .d.ts with the Java TypeInfo to create an enriched type that has both Java and JS members. + */ + private TypeInfo tryMergeJSWithJava(String baseName, JSTypeInfo jsTypeInfo) { + TypeInfo javaBase = getJSJavaMergeBase(baseName); + if (javaBase == null) return null; + + return jsMergeCache.computeIfAbsent(baseName, k -> { + TypeInfo result = TypeInfo.fromClass(javaBase.getJavaClass()); + if (result == null) result = javaBase; + TypeInfo.injectJSMembers(result, jsTypeInfo); + if (javaBase == TypeInfo.STRING) { + TypeInfo.jsString = result; + } else if (javaBase == TypeInfo.OBJECT) { + TypeInfo.jsObject = result; + } + return result; + }); + } + + /** + * Check if a JS type name is a primitive. + */ + public boolean isJSPrimitive(String typeName) { + return JS_PRIMITIVE_TO_JAVA.containsKey(typeName); + } + + // ==================== TYPE RESOLUTION ==================== + + /** + * Resolve a fully-qualified class name. + * Handles inner classes with both dot and dollar notation. + */ + public TypeInfo resolveFullName(String fullName) { + if (fullName == null || fullName.isEmpty()) { + return null; + } + + // Normalize: remove whitespace around dots + String normalized = fullName.replaceAll("\\s*\\.\\s*", ".").trim(); + + // Check cache first + if (typeCache.containsKey(normalized)) { + return typeCache.get(normalized); + } + + // Try direct resolution + TypeInfo result = tryResolveClass(normalized); + if (result != null) { + return result; + } + + // Try converting dots to $ for inner classes + // Work backwards from the end, trying each segment as an inner class + String[] segments = normalized.split("\\."); + for (int i = segments.length - 1; i > 0; i--) { + StringBuilder candidate = new StringBuilder(); + // Package portion + for (int j = 0; j < i; j++) { + if (j > 0) candidate.append('.'); + candidate.append(segments[j]); + } + // Class portion with $ + for (int j = i; j < segments.length; j++) { + candidate.append(j == i ? '.' : '$'); + candidate.append(segments[j]); + } + + result = tryResolveClass(candidate.toString()); + if (result != null) { + // Cache the original lookup + typeCache.put(normalized, result); + return result; + } + } + + // Not found - cache the miss + typeCache.put(normalized, null); + return null; + } + + /** + * Resolve a simple class name using provided import context. + */ + public TypeInfo resolveSimpleName(String simpleName, + Map imports, + Set wildcardPackages) { + if (simpleName == null || simpleName.isEmpty()) { + return TypeInfo.unresolved(simpleName,simpleName); + } + + // 1. Check explicit imports + ImportData importData = imports.get(simpleName); + if (importData != null && importData.getResolvedType() != null) { + return importData.getResolvedType(); + } + if (importData != null) { + TypeInfo resolved = resolveFullName(importData.getFullPath()); + if (resolved != null) { + importData.setResolvedType(resolved); + return resolved; + } + } + + // 2. Check java.lang + if (JAVA_LANG_CLASSES.contains(simpleName)) { + TypeInfo langType = resolveFullName("java.lang." + simpleName); + if (langType != null) { + return langType; + } + } + + // 3. Check wildcard packages + if (wildcardPackages != null) { + for (String pkg : wildcardPackages) { + // Try as package.ClassName + TypeInfo fromPkg = resolveFullName(pkg + "." + simpleName); + if (fromPkg != null) { + return fromPkg; + } + + // Try as OuterClass$InnerClass (for class-level wildcards like IOverlay.*) + TypeInfo fromInner = resolveFullName(pkg + "$" + simpleName); + if (fromInner != null) { + return fromInner; + } + } + } + + return TypeInfo.unresolved(simpleName,simpleName); + } + + /** + * Try to load a class and create TypeInfo for it. + */ + private TypeInfo tryResolveClass(String className) { + if (className == null || className.isEmpty()) { + return null; + } + + // Check cache + if (typeCache.containsKey(className)) { + return typeCache.get(className); + } + + try { + Class clazz = Class.forName(className); + TypeInfo info = TypeInfo.fromClass(clazz); + typeCache.put(className, info); + + // Register the package as valid + registerPackage(info.getPackageName()); + + return info; + } catch (ClassNotFoundException e) { + // Cache the miss + typeCache.put(className, null); + return null; + } catch (LinkageError e) { + // NoClassDefFoundError is a subclass of LinkageError + typeCache.put(className, null); + return null; + } + } + + // ==================== PACKAGE VALIDATION ==================== + + /** + * Check if a package path is valid. + */ + public boolean isValidPackage(String packagePath) { + if (packagePath == null || packagePath.isEmpty()) { + return false; + } + + if (validPackages.contains(packagePath)) { + return true; + } + + if (PackageFinder.find(packagePath)) { + registerPackage(packagePath); + return true; + } + + // Try to find a class in this package to validate it + String[] testClasses = getTestClassesForPackage(packagePath); + for (String testClass : testClasses) { + try { + Class.forName(testClass); + registerPackage(packagePath); + return true; + } catch (ClassNotFoundException | LinkageError ignored) { + } + } + + return false; + } + + /** + * Register a package path as valid (and all parent packages). + */ + private void registerPackage(String packagePath) { + if (packagePath == null || packagePath.isEmpty()) { + return; + } + validPackages.add(packagePath); + + // Also register parent packages + int lastDot; + String current = packagePath; + while ((lastDot = current.lastIndexOf('.')) > 0) { + current = current.substring(0, lastDot); + validPackages.add(current); + } + } + + private String[] getTestClassesForPackage(String packagePath) { + switch (packagePath) { + case "java": + return new String[]{"java.lang.Object"}; + case "java.util": + return new String[]{"java.util.List", "java.util.Map"}; + case "java.io": + return new String[]{"java.io.File", "java.io.InputStream"}; + case "java.net": + return new String[]{"java.net.URL", "java.net.Socket"}; + case "java.lang": + return new String[]{"java.lang.Object", "java.lang.String"}; + default: + return new String[]{}; + } + } + + // ==================== IMPORT RESOLUTION ==================== + + /** + * Resolve all imports and return a map of simple name -> ImportData. + */ + public Map resolveImports(List imports) { + Map resolved = new HashMap<>(); + + for (ImportData imp : imports) { + if (imp.isWildcard()) { + // Wildcard imports: validate the package exists + imp.markResolved(isValidPackage(imp.getFullPath()) || + resolveFullName(imp.getFullPath()) != null); + } else { + // Specific import: resolve the class + TypeInfo typeInfo = resolveFullName(imp.getFullPath()); + imp.setResolvedType(typeInfo); + if (imp.getSimpleName() != null) { + resolved.put(imp.getSimpleName(), imp); + } + } + } + + return resolved; + } + + // ==================== GENERIC TYPE PARSING ==================== + + /** + * Parse type names from generic content like "Map>". + * Returns TypeInfo for each type found. + */ + public List parseGenericTypes(String content, + Map imports, + Set wildcardPackages) { + List results = new ArrayList<>(); + parseGenericTypesRecursive(content, 0, imports, wildcardPackages, results); + return results; + } + + private void parseGenericTypesRecursive(String content, int baseOffset, + Map imports, + Set wildcardPackages, + List results) { + if (content == null || content.isEmpty()) return; + + int i = 0; + while (i < content.length()) { + char c = content.charAt(i); + + // Skip non-identifier characters + if (!Character.isJavaIdentifierStart(c)) { + i++; + continue; + } + + // Found start of identifier + int start = i; + while (i < content.length() && Character.isJavaIdentifierPart(content.charAt(i))) { + i++; + } + String typeName = content.substring(start, i); + + // Only process uppercase-starting identifiers as types + if (Character.isUpperCase(typeName.charAt(0))) { + TypeInfo info = resolveSimpleName(typeName, imports, wildcardPackages); + results.add(new GenericTypeOccurrence( + baseOffset + start, + baseOffset + i, + typeName, + info + )); + } + + // Skip whitespace + while (i < content.length() && Character.isWhitespace(content.charAt(i))) { + i++; + } + + // Check for nested generic + if (i < content.length() && content.charAt(i) == '<') { + int nestedStart = i + 1; + int depth = 1; + i++; + + while (i < content.length() && depth > 0) { + if (content.charAt(i) == '<') depth++; + else if (content.charAt(i) == '>') depth--; + i++; + } + + // Recursively parse nested content + if (nestedStart < i - 1) { + String nestedContent = content.substring(nestedStart, i - 1); + parseGenericTypesRecursive(nestedContent, baseOffset + nestedStart, + imports, wildcardPackages, results); + } + } + } + } + + + /** + * Check if a type name is a primitive type. + */ + public static boolean isPrimitiveType(String typeName) { + return typeName.equals("boolean") || typeName.equals("byte") || typeName.equals("char") || + typeName.equals("short") || typeName.equals("int") || typeName.equals("long") || + typeName.equals("float") || typeName.equals("double") || typeName.equals("void"); + } + + /** + * Check if a word is a Java modifier keyword. + */ + public static boolean isModifier(String word) { + return word.equals("public") || word.equals("private") || word.equals("protected") || + word.equals("static") || word.equals("final") || word.equals("abstract") || + word.equals("synchronized") || word.equals("volatile") || word.equals("transient") || + word.equals("native") || word.equals("strictfp"); + } + + // ==================== CLASS SEARCH ==================== + + /** + * Search for classes matching the given prefix. + * Uses ClassIndex for O(n) lookup where n is the number of indexed classes. + * + * @param prefix The prefix to match (case-sensitive for class names) + * @param maxResults Maximum number of results to return + * @return List of fully-qualified class names that match + */ + public List findClassesByPrefix(String prefix, int maxResults) { + return ClassIndex.getInstance().findByPrefix(prefix, maxResults); + } + + /** + * @deprecated Use findClassesByPrefix instead for prefix matching + */ + @Deprecated + public List findClassesBySimpleName(String simpleName, int maxResults) { + // Redirect to prefix matching for backwards compatibility + return findClassesByPrefix(simpleName, maxResults); + } + + /** + * Represents a type occurrence within generic content. + */ + public static class GenericTypeOccurrence { + public final int startOffset; + public final int endOffset; + public final String typeName; + public final TypeInfo typeInfo; + + public GenericTypeOccurrence(int startOffset, int endOffset, String typeName, TypeInfo typeInfo) { + this.startOffset = startOffset; + this.endOffset = endOffset; + this.typeName = typeName; + this.typeInfo = typeInfo; + } + + public TokenType getTokenType() { + if (typeInfo == null || !typeInfo.isResolved()) { + return TokenType.UNDEFINED_VAR; + } + return typeInfo.getTokenType(); + } + } + + /** + * Check if an expression represents static access (accessing a Class, not an instance). + * This checks if the expression STRING resolves to a TYPE name. + * + * Examples: + * - "String" -> true (it's a class name) + * - "myVar" -> false (it's a variable, even if myVar holds a ClassTypeInfo) + * - "Java" -> true (it's a synthetic type) + * + * Note: This is different from checking if a variable's TYPE is ClassTypeInfo. + * For variables holding ClassTypeInfo (like `var File = Java.type("File")`), + * the receiver type itself should be checked separately. + * + * @param typeInfo The resolved TypeInfo (can be null) + * @param wasResolvedAsType true if this was resolved as a type name (not a variable) + * @return true if this represents static access (direct class reference) + */ + public static boolean isStaticAccess(TypeInfo typeInfo, boolean wasResolvedAsType) { + // If explicitly resolved as a type name, it's static access + if (wasResolvedAsType) + return true; + + if (typeInfo == null) + return false; + + // If the typeInfo itself is a ClassTypeInfo (e.g., result of Java.type()), + // then accessing members on it should be static + if (typeInfo.isClassReference()) + return true; + + return false; + } + + /** + * Unified static access checker for expressions. + * Determines if an identifier represents static access (type name) or instance access (variable). + * + * This method is used by ScriptDocument, JavaAutocompleteProvider, and FieldChainMarker. + * + * @param identifier The identifier to check (e.g., "String", "myVar", "Java") + * @param position The position in the document for context + * @param document The script document for resolution + * @return true if this represents static access + */ + public static boolean isStaticAccessExpression(String identifier, int position, ScriptDocument document) { + if (identifier == null || identifier.isEmpty() || document == null) { + return false; + } + + // If the identifier contains dots, parentheses, brackets, or operators, it's a complex expression + // Complex expressions (method calls, field chains, arithmetic) are instance access by default + if (identifier.contains(".") || identifier.contains("(") || identifier.contains("[") || + document.containsOperators(identifier)) { + // For complex expressions, resolve as expression and check the result type + TypeInfo exprType = document.resolveExpressionType(identifier, position); + // Only static if the expression result is itself a ClassTypeInfo (e.g., Java.type("File")) + if (isStaticAccess(exprType, false)) + return true; + // Dotted script type name like "Outer.Inner" is always static access + if (!identifier.contains("(") && !identifier.contains("[") && !document.containsOperators(identifier)) { + TypeInfo dotResolved = document.resolveType(identifier); + if (dotResolved instanceof ScriptTypeInfo) + return true; + } + return false; + } + + // Simple identifier - check if it's a variable/field (instance access) + FieldInfo fieldInfo = document.resolveVariable(identifier, position); + if (fieldInfo != null && fieldInfo.isResolved()) { + // It's a variable - check if its type is a ClassTypeInfo + return isStaticAccess(fieldInfo.getTypeInfo(), false); + } + + // Not a variable - check if it's a type name by trying to resolve as type + TypeInfo typeCheck = document.resolveType(identifier); + boolean isType = typeCheck != null && typeCheck.isResolved(); + return isStaticAccess(typeCheck, isType); + } + + /** + * Parse string literal arguments from a method call. + * Used for resolving dynamic return types like Java.type("className"). + * + * @param argumentsStr The arguments string (e.g., "\"java.io.File\", 123") + * @return Array of parsed arguments + */ + public static String[] parseStringArguments(String argumentsStr) { + if (argumentsStr == null || argumentsStr.isEmpty()) { + return new String[0]; + } + + List args = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + int depth = 0; + boolean inString = false; + char stringChar = 0; + + for (int i = 0; i < argumentsStr.length(); i++) { + char c = argumentsStr.charAt(i); + + if (inString) { + current.append(c); + if (c == stringChar && (i == 0 || argumentsStr.charAt(i - 1) != '\\')) { + inString = false; + } + } else if (c == '"' || c == '\'') { + current.append(c); + inString = true; + stringChar = c; + } else if (c == '(' || c == '[' || c == '{') { + depth++; + current.append(c); + } else if (c == ')' || c == ']' || c == '}') { + depth--; + current.append(c); + } else if (c == ',' && depth == 0) { + args.add(current.toString().trim()); + current = new StringBuilder(); + } else { + current.append(c); + } + } + + if (current.length() > 0) { + args.add(current.toString().trim()); + } + + return args.toArray(new String[0]); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeStringNormalizer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeStringNormalizer.java new file mode 100644 index 000000000..fd464f6d3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeStringNormalizer.java @@ -0,0 +1,221 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import java.util.ArrayList; +import java.util.List; + +/** + * Shared utilities for cleaning and normalizing type expressions. + * + * This is intentionally a small, dependency-light helper that both the runtime resolver + * and the .d.ts parser can use. + */ +public final class TypeStringNormalizer { + + private TypeStringNormalizer() {} + + public static final class ArraySplit { + public final String base; + public final int dimensions; + + public ArraySplit(String base, int dimensions) { + this.base = base; + this.dimensions = dimensions; + } + } + + /** + * Strip TypeScript import() type references anywhere in the string. + * + * Examples: + * - import('./data/IAction').IAction -> IAction + * - Java.java.util.function.Consumer -> Java.java.util.function.Consumer + */ + public static String stripImportTypeSyntax(String type) { + if (type == null) { + return null; + } + + String out = type.trim(); + int importIdx; + while ((importIdx = out.indexOf("import(")) >= 0) { + int i = importIdx + "import(".length(); + int depth = 1; + boolean inString = false; + char stringChar = 0; + + while (i < out.length() && depth > 0) { + char c = out.charAt(i); + if (inString) { + if (c == stringChar && (i == 0 || out.charAt(i - 1) != '\\')) { + inString = false; + } + } else { + if (c == '\'' || c == '"') { + inString = true; + stringChar = c; + } else if (c == '(') { + depth++; + } else if (c == ')') { + depth--; + } + } + i++; + } + + // i is positioned just after the matching ')', if found. + if (depth != 0) { + break; // Unbalanced import( ... ) - stop trying to clean. + } + + // If immediately followed by ".", remove the "import(...)." prefix. + if (i < out.length() && out.charAt(i) == '.') { + int removeEnd = i + 1; + out = out.substring(0, importIdx) + out.substring(removeEnd); + } else { + // Remove just the import(...) portion. + out = out.substring(0, importIdx) + out.substring(i); + } + } + + return out; + } + + /** + * Split a trailing TypeScript nullable suffix: Foo? -> Foo. + */ + public static String stripNullableSuffix(String type) { + if (type == null) { + return null; + } + String out = type.trim(); + if (out.endsWith("?")) { + return out.substring(0, out.length() - 1).trim(); + } + return out; + } + + /** + * Split trailing array suffixes: Foo[][] -> base=Foo, dimensions=2. + */ + public static ArraySplit splitArraySuffixes(String type) { + if (type == null) { + return new ArraySplit(null, 0); + } + String out = type.trim(); + int dims = 0; + while (out.endsWith("[]")) { + dims++; + out = out.substring(0, out.length() - 2).trim(); + } + return new ArraySplit(out, dims); + } + + /** + * Split a top-level union (depth-aware) into branches. + */ + public static List splitTopLevelUnion(String type) { + List parts = new ArrayList<>(); + if (type == null) { + return parts; + } + + String expr = type.trim(); + if (expr.isEmpty()) { + parts.add(""); + return parts; + } + + int depth = 0; + boolean inString = false; + char stringChar = 0; + + int start = 0; + for (int i = 0; i < expr.length(); i++) { + char c = expr.charAt(i); + + if (inString) { + if (c == stringChar && (i == 0 || expr.charAt(i - 1) != '\\')) { + inString = false; + } + continue; + } + + if (c == '\'' || c == '"' || c == '`') { + inString = true; + stringChar = c; + continue; + } + + if (c == '<' || c == '(' || c == '[' || c == '{') { + depth++; + continue; + } + if (c == '>' || c == ')' || c == ']' || c == '}') { + if (depth > 0) { + depth--; + } + continue; + } + + if (c == '|' && depth == 0) { + String part = expr.substring(start, i).trim(); + if (!part.isEmpty()) { + parts.add(part); + } + start = i + 1; + } + } + + String tail = expr.substring(start).trim(); + if (!tail.isEmpty()) { + parts.add(tail); + } + + if (parts.isEmpty()) { + parts.add(expr); + } + return parts; + } + + /** + * Choose a single branch to represent a union type for resolution. + * + * Policy: + * - Prefer the first non-nullish branch (not null/undefined/void). + * - Otherwise, fall back to the first branch. + */ + public static String pickPreferredUnionBranch(String type) { + if (type == null) { + return null; + } + + List parts = splitTopLevelUnion(type); + if (parts.size() <= 1) { + return type.trim(); + } + + for (String part : parts) { + if (!isNullishBranch(part)) { + return part.trim(); + } + } + + return parts.get(0).trim(); + } + + private static boolean isNullishBranch(String part) { + if (part == null) { + return false; + } + + String s = part.trim(); + if (s.isEmpty()) { + return false; + } + + // Strip generics so "null<...>" doesn't behave weirdly. + s = GenericTypeParser.stripGenerics(s); + s = s.trim().toLowerCase(); + return "null".equals(s) || "undefined".equals(s) || "void".equals(s); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticField.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticField.java new file mode 100644 index 000000000..4bb2bc684 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticField.java @@ -0,0 +1,45 @@ +package noppes.npcs.client.gui.util.script.interpreter.type.synthetic; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.lang.reflect.Modifier; + +public class SyntheticField { + public final String name; + public final String typeName; + public final String documentation; + public final boolean isStatic; + + SyntheticField(String name, String typeName, String documentation, boolean isStatic) { + this.name = name; + this.typeName = typeName; + this.documentation = documentation; + this.isStatic = isStatic; + } + + /** + * Get the field type as TypeInfo. + * @return The resolved TypeInfo for the field type, or unresolved if not found + */ + public TypeInfo getTypeInfo() { + TypeInfo type = TypeResolver.getInstance().resolve(typeName); + if (type == null) { + type = TypeInfo.unresolved(typeName, typeName); + } + return type; + } + + public FieldInfo toFieldInfo() { + TypeInfo type = TypeResolver.getInstance().resolve(typeName); + if (type == null) { + type = TypeInfo.unresolved(typeName, typeName); + } + int modifiers = Modifier.PUBLIC; + if (isStatic) { + modifiers |= Modifier.STATIC; + } + return FieldInfo.external(name, type, documentation, modifiers); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticMethod.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticMethod.java new file mode 100644 index 000000000..2a7c35efc --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticMethod.java @@ -0,0 +1,165 @@ +package noppes.npcs.client.gui.util.script.interpreter.type.synthetic; + +import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParamTag; +import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocReturnTag; +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class SyntheticMethod { + public final String name; + public final String returnType; + public final List parameters; + public final String documentation; + public final boolean isStatic; + public final SyntheticTypeBuilder.ReturnTypeResolver returnTypeResolver; + + SyntheticMethod(String name, String returnType, List parameters, + String documentation, boolean isStatic, + SyntheticTypeBuilder.ReturnTypeResolver returnTypeResolver) { + this.name = name; + this.returnType = returnType; + this.parameters = Collections.unmodifiableList(new ArrayList<>(parameters)); + this.documentation = documentation; + this.isStatic = isStatic; + this.returnTypeResolver = returnTypeResolver; + } + + /** + * Get the return type as TypeInfo. + * @return The resolved TypeInfo for the return type, or unresolved if not found + */ + public TypeInfo getReturnTypeInfo() { + TypeInfo returnTypeInfo = TypeResolver.getInstance().resolve(returnType); + if (returnTypeInfo == null) { + returnTypeInfo = TypeInfo.unresolved(returnType, returnType); + } + return returnTypeInfo; + } + + /** + * Resolve the return type with dynamic arguments (for methods like Java.type). + * @param arguments The method call arguments + * @return The dynamically resolved TypeInfo, or static return type if no resolver + */ + public TypeInfo resolveReturnType(String[] arguments) { + if (returnTypeResolver != null) { + return returnTypeResolver.resolve(arguments); + } + return getReturnTypeInfo(); + } + + /** + * Create a MethodInfo from this synthetic method. + */ + public MethodInfo toMethodInfo(TypeInfo containingType) { + List paramInfos = new ArrayList<>(); + for (SyntheticParameter param : parameters) { + String typeName = param.typeName; + boolean isVarArg = typeName != null && typeName.endsWith("..."); + if (isVarArg) typeName = typeName.substring(0, typeName.length() - 3); + TypeInfo paramType = TypeResolver.getInstance().resolve(typeName); + if (paramType == null) { + paramType = TypeInfo.unresolved(typeName, typeName); + } + FieldInfo fieldInfo = FieldInfo.parameter(param.name, paramType, -1, null); + fieldInfo.setVarArg(isVarArg); + paramInfos.add(fieldInfo); + } + + TypeInfo returnTypeInfo = TypeResolver.getInstance().resolve(returnType); + if (returnTypeInfo == null) { + returnTypeInfo = TypeInfo.unresolved(returnType, returnType); + } + + int modifiers = Modifier.PUBLIC; + if (isStatic) { + modifiers |= Modifier.STATIC; + } + + MethodInfo methodInfo = MethodInfo.external(name, returnTypeInfo, containingType, paramInfos, modifiers, null); + + // Create JSDocInfo from documentation + if (documentation != null && !documentation.isEmpty()) { + JSDocInfo jsDocInfo = createJSDocInfo(returnTypeInfo); + methodInfo.setJSDocInfo(jsDocInfo); + } + + return methodInfo; + } + + /** + * Create JSDocInfo from the documentation string. + */ + private JSDocInfo createJSDocInfo(TypeInfo returnTypeInfo) { + // Parse the documentation to extract description and separate sections + String[] lines = documentation.split("\\n"); + StringBuilder descBuilder = new StringBuilder(); + + // Extract description (everything before @param or @returns) + for (String line : lines) { + line = line.trim(); + if (line.startsWith("@param") || line.startsWith("@returns") || line.startsWith("@return")) { + break; + } + if (!line.isEmpty()) { + if (descBuilder.length() > 0) + descBuilder.append("\n"); + descBuilder.append(line); + } + } + + JSDocInfo jsDocInfo = new JSDocInfo(documentation, -1, -1); + jsDocInfo.setDescription(descBuilder.toString()); + + // Add @param tags for each parameter + for (int i = 0; i < parameters.size(); i++) { + SyntheticParameter param = parameters.get(i); + TypeInfo paramType = TypeResolver.getInstance().resolve(param.typeName); + if (paramType == null) { + paramType = TypeInfo.unresolved(param.typeName, param.typeName); + } + + JSDocParamTag paramTag = JSDocParamTag.create( + -1, -1, -1, // offsets + param.typeName, paramType, -1, -1, // type info + param.name, -1, -1, // param name + param.documentation // description + ); + jsDocInfo.addParamTag(paramTag); + } + + // Add @returns tag + JSDocReturnTag returnTag = JSDocReturnTag.create( + "returns", -1, -1, -1, // offsets + returnTypeInfo.getSimpleName(), returnTypeInfo, -1, -1, // type info + null // description extracted from main documentation + ); + jsDocInfo.setReturnTag(returnTag); + + return jsDocInfo; + } + + /** + * Get signature string for display. + */ + public String getSignature() { + StringBuilder sb = new StringBuilder(); + sb.append(name).append("("); + for (int i = 0; i < parameters.size(); i++) { + if (i > 0) + sb.append(", "); + SyntheticParameter p = parameters.get(i); + sb.append(p.name).append(": ").append(p.typeName); + } + sb.append("): ").append(returnType); + return sb.toString(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticParameter.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticParameter.java new file mode 100644 index 000000000..bf9a5fe97 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticParameter.java @@ -0,0 +1,28 @@ +package noppes.npcs.client.gui.util.script.interpreter.type.synthetic; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver; + +public class SyntheticParameter { + public final String name; + public final String typeName; + public final String documentation; + + SyntheticParameter(String name, String typeName, String documentation) { + this.name = name; + this.typeName = typeName; + this.documentation = documentation; + } + + /** + * Get the parameter type as TypeInfo. + * @return The resolved TypeInfo for the parameter type, or unresolved if not found + */ + public TypeInfo getTypeInfo() { + TypeInfo type = TypeResolver.getInstance().resolve(typeName); + if (type == null) { + type = TypeInfo.unresolved(typeName, typeName); + } + return type; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticType.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticType.java new file mode 100644 index 000000000..01878d2f5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticType.java @@ -0,0 +1,95 @@ +package noppes.npcs.client.gui.util.script.interpreter.type.synthetic; + +import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.*; + +/** + * Represents a fully-built synthetic type. + */ +public class SyntheticType { + private final String name; + private final String documentation; + private final Map methods; + private final Map fields; + private TypeInfo typeInfo; + + SyntheticType(String name, String documentation, List methods, + List fields) { + this.name = name; + this.documentation = documentation; + this.methods = new LinkedHashMap<>(); + for (SyntheticMethod m : methods) { + this.methods.put(m.name, m); + } + this.fields = new LinkedHashMap<>(); + for (SyntheticField f : fields) { + this.fields.put(f.name, f); + } + } + + public String getName() { + return name; + } + + public String getDocumentation() { + return documentation; + } + + public SyntheticMethod getMethod(String methodName) { + return methods.get(methodName); + } + + public Collection getMethods() { + return methods.values(); + } + + public SyntheticField getField(String fieldName) { + return fields.get(fieldName); + } + + public Collection getFields() { + return fields.values(); + } + + public boolean hasMethod(String methodName) { + return methods.containsKey(methodName); + } + + public boolean hasField(String fieldName) { + return fields.containsKey(fieldName); + } + + /** + * Get or create the TypeInfo for this synthetic type. + */ + public TypeInfo getTypeInfo() { + if (typeInfo == null) { + typeInfo = TypeInfo.resolved(name, name, "", TypeInfo.Kind.CLASS, null); + } + return typeInfo; + } + + /** + * Create a MethodInfo for a method in this type. + */ + public MethodInfo getMethodInfo(String methodName) { + SyntheticMethod method = methods.get(methodName); + if (method == null) + return null; + return method.toMethodInfo(getTypeInfo()); + } + + /** + * Resolve the return type of a method given arguments. + * Used for special methods like Java.type(). + */ + public TypeInfo resolveMethodReturnType(String methodName, String[] arguments) { + SyntheticMethod method = methods.get(methodName); + if (method == null) + return null; + + return method.resolveReturnType(arguments); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticTypeBuilder.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticTypeBuilder.java new file mode 100644 index 000000000..02fc4d586 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/synthetic/SyntheticTypeBuilder.java @@ -0,0 +1,165 @@ +package noppes.npcs.client.gui.util.script.interpreter.type.synthetic; + +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; + +import java.util.*; + +/** + * Builder for creating synthetic (non-reflection-based) types. + * Used for built-in Nashorn objects like 'Java' that have no corresponding Java class. + * + *

Usage:

+ *
+ * SyntheticType javaType = new SyntheticTypeBuilder("Java")
+ *     .addMethod("type")
+ *         .parameter("className", "string")
+ *         .returns("Class")
+ *         .documentation("Loads a Java class by fully-qualified name.")
+ *         .done()
+ *     .build();
+ * 
+ */ +public class SyntheticTypeBuilder { + + private final String name; + private String documentation; + private final List methods = new ArrayList<>(); + private final List fields = new ArrayList<>(); + + public SyntheticTypeBuilder(String name) { + this.name = name; + } + + public SyntheticTypeBuilder documentation(String doc) { + this.documentation = doc; + return this; + } + + /** + * Start building a method for this type. + */ + public MethodBuilder addMethod(String methodName) { + return new MethodBuilder(this, methodName); + } + + /** + * Add a field to this type. + */ + public SyntheticTypeBuilder addField(String fieldName, String typeName, String doc) { + fields.add(new SyntheticField(fieldName, typeName, doc, false)); + return this; + } + + /** + * Add a static field to this type. + */ + public SyntheticTypeBuilder addStaticField(String fieldName, String typeName, String doc) { + fields.add(new SyntheticField(fieldName, typeName, doc, true)); + return this; + } + + void addBuiltMethod(SyntheticMethod method) { + methods.add(method); + } + + /** + * Build the synthetic type. + */ + public SyntheticType build() { + return new SyntheticType(name, documentation, methods, fields); + } + + // ==================== Inner classes ==================== + + /** + * Builder for methods within a synthetic type. + */ + public static class MethodBuilder { + private final SyntheticTypeBuilder parent; + private final String name; + private final List parameters = new ArrayList<>(); + private String returnType = "void"; + private String documentation; + private boolean isStatic = false; + private ReturnTypeResolver returnTypeResolver; + + MethodBuilder(SyntheticTypeBuilder parent, String name) { + this.parent = parent; + this.name = name; + } + + /** + * Add a parameter to this method. + */ + public MethodBuilder parameter(String paramName, String typeName) { + parameters.add(new SyntheticParameter(paramName, typeName, null)); + return this; + } + + /** + * Add a parameter with documentation. + */ + public MethodBuilder parameter(String paramName, String typeName, String doc) { + parameters.add(new SyntheticParameter(paramName, typeName, doc)); + return this; + } + + /** + * Set the return type. + */ + public MethodBuilder returns(String typeName) { + this.returnType = typeName; + return this; + } + + /** + * Set a dynamic return type resolver. + * Used for methods like Java.type() where return type depends on arguments. + */ + public MethodBuilder returnsResolved(ReturnTypeResolver resolver) { + this.returnTypeResolver = resolver; + return this; + } + + /** + * Set method documentation. + */ + public MethodBuilder documentation(String doc) { + this.documentation = doc; + return this; + } + + /** + * Mark this method as static. + */ + public MethodBuilder asStatic() { + this.isStatic = true; + return this; + } + + /** + * Finish building this method and return to the type builder. + */ + public SyntheticTypeBuilder done() { + parent.addBuiltMethod(new SyntheticMethod(name, returnType, parameters, documentation, isStatic, returnTypeResolver)); + return parent; + } + } + + /** + * Functional interface for resolving return types dynamically. + */ + @FunctionalInterface + public interface ReturnTypeResolver { + /** + * Resolve the return type given the arguments passed to the method. + * @param arguments The string arguments (for methods like Java.type("className")) + * @return The resolved TypeInfo, or null if cannot be resolved + */ + TypeInfo resolve(String[] arguments); + } + + // ==================== Data classes ==================== + + // ==================== SyntheticType (the result) ==================== +} diff --git a/src/main/java/noppes/npcs/client/key/KeyPreset.java b/src/main/java/noppes/npcs/client/key/KeyPreset.java index 566522c2a..be33eb62d 100644 --- a/src/main/java/noppes/npcs/client/key/KeyPreset.java +++ b/src/main/java/noppes/npcs/client/key/KeyPreset.java @@ -95,10 +95,8 @@ public class KeyPreset { int keyCode = keyCode(); if (keyCode == -1 || keyCode == 0) return; - - boolean isDown = isMouseKey() ? Mouse.isButtonDown(keyCode + 100) : Keyboard.isKeyDown(keyCode); - isDown = isDown && (isCtrlKeyDown() == hasCtrl()) && (isAltKeyDown() == hasAlt()) && (isShiftKeyDown() == hasShift()); - setDown(isDown); + + setDown(currentState.isDown()); } private static final long SHORT_PRESS_MS = 250L; @@ -217,6 +215,11 @@ public class KeyPreset { state.setState(keyCode, hasCtrl, hasAlt, hasShift); } + public boolean isDown() { + boolean isDown = isMouseKey() ? Mouse.isButtonDown(keyCode + 100) : Keyboard.isKeyDown(keyCode); + return isDown && (isCtrlKeyDown() == hasCtrl) && (isAltKeyDown() == hasAlt) && (isShiftKeyDown() == hasShift); + } + public boolean hasState() { return keyCode != -1; } @@ -259,6 +262,19 @@ public class KeyPreset { this.hasAlt = compound.getBoolean("hasAlt"); } + public boolean matches(int keycode, boolean checkModifiers) { + if (!checkModifiers) + return this.keyCode == keycode; + + return this.keyCode == keycode && this.hasCtrl == KeyPreset.isCtrlKeyDown() + && this.hasAlt == KeyPreset.isAltKeyDown() + && this.hasShift == KeyPreset.isShiftKeyDown(); + } + + public boolean isMouseKey() { + return keyCode < -1; + } + public String getName() { int code = keyCode; String name = ""; diff --git a/src/main/java/noppes/npcs/client/key/KeyPresetManager.java b/src/main/java/noppes/npcs/client/key/KeyPresetManager.java index 1a978cdc7..689600366 100644 --- a/src/main/java/noppes/npcs/client/key/KeyPresetManager.java +++ b/src/main/java/noppes/npcs/client/key/KeyPresetManager.java @@ -24,6 +24,15 @@ public class KeyPresetManager { return preset; } + public boolean hasMatchingKeyPressed(int keyCode) { + for (KeyPreset key : keys) { + if (key.currentState.matches(keyCode, true)) + return true; + } + + return false; + } + public void tick() { for (KeyPreset key : keys) key.tick(); @@ -34,8 +43,15 @@ public class KeyPresetManager { try { File dir = getDir(); File file = new File(dir, fileName + ".json"); - if (!file.exists()) + if (!file.exists()) { + // First run: initialize all keys to their default states if not already set + for (KeyPreset key : keys) { + if (!key.defaultState.hasState()) { + key.currentState.readFrom(key.defaultState); + } + } return; + } NBTTagCompound compound = NBTJsonUtil.LoadFile(file); for (KeyPreset key : keys) diff --git a/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java b/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java index 4a9e294d0..3029d4424 100644 --- a/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java +++ b/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java @@ -18,6 +18,11 @@ public class ScriptEditorKeys extends KeyPresetManager { public final KeyPreset FORMAT = add("Format Code").setDefaultState(Keyboard.KEY_F, false, true, false); public final KeyPreset TOGGLE_COMMENT = add("Toggle Comment").setDefaultState(Keyboard.KEY_SLASH, true, false, false); + // Editing + public final KeyPreset DELETE_LINE = add("Delete Line").setDefaultState(Keyboard.KEY_DELETE, true, false, false); + public final KeyPreset MOVE_LINE_UP = add("Move Line Up").setDefaultState(Keyboard.KEY_UP, false, true, false); + public final KeyPreset MOVE_LINE_DOWN = add("Move Line Down").setDefaultState(Keyboard.KEY_DOWN, false, true, false); + // Search/Replace public final KeyPreset SEARCH = add("Search").setDefaultState(Keyboard.KEY_F, true, false, false); public final KeyPreset SEARCH_REPLACE = add("Replace").setDefaultState(Keyboard.KEY_F, true, false, true); @@ -30,6 +35,9 @@ public class ScriptEditorKeys extends KeyPresetManager { // View public final KeyPreset FULLSCREEN = add("Toggle Fullscreen").setDefaultState(Keyboard.KEY_F11, false, false, false); + + // Autocomplete + public final KeyPreset AUTOCOMPLETE = add("Autocomplete").setDefaultState(Keyboard.KEY_SPACE, true, false, false); public ScriptEditorKeys() { super("script_editor"); diff --git a/src/main/java/noppes/npcs/client/model/ModelMPM.java b/src/main/java/noppes/npcs/client/model/ModelMPM.java index 7a8273a77..76bf0e591 100644 --- a/src/main/java/noppes/npcs/client/model/ModelMPM.java +++ b/src/main/java/noppes/npcs/client/model/ModelMPM.java @@ -422,7 +422,7 @@ public class ModelMPM extends ModelNPCMale { Minecraft.getMinecraft().entityRenderer.disableLightmap((double) 0); } - GL11.glColor4f(1.0F, 1.0F, 1.0F, overlayData.getAlpha()); + glColor(overlayData.getColor(), overlayData.getAlpha()); GL11.glDepthMask(!npc.isInvisible()); @@ -522,6 +522,14 @@ public class ModelMPM extends ModelNPCMale { } + private static void glColor(int color, float alpha) { + float r = ((color >> 16) & 0xFF) / 255.0F; + float g = ((color >> 8) & 0xFF) / 255.0F; + float b = (color & 0xFF) / 255.0F; + + GL11.glColor4f(r, g, b, alpha); + } + @Override public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, diff --git a/src/main/java/noppes/npcs/client/model/part/tails/ModelMonkeyTail.java b/src/main/java/noppes/npcs/client/model/part/tails/ModelMonkeyTail.java index fae556349..347b5ebfa 100644 --- a/src/main/java/noppes/npcs/client/model/part/tails/ModelMonkeyTail.java +++ b/src/main/java/noppes/npcs/client/model/part/tails/ModelMonkeyTail.java @@ -34,7 +34,9 @@ public class ModelMonkeyTail extends ModelRenderer { public ModelMonkeyTail(ModelBiped base) { super(base); - float heightFactor = -9.0f; + // Cancels ModelTail's rotationPointY of 11 so the boxes land where JBRA puts them + // on players: plain tail at 10, wrapped tail at 0. + float heightFactor = -11.0f; (this.monkey_large = new ModelRenderer(base, 38, 54)).addBox(-2.0f, -2.0f, 0.0f, 4, 4, 6); this.setRotation(this.monkey_large, -0.5235988f, 0.0f, 0.0f); diff --git a/src/main/java/noppes/npcs/client/renderer/AnimationHelper.java b/src/main/java/noppes/npcs/client/renderer/AnimationHelper.java new file mode 100644 index 000000000..c847d6e14 --- /dev/null +++ b/src/main/java/noppes/npcs/client/renderer/AnimationHelper.java @@ -0,0 +1,49 @@ +package noppes.npcs.client.renderer; + +import net.minecraft.client.Minecraft; + +/** + * Static utility for computing animated texture UV offsets. + * Used by renderers when animation parameters come from data class fields + * rather than .mcmeta auto-detection on ImageData. + */ +public class AnimationHelper { + + /** + * Returns the V-coordinate offset (0.0-1.0) for the current animation frame. + * Based on system time for consistent sync across all animated textures. + * + * @param totalHeight Total pixel height of the sprite strip + * @param frameCount Number of frames in the strip + * @param frametime Ticks per frame (1 tick = 50ms) + * @return V offset in 0.0-1.0 range, or 0.0 if not animated + */ + public static float getFrameVOffset(int totalHeight, int frameCount, int frametime) { + if (frameCount <= 1 || totalHeight <= 0) { + return 0f; + } + + frametime = Math.max(1, frametime); + long millis = Minecraft.getSystemTime(); + int tick = (int) (millis / 50L); + int frameIdx = (tick / frametime) % frameCount; + int frameHeight = totalHeight / frameCount; + + return (float) (frameIdx * frameHeight) / (float) totalHeight; + } + + /** + * Returns the V-coordinate size of a single frame in 0.0-1.0 range. + * + * @param totalHeight Total pixel height of the sprite strip + * @param frameCount Number of frames in the strip + * @return V size of one frame, or 1.0 if not animated + */ + public static float getFrameVSize(int totalHeight, int frameCount) { + if (frameCount <= 1 || totalHeight <= 0) { + return 1f; + } + int frameHeight = totalHeight / frameCount; + return (float) frameHeight / (float) totalHeight; + } +} diff --git a/src/main/java/noppes/npcs/client/renderer/ImageData.java b/src/main/java/noppes/npcs/client/renderer/ImageData.java index 15c383e40..b85e51502 100644 --- a/src/main/java/noppes/npcs/client/renderer/ImageData.java +++ b/src/main/java/noppes/npcs/client/renderer/ImageData.java @@ -1,5 +1,8 @@ package noppes.npcs.client.renderer; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.IResource; @@ -11,6 +14,7 @@ import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; public class ImageData { private final ResourceLocation location; @@ -23,9 +27,17 @@ public class ImageData { private boolean gotWidthHeight; private boolean invalid; + // Animation fields + private boolean animated = false; + private int frameCount = 1; + private int frametime = 2; + private int[] frames = null; + private boolean interpolate = false; + private boolean mcmetaChecked = false; + 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)); @@ -141,6 +153,11 @@ public class ImageData { private void correctWidthHeight() { this.totalWidth = Math.max(this.totalWidth, 1); this.totalHeight = Math.max(this.totalHeight, 1); + + if (!this.isUrl && !this.mcmetaChecked) { + this.mcmetaChecked = true; + tryLoadMcmeta(); + } } public int getTotalWidth() { @@ -150,4 +167,112 @@ public class ImageData { public int getTotalHeight() { return this.gotWidthHeight ? this.totalHeight : -1; } + + // ═══════════════════════════════════════════════════════════════════ + // ANIMATION + // ═══════════════════════════════════════════════════════════════════ + + private void tryLoadMcmeta() { + try { + ResourceLocation mcmetaLoc = new ResourceLocation( + location.getResourceDomain(), + location.getResourcePath() + ".mcmeta" + ); + IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(mcmetaLoc); + InputStream stream = resource.getInputStream(); + try { + InputStreamReader reader = new InputStreamReader(stream); + JsonObject root = new JsonParser().parse(reader).getAsJsonObject(); + if (root.has("animation")) { + JsonObject anim = root.getAsJsonObject("animation"); + this.animated = true; + + if (anim.has("frametime")) { + this.frametime = Math.max(1, anim.get("frametime").getAsInt()); + } + if (anim.has("interpolate")) { + this.interpolate = anim.get("interpolate").getAsBoolean(); + } + if (anim.has("frames")) { + JsonArray framesArray = anim.getAsJsonArray("frames"); + this.frames = new int[framesArray.size()]; + int maxFrame = 0; + for (int i = 0; i < framesArray.size(); i++) { + this.frames[i] = framesArray.get(i).getAsInt(); + if (this.frames[i] > maxFrame) { + maxFrame = this.frames[i]; + } + } + this.frameCount = maxFrame + 1; + } else if (this.totalWidth > 0) { + this.frameCount = Math.max(1, this.totalHeight / this.totalWidth); + } + } + } finally { + stream.close(); + } + } catch (Exception ignored) { + // No .mcmeta found or parse error — not animated + } + } + + /** + * Programmatically enable animation on this ImageData. + * Used when animation settings come from data class fields rather than .mcmeta files. + */ + public void setAnimation(int frameCount, int frametime) { + if (frameCount > 1) { + this.animated = true; + this.frameCount = Math.max(1, frameCount); + this.frametime = Math.max(1, frametime); + } + } + + public boolean isAnimated() { + return this.animated && this.frameCount > 1; + } + + public int getFrameCount() { + return this.frameCount; + } + + public int getFrameTime() { + return this.frametime; + } + + /** + * Returns the pixel height of a single animation frame. + * For non-animated textures, returns the total height. + */ + public int getFrameHeight() { + if (this.animated && this.frameCount > 1) { + return Math.max(1, this.totalHeight / this.frameCount); + } + return this.gotWidthHeight ? this.totalHeight : -1; + } + + /** + * Returns the V-coordinate offset (0.0-1.0) for the current animation frame. + * Based on system time so all instances of the same texture animate in sync. + * Returns 0.0 for non-animated textures. + */ + public float getCurrentFrameVOffset() { + if (!this.animated || this.frameCount <= 1 || this.totalHeight <= 0) { + return 0f; + } + + long millis = Minecraft.getSystemTime(); + int tick = (int) (millis / 50L); + int frameIdx; + + if (this.frames != null && this.frames.length > 0) { + frameIdx = (tick / this.frametime) % this.frames.length; + frameIdx = this.frames[frameIdx]; + } else { + frameIdx = (tick / this.frametime) % this.frameCount; + } + + int frameHeight = this.totalHeight / this.frameCount; + return (float) (frameIdx * frameHeight) / (float) this.totalHeight; + } } diff --git a/src/main/java/noppes/npcs/client/renderer/RenderCNPCPlayer.java b/src/main/java/noppes/npcs/client/renderer/RenderCNPCPlayer.java index 7f532c2ad..d1042628e 100644 --- a/src/main/java/noppes/npcs/client/renderer/RenderCNPCPlayer.java +++ b/src/main/java/noppes/npcs/client/renderer/RenderCNPCPlayer.java @@ -79,7 +79,7 @@ public class RenderCNPCPlayer extends RenderPlayer { RenderHelper.disableStandardItemLighting(); } - GL11.glColor4f(1.0F, 1.0F, 1.0F, overlayData.alpha); + glColor(overlayData.getColor(), overlayData.getAlpha()); GL11.glDepthMask(!player.isInvisible()); @@ -97,6 +97,14 @@ public class RenderCNPCPlayer extends RenderPlayer { return true; } + private static void glColor(int color, float alpha) { + float r = ((color >> 16) & 0xFF) / 255.0F; + float g = ((color >> 8) & 0xFF) / 255.0F; + float b = (color & 0xFF) / 255.0F; + + GL11.glColor4f(r, g, b, alpha); + } + public void postRenderOverlay() { GL11.glPopMatrix(); diff --git a/src/main/java/noppes/npcs/client/renderer/RenderNPCInterface.java b/src/main/java/noppes/npcs/client/renderer/RenderNPCInterface.java index 2d1d1f258..5c8c376f7 100644 --- a/src/main/java/noppes/npcs/client/renderer/RenderNPCInterface.java +++ b/src/main/java/noppes/npcs/client/renderer/RenderNPCInterface.java @@ -482,7 +482,7 @@ public class RenderNPCInterface extends RenderLiving { Minecraft.getMinecraft().entityRenderer.disableLightmap((double) 0); } - GL11.glColor4f(1.0F, 1.0F, 1.0F, overlayData.getAlpha()); + glColor(overlayData.getColor(), overlayData.getAlpha()); GL11.glDepthMask(!npc.isInvisible()); @@ -521,6 +521,14 @@ public class RenderNPCInterface extends RenderLiving { } } + private static void glColor(int color, float alpha) { + float r = ((color >> 16) & 0xFF) / 255.0F; + float g = ((color >> 8) & 0xFF) / 255.0F; + float b = (color & 0xFF) / 255.0F; + + GL11.glColor4f(r, g, b, alpha); + } + @Override protected float handleRotationFloat(EntityLivingBase par1EntityLiving, float par2) { EntityNPCInterface npc = (EntityNPCInterface) par1EntityLiving; @@ -536,72 +544,106 @@ public class RenderNPCInterface extends RenderLiving { @Override public ResourceLocation getEntityTexture(Entity entity) { - EntityNPCInterface npc = (EntityNPCInterface) entity; - if (npc.textureLocation == null) { - if (npc.display.skinType == 0) { + + // Early exit if texture already resolved + if (npc.textureLocation != null) { + return npc.textureLocation; + } + + // SkinType 0: custom texture or default + if (npc.display.skinType == 0) { + if (npc.display.texture.isEmpty()) { + return npc.textureLocation = fallBackSkin(npc); + } + + try { if (npc instanceof EntityCustomNpc && ((EntityCustomNpc) npc).modelData.entityClass == null) { - if (!(npc.display.texture).isEmpty()) { - try { - npc.textureLocation = adjustLocalTexture(npc, new ResourceLocation(npc.display.texture)); - } catch (IOException ignored) { - } - } + npc.textureLocation = adjustLocalTexture(npc, new ResourceLocation(npc.display.texture)); } else { - npc.textureLocation = new ResourceLocation(npc.display.texture); + ResourceLocation resLoc = new ResourceLocation(npc.display.texture); + Minecraft.getMinecraft().getResourceManager().getResource(resLoc); + npc.textureLocation = resLoc; } - } else if (npc.display.skinType == 1 && npc.display.playerProfile != null) { - Minecraft minecraft = Minecraft.getMinecraft(); - Map map = minecraft.func_152342_ad().func_152788_a(npc.display.playerProfile); - if (map.containsKey(Type.SKIN)) { - npc.textureLocation = minecraft.func_152342_ad().func_152792_a((MinecraftProfileTexture) map.get(Type.SKIN), Type.SKIN); - } - LastTextureTick = 0; - } else if (npc.display.skinType == 2 || npc.display.skinType == 3) { - ResourceLocation location = new ResourceLocation("skins/" + (npc.display.skinType + npc.display.url).hashCode()); - // If URL Empty Steve - if (npc.display.url.isEmpty()) { - return fallBackSkin(npc); - } - // If URL Cached then grab it - else if (ClientCacheHandler.isCachedNPC(location)) { - try { - ResourceLocation loc = ClientCacheHandler.getNPCTexture(npc.display.url, npc.display.skinType == 3, location).getLocation(); - if (loc != null) { - npc.textureLocation = loc; - } else { - return fallBackSkin(npc); - } - } catch (Exception ignored) { - } - } - // For New URL Requests do not spam it - else if (LastTextureTick < 5) { //fixes request flood somewhat - return fallBackSkin(npc); - } else { - try { - ResourceLocation loc = ClientCacheHandler.getNPCTexture(npc.display.url, npc.display.skinType == 3, location).getLocation(); - if (loc != null) { - npc.textureLocation = loc; - } else { - return fallBackSkin(npc); - } - LastTextureTick = 0; - } catch (Exception ignored) { - } - } - } else { + } catch (IOException ignored) { return fallBackSkin(npc); } } - return npc.textureLocation; + + // SkinType 1: player profile skin + else if (npc.display.skinType == 1 && npc.display.playerProfile != null) { + final Minecraft minecraft = Minecraft.getMinecraft(); + Map map = minecraft.func_152342_ad().func_152788_a(npc.display.playerProfile); + if (map.containsKey(Type.SKIN)) { + npc.textureLocation = minecraft.func_152342_ad() + .func_152792_a((MinecraftProfileTexture) map.get(Type.SKIN), Type.SKIN); + } + LastTextureTick = 0; + } + + // SkinType 2 / 3: load from URL + else if (npc.display.skinType == 2 || npc.display.skinType == 3) { + if (npc.display.url.isEmpty()) { // If URL is empty → fallback + return fallBackSkin(npc); + } + + ResourceLocation location = new ResourceLocation("skins/" + (npc.display.skinType + npc.display.url).hashCode()); + + try { + if (ClientCacheHandler.isCachedNPC(location)) { // If URL is cached + ResourceLocation loc = ClientCacheHandler + .getNPCTexture(npc.display.url, npc.display.skinType == 3, location) + .getLocation(); + if (loc == null) return fallBackSkin(npc); + npc.textureLocation = loc; + } else if (LastTextureTick >= 5) { // Prevent request flooding + ResourceLocation loc = ClientCacheHandler + .getNPCTexture(npc.display.url, npc.display.skinType == 3, location) + .getLocation(); + if (loc == null) return fallBackSkin(npc); + npc.textureLocation = loc; + LastTextureTick = 0; + } else { + return fallBackSkin(npc); + } + } catch (Exception ignored) { + return fallBackSkin(npc); + } + } + + // Fallback: if no valid skin type matched + else { + return fallBackSkin(npc); + } + + // Final safety net + return npc.textureLocation == null ? fallBackSkin(npc) : npc.textureLocation; } private ResourceLocation adjustLocalTexture(EntityNPCInterface npc, ResourceLocation location) throws IOException { InputStream inputstream = null; try { TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); - texturemanager.deleteTexture(location); + + // Compute the hash-based skin location first + ResourceLocation skinLocation = location; + try { + MessageDigest digest = MessageDigest.getInstance("MD5"); + byte[] hash = digest.digest(npc.display.texture.getBytes("UTF-8")); + StringBuilder sb = new StringBuilder(2 * hash.length); + for (byte b : hash) { + sb.append(String.format("%02x", b & 0xff)); + } + if (npc.display.modelType == 0) { + skinLocation = new ResourceLocation("skin/" + sb.toString()); + } else { + skinLocation = new ResourceLocation("skin64/" + sb.toString()); + } + } catch (Exception ignored) { + } + + // Delete old processed skin texture if cached (prevents GL texture leak) + texturemanager.deleteTexture(skinLocation); IResource iresource = Minecraft.getMinecraft().getResourceManager().getResource(location); inputstream = iresource.getInputStream(); @@ -617,22 +659,8 @@ public class RenderNPCInterface extends RenderLiving { ImageDownloadAlt object = new ImageDownloadAlt(null, npc.display.texture, SkinManager.field_152793_a, new ImageBufferDownloadAlt(true)); object.setBufferedImage(bufferedimage); - try { - MessageDigest digest = MessageDigest.getInstance("MD5"); - byte[] hash = digest.digest(npc.display.texture.getBytes("UTF-8")); - StringBuilder sb = new StringBuilder(2 * hash.length); - for (byte b : hash) { - sb.append(String.format("%02x", b & 0xff)); - } - if (npc.display.modelType == 0) { - location = new ResourceLocation("skin/" + sb.toString()); - } else { - location = new ResourceLocation("skin64/" + sb.toString()); - } - } catch (Exception ignored) { - } - texturemanager.loadTexture(location, object); - return location; + texturemanager.loadTexture(skinLocation, object); + return skinLocation; } finally { if (inputstream != null) { inputstream.close(); diff --git a/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java b/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java index 8b8c1f452..83b83b9b6 100644 --- a/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java +++ b/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java @@ -17,6 +17,7 @@ import net.minecraftforge.client.IItemRenderer; import noppes.npcs.api.item.IItemCustomizable; import noppes.npcs.api.item.IItemStack; import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.items.ItemCustomizable; import noppes.npcs.scripted.NpcAPI; @@ -222,7 +223,8 @@ public class ItemCustomRenderer implements IItemRenderer { int pass = 0; GL11.glPushMatrix(); - ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture(); + ImageData entityImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + entityImageData.bindTexture(); if (renderInFrame) { GL11.glTranslatef(0.0F, -0.05F, 0.0F); @@ -233,10 +235,22 @@ public class ItemCustomRenderer implements IItemRenderer { Tessellator tessellator = Tessellator.instance; + // Animation V offset for entity rendering + float entityVOff = 0f; + float entityVEnd = 1f; + if (entityImageData.isAnimated()) { + entityVOff = entityImageData.getCurrentFrameVOffset(); + entityVEnd = entityVOff + (float) entityImageData.getFrameHeight() / entityImageData.getTotalHeight(); + } else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() + && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) { + entityVOff = AnimationHelper.getFrameVOffset(entityImageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime()); + entityVEnd = entityVOff + AnimationHelper.getFrameVSize(entityImageData.getTotalHeight(), scriptCustomItem.getFrameCount()); + } + float f14 = 0.0F; float f15 = 1.0F; - float f4 = 0.0F; - float f5 = 1.0F; + float f4 = entityVOff; + float f5 = entityVEnd; float f6 = 1.0F; float f7 = 0.5F; float f8 = 0.25F; @@ -272,8 +286,11 @@ public class ItemCustomRenderer implements IItemRenderer { GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); }*/ - ImageData imageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); - ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, imageData.getTotalWidth(), imageData.getTotalHeight(), f9); + ImageData loopImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + int entityFrameH = loopImageData.isAnimated() ? loopImageData.getFrameHeight() + : (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1 + ? loopImageData.getTotalHeight() / scriptCustomItem.getFrameCount() : loopImageData.getTotalHeight()); + ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, loopImageData.getTotalWidth(), entityFrameH, f9); if (itemStack.hasEffect(pass)) { GL11.glDepthFunc(GL11.GL_EQUAL); @@ -359,8 +376,20 @@ public class ItemCustomRenderer implements IItemRenderer { GL11.glDisable(GL11.GL_LIGHTING); //Forge: Make sure that render states are reset, a renderEffect can derp them up. GL11.glEnable(GL11.GL_ALPHA_TEST); - ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture(); - renderCustomItemSlot(0, 0, 16, 16, itemRed, itemGreen, itemBlue); + ImageData imageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + imageData.bindTexture(); + + float vOff = 0f; + float vEnd = 1f; + if (imageData.isAnimated()) { + vOff = imageData.getCurrentFrameVOffset(); + vEnd = vOff + (float) imageData.getFrameHeight() / imageData.getTotalHeight(); + } else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() + && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) { + vOff = AnimationHelper.getFrameVOffset(imageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime()); + vEnd = vOff + AnimationHelper.getFrameVSize(imageData.getTotalHeight(), scriptCustomItem.getFrameCount()); + } + renderCustomItemSlot(0, 0, 16, 16, itemRed, itemGreen, itemBlue, vOff, vEnd); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); @@ -412,13 +441,17 @@ public class ItemCustomRenderer implements IItemRenderer { } public void renderCustomItemSlot(int posX, int posY, int imageWidth, int imageHeight, float itemRed, float itemGreen, float itemBlue) { + renderCustomItemSlot(posX, posY, imageWidth, imageHeight, itemRed, itemGreen, itemBlue, 0f, 1f); + } + + public void renderCustomItemSlot(int posX, int posY, int imageWidth, int imageHeight, float itemRed, float itemGreen, float itemBlue, float vOff, float vEnd) { Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.setColorRGBA_F(itemRed, itemGreen, itemBlue, 1.0F); - tessellator.addVertexWithUV((double) (posX), (double) (posY + imageHeight), 0, 0, 1); - tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY + imageHeight), 0, 1, 1); - tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY), 0, 1, 0); - tessellator.addVertexWithUV((double) (posX), (double) (posY), 0, 0, 0); + tessellator.addVertexWithUV((double) (posX), (double) (posY + imageHeight), 0, 0, vEnd); + tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY + imageHeight), 0, 1, vEnd); + tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY), 0, 1, vOff); + tessellator.addVertexWithUV((double) (posX), (double) (posY), 0, 0, vOff); tessellator.draw(); } @@ -429,7 +462,8 @@ public class ItemCustomRenderer implements IItemRenderer { TextureManager texturemanager = mc.getTextureManager(); int par3 = 0; - ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture(); + ImageData item3dImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + item3dImageData.bindTexture(); Tessellator tessellator = Tessellator.instance; IIcon icon = entityLivingBase.getItemIcon(itemStack, par3); @@ -447,7 +481,19 @@ public class ItemCustomRenderer implements IItemRenderer { GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F); - renderCustomItemIn2D(scriptCustomItem, tessellator, 1.0F, 0.0F, 0.0F, 1.0F, 0.0625F); + // Animation V offset for 3D handheld rendering + float item3dVOff = 0f; + float item3dVEnd = 1f; + if (item3dImageData.isAnimated()) { + item3dVOff = item3dImageData.getCurrentFrameVOffset(); + item3dVEnd = item3dVOff + (float) item3dImageData.getFrameHeight() / item3dImageData.getTotalHeight(); + } else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() + && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) { + item3dVOff = AnimationHelper.getFrameVOffset(item3dImageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime()); + item3dVEnd = item3dVOff + AnimationHelper.getFrameVSize(item3dImageData.getTotalHeight(), scriptCustomItem.getFrameCount()); + } + + renderCustomItemIn2D(scriptCustomItem, tessellator, 1.0F, item3dVOff, 0.0F, item3dVEnd, 0.0625F); if (itemStack.hasEffect(par3)) { GL11.glDepthFunc(GL11.GL_EQUAL); @@ -485,7 +531,10 @@ public class ItemCustomRenderer implements IItemRenderer { public static void renderCustomItemIn2D(IItemCustomizable wrapper, Tessellator p_78439_0_, float p_78439_1_, float p_78439_2_, float p_78439_3_, float p_78439_4_, float p_78439_7_) { ImageData imageData = ClientCacheHandler.getImageData(wrapper.getTexture()); int width = imageData.getTotalWidth(); - int height = imageData.getTotalHeight(); + // Use frame height for edge pixel calculations so animated strips render correctly + int height = imageData.isAnimated() ? imageData.getFrameHeight() + : (wrapper.isTextureAnimated() != null && wrapper.isTextureAnimated() && wrapper.getFrameCount() != null && wrapper.getFrameCount() > 1 + ? imageData.getTotalHeight() / wrapper.getFrameCount() : imageData.getTotalHeight()); p_78439_0_.startDrawingQuads(); p_78439_0_.setNormal(0.0F, 0.0F, 1.0F); diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index d8c093382..fa4376334 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -17,6 +17,7 @@ public class ConfigClient { public final static String MODEL = "Model"; public final static String TEXTURE = "Texture"; public final static String HUD = "Hud"; + public final static String RENDERING = "Rendering"; /** @@ -52,6 +53,20 @@ public class ConfigClient { public static Property HideEffectsBarProperty; public static boolean HideEffectsBar = false; + // Rendering Properties + public static Property LowResExplosionProperty; + public static boolean LowResExplosion = false; + + // Proximity Alpha (owner-only fade for energy projectiles near camera) + public static Property ProximityAlphaMinProperty; + public static float ProximityAlphaMin = 0.15f; + + public static Property ProximityAlphaDistanceProperty; + public static float ProximityAlphaDistance = 10.0f; + + public static Property ProximityAlphaAgeTicksProperty; + public static int ProximityAlphaAgeTicks = 60; + /** * Questing Properties **/ @@ -69,13 +84,13 @@ public class ConfigClient { // HUD PROPERTIES public static Property QuestOverlayXProperty; - public static int QuestOverlayX = 0; + public static float QuestOverlayX = 0; public static Property QuestOverlayYProperty; - public static int QuestOverlayY = 31; + public static float QuestOverlayY = 14; public static Property QuestOverlayScaleProperty; - public static int QuestOverlayScale = 223; + public static int QuestOverlayScale = 246; public static Property QuestOverlayTextAlignProperty; public static int QuestOverlayTextAlign = 0; // 0: Left, 1: Center, 2: Right @@ -84,16 +99,51 @@ public class ConfigClient { public static boolean CompassEnabled = true; public static Property CompassOverlayXProperty; - public static int CompassOverlayX = 37; + public static float CompassOverlayX = 36; public static Property CompassOverlayYProperty; - public static int CompassOverlayY = 0; + public static float CompassOverlayY = 0; public static Property CompassOverlayScaleProperty; - public static int CompassOverlayScale = 276; + public static int CompassOverlayScale = 344; public static Property CompassOverlayWidthProperty; - public static int CompassOverlayWidth = 200; + public static int CompassOverlayWidth = 158; + + // Ability Hotbar HUD + public static Property AbilityHotbarEnabledProperty; + public static boolean AbilityHotbarEnabled = true; + + public static Property AbilityHotbarXProperty; + public static float AbilityHotbarX = 0; + + public static Property AbilityHotbarYProperty; + public static float AbilityHotbarY = 43; + + public static Property AbilityHotbarScaleProperty; + public static int AbilityHotbarScale = 227; + + public static Property AbilityHotbarHorizontalProperty; + public static boolean AbilityHotbarHorizontal = false; + + public static Property AbilityHotbarAltTextureProperty; + public static boolean AbilityHotbarAltTexture = true; + + // 1=Above(H)/Left(V), 2=Below(H)/Right(V) + public static Property AbilityHotbarTextPositionProperty; + public static int AbilityHotbarTextPosition = 2; + + // Max visible slots: 3, 5, or 7 + public static Property AbilityHotbarVisibleSlotsProperty; + public static int AbilityHotbarVisibleSlots = 5; + + // Show Always: true = always visible, false = only visible while HUD key held + public static Property AbilityHotbarShowAlwaysProperty; + public static boolean AbilityHotbarShowAlways = true; + + // Text Visibility: 0=Shown, 1=Hidden, 2=Held (only while HUD key held) + public static Property AbilityHotbarTextVisibilityProperty; + public static int AbilityHotbarTextVisibility = 0; /** * Texture Properties @@ -117,6 +167,7 @@ public class ConfigClient { public static boolean LegacyTallLamp = false; public static boolean LegacyPedestal = false; public static boolean LegacyMailbox = false; + public static boolean ImprovedImageDownloadConnection = true; public static void init(File configFile) { config = new Configuration(configFile); @@ -125,14 +176,14 @@ public class ConfigClient { config.load(); // Hud Quest Overlay settings - QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0, "X position of the quest overlay."); - QuestOverlayX = QuestOverlayXProperty.getInt(0); + QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0.0, "X position of the quest overlay."); + QuestOverlayX = (float) QuestOverlayXProperty.getDouble(0); - QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31, "Y position of the quest overlay."); - QuestOverlayY = QuestOverlayYProperty.getInt(31); + QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 14.0, "Y position of the quest overlay."); + QuestOverlayY = (float) QuestOverlayYProperty.getDouble(14); - QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 223, "Scale percentage of the quest overlay."); - QuestOverlayScale = QuestOverlayScaleProperty.getInt(223); + QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 246, "Scale percentage of the quest overlay."); + QuestOverlayScale = QuestOverlayScaleProperty.getInt(246); QuestOverlayTextAlignProperty = config.get(HUD, "Quest Hud Text Alignment", 0, "Text alignment in quest overlay (0: Left, 1: Center, 2: Right)."); QuestOverlayTextAlign = QuestOverlayTextAlignProperty.getInt(0); @@ -149,43 +200,69 @@ public class ConfigClient { CompassOverlayXProperty = config.get( HUD, "Compass Hud X", - 37, - "Horizontal position of compass overlay (0-100 percentage)", - 0, - 100 + 36.0, + "Horizontal position of compass overlay (0-100 percentage)" ); - CompassOverlayX = CompassOverlayXProperty.getInt(); + CompassOverlayX = (float) CompassOverlayXProperty.getDouble(); CompassOverlayYProperty = config.get( HUD, "Compass Hud Y", - 0, - "Vertical position of compass overlay (0-100 percentage)", - 0, - 100 + 0.0, + "Vertical position of compass overlay (0-100 percentage)" ); - CompassOverlayY = CompassOverlayYProperty.getInt(); + CompassOverlayY = (float) CompassOverlayYProperty.getDouble(); CompassOverlayScaleProperty = config.get( HUD, "Compass Hud Scale", - 276, + 344, "Scale percentage of compass overlay", 50, - 300 + 500 ); CompassOverlayScale = CompassOverlayScaleProperty.getInt(); CompassOverlayWidthProperty = config.get( HUD, "Compass Hud Width", - 200, + 158, "Base width of compass bar in pixels", - 100, + 50, 1000 ); CompassOverlayWidth = CompassOverlayWidthProperty.getInt(); + // Ability Hotbar HUD Configs + AbilityHotbarEnabledProperty = config.get(HUD, "Ability Hotbar Enabled", true, "Enable Ability Hotbar HUD Component"); + AbilityHotbarEnabled = AbilityHotbarEnabledProperty.getBoolean(); + + AbilityHotbarXProperty = config.get(HUD, "Ability Hotbar X", 0.0, "Horizontal position (0-100 percentage)"); + AbilityHotbarX = (float) AbilityHotbarXProperty.getDouble(); + + AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 43.0, "Vertical position (0-100 percentage)"); + AbilityHotbarY = (float) AbilityHotbarYProperty.getDouble(); + + AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 227, "Scale percentage", 50, 500); + AbilityHotbarScale = AbilityHotbarScaleProperty.getInt(); + + AbilityHotbarHorizontalProperty = config.get(HUD, "Ability Hotbar Horizontal", false, "Display horizontally instead of vertically"); + AbilityHotbarHorizontal = AbilityHotbarHorizontalProperty.getBoolean(); + + AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", true, "Use rounded square instead of circle slots"); + AbilityHotbarAltTexture = AbilityHotbarAltTextureProperty.getBoolean(); + + AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (1=Above/Left, 2=Below/Right)"); + AbilityHotbarTextPosition = AbilityHotbarTextPositionProperty.getInt(2); + + AbilityHotbarVisibleSlotsProperty = config.get(HUD, "Ability Hotbar Visible Slots", 5, "Max visible slots in hotbar (3, 5, or 7)"); + AbilityHotbarVisibleSlots = AbilityHotbarVisibleSlotsProperty.getInt(5); + + AbilityHotbarShowAlwaysProperty = config.get(HUD, "Ability Hotbar Show Always", true, "Always show hotbar (false = only while HUD key is held)"); + AbilityHotbarShowAlways = AbilityHotbarShowAlwaysProperty.getBoolean(true); + + AbilityHotbarTextVisibilityProperty = config.get(HUD, "Ability Hotbar Text Visibility", 0, "Text visibility (0=Shown, 1=Hidden, 2=Held)"); + AbilityHotbarTextVisibility = AbilityHotbarTextVisibilityProperty.getInt(0); // General AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side."); @@ -216,6 +293,38 @@ public class ConfigClient { HideEffectsBarProperty = config.get(VISUAL, "Hide Effects Bar", false, "Hides CNPC+ Inventory Effects Bar"); HideEffectsBar = HideEffectsBarProperty.getBoolean(false); + LowResExplosionProperty = config.get( + RENDERING, + "Low Res Explosion", + false, + "Disables most Energy Explosion voxel rendering and keeps particle effects only." + ); + LowResExplosion = LowResExplosionProperty.getBoolean(false); + + ProximityAlphaMinProperty = config.get( + RENDERING, + "Proximity Alpha Min", + 0.15, + "Minimum alpha for owner's energy projectiles when very close to camera. Set to 1.0 to disable proximity fade." + ); + ProximityAlphaMin = (float) Math.max(0.0, Math.min(1.0, ProximityAlphaMinProperty.getDouble(0.15))); + + ProximityAlphaDistanceProperty = config.get( + RENDERING, + "Proximity Alpha Distance", + 7.0, + "Distance in blocks at which owner's energy projectiles reach full alpha." + ); + ProximityAlphaDistance = (float) Math.max(1.0, ProximityAlphaDistanceProperty.getDouble(10.0)); + + ProximityAlphaAgeTicksProperty = config.get( + RENDERING, + "Proximity Alpha Age Ticks", + 60, + "After this many ticks alive, proximity alpha fade is disabled (projectile always renders at full alpha). Does not apply while charging or to attached beams/lasers." + ); + ProximityAlphaAgeTicks = Math.max(0, ProximityAlphaAgeTicksProperty.getInt(60)); + DialogSpeedProperty = config.get(VISUAL, "Dialog Speed", true, "Only set for gradual dialogs"); DialogSpeed = DialogSpeedProperty.getInt(10); @@ -229,6 +338,7 @@ public class ConfigClient { BannerAlerts = BannerAlertsProperty.getBoolean(true); WoodTextures = config.get(TEXTURE, "Wood Textures", false, "Models like Chairs and Stools will use default MC Wood Textures").getBoolean(false); + ImprovedImageDownloadConnection = config.get(TEXTURE, "DEBUG: Better handling of image downloads: ", true).getBoolean(true); LegacyCampfire = config.get(MODEL, "Legacy Campfire Model", false).getBoolean(false); LegacyBanner = config.get(MODEL, "Legacy Banner Model", false).getBoolean(false); @@ -259,6 +369,7 @@ public class ConfigClient { FontSize = LegacyConfig.FontSize; FontSizeProperty.set(FontSize); } + } catch (Exception e) { FMLLog.log(Level.ERROR, e, "CNPC+ has had a problem loading its client configuration"); } finally { diff --git a/src/main/java/noppes/npcs/config/ConfigEnergy.java b/src/main/java/noppes/npcs/config/ConfigEnergy.java new file mode 100644 index 000000000..197bb4968 --- /dev/null +++ b/src/main/java/noppes/npcs/config/ConfigEnergy.java @@ -0,0 +1,50 @@ +package noppes.npcs.config; + +import cpw.mods.fml.common.FMLLog; +import net.minecraftforge.common.config.Configuration; +import org.apache.logging.log4j.Level; + +import java.io.File; + +public class ConfigEnergy { + public static Configuration config; + + public final static String DOMES = "Domes"; + public final static String EXPLOSIONS = "Explosions"; + + public static String[] DomeItemBlacklist; + /** + * Server-side toggle for energy projectile terrain destruction. + * Disabled by default to avoid block grief. + */ + public static boolean EnableEnergyExplosionBlockDamage; + + public static void init(File configFile) { + config = new Configuration(configFile); + + try { + config.load(); + + DomeItemBlacklist = config.getStringList( + "Item Blacklist", DOMES, + new String[]{"minecraft:ender_pearl"}, + "Items that cannot be used while inside an Energy Dome.\n" + + "Format: modid:itemname (e.g., minecraft:ender_pearl)" + ); + + EnableEnergyExplosionBlockDamage = config.getBoolean( + "Enable Energy Explosion Block Damage", EXPLOSIONS, + false, + "If true, explosive ENERGY projectile abilities can destroy terrain.\n" + + "This is intended for server-side use and is disabled by default." + ); + + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "CustomNPC+ has had a problem loading its energy configuration"); + } finally { + if (config.hasChanged()) { + config.save(); + } + } + } +} diff --git a/src/main/java/noppes/npcs/config/ConfigMarket.java b/src/main/java/noppes/npcs/config/ConfigMarket.java index e14861033..976452d08 100644 --- a/src/main/java/noppes/npcs/config/ConfigMarket.java +++ b/src/main/java/noppes/npcs/config/ConfigMarket.java @@ -79,11 +79,12 @@ public class ConfigMarket { CurrencyName = config.get(CURRENCY, "Currency Name", "Coins", "Display name for the currency (e.g. 'Coins', 'Gold', 'Credits')").getString(); - StartingBalance = config.get(CURRENCY, "Starting Balance", 0, - "Starting currency balance for new players").getInt(0); + StartingBalance = parseLongConfig(config.get(CURRENCY, "Starting Balance", "0", + "Starting currency balance for new players").getString(), 0); - MaxBalance = config.get(CURRENCY, "Max Balance", Integer.MAX_VALUE, - "Maximum currency balance a player can have").getInt(Integer.MAX_VALUE); + MaxBalance = parseLongConfig(config.get(CURRENCY, "Max Balance", String.valueOf(Long.MAX_VALUE), + "Maximum currency balance a player can have").getString(), Long.MAX_VALUE); + if (MaxBalance < 0) MaxBalance = Long.MAX_VALUE; // ========================================= // Auction Settings @@ -95,16 +96,19 @@ public class ConfigMarket { AuctionDurationHours = config.get(AUCTION, "Auction Duration Hours", 24, "Default duration for auctions in hours").getInt(24); + if (AuctionDurationHours < 1) AuctionDurationHours = 1; - ListingFee = config.get(AUCTION, "Listing Fee", 10, - "Flat fee charged when creating a listing").getInt(10); + ListingFee = parseLongConfig(config.get(AUCTION, "Listing Fee", "10", + "Flat fee charged when creating a listing").getString(), 10); + if (ListingFee < 0) ListingFee = 0; - MinimumListingPrice = config.get(AUCTION, "Minimum Listing Price", 1, - "Minimum starting price for auction listings").getInt(1); + MinimumListingPrice = parseLongConfig(config.get(AUCTION, "Minimum Listing Price", "1", + "Minimum starting price for auction listings").getString(), 1); if (MinimumListingPrice < 1) MinimumListingPrice = 1; SalesTaxPercent = config.get(AUCTION, "Sales Tax Percent", 0.05, "Percentage of sale price taken as tax (0.05 = 5%). Tax is deleted as a currency sink.").getDouble(0.05); + SalesTaxPercent = Math.max(0.0, Math.min(1.0, SalesTaxPercent)); int maxTrades = config.get(AUCTION, "Default Max Trades", 8, "Default maximum number of trade slots per player (listings + bids + claims). Min: 1, Max: 45. Players can have more via customnpcs.auction.trades.X permissions.").getInt(8); @@ -112,26 +116,30 @@ public class ConfigMarket { SnipeProtectionMinutes = config.get(AUCTION, "Snipe Protection Minutes", 2, "When a bid is placed with less than this many minutes remaining, the auction is extended to this duration").getInt(2); + if (SnipeProtectionMinutes < 0) SnipeProtectionMinutes = 0; ClaimExpirationDays = config.get(AUCTION, "Claim Expiration Days", 20, "Number of days before unclaimed items/currency are deleted").getInt(20); + if (ClaimExpirationDays < 1) ClaimExpirationDays = 1; MinBidIncrementPercent = config.get(AUCTION, "Min Bid Increment Percent", 0.05, "Minimum bid increment as a percentage of current bid (0.05 = 5%)").getDouble(0.05); + MinBidIncrementPercent = Math.max(0.0, Math.min(1.0, MinBidIncrementPercent)); CancellationPenaltyPercent = config.get(AUCTION, "Cancellation Penalty Percent", 0.10, "Percentage of current bid taken as penalty when seller cancels an auction with bids (0.10 = 10%)").getDouble(0.10); + CancellationPenaltyPercent = Math.max(0.0, Math.min(1.0, CancellationPenaltyPercent)); // ========================================= // Auction Blacklist Settings // ========================================= config.setCategoryComment(AUCTION_BLACKLIST, "Item Blacklist settings for the Auction House.\n" + - "Prevents specific items, mods, or items with certain NBT tags from being listed.\n\n" + - "ITEM FORMAT: Use 'modid:itemname' format (e.g., 'minecraft:bedrock', 'customnpcs:npcWand')\n" + - "WILDCARDS: Use * for wildcards (e.g., 'customnpcs:npc*' blocks all items starting with 'npc')\n" + - "MOD FORMAT: Use just the mod ID (e.g., 'projecte' blocks all items from that mod)\n" + - "NBT FORMAT: Use the NBT tag key name (e.g., 'AdminOnly' blocks items with that tag)"); + "Prevents specific items, mods, or items with certain NBT tags from being listed.\n\n" + + "ITEM FORMAT: Use 'modid:itemname' format (e.g., 'minecraft:bedrock', 'customnpcs:npcWand')\n" + + "WILDCARDS: Use * for wildcards (e.g., 'customnpcs:npc*' blocks all items starting with 'npc')\n" + + "MOD FORMAT: Use just the mod ID (e.g., 'projecte' blocks all items from that mod)\n" + + "NBT FORMAT: Use the NBT tag key name (e.g., 'AdminOnly' blocks items with that tag)"); BlacklistEnabled = config.get(AUCTION_BLACKLIST, "Enable Blacklist", true, "Enable item blacklist checking when creating listings").getBoolean(true); @@ -149,17 +157,17 @@ public class ConfigMarket { "customnpcs:npcSoulstoneFilled" }, "Items that cannot be listed on the Auction House.\n" + - "Format: modid:itemname (supports * wildcards)\n" + - "Example: 'minecraft:diamond_sword' or 'customnpcs:npc*'").getStringList(); + "Format: modid:itemname (supports * wildcards)\n" + + "Example: 'minecraft:diamond_sword' or 'customnpcs:npc*'").getStringList(); BlacklistedMods = config.get(AUCTION_BLACKLIST, "Blacklisted Mods", new String[]{}, "All items from these mods are blocked from the Auction House.\n" + - "Format: modid (e.g., 'projecte', 'thaumcraft')").getStringList(); + "Format: modid (e.g., 'projecte', 'thaumcraft')").getStringList(); BlacklistedNBTTags = config.get(AUCTION_BLACKLIST, "Blacklisted NBT Tags", new String[]{}, "Items containing any of these NBT tag keys are blocked.\n" + - "Checks the root level of the item's NBT compound.\n" + - "Example: 'AdminOnly', 'CreativeMode'").getStringList(); + "Checks the root level of the item's NBT compound.\n" + + "Example: 'AdminOnly', 'CreativeMode'").getStringList(); // ========================================= // Auction Logging Settings @@ -237,4 +245,13 @@ public class ConfigMarket { } } } + + private static long parseLongConfig(String value, long defaultValue) { + if (value == null || value.trim().isEmpty()) return defaultValue; + try { + return Long.parseLong(value.trim()); + } catch (NumberFormatException e) { + return defaultValue; + } + } } diff --git a/src/main/java/noppes/npcs/config/ConfigMixin.java b/src/main/java/noppes/npcs/config/ConfigMixin.java index c9491fe0e..5ee2029fb 100644 --- a/src/main/java/noppes/npcs/config/ConfigMixin.java +++ b/src/main/java/noppes/npcs/config/ConfigMixin.java @@ -11,6 +11,7 @@ public class ConfigMixin { public static Configuration config; public final static String CLIENT = "CLIENT"; + public final static String SERVER = "SERVER"; public final static String GENERAL = "GENERAL"; /** @@ -25,6 +26,9 @@ public class ConfigMixin { public static Property FirstPersonAnimationMixinProperty; public static boolean FirstPersonAnimationMixin = true; + public static Property EntitySpawnFixMixinProperty; + public static boolean EntitySpawnFixMixin = true; + public static void init(File configFile) { config = new Configuration(configFile); @@ -43,6 +47,9 @@ public class ConfigMixin { } else { FirstPersonAnimationMixin = false; } + + EntitySpawnFixMixinProperty = config.get(SERVER, "Entity Spawn Packet Fix", true, "Fixes a Forge race condition where mod entity spawn packets can be lost or sent to the wrong player. This prevents invisible entities on servers with multiple players."); + EntitySpawnFixMixin = EntitySpawnFixMixinProperty.getBoolean(true); } catch (Exception e) { FMLLog.log(Level.ERROR, e, "CNPC+ has had a problem loading its mixin configuration"); } finally { diff --git a/src/main/java/noppes/npcs/config/ConfigScript.java b/src/main/java/noppes/npcs/config/ConfigScript.java index 15c2b9ca0..2b3d5d9d0 100644 --- a/src/main/java/noppes/npcs/config/ConfigScript.java +++ b/src/main/java/noppes/npcs/config/ConfigScript.java @@ -66,6 +66,9 @@ public class ConfigScript { public static Property ClearActionsOnDeathProperty; public static boolean ClearActionsOnDeath = true; + public static Property ShowImplementationFieldsInAutocompleteProperty; + public static boolean ShowImplementationFieldsInAutocomplete = false; + public static boolean IndividualPlayerScripts = false; public static void init(File configFile) { @@ -131,6 +134,11 @@ public class ConfigScript { ClearActionsOnDeathProperty = config.get(CUSTOMIZATION, "Clear Actions On Death", true, "If true, clears the Action Manager for players and NPCs when they die"); ClearActionsOnDeath = ClearActionsOnDeathProperty.getBoolean(true); + ShowImplementationFieldsInAutocompleteProperty = config.get(CUSTOMIZATION, "Autocomplete Implementation Fields", false, + "If true, shows fields from implementation classes in autocomplete menu like 'event.npc'.\n"+ + " This can be useful for advanced scripters who want to use fields from implementation classes."); + ShowImplementationFieldsInAutocomplete = ShowImplementationFieldsInAutocompleteProperty.getBoolean(false); + // Convert to Legacy if (CustomNpcs.legacyExist) { ScriptingEnabled = LegacyConfig.ScriptingEnabled; diff --git a/src/main/java/noppes/npcs/config/GlyphCache.java b/src/main/java/noppes/npcs/config/GlyphCache.java index 86f34d433..8cc890869 100644 --- a/src/main/java/noppes/npcs/config/GlyphCache.java +++ b/src/main/java/noppes/npcs/config/GlyphCache.java @@ -1,9 +1,11 @@ package noppes.npcs.config; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; import java.awt.AlphaComposite; import java.awt.Color; @@ -43,13 +45,13 @@ public class GlyphCache { * The width in pixels of every texture used for caching pre-rendered glyph images. Used by GlyphCache when calculating * floating point 0.0-1.0 texture coordinates. Must be a power of two for mip-mapping to work. */ - private static final int TEXTURE_WIDTH = 256; + private static final int TEXTURE_WIDTH = 512; /** * The height in pixels of every texture used for caching pre-rendered glyph images. Used by GlyphCache when calculating * floating point 0.0-1.0 texture coordinates. Must be a power of two for mip-mapping to work. */ - private static final int TEXTURE_HEIGHT = 256; + private static final int TEXTURE_HEIGHT = 512; /** * Initial width in pixels of the stringImage buffer used to extract individual glyph images. @@ -66,7 +68,23 @@ public class GlyphCache { * glyphs from "bleeding through" when the scaled GUI resolution is not pixel aligned and sometimes results in off-by-one * sampling of the glyph cache textures. */ - private static final int GLYPH_BORDER = 1; + private static final int GLYPH_BORDER = 2; + + /** + * Extra padding (in pixels) added around each glyph's reported pixel bounds before blitting into the atlas. + * Font hinting (especially GASP-aware rendering) can cause rendered pixels to extend beyond the bounds + * reported by GlyphVector.getGlyphPixelBounds(). This padding ensures those overflow pixels are captured. + */ + private static final int GLYPH_PADDING = 2; + + /** + * Minimum spacing (in pixels) inserted between adjacent glyphs in the temporary string image during + * rasterization. Each glyph is shifted right by glyphSpacing * glyphIndex to prevent kerning from + * merging adjacent glyphs. This base value is used for plain/bold styles. For italic fonts, the + * spacing is increased dynamically by {@link #computeGlyphSpacing(Font)} to account for the + * horizontal overhang caused by the italic slant. + */ + private static final int GLYPH_SPACING_BASE = 2 * GLYPH_PADDING + 1; /** * Transparent (alpha zero) white background color for use with BufferedImage.clearRect(). @@ -83,6 +101,21 @@ public class GlyphCache { */ private boolean antiAliasEnabled = false; + /** + * The current Minecraft GUI scale factor (1-4). Glyphs are rasterized at fontSize * guiScaleFactor + * so the atlas has enough texel density for the actual display resolution. This prevents + * GL_LINEAR texture filtering from diluting alpha values at high resolutions. + */ + private int guiScaleFactor = 1; + + /** + * Return the GUI scale factor used for glyph rasterization. StringCache uses this + * to compute an effective render scale that compensates for the larger atlas images. + */ + int getGuiScaleFactor() { + return guiScaleFactor; + } + /** * Temporary image for rendering a string to and then extracting the glyph images from. @@ -95,6 +128,7 @@ public class GlyphCache { private Graphics2D stringGraphics; + /** * All font glyphs are packed inside this image and are then loaded from here into an OpenGL texture. */ @@ -107,9 +141,53 @@ public class GlyphCache { /** * Needed for all text layout operations that create GlyphVectors (maps point size to pixel size). + * Rebuilt after setRenderingHints() so layout FRC matches rendering FRC (especially for GASP hinting). */ private FontRenderContext fontRenderContext = glyphCacheGraphics.getFontRenderContext(); + /** + * Return the current FontRenderContext used for glyph layout and rendering. + * StringCache must use this same FRC when computing glyph pixel bounds for positioning, + * so that layout positions match the GASP-aware hinting used during rasterization. + */ + FontRenderContext getFontRenderContext() { + return fontRenderContext; + } + + int getGlyphPadding() { + return GLYPH_PADDING; + } + + /** + * Compute the inter-glyph spacing needed for a given font when rasterizing into the temporary + * string image. For plain and bold fonts, the base spacing (2*GLYPH_PADDING+1) is sufficient. + * For italic fonts, the slant causes the top of each glyph to lean horizontally, and at large + * raster sizes (e.g. 54pt at scale 3) this overhang can be 8+ pixels — far exceeding the base + * spacing's 1-pixel effective gap. Without adequate spacing, adjacent italic glyphs' rendered + * pixels overlap in the string image, and narrow glyphs like 'I'/'i' capture neighboring + * fragments as visible dot artifacts in their cached texture. + * + * The italic overhang is computed as: lineHeight * |italicAngle|. Java2D's standard italic + * angle is ~0.2 (approx 12°). A safety factor of 1.5× is applied since antialiasing can + * produce faint alpha slightly beyond the geometric slant boundary. + */ + private int computeGlyphSpacing(Font font) { + float italicAngle = font.getItalicAngle(); + if (italicAngle == 0 && font.isItalic()) { + italicAngle = -0.2f; // Java2D synthetic italic default shear + } + + if (italicAngle == 0) { + return GLYPH_SPACING_BASE; + } + + java.awt.font.LineMetrics lm = font.getLineMetrics("I", fontRenderContext); + float lineHeight = lm.getAscent() + lm.getDescent(); + int italicOverhang = (int) Math.ceil(lineHeight * Math.abs(italicAngle) * 1.5f); + + return Math.max(GLYPH_SPACING_BASE, 2 * GLYPH_PADDING + italicOverhang + 1); + } + /** * Intermediate data array for use with textureImage.getRgb(). @@ -258,6 +336,7 @@ public class GlyphCache { fontSize = size; antiAliasEnabled = antiAlias; + guiScaleFactor = queryGuiScaleFactor(); setRenderingHints(); } @@ -273,15 +352,60 @@ public class GlyphCache { fontSize = size; antiAliasEnabled = antiAlias; + guiScaleFactor = queryGuiScaleFactor(); setRenderingHints(); } } + private static int queryGuiScaleFactor() { + try { + Minecraft mc = Minecraft.getMinecraft(); + if (mc != null && mc.displayWidth > 0 && mc.displayHeight > 0) { + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + return Math.max(1, sr.getScaleFactor()); + } + } catch (Exception ignored) { + } + return 1; + } + + /** + * Check if the GUI scale factor has changed (e.g. due to window resize) and invalidate the glyph + * cache if so. Glyphs must be re-rasterized at the new density to prevent GL_LINEAR filtering + * from diluting alpha at high display resolutions. + * + * @return true if the scale factor changed and glyphs were invalidated + */ + boolean checkAndUpdateScaleFactor() { + int newScale = queryGuiScaleFactor(); + if (newScale != guiScaleFactor) { + guiScaleFactor = newScale; + invalidateGlyphCache(); + return true; + } + return false; + } + + private void invalidateGlyphCache() { + glyphCache.clear(); + fontCache.clear(); + cachePosX = GLYPH_BORDER; + cachePosY = GLYPH_BORDER; + cacheLineHeight = 0; + allocateGlyphCacheTexture(); + allocateStringImage(STRING_WIDTH, STRING_HEIGHT); + } + int fontHeight(String s) { Font font = lookupFont(s.toCharArray(), 0, s.length(), 0); return (int) (font.getLineMetrics(s, this.fontRenderContext).getHeight()); } + java.awt.font.LineMetrics getLineMetrics(String s) { + Font font = lookupFont(s.toCharArray(), 0, s.length(), 0); + return font.getLineMetrics(s, this.fontRenderContext); + } + /** * Given a single OpenType font, perform full text layout and create a new GlyphVector for a string. * @@ -311,6 +435,9 @@ public class GlyphCache { * @return an OpenType font capable of displaying at least the first character at the start position in text */ Font lookupFont(char text[], int start, int limit, int style) { + /* Rasterize at scaled size so atlas texel density matches display resolution */ + int renderSize = fontSize * guiScaleFactor; + /* Try using an already known base font; the first font in usedFonts list is the one set with setDefaultFont() */ Iterator iterator = usedFonts.iterator(); while (iterator.hasNext()) { @@ -318,7 +445,7 @@ public class GlyphCache { Font font = iterator.next(); if (font.canDisplayUpTo(text, start, limit) != start) { /* Return a font instance of the proper point size and style; usedFonts has only 1pt sized plain style fonts */ - return font.deriveFont(style, fontSize); + return font.deriveFont(style, renderSize); } } @@ -333,7 +460,7 @@ public class GlyphCache { usedFonts.add(font); /* Return a font instance of the proper point size and style; allFonts has only 1pt sized plain style fonts */ - return font.deriveFont(style, fontSize); + return font.deriveFont(style, renderSize); } } @@ -341,7 +468,7 @@ public class GlyphCache { Font font = usedFonts.get(0); /* Return a font instance of the proper point size and style; usedFonts only 1pt sized plain style fonts */ - return font.deriveFont(style, fontSize); + return font.deriveFont(style, renderSize); } /** @@ -384,14 +511,37 @@ public class GlyphCache { int numGlyphs = vector.getNumGlyphs(); /* Length of the GlyphVector */ Rectangle dirty = null; /* Total area within texture that needs to be updated with glTexSubImage2D() */ boolean vectorRendered = false; /* True if entire GlyphVector was rendered into stringImage */ + int glyphSpacing = computeGlyphSpacing(font); for (int index = 0; index < numGlyphs; index++) { + int charIndex = start + vector.getGlyphCharIndex(index); + if (charIndex >= start && charIndex < limit) { + char c = text[charIndex]; + if (c == '\n' || c == '\r') { + continue; + } + } + /* If this glyph code is already in glyphCache, then there is no reason to pre-render it again */ int glyphCode = vector.getGlyphCode(index); if (glyphCache.containsKey(fontKey | glyphCode)) { continue; } + /* + * Skip whitespace glyphs that have no visible ink (spaces, tabs, etc.). These characters + * contribute only advance width, not visible pixels. Without this check, GLYPH_PADDING + * expansion would create a small non-zero rect for the empty glyph, and the blit from + * stringImage could capture stray antialiased fringe pixels from neighboring glyphs, + * causing whitespace to render as visible dots. + */ + { + Rectangle glyphBounds = vector.getGlyphPixelBounds(index, fontRenderContext, 0, 0); + if (glyphBounds.width == 0 || glyphBounds.height == 0) { + continue; + } + } + /* * The only way to get glyph shapes with font hinting is to draw the entire glyph vector into a * temporary BufferedImage, and then bit blit the individual glyphs based on their bounding boxes @@ -410,7 +560,7 @@ public class GlyphCache { */ for (int i = 0; i < numGlyphs; i++) { Point2D pos = vector.getGlyphPosition(i); - pos.setLocation(pos.getX() + 2 * i, pos.getY()); + pos.setLocation(pos.getX() + glyphSpacing * i, pos.getY()); vector.setGlyphPosition(i, pos); } @@ -422,15 +572,26 @@ public class GlyphCache { */ vectorBounds = vector.getPixelBounds(fontRenderContext, 0, 0); - /* Enlage the stringImage if it is too small to store the entire rendered string */ + /* Expand bounds to account for hinting overflow */ + vectorBounds.grow(GLYPH_PADDING, GLYPH_PADDING); + + /* Enlarge the stringImage if it is too small to store the entire rendered string */ if (stringImage == null || vectorBounds.width > stringImage.getWidth() || vectorBounds.height > stringImage.getHeight()) { int width = Math.max(vectorBounds.width, stringImage.getWidth()); int height = Math.max(vectorBounds.height, stringImage.getHeight()); allocateStringImage(width, height); } - /* Erase the upper-left corner where the string will get drawn*/ - stringGraphics.clearRect(0, 0, vectorBounds.width, vectorBounds.height); + /* + * Clear the ENTIRE stringImage, not just the vectorBounds area. The stringImage is reused + * across calls and may be larger than the current vectorBounds. Individual glyph pixel bounds + * (from getGlyphPixelBounds()) can differ slightly from the aggregate vector bounds + * (from getPixelBounds()) due to integer rounding. After GLYPH_PADDING expansion, a glyph's + * padded rect could extend 1-2 pixels beyond the vectorBounds area, capturing stale pixels + * from a previous render. This caused tiny dot artifacts above capital letters whose ink + * extends to the top of the line bounds. Clearing the full image eliminates this class of bugs. + */ + stringGraphics.clearRect(0, 0, stringImage.getWidth(), stringImage.getHeight()); /* Draw string with opaque white color and baseline adjustment so the upper-left corner of the image is at (0,0) */ stringGraphics.drawGlyphVector(vector, -vectorBounds.x, -vectorBounds.y); @@ -441,8 +602,35 @@ public class GlyphCache { * by this method is positioned around the origin of each individual glyph." However, the actual * bounds are all relative to the start of the entire GlyphVector, which is actually more useful * for extracting the glyph's image from the rendered string. + * + * Passing fontRenderContext ensures bounds match the GASP-aware rendering hints. */ - Rectangle rect = vector.getGlyphPixelBounds(index, null, -vectorBounds.x, -vectorBounds.y); + Rectangle rect = vector.getGlyphPixelBounds(index, fontRenderContext, -vectorBounds.x, -vectorBounds.y); + rect.grow(GLYPH_PADDING, GLYPH_PADDING); + + /* + * Clamp the padded rect to the stringImage bounds. Due to rounding differences between + * getPixelBounds() and getGlyphPixelBounds(), a padded glyph rect can occasionally extend + * beyond the image edge. Reading pixels outside the image would cause an exception or + * capture garbage data. + */ + if (rect.x < 0) { + rect.width += rect.x; // shrink width by the overshoot + rect.x = 0; + } + if (rect.y < 0) { + rect.height += rect.y; // shrink height by the overshoot + rect.y = 0; + } + if (rect.x + rect.width > stringImage.getWidth()) { + rect.width = stringImage.getWidth() - rect.x; + } + if (rect.y + rect.height > stringImage.getHeight()) { + rect.height = stringImage.getHeight() - rect.y; + } + if (rect.width <= 0 || rect.height <= 0) { + continue; + } /* If the current line in cache image is full, then advance to the next line */ if (cachePosX + rect.width + GLYPH_BORDER > TEXTURE_WIDTH) { @@ -573,10 +761,23 @@ public class GlyphCache { private void setRenderingHints() { stringGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAliasEnabled ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); - stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - antiAliasEnabled ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); +// if (antiAliasEnabled) { +// stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, +// RenderingHints.VALUE_TEXT_ANTIALIAS_ON); +// stringGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, +// RenderingHints.VALUE_RENDER_QUALITY); +// } else { +// stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, +// RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); +// } + + stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + stringGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); stringGraphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); + + fontRenderContext = stringGraphics.getFontRenderContext(); } /** @@ -608,8 +809,10 @@ public class GlyphCache { GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imageBuffer); /* Explicitely disable mipmap support becuase updateTexture() will only update the base level 0 */ - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); } /** diff --git a/src/main/java/noppes/npcs/config/LoadConfiguration.java b/src/main/java/noppes/npcs/config/LoadConfiguration.java index dfac43d90..0fc46e3e3 100644 --- a/src/main/java/noppes/npcs/config/LoadConfiguration.java +++ b/src/main/java/noppes/npcs/config/LoadConfiguration.java @@ -10,6 +10,7 @@ public class LoadConfiguration { public static File clientConfigFile; public static File experimentalConfigFile; public static File marketConfigFile; + public static File energyConfigFile; public static void init(String configpath) { mainConfigFile = new File(configpath + "main.cfg"); @@ -19,6 +20,7 @@ public class LoadConfiguration { debugConfigFile = new File(configpath + "debug.cfg"); experimentalConfigFile = new File(configpath + "experimental.cfg"); marketConfigFile = new File(configpath + "market.cfg"); + energyConfigFile = new File(configpath + "energy.cfg"); ConfigMain.init(mainConfigFile); ConfigItem.init(itemConfigFile); @@ -27,5 +29,6 @@ public class LoadConfiguration { ConfigDebug.init(debugConfigFile); ConfigExperimental.init(experimentalConfigFile); ConfigMarket.init(marketConfigFile); + ConfigEnergy.init(energyConfigFile); } } diff --git a/src/main/java/noppes/npcs/config/StringCache.java b/src/main/java/noppes/npcs/config/StringCache.java index c40d59f1c..63c0b6a91 100644 --- a/src/main/java/noppes/npcs/config/StringCache.java +++ b/src/main/java/noppes/npcs/config/StringCache.java @@ -3,11 +3,13 @@ package noppes.npcs.config; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; +import noppes.npcs.LogWriter; import org.lwjgl.opengl.GL11; import java.awt.Font; -import java.awt.Point; +import java.awt.Rectangle; import java.awt.font.GlyphVector; +import java.awt.geom.Point2D; import java.lang.ref.WeakReference; import java.text.Bidi; import java.util.ArrayList; @@ -71,6 +73,38 @@ public class StringCache { */ private static final int STRIKETHROUGH_THICKNESS = 2; + // BetterFonts base scale: maps internal 2x glyph coords to GUI coords. + // With scale-aware rasterization, the effective scale becomes BASE_RENDER_SCALE / guiScaleFactor. + private static final float BASE_RENDER_SCALE = 0.5F; + private static final boolean FONT_DEBUG_LOG = Boolean.getBoolean("cnpc.font.debug"); + private static final boolean FONT_DEBUG_DISABLE_INK_OFFSET = Boolean.getBoolean("cnpc.font.debug.disableInkOffset"); + + private static boolean isLineBreak(char c) { + return c == '\n' || c == '\r'; + } + + private static boolean isSpacingDebugGlyph(char c) { + return c == '(' || c == '"' || c == 't' || c == '.'; + } + + private static String debugGlyphLabel(char c) { + return c == '"' ? "\\\"" : String.valueOf(c); + } + + private float renderScale() { + return BASE_RENDER_SCALE / glyphCache.getGuiScaleFactor(); + } + + private float pixelSnap(float coord) { + float scale = renderScale(); + float invScale = 1.0F / scale; + return (float) Math.floor(coord * invScale + 0.5F) * scale; + } + + private int baselineOffset = BASELINE_OFFSET; + private int underlineOffset = UNDERLINE_OFFSET; + private int strikethroughOffset = STRIKETHROUGH_OFFSET; + /** * Reference to the unicode.FontRenderer class. Needed for creating GlyphVectors and retrieving glyph texture coordinates. */ @@ -319,31 +353,21 @@ public class StringCache { * the string to which this Glyph object belongs. */ static private class Glyph implements Comparable { - /** - * The index into the original string (i.e. with color codes) for the character that generated this glyph. - */ public int stringIndex; - - /** - * Texture ID and position/size of the glyph's pre-rendered image within the cache texture. - */ public GlyphCache.Entry texture; - /** - * Glyph's horizontal position (in pixels) relative to the entire string's baseline - */ + /** Logical horizontal position from getGlyphPosition() — used for spacing/advance */ public int x; - /** - * Glyph's vertical position (in pixels) relative to the entire string's baseline - */ + /** Ink vertical position from getGlyphPixelBounds() — used for texture quad placement */ public int y; - /** - * Glyph's horizontal advance (in pixels) used for strikethrough and underline effects - */ + /** Horizontal advance (logical) used for strikethrough and underline effects */ public int advance; + /** Ink X offset from logical position (inkBoundsX - logicalX) for texture quad placement */ + public int inkOffsetX; + /** * Allows arrays of Glyph objects to be sorted. Performs numeric comparison on stringIndex. * @@ -451,7 +475,44 @@ public class StringCache { if (g.y > maxY) maxY = g.y; } - fontHeight = (int) ((maxY + height) / 2.0F - minY / 2.0F); + int scaleFactor = glyphCache.getGuiScaleFactor(); + fontHeight = (int) (((maxY + height) - minY) / 2.0F / scaleFactor); + updateFontMetrics(); + } + + private void updateFontMetrics() { + java.awt.font.LineMetrics lm = glyphCache.getLineMetrics("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); + float ascent = lm.getAscent(); + float descent = lm.getDescent(); + + /* + * baselineOffset is added directly to startY (GUI pixels) at render time, so it must be a + * scale-invariant GUI-pixel value. The constant BASELINE_OFFSET (7) is correct for the default + * 18pt font and remains stable across all GUI scale factors because it operates in GUI coordinate + * space — independent of the glyph rasterization scale. + * + * A dynamic formula like (ascent - padding) * renderScale is fragile: ascent comes from the + * scaled font (fontSize * scaleFactor) and rounding/font-metric variations across scales can + * produce values 1-2 pixels too large, visibly shifting text down within its highlight box. + */ + baselineOffset = BASELINE_OFFSET; + + /* + * underlineOffset and strikethroughOffset are multiplied by renderScale() at draw time + * (same as glyph.x/glyph.y), so they must be in glyph-space pixels. These scale correctly + * because ascent/descent are proportional to the rasterization size. + */ + underlineOffset = (int) (descent * 0.25f + 0.5f); + strikethroughOffset = -(int) (ascent * 0.35f + 0.5f); + } + + private void checkForScaleChange() { + if (glyphCache.checkAndUpdateScaleFactor()) { + weakRefCache.clear(); + stringCache.clear(); + cacheDightGlyphs(); + updateHeight(); + } } /** @@ -490,12 +551,14 @@ public class StringCache { return 0; } + /* Detect window resize: if GUI scale factor changed, invalidate all caches and re-rasterize */ + checkForScaleChange(); /* Make sure the entire string is cached before rendering and return its glyph representation */ Entry entry = cacheString(str); /* Adjust the baseline of the string because the startY coordinate in Minecraft is for the top of the string */ - startY += BASELINE_OFFSET; + startY += baselineOffset; /* Color currently selected by color code; reapplied to Tessellator instance after glBindTexture() */ @@ -548,7 +611,13 @@ public class StringCache { /* Select the current glyph's texture information and horizontal layout position within this string */ Glyph glyph = entry.glyphs[glyphIndex]; GlyphCache.Entry texture = glyph.texture; - int glyphX = glyph.x; + + /* Skip glyphs with no cached texture (whitespace characters like spaces and tabs) */ + if (texture == null) { + continue; + } + + int glyphX = glyph.x + glyph.inkOffsetX; /* * Replace ASCII digits in the string with their respective glyphs; strings differing by digits are only cached once. @@ -557,6 +626,10 @@ public class StringCache { * of the width mismatch. */ char c = str.charAt(glyph.stringIndex); + if (isLineBreak(c)) { + continue; + } + if (c >= '0' && c <= '9') { int oldWidth = texture.width; texture = digitGlyphs[fontStyle][c - '0'].texture; @@ -580,10 +653,21 @@ public class StringCache { } /* The divide by 2.0F is needed to align with the scaled GUI coordinate system; startX/startY are already scaled */ - float x1 = startX + (glyphX) / 2.0F; - float x2 = startX + (glyphX + texture.width) / 2.0F; - float y1 = startY + (glyph.y) / 2.0F; - float y2 = startY + (glyph.y + texture.height) / 2.0F; + if (FONT_DEBUG_DISABLE_INK_OFFSET) { + glyphX = glyph.x; + } + float rs = renderScale(); + float x1 = pixelSnap(startX + (glyphX) * rs); + float x2 = pixelSnap(startX + (glyphX + texture.width) * rs); + float y1 = pixelSnap(startY + (glyph.y) * rs); + float y2 = pixelSnap(startY + (glyph.y + texture.height) * rs); + + if (FONT_DEBUG_LOG && isSpacingDebugGlyph(c)) { + LogWriter.info("[StringCache glyph-debug] char='" + debugGlyphLabel(c) + "' idx=" + glyph.stringIndex + + " x=" + glyph.x + " advance=" + glyph.advance + " texW=" + texture.width + + " inkOffsetX=" + glyph.inkOffsetX + " quadX1=" + x1 + " quadX2=" + x2 + + " y=" + glyph.y + " tex=" + texture.textureName); + } tessellator.addVertexWithUV(x1, y1, 0, texture.u1, texture.v1); tessellator.addVertexWithUV(x1, y2, 0, texture.u1, texture.v2); @@ -620,15 +704,16 @@ public class StringCache { Glyph glyph = entry.glyphs[glyphIndex]; /* The strike/underlines are drawn beyond the glyph's width to include the extra space between glyphs */ - int glyphSpace = glyph.advance - glyph.texture.width; + int glyphSpace = glyph.texture != null ? glyph.advance - glyph.texture.width : 0; /* Draw underline under glyph if the style is enabled */ if ((renderStyle & ColorCode.UNDERLINE) != 0) { /* The divide by 2.0F is needed to align with the scaled GUI coordinate system; startX/startY are already scaled */ - float x1 = startX + (glyph.x - glyphSpace) / 2.0F; - float x2 = startX + (glyph.x + glyph.advance) / 2.0F; - float y1 = startY + (UNDERLINE_OFFSET) / 2.0F; - float y2 = startY + (UNDERLINE_OFFSET + UNDERLINE_THICKNESS) / 2.0F; + float urs = renderScale(); + float x1 = pixelSnap(startX + (glyph.x - glyphSpace) * urs); + float x2 = pixelSnap(startX + (glyph.x + glyph.advance) * urs); + float y1 = pixelSnap(startY + (underlineOffset) * urs); + float y2 = pixelSnap(startY + (underlineOffset + UNDERLINE_THICKNESS) * urs); tessellator.addVertex(x1, y1, 0); tessellator.addVertex(x1, y2, 0); @@ -639,10 +724,11 @@ public class StringCache { /* Draw strikethrough in the middle of glyph if the style is enabled */ if ((renderStyle & ColorCode.STRIKETHROUGH) != 0) { /* The divide by 2.0F is needed to align with the scaled GUI coordinate system; startX/startY are already scaled */ - float x1 = startX + (glyph.x - glyphSpace) / 2.0F; - float x2 = startX + (glyph.x + glyph.advance) / 2.0F; - float y1 = startY + (STRIKETHROUGH_OFFSET) / 2.0F; - float y2 = startY + (STRIKETHROUGH_OFFSET + STRIKETHROUGH_THICKNESS) / 2.0F; + float srs = renderScale(); + float x1 = pixelSnap(startX + (glyph.x - glyphSpace) * srs); + float x2 = pixelSnap(startX + (glyph.x + glyph.advance) * srs); + float y1 = pixelSnap(startY + (strikethroughOffset) * srs); + float y2 = pixelSnap(startY + (strikethroughOffset + STRIKETHROUGH_THICKNESS) * srs); tessellator.addVertex(x1, y1, 0); tessellator.addVertex(x1, y2, 0); @@ -658,7 +744,7 @@ public class StringCache { /* Return total horizontal advance (slightly wider than the bounding box, but close enough for centering strings) */ - return entry.advance / 2; + return (int) (entry.advance * renderScale()); } /** @@ -673,11 +759,50 @@ public class StringCache { return 0; } + checkForScaleChange(); + /* Make sure the entire string is cached and rendered since it will probably be used again in a renderString() call */ Entry entry = cacheString(str); /* Return total horizontal advance (slightly wider than the bounding box, but close enough for centering strings) */ - return entry.advance / 2; + return (int) (entry.advance * renderScale()); + } + + /** + * Return the width of a string in pixels when rendered with the specified font style. + * This is needed when measuring text that will be rendered with bold/italic formatting, + * since bold glyphs are wider than plain glyphs. + * + *

The font style is applied by prepending the appropriate Minecraft formatting codes + * (§l for bold, §o for italic) to the string before measuring. This causes cacheString() + * to lay out the entire string using the specified font style. + * + * @param str compute the width of this string + * @param fontStyle combination of {@link java.awt.Font#BOLD} and {@link java.awt.Font#ITALIC} + * @return the width in pixels (in the scaled GUI coordinate system) + */ + public int getStringWidth(String str, int fontStyle) { + /* Check for invalid arguments */ + if (str == null || str.isEmpty()) { + return 0; + } + + /* If plain style, delegate to the normal method (no prefix needed) */ + if (fontStyle == Font.PLAIN) { + return getStringWidth(str); + } + + /* Build the style prefix: §l for bold, §o for italic */ + StringBuilder sb = new StringBuilder(); + if ((fontStyle & Font.BOLD) != 0) { + sb.append('\u00A7').append('l'); + } + if ((fontStyle & Font.ITALIC) != 0) { + sb.append('\u00A7').append('o'); + } + sb.append(str); + + return getStringWidth(sb.toString()); } /** @@ -696,8 +821,8 @@ public class StringCache { return 0; } - /* Convert the width from GUI coordinate system to pixels */ - width += width; + /* Convert the width from GUI coordinate system to internal glyph pixels */ + width = (int) (width / renderScale()); /* The glyph array for a string is sorted by the string's logical character position */ Glyph glyphs[] = cacheString(str).glyphs; @@ -1125,6 +1250,11 @@ public class StringCache { /* Break the string up into segments, where each segment can be displayed using a single font */ while (start < limit) { + if (isLineBreak(text[start])) { + start++; + continue; + } + Font font = glyphCache.lookupFont(text, start, limit, style); int next = font.canDisplayUpTo(text, start, limit); @@ -1177,20 +1307,41 @@ public class StringCache { /* Creating a GlyphVector takes care of all language specific OpenType glyph substitutions and positionings */ GlyphVector vector = glyphCache.layoutGlyphVector(font, text, start, limit, layoutFlags); + /* + * Use the same GASP-aware FontRenderContext that was used to rasterize glyphs into the atlas. + * Passing null here would use a default FRC that can produce different pixel bounds for hinted + * glyphs, causing position mismatches and visible spacing gaps (especially on punctuation). + */ + java.awt.font.FontRenderContext frc = glyphCache.getFontRenderContext(); + /* * Extract all needed information for each glyph from the GlyphVector so it won't be needed for actual rendering. * Note that initially, glyph.start holds the character index into the stripped text array. But after the entire * string is layed out, this field will be adjusted on every Glyph object to correctly index the original unstripped * string. + * + * Use getGlyphPosition() (logical font metrics) for horizontal placement and advance calculation. + * Use getGlyphPixelBounds() only for the Y position and to compute the ink X offset from the logical X. + * This separation ensures proper inter-glyph spacing (from logical metrics) while keeping correct + * texture quad alignment (from ink bounds). Under GASP hinting, ink bounds can be tighter than + * logical positions, causing glyphs to visually touch or overlap if used for spacing. */ Glyph glyph = null; int numGlyphs = vector.getNumGlyphs(); + int glyphPadding = glyphCache.getGlyphPadding(); for (int index = 0; index < numGlyphs; index++) { - Point position = vector.getGlyphPixelBounds(index, null, advance, 0).getLocation(); + int charIndex = start + vector.getGlyphCharIndex(index); + if (charIndex >= start && charIndex < limit && isLineBreak(text[charIndex])) { + continue; + } - /* Compute horizontal advance for the previous glyph based on this glyph's position */ + Point2D logicalPos = vector.getGlyphPosition(index); + int logicalX = advance + (int) logicalPos.getX(); + Rectangle inkBounds = vector.getGlyphPixelBounds(index, frc, advance, 0); + + /* Compute horizontal advance for the previous glyph based on logical positions */ if (glyph != null) { - glyph.advance = position.x - glyph.x; + glyph.advance = logicalX - glyph.x; } /* @@ -1198,10 +1349,11 @@ public class StringCache { * it will be corrected later to account for the color codes that have been stripped out. */ glyph = new Glyph(); - glyph.stringIndex = start + vector.getGlyphCharIndex(index); + glyph.stringIndex = charIndex; glyph.texture = glyphCache.lookupGlyph(font, vector.getGlyphCode(index)); - glyph.x = position.x; - glyph.y = position.y; + glyph.x = logicalX; + glyph.y = inkBounds.y - glyphPadding; + glyph.inkOffsetX = (inkBounds.x - logicalX) - glyphPadding; glyphList.add(glyph); } @@ -1215,5 +1367,3 @@ public class StringCache { return advance; } } - - diff --git a/src/main/java/noppes/npcs/constants/EnumAuctionLogAction.java b/src/main/java/noppes/npcs/constants/EnumAuctionLogAction.java new file mode 100644 index 000000000..6c6fdce44 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionLogAction.java @@ -0,0 +1,44 @@ +package noppes.npcs.constants; + +import noppes.npcs.config.ConfigMarket; + +/** + * Enum for auction log action types. + * Used by AuctionController.logAuction() for type-safe logging. + */ +public enum EnumAuctionLogAction { + CREATED, + BID, + BUYOUT, + SOLD, + EXPIRED, + CANCELLED, + CLAIMED, + CLAIM_EXPIRED; + + /** + * Check if this action should be logged based on config settings + */ + public boolean shouldLog() { + if (!ConfigMarket.AuctionLoggingEnabled) return false; + switch (this) { + case CREATED: + return ConfigMarket.LogAuctionCreated; + case BID: + return ConfigMarket.LogAuctionBid; + case BUYOUT: + return ConfigMarket.LogAuctionBuyout; + case SOLD: + return ConfigMarket.LogAuctionSold; + case EXPIRED: + return ConfigMarket.LogAuctionExpired; + case CANCELLED: + return ConfigMarket.LogAuctionCancelled; + case CLAIMED: + case CLAIM_EXPIRED: + return ConfigMarket.LogAuctionClaimed; + default: + return false; + } + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumAuctionPage.java b/src/main/java/noppes/npcs/constants/EnumAuctionPage.java new file mode 100644 index 000000000..7f98cb2f0 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionPage.java @@ -0,0 +1,28 @@ +package noppes.npcs.constants; + +/** + * Enum for auction GUI page navigation. + * Maps page indices to GUI types for packet-based navigation. + */ +public enum EnumAuctionPage { + LISTINGS(EnumGuiType.PlayerAuction), + SELL(EnumGuiType.PlayerAuctionSell), + TRADES(EnumGuiType.PlayerAuctionTrades); + + private final EnumGuiType guiType; + + EnumAuctionPage(EnumGuiType guiType) { + this.guiType = guiType; + } + + public EnumGuiType getGuiType() { + return guiType; + } + + public static EnumAuctionPage fromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } + return LISTINGS; + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumCategoryType.java b/src/main/java/noppes/npcs/constants/EnumCategoryType.java new file mode 100644 index 000000000..444611a49 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumCategoryType.java @@ -0,0 +1,13 @@ +package noppes.npcs.constants; + +/** + * Identifies which controller a category operation targets. + * Used by category packets to route to the correct CategoryManager. + */ +public class EnumCategoryType { + public static final int EFFECT = 1; + public static final int ANIMATION = 2; + public static final int LINKED_ITEM = 3; + public static final int ABILITY = 4; + public static final int CHAINED_ABILITY = 5; +} 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..0de53db10 100644 --- a/src/main/java/noppes/npcs/constants/EnumScriptType.java +++ b/src/main/java/noppes/npcs/constants/EnumScriptType.java @@ -125,13 +125,52 @@ public enum EnumScriptType { ABILITY_INTERRUPT("abilityInterrupt"), ABILITY_COMPLETE("abilityComplete"), ABILITY_HIT("abilityHit"), - ABILITY_TICK("abilityTick"); + ABILITY_DEFEND("abilityDefend"), + ABILITY_TICK("abilityTick"), + ABILITY_TOGGLE("abilityToggle"), + ABILITY_TOGGLE_TICK("abilityToggleTick"), + + CHAIN_START("chainStart"), + CHAIN_NEXT("chainNext"), + CHAIN_COMPLETE("chainComplete"), + CHAIN_INTERRUPT("chainInterrupt"), + + ENERGY_PROJECTILE_FIRED("energyProjectileFired"), + ENERGY_PROJECTILE_TICK("energyProjectileTick"), + ENERGY_PROJECTILE_ENTITY_IMPACT("energyProjectileEntityImpact"), + ENERGY_PROJECTILE_BLOCK_IMPACT("energyProjectileBlockImpact"), + ENERGY_PROJECTILE_EXPIRED("energyProjectileExpired"), + + // Energy Barrier Events + ENERGY_BARRIER_SPAWNED("energyBarrierSpawned"), + ENERGY_BARRIER_TICK("energyBarrierTick"), + ENERGY_BARRIER_HIT("energyBarrierHit"), + ENERGY_BARRIER_DESTROYED("energyBarrierDestroyed"), + + // Auction Events + AUCTION_CREATE("auctionCreate"), + AUCTION_BID("auctionBid"), + AUCTION_BUYOUT("auctionBuyout"), + AUCTION_CANCEL("auctionCancel"), + AUCTION_CLAIM("auctionClaim"); public String function; + private static final java.util.Map BY_FUNCTION = new java.util.HashMap<>(); + static { + for (EnumScriptType type : values()) { + BY_FUNCTION.put(type.function, type); + } + } + public static EnumScriptType valueOfIgnoreCase(String channelName) { - channelName = channelName.toUpperCase(); - return valueOf(channelName); + // First try by function name (e.g. "abilityStart") + EnumScriptType type = BY_FUNCTION.get(channelName); + if (type != null) { + return type; + } + // Fallback to enum constant name (e.g. "ABILITY_START") + return valueOf(channelName.toUpperCase()); } private EnumScriptType(String function) { diff --git a/src/main/java/noppes/npcs/constants/EnumScrollData.java b/src/main/java/noppes/npcs/constants/EnumScrollData.java index 06d5a6ec3..bfa6e09a7 100644 --- a/src/main/java/noppes/npcs/constants/EnumScrollData.java +++ b/src/main/java/noppes/npcs/constants/EnumScrollData.java @@ -8,6 +8,10 @@ public enum EnumScrollData { QUEST_GROUP, ABILITY_TYPES, CUSTOM_ABILITIES, + BUILTIN_ABILITIES, ANIMATIONS, - BUILTIN_ANIMATIONS + BUILTIN_ANIMATIONS, + CHAINED_ABILITIES, + CATEGORY_GROUP, + CATEGORY_LIST } diff --git a/src/main/java/noppes/npcs/constants/EnumTradeSlotType.java b/src/main/java/noppes/npcs/constants/EnumTradeSlotType.java new file mode 100644 index 000000000..16850a79e --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumTradeSlotType.java @@ -0,0 +1,35 @@ +package noppes.npcs.constants; + +/** + * Enum for trade slot types in the player's auction trades view. + * Used by ContainerAuctionTrades to identify what each slot contains. + */ +public enum EnumTradeSlotType { + EMPTY, + SELLING, + BIDDING, + CLAIM; + + public boolean isSelling() { + return this == SELLING; + } + + public boolean isBidding() { + return this == BIDDING; + } + + public boolean isClaim() { + return this == CLAIM; + } + + public boolean isEmpty() { + return this == EMPTY; + } + + public static EnumTradeSlotType fromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } + return EMPTY; + } +} diff --git a/src/main/java/noppes/npcs/constants/ScriptContext.java b/src/main/java/noppes/npcs/constants/ScriptContext.java index dcc5b5d95..572b8e038 100644 --- a/src/main/java/noppes/npcs/constants/ScriptContext.java +++ b/src/main/java/noppes/npcs/constants/ScriptContext.java @@ -1,17 +1,24 @@ package noppes.npcs.constants; +import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.api.event.IAnimationEvent; +import noppes.npcs.api.event.IAuctionEvent; import noppes.npcs.api.event.IBlockEvent; import noppes.npcs.api.event.ICustomGuiEvent; import noppes.npcs.api.event.IDialogEvent; +import noppes.npcs.api.event.IEnergyBarrierEvent; +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.ILinkedItemEvent; import noppes.npcs.api.event.INpcEvent; import noppes.npcs.api.event.IPartyEvent; +import noppes.npcs.api.event.IChainEvent; import noppes.npcs.api.event.IPlayerEvent; import noppes.npcs.api.event.IProjectileEvent; import noppes.npcs.api.event.IQuestEvent; +import noppes.npcs.api.event.IRecipeEvent; import java.util.ArrayList; import java.util.Arrays; @@ -52,7 +59,12 @@ public class ScriptContext { public static final ScriptContext NPC = register("NPC", "npc", INpcEvent.class, - IProjectileEvent.class + IProjectileEvent.class, + IEnergyProjectileEvent.class, + IEnergyBarrierEvent.class, + IAbilityEvent.class, + IChainEvent.class, + IAnimationEvent.class ); public static final ScriptContext PLAYER = register("PLAYER", "player", @@ -62,7 +74,12 @@ public class ScriptContext { IDialogEvent.class, IQuestEvent.class, IFactionEvent.class, - ICustomGuiEvent.class + ICustomGuiEvent.class, + IEnergyProjectileEvent.class, + IEnergyBarrierEvent.class, + IAbilityEvent.class, + IChainEvent.class, + IAuctionEvent.class ); public static final ScriptContext BLOCK = register("BLOCK", "block", @@ -78,15 +95,24 @@ public class ScriptContext { ); public static final ScriptContext LINKED_ITEM = register("LINKED_ITEM", "linked_item", + ILinkedItemEvent.class, IItemEvent.class ); public static final ScriptContext RECIPE = register("RECIPE", "recipe", - "Recipe" + IRecipeEvent.class ); public static final ScriptContext EFFECT = register("EFFECT", "effect", - "Effect" + IPlayerEvent.class + ); + + public static final ScriptContext ABILITY = register("ABILITY", "ability", + IAbilityEvent.class + ); + + public static final ScriptContext CHAINED_ABILITY = register("CHAINED_ABILITY", "chained_ability", + IChainEvent.class ); public static final ScriptContext GLOBAL = register("GLOBAL", "", @@ -110,6 +136,12 @@ public class ScriptContext { */ private final List namespaces; + /** + * Fully qualified names of the event interface classes this context supports. + * Only populated when registered via the Class overload. + */ + private final List namespaceFQNs = new ArrayList<>(); + // ==================== CONSTRUCTOR ==================== private ScriptContext(String id, String hookContext, String... namespaces) { @@ -129,6 +161,16 @@ public class ScriptContext { return Collections.unmodifiableList(namespaces); } + /** + * Get the fully qualified names of event interface classes this context supports. + * Only populated for contexts registered with Class references. + * + * @return Unmodifiable list of FQN strings (e.g., "noppes.npcs.api.event.INpcEvent") + */ + public List getNamespaceFQNs() { + return Collections.unmodifiableList(namespaceFQNs); + } + /** * Check if this context includes a specific namespace. * @@ -194,7 +236,11 @@ public class ScriptContext { for (int i = 0; i < eventClasses.length; i++) { namespaces[i] = eventClasses[i].getSimpleName(); } - return register(id, hookContext, namespaces); + ScriptContext context = register(id, hookContext, namespaces); + for (Class clazz : eventClasses) { + context.namespaceFQNs.add(clazz.getName().replace('$', '.')); + } + return context; } /** diff --git a/src/main/java/noppes/npcs/containers/ContainerAuction.java b/src/main/java/noppes/npcs/containers/ContainerAuction.java index 2ccaa2e52..0741fdd9a 100644 --- a/src/main/java/noppes/npcs/containers/ContainerAuction.java +++ b/src/main/java/noppes/npcs/containers/ContainerAuction.java @@ -71,6 +71,7 @@ public class ContainerAuction extends ContainerNpcInterface { /** * Get the ItemStack in a player inventory slot. + * * @param containerSlotIndex The container slot index (0-35 for player inv) */ public ItemStack getPlayerInventoryStack(int containerSlotIndex) { diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java b/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java index 2b40000ac..2b6f9a67f 100644 --- a/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java @@ -14,9 +14,9 @@ import noppes.npcs.entity.EntityNPCInterface; */ public class ContainerAuctionBidding extends ContainerAuction { // Display slot layout - private int itemSlotX = 71; - private int itemSlotY = 76; - private int itemSlotIndex = PLAYER_INV_SLOT_COUNT; + private static final int ITEM_SLOT_X = 71; + private static final int ITEM_SLOT_Y = 76; + private static final int ITEM_SLOT_INDEX = PLAYER_INV_SLOT_COUNT; private final IInventory displayInventory; private AuctionListing listing; @@ -26,11 +26,16 @@ public class ContainerAuctionBidding extends ContainerAuction { displayInventory = new InventoryBasic("Display", false, 1); // Display slot (read-only) - addSlotToContainer(new Slot(displayInventory, 0, itemSlotX, itemSlotY) { + addSlotToContainer(new Slot(displayInventory, 0, ITEM_SLOT_X, ITEM_SLOT_Y) { @Override - public boolean isItemValid(ItemStack stack) { return false; } + public boolean isItemValid(ItemStack stack) { + return false; + } + @Override - public boolean canTakeStack(EntityPlayer player) { return false; } + public boolean canTakeStack(EntityPlayer player) { + return false; + } }); } @@ -58,6 +63,6 @@ public class ContainerAuctionBidding extends ContainerAuction { * Check if this is the display slot. */ public boolean isDisplaySlot(int slotIndex) { - return slotIndex == itemSlotIndex; + return slotIndex == ITEM_SLOT_INDEX; } } diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java b/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java index 14b381f40..f703a206d 100644 --- a/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java @@ -13,10 +13,10 @@ import noppes.npcs.entity.EntityNPCInterface; * Items are cloned from inventory, not moved. Validation happens on submit. */ public class ContainerAuctionSell extends ContainerAuction { - private int sellSlotX = 59; - private int sellSlotY = 101; - private int sellSlotIndex = PLAYER_INV_SLOT_COUNT; - private int maxStack = 64; + private static final int SELL_SLOT_X = 59; + private static final int SELL_SLOT_Y = 101; + private static final int SELL_SLOT_INDEX = PLAYER_INV_SLOT_COUNT; + private static final int MAX_STACK = 64; private final IInventory sellInventory; @@ -25,11 +25,16 @@ public class ContainerAuctionSell extends ContainerAuction { sellInventory = new InventoryBasic("Sell", false, 1); // Sell slot blocks direct interaction - addSlotToContainer(new Slot(sellInventory, 0, sellSlotX, sellSlotY) { + addSlotToContainer(new Slot(sellInventory, 0, SELL_SLOT_X, SELL_SLOT_Y) { @Override - public boolean isItemValid(ItemStack stack) { return false; } + public boolean isItemValid(ItemStack stack) { + return false; + } + @Override - public boolean canTakeStack(EntityPlayer player) { return false; } + public boolean canTakeStack(EntityPlayer player) { + return false; + } }); } @@ -44,8 +49,9 @@ public class ContainerAuctionSell extends ContainerAuction { /** * Add items from inventory to sell slot. * Not limited by inventory - just stages items for sale. Validation on submit. + * * @param sourceSlot Inventory slot index - * @param fullStack True=full stack, False=1 item + * @param fullStack True=full stack, False=1 item */ public void addToSellSlot(int sourceSlot, boolean fullStack) { if (!isPlayerInventorySlot(sourceSlot)) return; @@ -59,11 +65,11 @@ public class ContainerAuctionSell extends ContainerAuction { if (sellStack == null) { // Empty slot - create new stack ItemStack newStack = source.copy(); - newStack.stackSize = Math.min(toAdd, maxStack); + newStack.stackSize = Math.min(toAdd, MAX_STACK); sellInventory.setInventorySlotContents(0, newStack); } else if (itemsMatch(sellStack, source)) { // Same item - add to existing (capped at 64) - int space = maxStack - sellStack.stackSize; + int space = MAX_STACK - sellStack.stackSize; int add = Math.min(toAdd, space); if (add > 0) { sellStack.stackSize += add; @@ -71,13 +77,14 @@ public class ContainerAuctionSell extends ContainerAuction { } else { // Different item - replace ItemStack newStack = source.copy(); - newStack.stackSize = Math.min(toAdd, maxStack); + newStack.stackSize = Math.min(toAdd, MAX_STACK); sellInventory.setInventorySlotContents(0, newStack); } } /** * Remove items from sell slot. + * * @param removeAll True=clear slot, False=remove 1 item */ public void removeFromSellSlot(boolean removeAll) { @@ -91,12 +98,16 @@ public class ContainerAuctionSell extends ContainerAuction { } } - /** Check if sell slot is this container slot index */ + /** + * Check if sell slot is this container slot index + */ public boolean isSellSlot(int slotIndex) { - return slotIndex == sellSlotIndex; + return slotIndex == SELL_SLOT_INDEX; } - /** Check if two stacks match using NoppesUtilPlayer.compareItems (same item, damage, and NBT) */ + /** + * Check if two stacks match using NoppesUtilPlayer.compareItems (same item, damage, and NBT) + */ private boolean itemsMatch(ItemStack a, ItemStack b) { return NoppesUtilPlayer.compareItems(a, b, false, false); } diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java b/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java index eab491c70..187d50d13 100644 --- a/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java @@ -5,12 +5,14 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import noppes.npcs.constants.EnumClaimType; +import noppes.npcs.constants.EnumTradeSlotType; import noppes.npcs.controllers.AuctionController; import noppes.npcs.controllers.data.AuctionClaim; import noppes.npcs.controllers.data.AuctionListing; import noppes.npcs.entity.EntityNPCInterface; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -34,7 +36,7 @@ public class ContainerAuctionTrades extends ContainerAuction { private int maxTradeSlots = 8; // Player's max trade slots (permission-aware, synced from server) // Slot type tracking for proper accessor methods - private int[] slotTypes = new int[SLOT_COUNT]; // 0=empty, 1=selling, 2=bidding, 3=claim + private EnumTradeSlotType[] slotTypes = new EnumTradeSlotType[SLOT_COUNT]; private int[] slotDataIndex = new int[SLOT_COUNT]; // Index into respective list public ContainerAuctionTrades(EntityNPCInterface npc, EntityPlayer player) { @@ -53,7 +55,9 @@ public class ContainerAuctionTrades extends ContainerAuction { refreshData(); } - /** Refresh data from controller (server-side only) */ + /** + * Refresh data from controller (server-side only) + */ public void refreshData() { // Clear existing data clearData(); @@ -68,7 +72,9 @@ public class ContainerAuctionTrades extends ContainerAuction { populateDisplay(newListings, newBids, newClaims); } - /** Set data from NBT received from server (client-side) */ + /** + * Set data from NBT received from server (client-side) + */ public void setTradesData(NBTTagCompound compound) { // Clear existing data clearData(); @@ -109,7 +115,9 @@ public class ContainerAuctionTrades extends ContainerAuction { populateDisplay(newListings, newBids, newClaims); } - /** Clear all data and reset display */ + /** + * Clear all data and reset display + */ private void clearData() { activeListings.clear(); activeBids.clear(); @@ -117,13 +125,15 @@ public class ContainerAuctionTrades extends ContainerAuction { displayInventory.clear(); // Reset slot tracking + Arrays.fill(slotTypes, EnumTradeSlotType.EMPTY); for (int i = 0; i < SLOT_COUNT; i++) { - slotTypes[i] = 0; slotDataIndex[i] = -1; } } - /** Populate display from provided data lists */ + /** + * Populate display from provided data lists + */ private void populateDisplay(List newListings, List newBids, List allClaims) { activeListings = new ArrayList<>(newListings); activeBids = new ArrayList<>(newBids); @@ -156,7 +166,7 @@ public class ContainerAuctionTrades extends ContainerAuction { if (slot >= SLOT_COUNT) break; claims.add(claim); displayInventory.setClaimItem(slot, claim); - slotTypes[slot] = 3; // claim + slotTypes[slot] = EnumTradeSlotType.CLAIM; slotDataIndex[slot] = claims.size() - 1; slot++; } @@ -166,7 +176,7 @@ public class ContainerAuctionTrades extends ContainerAuction { if (slot >= SLOT_COUNT) break; claims.add(claim); displayInventory.setClaimItem(slot, claim); - slotTypes[slot] = 3; // claim + slotTypes[slot] = EnumTradeSlotType.CLAIM; slotDataIndex[slot] = claims.size() - 1; slot++; } @@ -176,7 +186,7 @@ public class ContainerAuctionTrades extends ContainerAuction { if (slot >= SLOT_COUNT) break; claims.add(claim); displayInventory.setClaimItem(slot, claim); - slotTypes[slot] = 3; // claim + slotTypes[slot] = EnumTradeSlotType.CLAIM; slotDataIndex[slot] = claims.size() - 1; slot++; } @@ -186,7 +196,7 @@ public class ContainerAuctionTrades extends ContainerAuction { for (AuctionListing listing : activeListings) { if (slot >= SLOT_COUNT) break; if (listing.item != null) displayInventory.setInventorySlotContents(slot, listing.item.copy()); - slotTypes[slot] = 1; // selling + slotTypes[slot] = EnumTradeSlotType.SELLING; slotDataIndex[slot] = listingIdx; slot++; listingIdx++; @@ -197,7 +207,7 @@ public class ContainerAuctionTrades extends ContainerAuction { for (AuctionListing bid : activeBids) { if (slot >= SLOT_COUNT) break; if (bid.item != null) displayInventory.setInventorySlotContents(slot, bid.item.copy()); - slotTypes[slot] = 2; // bidding + slotTypes[slot] = EnumTradeSlotType.BIDDING; slotDataIndex[slot] = bidIdx; slot++; bidIdx++; @@ -208,7 +218,7 @@ public class ContainerAuctionTrades extends ContainerAuction { if (slot >= SLOT_COUNT) break; claims.add(claim); displayInventory.setClaimItem(slot, claim); - slotTypes[slot] = 3; // claim + slotTypes[slot] = EnumTradeSlotType.CLAIM; slotDataIndex[slot] = claims.size() - 1; slot++; } @@ -216,25 +226,29 @@ public class ContainerAuctionTrades extends ContainerAuction { // ========== Slot Data Accessors ========== - /** Get listing at slot (or null if claim/empty) */ + /** + * Get listing at slot (or null if claim/empty) + */ public AuctionListing getListingAt(int slot) { if (slot < 0 || slot >= SLOT_COUNT) return null; - int type = slotTypes[slot]; + EnumTradeSlotType type = slotTypes[slot]; int idx = slotDataIndex[slot]; if (idx < 0) return null; - if (type == 1 && idx < activeListings.size()) { + if (type == EnumTradeSlotType.SELLING && idx < activeListings.size()) { return activeListings.get(idx); - } else if (type == 2 && idx < activeBids.size()) { + } else if (type == EnumTradeSlotType.BIDDING && idx < activeBids.size()) { return activeBids.get(idx); } return null; } - /** Get claim at slot (or null if listing/empty) */ + /** + * Get claim at slot (or null if listing/empty) + */ public AuctionClaim getClaimAt(int slot) { if (slot < 0 || slot >= SLOT_COUNT) return null; - if (slotTypes[slot] == 3) { + if (slotTypes[slot] == EnumTradeSlotType.CLAIM) { int idx = slotDataIndex[slot]; if (idx >= 0 && idx < claims.size()) { return claims.get(idx); @@ -243,17 +257,23 @@ public class ContainerAuctionTrades extends ContainerAuction { return null; } - /** Check if slot is player's active listing */ + /** + * Check if slot is player's active listing + */ public boolean isSellingAt(int slot) { - return slot >= 0 && slot < SLOT_COUNT && slotTypes[slot] == 1; + return slot >= 0 && slot < SLOT_COUNT && slotTypes[slot] == EnumTradeSlotType.SELLING; } - /** Check if slot is player's active bid */ + /** + * Check if slot is player's active bid + */ public boolean isBiddingAt(int slot) { - return slot >= 0 && slot < SLOT_COUNT && slotTypes[slot] == 2; + return slot >= 0 && slot < SLOT_COUNT && slotTypes[slot] == EnumTradeSlotType.BIDDING; } - /** Find listing matching item (searches both selling and bidding) */ + /** + * Find listing matching item (searches both selling and bidding) + */ public AuctionListing getListingForItem(ItemStack stack) { if (stack == null) return null; for (AuctionListing listing : activeListings) { @@ -265,7 +285,9 @@ public class ContainerAuctionTrades extends ContainerAuction { return null; } - /** Find listing in selling list */ + /** + * Find listing in selling list + */ public AuctionListing getSellingListingForItem(ItemStack stack) { if (stack == null) return null; for (AuctionListing listing : activeListings) { @@ -274,7 +296,9 @@ public class ContainerAuctionTrades extends ContainerAuction { return null; } - /** Find listing in bidding list */ + /** + * Find listing in bidding list + */ public AuctionListing getBiddingListingForItem(ItemStack stack) { if (stack == null) return null; for (AuctionListing bid : activeBids) { @@ -283,7 +307,9 @@ public class ContainerAuctionTrades extends ContainerAuction { return null; } - /** Find claim matching item */ + /** + * Find claim matching item + */ public AuctionClaim getClaimForItem(ItemStack stack) { if (stack == null) return null; for (AuctionClaim claim : claims) { @@ -294,14 +320,27 @@ public class ContainerAuctionTrades extends ContainerAuction { // ========== List Getters ========== - public List getActiveListings() { return activeListings; } - public List getActiveBids() { return activeBids; } - public List getClaims() { return claims; } - public int getTotalTradeCount() { return activeListings.size() + activeBids.size() + claims.size(); } + public List getActiveListings() { + return activeListings; + } + + public List getActiveBids() { + return activeBids; + } + + public List getClaims() { + return claims; + } + + public int getTotalTradeCount() { + return activeListings.size() + activeBids.size() + claims.size(); + } // ========== Slot Hiding (for pending operations) ========== - /** Hide slot for pending operation display */ + /** + * Hide slot for pending operation display + */ public void setHiddenSlot(int slot) { if (hiddenSlot >= 0 && hiddenSlot < SLOT_COUNT) { restoreSlotItem(hiddenSlot); @@ -312,7 +351,9 @@ public class ContainerAuctionTrades extends ContainerAuction { } } - /** Restore hidden slot */ + /** + * Restore hidden slot + */ public void clearHiddenSlot() { if (hiddenSlot >= 0 && hiddenSlot < SLOT_COUNT) { restoreSlotItem(hiddenSlot); @@ -320,34 +361,42 @@ public class ContainerAuctionTrades extends ContainerAuction { hiddenSlot = -1; } - /** Restore item at slot from data using slot tracking */ + /** + * Restore item at slot from data using slot tracking + */ private void restoreSlotItem(int slot) { if (slot < 0 || slot >= SLOT_COUNT) return; - int type = slotTypes[slot]; + EnumTradeSlotType type = slotTypes[slot]; int idx = slotDataIndex[slot]; if (idx < 0) return; - if (type == 1 && idx < activeListings.size()) { + if (type == EnumTradeSlotType.SELLING && idx < activeListings.size()) { // Selling AuctionListing listing = activeListings.get(idx); if (listing != null && listing.item != null) { displayInventory.setInventorySlotContents(slot, listing.item.copy()); } - } else if (type == 2 && idx < activeBids.size()) { + } else if (type == EnumTradeSlotType.BIDDING && idx < activeBids.size()) { // Bidding AuctionListing bid = activeBids.get(idx); if (bid != null && bid.item != null) { displayInventory.setInventorySlotContents(slot, bid.item.copy()); } - } else if (type == 3 && idx < claims.size()) { + } else if (type == EnumTradeSlotType.CLAIM && idx < claims.size()) { // Claim displayInventory.setClaimItem(slot, claims.get(idx)); } } - public int getHiddenSlot() { return hiddenSlot; } + public int getHiddenSlot() { + return hiddenSlot; + } - /** Get player's max trade slots (synced from server based on permissions) */ - public int getMaxTradeSlots() { return maxTradeSlots; } + /** + * Get player's max trade slots (synced from server based on permissions) + */ + public int getMaxTradeSlots() { + return maxTradeSlots; + } } diff --git a/src/main/java/noppes/npcs/containers/ContainerManageAuction.java b/src/main/java/noppes/npcs/containers/ContainerManageAuction.java new file mode 100644 index 000000000..1b6b05684 --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerManageAuction.java @@ -0,0 +1,384 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryBasic; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import noppes.npcs.NoppesUtilPlayer; +import noppes.npcs.constants.EnumClaimType; +import noppes.npcs.controllers.data.AuctionClaim; +import noppes.npcs.controllers.data.AuctionListing; + +import java.util.ArrayList; +import java.util.List; + +/** + * Global auction management container. + * Uses a 9x5 display grid plus staged/detail slots on the right panel and player inventory below the grid. + */ +public class ContainerManageAuction extends ContainerNpcInterface { + public enum DisplayMode { + LISTINGS, + CLAIMS + } + + public static final int DISPLAY_COLS = 9; + public static final int DISPLAY_ROWS = 5; + public static final int DISPLAY_SLOT_COUNT = DISPLAY_COLS * DISPLAY_ROWS; + + public static final int DISPLAY_X = 8; + public static final int DISPLAY_Y = 16; + + public static final int PLAYER_INV_X = 8; + public static final int PLAYER_INV_Y = 113; + public static final int HOTBAR_Y = 171; + public static final int PLAYER_SLOT_COUNT = 36; + + public static final int CREATE_SLOT_X = 188; + public static final int CREATE_SLOT_Y = 156; + public static final int DETAIL_SLOT_X = 194; + public static final int DETAIL_SLOT_Y = 56; + private static final int MAX_STACK = 64; + + public static final int DISPLAY_SLOT_START = 0; + public static final int PLAYER_SLOT_START = DISPLAY_SLOT_START + DISPLAY_SLOT_COUNT; + public static final int DETAIL_SLOT_INDEX = PLAYER_SLOT_START + PLAYER_SLOT_COUNT; + public static final int CREATE_SLOT_INDEX = DETAIL_SLOT_INDEX + 1; + + private static final int HIDDEN_SLOT_X = -1000; + private static final int HIDDEN_SLOT_Y = -1000; + + public final InventoryAuctionDisplay displayInventory; + private final IInventory detailInventory; + private final IInventory createInventory; + private DisplayMode displayMode = DisplayMode.LISTINGS; + private Slot detailSlot; + private Slot createSlot; + private int hiddenDisplaySlot = -1; + + public ContainerManageAuction(EntityPlayer player) { + super(player); + this.player = player; + + displayInventory = new InventoryAuctionDisplay(DISPLAY_SLOT_COUNT); + detailInventory = new InventoryBasic("GlobalAuctionDetail", false, 1); + createInventory = new InventoryBasic("GlobalAuctionCreate", false, 1); + + // 9x5 display grid (listings / global claims) + for (int row = 0; row < DISPLAY_ROWS; row++) { + for (int col = 0; col < DISPLAY_COLS; col++) { + int slotIndex = col + row * DISPLAY_COLS; + int x = DISPLAY_X + col * 18; + int y = DISPLAY_Y + row * 18; + addSlotToContainer(new SlotAuctionDisplay(displayInventory, slotIndex, x, y)); + } + } + + // Player inventory below display grid + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 9; col++) { + int playerIndex = col + row * 9 + 9; + int x = PLAYER_INV_X + col * 18; + int y = PLAYER_INV_Y + row * 18; + addSlotToContainer(new Slot(player.inventory, playerIndex, x, y)); + } + } + for (int col = 0; col < 9; col++) { + int x = PLAYER_INV_X + col * 18; + addSlotToContainer(new Slot(player.inventory, col, x, HOTBAR_Y)); + } + + // Listing details slot (right panel) + detailSlot = new SlotAuctionDisplay(detailInventory, 0, DETAIL_SLOT_X, DETAIL_SLOT_Y); + addSlotToContainer(detailSlot); + + // Staged fake listing slot + createSlot = new Slot(createInventory, 0, CREATE_SLOT_X, CREATE_SLOT_Y) { + @Override + public boolean isItemValid(ItemStack stack) { + return false; + } + + @Override + public boolean canTakeStack(EntityPlayer player) { + return false; + } + }; + addSlotToContainer(createSlot); + + setDetailSlotVisible(false); + setCreateSlotVisible(false); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { + return null; + } + + @Override + public ItemStack slotClick(int slotIndex, int mouseButton, int mode, EntityPlayer player) { + // Block native container interactions. GUI handles all click behaviors. + return null; + } + + public void setDisplayMode(DisplayMode mode) { + this.displayMode = mode != null ? mode : DisplayMode.LISTINGS; + } + + public DisplayMode getDisplayMode() { + return displayMode; + } + + public void clearDisplay() { + displayInventory.clear(); + } + + public void setListingsPage(List listings) { + displayMode = DisplayMode.LISTINGS; + clearHiddenDisplaySlot(); + displayInventory.clear(); + if (listings == null) return; + + for (int i = 0; i < listings.size() && i < DISPLAY_SLOT_COUNT; i++) { + displayInventory.setListing(i, listings.get(i)); + } + } + + public void setClaimsPage(List claims) { + displayMode = DisplayMode.CLAIMS; + clearHiddenDisplaySlot(); + displayInventory.clear(); + if (claims == null) return; + + for (int i = 0; i < claims.size() && i < DISPLAY_SLOT_COUNT; i++) { + displayInventory.setClaimItem(i, claims.get(i)); + } + } + + /** + * Claims page can contain both global claims and active global listings. + * Order mirrors My Trades: + * sold claims, outbid claims, won claims, active listings, expired claims. + */ + public void setClaimsAndListingsPage(List claims, List listings) { + displayMode = DisplayMode.CLAIMS; + clearHiddenDisplaySlot(); + displayInventory.clear(); + + List soldClaims = new ArrayList(); + List outbidClaims = new ArrayList(); + List wonClaims = new ArrayList(); + List expiredClaims = new ArrayList(); + if (claims != null) { + for (AuctionClaim claim : claims) { + if (claim == null) continue; + if (claim.type == EnumClaimType.CURRENCY) { + soldClaims.add(claim); + } else if (claim.type == EnumClaimType.REFUND) { + outbidClaims.add(claim); + } else if (claim.type == EnumClaimType.ITEM) { + if (claim.isReturned) { + expiredClaims.add(claim); + } else { + wonClaims.add(claim); + } + } else { + wonClaims.add(claim); + } + } + } + + int slot = 0; + slot = fillClaims(slot, soldClaims); + slot = fillClaims(slot, outbidClaims); + slot = fillClaims(slot, wonClaims); + + if (listings != null) { + for (int i = 0; i < listings.size() && slot < DISPLAY_SLOT_COUNT; i++) { + displayInventory.setListing(slot, listings.get(i)); + slot++; + } + } + + fillClaims(slot, expiredClaims); + } + + private int fillClaims(int slot, List claims) { + if (claims == null) return slot; + for (int i = 0; i < claims.size() && slot < DISPLAY_SLOT_COUNT; i++) { + displayInventory.setClaimItem(slot, claims.get(i)); + slot++; + } + return slot; + } + + public boolean isDisplaySlot(int containerSlotIndex) { + return containerSlotIndex >= DISPLAY_SLOT_START && containerSlotIndex < DISPLAY_SLOT_START + DISPLAY_SLOT_COUNT; + } + + public int toDisplayIndex(int containerSlotIndex) { + if (!isDisplaySlot(containerSlotIndex)) return -1; + return containerSlotIndex - DISPLAY_SLOT_START; + } + + public AuctionListing getListingAtDisplay(int displayIndex) { + if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) return null; + return displayInventory.getListing(displayIndex); + } + + public AuctionClaim getClaimAtDisplay(int displayIndex) { + if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) return null; + return displayInventory.getClaim(displayIndex); + } + + public boolean isPlayerSlot(int containerSlotIndex) { + return containerSlotIndex >= PLAYER_SLOT_START && containerSlotIndex < PLAYER_SLOT_START + PLAYER_SLOT_COUNT; + } + + public boolean isCreateSlot(int containerSlotIndex) { + return containerSlotIndex == CREATE_SLOT_INDEX; + } + + public boolean isDetailSlot(int containerSlotIndex) { + return containerSlotIndex == DETAIL_SLOT_INDEX; + } + + public void setDetailItem(ItemStack stack) { + detailInventory.setInventorySlotContents(0, stack != null ? stack.copy() : null); + } + + public void clearDetailItem() { + detailInventory.setInventorySlotContents(0, null); + } + + public void setDetailSlotVisible(boolean visible) { + if (detailSlot == null) return; + detailSlot.xDisplayPosition = visible ? DETAIL_SLOT_X : HIDDEN_SLOT_X; + detailSlot.yDisplayPosition = visible ? DETAIL_SLOT_Y : HIDDEN_SLOT_Y; + } + + public void setCreateSlotVisible(boolean visible) { + if (createSlot == null) return; + createSlot.xDisplayPosition = visible ? CREATE_SLOT_X : HIDDEN_SLOT_X; + createSlot.yDisplayPosition = visible ? CREATE_SLOT_Y : HIDDEN_SLOT_Y; + } + + public void setHiddenDisplaySlot(int displayIndex) { + if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) { + clearHiddenDisplaySlot(); + return; + } + if (hiddenDisplaySlot == displayIndex) return; + + clearHiddenDisplaySlot(); + hiddenDisplaySlot = displayIndex; + displayInventory.setInventorySlotContents(displayIndex, null); + } + + public void clearHiddenDisplaySlot() { + if (hiddenDisplaySlot < 0 || hiddenDisplaySlot >= DISPLAY_SLOT_COUNT) { + hiddenDisplaySlot = -1; + return; + } + restoreDisplaySlot(hiddenDisplaySlot); + hiddenDisplaySlot = -1; + } + + public int getHiddenDisplaySlot() { + return hiddenDisplaySlot; + } + + private void restoreDisplaySlot(int displayIndex) { + if (displayIndex < 0 || displayIndex >= DISPLAY_SLOT_COUNT) return; + + AuctionClaim claim = displayInventory.getClaim(displayIndex); + if (claim != null) { + displayInventory.setClaimItem(displayIndex, claim); + return; + } + + AuctionListing listing = displayInventory.getListing(displayIndex); + if (listing != null) { + displayInventory.setListing(displayIndex, listing); + return; + } + + displayInventory.setInventorySlotContents(displayIndex, null); + } + + public ItemStack getCreateItem() { + return createInventory.getStackInSlot(0); + } + + public void clearCreateSlot() { + createInventory.setInventorySlotContents(0, null); + } + + public void addToCreateSlot(int containerPlayerSlot, boolean fullStack) { + if (!isPlayerSlot(containerPlayerSlot)) return; + + Slot slot = (Slot) inventorySlots.get(containerPlayerSlot); + if (slot == null) return; + ItemStack source = slot.getStack(); + if (source == null) return; + + ItemStack staged = createInventory.getStackInSlot(0); + int toAdd = fullStack ? source.stackSize : 1; + + if (staged == null) { + ItemStack copy = source.copy(); + copy.stackSize = Math.min(MAX_STACK, toAdd); + createInventory.setInventorySlotContents(0, copy); + return; + } + + if (!itemsMatch(staged, source)) { + ItemStack copy = source.copy(); + copy.stackSize = Math.min(MAX_STACK, toAdd); + createInventory.setInventorySlotContents(0, copy); + return; + } + + int space = MAX_STACK - staged.stackSize; + int add = Math.min(space, toAdd); + if (add > 0) { + staged.stackSize += add; + } + } + + public void removeFromCreateSlot(boolean removeAll) { + ItemStack staged = createInventory.getStackInSlot(0); + if (staged == null) return; + + if (removeAll || staged.stackSize <= 1) { + createInventory.setInventorySlotContents(0, null); + } else { + staged.stackSize--; + } + } + + public int countItemInPlayerInventory(ItemStack target) { + if (target == null || player == null || player.inventory == null) return 0; + int total = 0; + for (int i = 0; i < player.inventory.mainInventory.length; i++) { + ItemStack stack = player.inventory.mainInventory[i]; + if (stack != null && itemsMatch(target, stack)) { + total += stack.stackSize; + } + } + return total; + } + + private boolean itemsMatch(ItemStack a, ItemStack b) { + return NoppesUtilPlayer.compareItems(a, b, false, false); + } + + @Override + public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + clearHiddenDisplaySlot(); + clearDetailItem(); + clearCreateSlot(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/APIRegistry.java b/src/main/java/noppes/npcs/controllers/APIRegistry.java new file mode 100644 index 000000000..746bc4acd --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/APIRegistry.java @@ -0,0 +1,25 @@ +package noppes.npcs.controllers; + +import java.util.LinkedHashMap; + +public class APIRegistry { + public static final APIRegistry Instance = new APIRegistry(); + + private final LinkedHashMap entries = new LinkedHashMap<>(); + + public void register(String name, String url) { + entries.put(name, url); + } + + public void unregister(String name) { + entries.remove(name); + } + + public LinkedHashMap getEntries() { + return entries; + } + + public int size() { + return entries.size(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/AnimationController.java b/src/main/java/noppes/npcs/controllers/AnimationController.java index b4203b452..cf1bd2c95 100644 --- a/src/main/java/noppes/npcs/controllers/AnimationController.java +++ b/src/main/java/noppes/npcs/controllers/AnimationController.java @@ -1,5 +1,6 @@ package noppes.npcs.controllers; +import kamkeel.npcs.util.Register; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -21,7 +22,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; @@ -31,7 +31,8 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; @@ -42,17 +43,19 @@ public class AnimationController implements IAnimationHandler { // Built-in animations loaded from assets folder (read-only, keyed by name) public HashMap builtInAnimations = new HashMap<>(); - private static final String BUILTIN_ANIMATIONS_PATH = "/assets/customnpcs/animations"; - private static final String BUILTIN_ANIMATIONS_RESOURCE = "assets/customnpcs/animations"; + private static final String BUILTIN_ANIMATIONS_PATH = "/assets/customnpcs/cnpc_animations"; + private static final String BUILTIN_ANIMATIONS_RESOURCE = "assets/customnpcs/cnpc_animations"; - public static AnimationController Instance; + public static AnimationController Instance = new AnimationController(); private int lastUsedID = 0; + public CategoryManager categoryManager = new CategoryManager(); + + public LinkedHashMap registeredAnimations = new LinkedHashMap<>(); public AnimationController() { Instance = this; bootOrder = new HashMap<>(); animations = new HashMap<>(); - load(); } public static AnimationController getInstance() { @@ -65,13 +68,14 @@ public class AnimationController implements IAnimationHandler { builtInAnimations = new HashMap<>(); LogWriter.info("Loading animations..."); loadBuiltInAnimations(); + loadRegisteredBuiltIns(); readAnimationMap(); loadAnimations(); LogWriter.info("Done loading animations."); } /** - * Load built-in animations from assets/customnpcs/animations/ folder. + * Load built-in animations from assets/customnpcs/cnpc_animations/ folder. * These animations are read-only and accessed by name only (no IDs). * Scans the folder directly instead of using a manifest. */ @@ -124,6 +128,7 @@ public class AnimationController implements IAnimationHandler { String resourcePath = path + "/" + animName + ".json"; try (InputStream stream = modClass.getResourceAsStream(resourcePath)) { if (stream == null) { + LogWriter.error("Animation not found: " + animName.toLowerCase()); return; } @@ -144,6 +149,7 @@ public class AnimationController implements IAnimationHandler { // Store with lowercase key for case-insensitive lookup builtInAnimations.put(animName.toLowerCase(), animation); + LogWriter.info("Registered animation: " + animName.toLowerCase()); } } @@ -160,45 +166,83 @@ public class AnimationController implements IAnimationHandler { File dir = getDir(); if (!dir.exists()) { dir.mkdir(); - } else { - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - try { - Animation animation = new Animation(); - animation.readFromNBT(NBTJsonUtil.LoadFile(file)); - animation.name = file.getName().substring(0, file.getName().length() - 5); + } - if (animation.id == -1) { - animation.id = getUnusedId(); - } + categoryManager.loadCategories(dir); - int originalID = animation.id; - int setID = animation.id; - while (bootOrder.containsKey(setID) || animations.containsKey(setID)) { - if (bootOrder.containsKey(setID)) - if (bootOrder.get(setID).equals(animation.name)) - break; + // Load uncategorized animations (root level .json files) + loadAnimationsFromDir(dir, CategoryManager.UNCATEGORIZED_ID); - setID++; - } - - animation.id = setID; - if (originalID != setID) { - LogWriter.info("Found Animation ID Mismatch: " + animation.name + ", New ID: " + setID); - animation.save(); - } - - animations.put(animation.id, animation); - } catch (Exception e) { - LogWriter.error("Error loading: " + file.getAbsolutePath(), e); - } - } + // Load categorized animations (subdirectories) + for (Map.Entry entry : categoryManager.getCategories().entrySet()) { + File catDir = categoryManager.getCategoryDir(entry.getKey()); + loadAnimationsFromDir(catDir, entry.getKey()); } saveAnimationMap(); } + private void loadAnimationsFromDir(File dir, int catId) { + File[] files = dir.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) + continue; + try { + Animation animation = new Animation(); + animation.readFromNBT(NBTJsonUtil.LoadFile(file)); + animation.name = file.getName().substring(0, file.getName().length() - 5); + + if (animation.id == -1) { + animation.id = getUnusedId(); + } + + int originalID = animation.id; + int setID = animation.id; + while (bootOrder.containsKey(setID) || animations.containsKey(setID)) { + if (bootOrder.containsKey(setID)) + if (bootOrder.get(setID).equals(animation.name)) + break; + + setID++; + } + + animation.id = setID; + if (originalID != setID) { + LogWriter.info("Found Animation ID Mismatch: " + animation.name + ", New ID: " + setID); + animation.save(); + } + + animations.put(animation.id, animation); + categoryManager.registerItem(animation.id, catId); + } catch (Exception e) { + LogWriter.error("Error loading: " + file.getAbsolutePath(), e); + } + } + } + + public void addAnimationRegister(String namespace, Register.Animations register) { + registeredAnimations.put(namespace, register); + } + + private void loadRegisteredBuiltIns() { + for (Register.Animations register : registeredAnimations.values()) { + register.register(); + } + } + + /** + * Loads built-in animations for client-side usage. + * On dedicated servers, AnimationController.load() never runs on the client JVM, + * so built-in animations would be missing for client-only systems like ability preview. + * This method loads just the built-in animations (from assets and registered addons) + * without touching user animations or world save data. + */ + public void loadClientBuiltIns() { + loadBuiltInAnimations(); + loadRegisteredBuiltIns(); + } + private File getDir() { return new File(CustomNpcs.getWorldSaveDirectory(), "animations"); } @@ -239,7 +283,7 @@ public class AnimationController implements IAnimationHandler { saveAnimationMap(); // Save Animation File - File dir = this.getDir(); + File dir = categoryManager.getItemDir(animation.getID()); if (!dir.exists()) dir.mkdirs(); @@ -266,49 +310,54 @@ public class AnimationController implements IAnimationHandler { return false; } + public Animation cloneAnimation(int originalId) { + Animation original = animations.get(originalId); + if (original == null || original instanceof BuiltInAnimation) return null; + + int originalCatId = categoryManager.getItemCategory(originalId); + + Animation clone = new Animation(); + clone.readFromNBT(original.writeToNBT()); + clone.id = getUnusedId(); + + String name = clone.name; + while (hasName(name)) name += "_"; + clone.name = name; + + if (originalCatId > CategoryManager.UNCATEGORIZED_ID) { + categoryManager.registerItem(clone.id, originalCatId); + } + + saveAnimation(clone); + return clone; + } + public void delete(String name) { Animation delete = getAnimationFromName(name); if (delete != null) { - // Reject deleting built-in animations - if (delete instanceof BuiltInAnimation) { - LogWriter.info("Cannot delete built-in animation: " + name); - return; - } - - Animation foundAnimation = this.animations.remove(delete.getID()); - if (foundAnimation != null && foundAnimation.name != null) { - File dir = this.getDir(); - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - if (file.getName().equals(foundAnimation.name + ".json")) { - file.delete(); - break; - } - } - - saveAnimationMap(); - } + delete(delete.getID()); } } public void delete(int id) { - // Only user animations have valid IDs (>= 0) if (id < 0 || !this.animations.containsKey(id)) return; + // Reject deleting built-in animations + Animation anim = this.animations.get(id); + if (anim instanceof BuiltInAnimation) { + LogWriter.info("Cannot delete built-in animation: " + anim.name); + return; + } + Animation foundAnimation = this.animations.remove(id); if (foundAnimation != null && foundAnimation.name != null) { - File dir = this.getDir(); - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - if (file.getName().equals(foundAnimation.name + ".json")) { - file.delete(); - break; - } + File dir = categoryManager.getItemDir(id); + File file = new File(dir, foundAnimation.name + ".json"); + if (file.exists()) { + file.delete(); } - + categoryManager.removeItem(id); saveAnimationMap(); } } @@ -353,6 +402,7 @@ public class AnimationController implements IAnimationHandler { /** * Get a built-in animation by name. + * * @param name The animation name (case-insensitive) * @return The built-in animation, or null if not found */ @@ -384,6 +434,7 @@ public class AnimationController implements IAnimationHandler { /** * Check if an animation name is a built-in animation. + * * @param name The animation name to check * @return true if this is a built-in animation */ @@ -525,5 +576,29 @@ public class AnimationController implements IAnimationHandler { } //////////////////////////////////////////////////////// + // CATEGORY HELPERS //////////////////////////////////////////////////////// + + public Map getCategoryScrollData() { + return categoryManager.getCategoryScrollData(); + } + + public void moveItemToCategory(int itemId, int catId) { + Animation animation = animations.get(itemId); + if (animation == null) return; + categoryManager.moveItem(itemId, animation.name + ".json", catId); + saveAnimationMap(); + } + + public Map getItemsByCategoryScrollData(int catId) { + Map map = new HashMap<>(); + List itemIds = categoryManager.getItemsInCategory(catId, animations.keySet()); + for (int itemId : itemIds) { + Animation animation = animations.get(itemId); + if (animation != null) { + map.put(animation.name, animation.id); + } + } + return map; + } } diff --git a/src/main/java/noppes/npcs/controllers/AuctionConfigSync.java b/src/main/java/noppes/npcs/controllers/AuctionConfigSync.java index 9b8c1f995..dae214f5c 100644 --- a/src/main/java/noppes/npcs/controllers/AuctionConfigSync.java +++ b/src/main/java/noppes/npcs/controllers/AuctionConfigSync.java @@ -7,7 +7,7 @@ import noppes.npcs.config.ConfigMarket; /** * Server-side utility for syncing auction configuration to clients. * Handles Vault integration for currency name resolution. - * + *

* This class is SERVER-SIDE ONLY. Client reads via AuctionClientConfig. */ public class AuctionConfigSync { @@ -15,7 +15,7 @@ public class AuctionConfigSync { /** * Write auction config to NBT for sending to client. * Called on server side when building login packet. - * + *

* Currency name is resolved from Vault if enabled and available, * otherwise falls back to ConfigMarket.CurrencyName. */ @@ -40,7 +40,7 @@ public class AuctionConfigSync { public static String getEffectiveCurrencyName() { if (ConfigMarket.UseVault && VaultUtil.isEnabled()) { String vaultName = VaultUtil.getCurrencyNamePlural(); - if (vaultName != null && !vaultName.isEmpty() && !vaultName.equals("coins")) { + if (vaultName != null && !vaultName.isEmpty()) { return vaultName; } } diff --git a/src/main/java/noppes/npcs/controllers/AuctionController.java b/src/main/java/noppes/npcs/controllers/AuctionController.java index e6ca0c6cf..e51c07a5d 100644 --- a/src/main/java/noppes/npcs/controllers/AuctionController.java +++ b/src/main/java/noppes/npcs/controllers/AuctionController.java @@ -6,17 +6,18 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import noppes.npcs.CustomNpcs; import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.EventHooks; import noppes.npcs.LogWriter; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.handler.IAuctionHandler; import noppes.npcs.api.handler.data.IAuctionListing; import noppes.npcs.api.item.IItemStack; import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionLogAction; import noppes.npcs.constants.EnumAuctionSort; import noppes.npcs.constants.EnumAuctionStatus; import noppes.npcs.constants.EnumClaimType; @@ -26,24 +27,33 @@ import noppes.npcs.controllers.data.AuctionClaim; import noppes.npcs.controllers.data.AuctionFilter; import noppes.npcs.controllers.data.AuctionListing; import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.PlayerDataScript; import noppes.npcs.controllers.data.PlayerTradeData; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.scripted.event.player.AuctionEvent; import noppes.npcs.util.CustomNPCsThreader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; /** * Main controller for the Auction system. - * + *

* Thread Safety: * - Uses ConcurrentHashMap for all data stores - no locking required * - Claims are stored in PlayerData, not here - reduces contention * - Saves are performed asynchronously on the CNPC+ thread - * + *

* Performance: * - Auction processing runs every 30 seconds (600 ticks) * - Save interval is every 30 seconds (600 ticks) @@ -54,35 +64,48 @@ public class AuctionController implements IAuctionHandler { // Main data stores - listings only, claims are stored in PlayerData private final Map listings = new ConcurrentHashMap<>(); - // Claims are now stored in PlayerData.tradeData, not here + // Shared global claims for admin-managed auction actions + private final List globalClaims = new CopyOnWriteArrayList<>(); // ========================================= // Player Indices for O(1) Lookups // ========================================= - /** Listings by seller UUID - for quick "my listings" lookups */ + /** + * Listings by seller UUID - for quick "my listings" lookups + */ private final Map> playerListingIds = new ConcurrentHashMap<>(); - /** Listings where player is current high bidder */ + /** + * Listings where player is current high bidder + */ private final Map> playerBidIds = new ConcurrentHashMap<>(); - /** Cached max trade slots per player - computed on login, cleared on logout */ + /** + * Cached max trade slots per player - computed on login, cleared on logout + */ private final Map playerMaxTradesCache = new ConcurrentHashMap<>(); // ========================================= // Threading & State // ========================================= - /** Flag indicating data needs to be saved */ + /** + * Flag indicating data needs to be saved + */ private final AtomicBoolean dirty = new AtomicBoolean(false); - /** Flag to prevent concurrent saves */ + /** + * Flag to prevent concurrent saves + */ private final AtomicBoolean saving = new AtomicBoolean(false); private String filePath = ""; private int tickCounter = 0; - /** Process auctions and save every 30 seconds (600 ticks) */ + /** + * Process auctions and save every 30 seconds (600 ticks) + */ private static final int TICK_INTERVAL = 600; public AuctionController() { @@ -138,52 +161,71 @@ public class AuctionController implements IAuctionHandler { } private void endAuction(AuctionListing listing) { - listing.status = EnumAuctionStatus.ENDED; + synchronized (listing) { + if (listing.status != EnumAuctionStatus.ACTIVE) return; - // Remove from seller's active listings - removeFromPlayerListings(listing.sellerUUID, listing.id); + listing.status = EnumAuctionStatus.ENDED; + boolean isGlobalListing = listing.isGlobalListing; - // Remove from bidder's active bids if any - if (listing.highBidderUUID != null) { - removeFromPlayerBids(listing.highBidderUUID, listing.id); - } + // Remove from seller's active listings + if (!isGlobalListing && listing.sellerUUID != null) { + removeFromPlayerListings(listing.sellerUUID, listing.id); + } - // Get item display name safely - String itemDisplayName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item"; + // Remove from bidder's active bids if any + if (listing.highBidderUUID != null) { + removeFromPlayerBids(listing.highBidderUUID, listing.id); + } - if (listing.hasBids()) { - // Auction sold - create claims - AuctionClaim itemClaim = AuctionClaim.createItemWonClaim( - listing.highBidderUUID, listing.highBidderName, listing.id, listing.item); - addClaimToPlayer(listing.highBidderUUID, itemClaim); + // Get item display name safely + String itemDisplayName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item"; - long saleAmount = listing.currentBid; - long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent); - long sellerReceives = saleAmount - tax; + if (listing.hasBids()) { + // Auction sold - create claims + AuctionClaim itemClaim = AuctionClaim.createItemWonClaim( + listing.highBidderUUID, listing.highBidderName, listing.id, listing.item); + addClaimToPlayer(listing.highBidderUUID, itemClaim); - AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim( - listing.sellerUUID, listing.sellerName, listing.id, sellerReceives, - itemDisplayName, listing.highBidderName); - addClaimToPlayer(listing.sellerUUID, currencyClaim); + long saleAmount = listing.currentBid; + long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent); + long sellerReceives = saleAmount - tax; - // Notifications - sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_WON, listing.id, - "You won the auction for " + itemDisplayName + "!"); - sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id, - "Your " + itemDisplayName + " sold for " + saleAmount + " " + ConfigMarket.CurrencyName + "!"); + AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim( + listing.sellerUUID, listing.sellerName, listing.id, sellerReceives, + itemDisplayName, listing.highBidderName); + if (isGlobalListing) { + addGlobalClaim(currencyClaim); + } else { + addClaimToPlayer(listing.sellerUUID, currencyClaim); + } - logAuction("SOLD", listing.sellerName, itemDisplayName, saleAmount, - "Winner: " + listing.highBidderName + ", Tax: " + tax); - } else { - // No bids - return item to seller - AuctionClaim returnClaim = AuctionClaim.createItemReturnedClaim( - listing.sellerUUID, listing.sellerName, listing.id, listing.item); - addClaimToPlayer(listing.sellerUUID, returnClaim); + // Notifications + sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_WON, listing.id, + "You won the auction for " + itemDisplayName + "!"); + if (!isGlobalListing && listing.sellerUUID != null) { + sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id, + "Your " + itemDisplayName + " sold for " + saleAmount + " " + ConfigMarket.CurrencyName + "!"); + } - sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_EXPIRED, listing.id, - "Your auction for " + itemDisplayName + " expired with no bids."); + logAuction(EnumAuctionLogAction.SOLD, listing.sellerName, itemDisplayName, saleAmount, + "Winner: " + listing.highBidderName + ", Tax: " + tax + (isGlobalListing ? ", Global listing" : "")); + } else { + // No bids - return item to seller/global claims + AuctionClaim returnClaim = AuctionClaim.createItemReturnedClaim( + listing.sellerUUID, listing.sellerName, listing.id, listing.item); + if (isGlobalListing) { + addGlobalClaim(returnClaim); + } else { + addClaimToPlayer(listing.sellerUUID, returnClaim); + if (listing.sellerUUID != null) { + sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_EXPIRED, listing.id, + "Your auction for " + itemDisplayName + " expired with no bids."); + } + } - logAuction("EXPIRED", listing.sellerName, itemDisplayName, listing.startingPrice, "No bids"); + logAuction(EnumAuctionLogAction.EXPIRED, listing.sellerName, itemDisplayName, listing.startingPrice, + "No bids" + (isGlobalListing ? ", Global listing" : "")); + } } } @@ -192,10 +234,12 @@ public class AuctionController implements IAuctionHandler { // ========================================= private void addToPlayerListings(UUID playerUUID, String listingId) { + if (playerUUID == null || listingId == null || listingId.isEmpty()) return; playerListingIds.computeIfAbsent(playerUUID, k -> ConcurrentHashMap.newKeySet()).add(listingId); } private void removeFromPlayerListings(UUID playerUUID, String listingId) { + if (playerUUID == null || listingId == null || listingId.isEmpty()) return; Set ids = playerListingIds.get(playerUUID); if (ids != null) { ids.remove(listingId); @@ -206,10 +250,12 @@ public class AuctionController implements IAuctionHandler { } private void addToPlayerBids(UUID playerUUID, String listingId) { + if (playerUUID == null || listingId == null || listingId.isEmpty()) return; playerBidIds.computeIfAbsent(playerUUID, k -> ConcurrentHashMap.newKeySet()).add(listingId); } private void removeFromPlayerBids(UUID playerUUID, String listingId) { + if (playerUUID == null || listingId == null || listingId.isEmpty()) return; Set ids = playerBidIds.get(playerUUID); if (ids != null) { ids.remove(listingId); @@ -234,6 +280,82 @@ public class AuctionController implements IAuctionHandler { } } + /** + * Add a claim to the global admin claims pool. + */ + private void addGlobalClaim(AuctionClaim claim) { + if (claim == null || claim.claimed) return; + + // Global claims are not tied to a single player. + claim.playerUUID = null; + claim.playerName = "Global"; + synchronized (globalClaims) { + // Prevent duplicate claim IDs + for (AuctionClaim existing : globalClaims) { + if (existing.id.equals(claim.id)) { + return; + } + } + globalClaims.add(claim); + } + markDirty(); + } + + private List getGlobalClaimsSnapshot() { + List result = new ArrayList<>(); + for (AuctionClaim claim : globalClaims) { + if (claim != null && !claim.claimed) { + result.add(claim); + } + } + return result; + } + + private AuctionClaim getGlobalClaimInternal(String claimId) { + if (claimId == null || claimId.isEmpty()) return null; + synchronized (globalClaims) { + for (AuctionClaim claim : globalClaims) { + if (claim != null && !claim.claimed && claimId.equals(claim.id)) { + return claim; + } + } + } + return null; + } + + private boolean claimAndRemoveGlobal(String claimId) { + synchronized (globalClaims) { + AuctionClaim claim = getGlobalClaimInternal(claimId); + if (claim == null) return false; + claim.claimed = true; + return globalClaims.remove(claim); + } + } + + /** + * Full list of unclaimed global claims sorted newest-first. + */ + public List getAllGlobalClaims() { + List snapshot = getGlobalClaimsSnapshot(); + snapshot.sort((a, b) -> Long.compare(b.createdTime, a.createdTime)); + return snapshot; + } + + /** + * Full list of active global listings sorted newest-first. + */ + public List getActiveGlobalListings() { + List result = new ArrayList<>(); + for (AuctionListing listing : listings.values()) { + if (listing == null) continue; + if (!listing.isGlobalListing) continue; + if (!listing.isActive()) continue; + result.add(listing); + } + result.sort((a, b) -> Long.compare(b.createdTime, a.createdTime)); + return result; + } + // ========================================= // Listing Management // ========================================= @@ -248,15 +370,27 @@ public class AuctionController implements IAuctionHandler { return "This item cannot be listed on the Auction House."; } - // Validate minimum price + // Validate prices + if (startingPrice <= 0) { + return "Starting price must be positive."; + } if (startingPrice < ConfigMarket.MinimumListingPrice) { return "Starting price must be at least " + ConfigMarket.MinimumListingPrice + " " + ConfigMarket.CurrencyName + "."; } + if (startingPrice > ConfigMarket.MaxBalance) { + return "Starting price exceeds maximum allowed value."; + } // Validate buyout price if set + if (buyoutPrice < 0) { + return "Buyout price cannot be negative."; + } if (buyoutPrice > 0 && buyoutPrice < startingPrice) { return "Buyout price must be higher than starting price."; } + if (buyoutPrice > ConfigMarket.MaxBalance) { + return "Buyout price exceeds maximum allowed value."; + } UUID playerUUID = player.getUniqueID(); String playerName = player.getCommandSenderName(); @@ -276,12 +410,21 @@ public class AuctionController implements IAuctionHandler { PlayerTradeData currency = playerData.tradeData; long fee = ConfigMarket.ListingFee; - if (!currency.canAfford(fee)) { + if (fee > 0 && !currency.canAfford(fee)) { return "You cannot afford the listing fee (" + fee + " " + ConfigMarket.CurrencyName + ")."; } + // Fire auction create event (cancelable) + PlayerDataScript createHandler = ScriptController.Instance.getPlayerScripts(player); + IPlayer iCreator = (IPlayer) NpcAPI.Instance().getIEntity(player); + AuctionEvent.CreateEvent createEvent = new AuctionEvent.CreateEvent( + iCreator, NpcAPI.Instance().getIItemStack(item), startingPrice, buyoutPrice); + if (EventHooks.onAuctionCreate(createHandler, createEvent)) { + return "Auction creation was cancelled."; + } + // Deduct fee - if (!currency.withdraw(fee)) { + if (fee > 0 && !currency.withdraw(fee)) { return "Failed to deduct listing fee."; } @@ -295,67 +438,144 @@ public class AuctionController implements IAuctionHandler { markDirty(); - logAuction("CREATED", playerName, item.getDisplayName(), startingPrice, + logAuction(EnumAuctionLogAction.CREATED, playerName, item.getDisplayName(), startingPrice, "Buyout: " + (buyoutPrice > 0 ? buyoutPrice : "None") + ", Fee: " + fee); return null; // Success } + /** + * Create a fake/global listing managed through the global auction admin GUI. + * Global listings do not consume player currency and route proceeds to global claims. + */ + public String createGlobalListing(EntityPlayer admin, String sellerName, ItemStack item, long startingPrice, long buyoutPrice, int durationHours) { + if (!ConfigMarket.AuctionEnabled) { + return "Auction is disabled."; + } + if (admin == null) { + return "Admin is missing."; + } + if (item == null) { + return "No item provided."; + } + + // Validate prices + if (startingPrice <= 0) { + return "Starting price must be positive."; + } + if (startingPrice < ConfigMarket.MinimumListingPrice) { + return "Starting price must be at least " + ConfigMarket.MinimumListingPrice + " " + ConfigMarket.CurrencyName + "."; + } + if (buyoutPrice < 0) { + return "Buyout price cannot be negative."; + } + if (buyoutPrice > 0 && buyoutPrice < startingPrice) { + return "Buyout price must be higher than starting price."; + } + + String cleanSeller = sellerName != null ? sellerName.trim() : ""; + if (cleanSeller.isEmpty()) { + cleanSeller = "Server"; + } + + int hours = durationHours > 0 ? durationHours : ConfigMarket.AuctionDurationHours; + long durationMs = hours * 60L * 60L * 1000L; + + // Global listings do not belong to a player UUID, only to the global pool. + AuctionListing listing = new AuctionListing(null, cleanSeller, item, startingPrice, buyoutPrice, durationMs); + listing.isGlobalListing = true; + listings.put(listing.id, listing); + markDirty(); + + logAuction(EnumAuctionLogAction.CREATED, admin.getCommandSenderName(), item.getDisplayName(), startingPrice, + "Global listing, Seller: " + cleanSeller + ", Buyout: " + (buyoutPrice > 0 ? buyoutPrice : "None") + ", DurationHours: " + hours); + return null; + } + public String cancelListing(String listingId, EntityPlayer player, boolean isAdmin) { AuctionListing listing = listings.get(listingId); if (listing == null) { return "Listing not found."; } - if (!listing.status.canCancel()) { - return "This auction cannot be cancelled."; + if (isAdmin && listing.isGlobalListing) { + return adminStopListingToGlobal(listingId, player, true); } - UUID playerUUID = player.getUniqueID(); - if (!isAdmin && !listing.isSeller(playerUUID)) { - return "You can only cancel your own listings."; + synchronized (listing) { + if (!listing.status.canCancel()) { + return "This auction cannot be cancelled."; + } + + UUID playerUUID = player.getUniqueID(); + if (!isAdmin && !listing.isSeller(playerUUID)) { + return "You can only cancel your own listings."; + } + + // Fire auction cancel event (cancelable) + PlayerDataScript cancelHandler = ScriptController.Instance.getPlayerScripts(player); + IPlayer iCanceller = (IPlayer) NpcAPI.Instance().getIEntity(player); + AuctionEvent.CancelEvent cancelEvent = new AuctionEvent.CancelEvent(iCanceller, listing, isAdmin); + if (EventHooks.onAuctionCancel(cancelHandler, cancelEvent)) { + return "Auction cancellation was prevented."; + } + + // Handle penalty if there are bids + if (listing.hasBids()) { + long penalty = (long) (listing.currentBid * ConfigMarket.CancellationPenaltyPercent); + + // Refund bidder (no item - can't rebid on cancelled auction) + AuctionClaim refundClaim = AuctionClaim.createRefundClaim( + listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid, + listing.item.getDisplayName(), listing.sellerName, null); + addClaimToPlayer(listing.highBidderUUID, refundClaim); + + // Remove from bidder's active bids + removeFromPlayerBids(listing.highBidderUUID, listing.id); + + sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id, + "The auction for " + listing.item.getDisplayName() + " was cancelled. Your bid has been refunded."); + + // Return item to seller + AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim( + listing.sellerUUID, listing.sellerName, listing.id, listing.item); + addClaimToPlayer(listing.sellerUUID, itemClaim); + + // Deduct cancellation penalty from seller + if (penalty > 0) { + PlayerData sellerData = PlayerDataController.Instance.getData(listing.sellerUUID); + if (sellerData != null) { + if (!sellerData.tradeData.withdraw(penalty)) { + // Withdraw whatever they have if they can't cover the full penalty + long available = sellerData.tradeData.getBalance(); + if (available > 0) { + sellerData.tradeData.withdraw(available); + } + } + sellerData.save(); + } + } + + logAuction(EnumAuctionLogAction.CANCELLED, listing.sellerName, listing.item.getDisplayName(), listing.currentBid, + "Penalty: " + penalty + ", Bidder refunded: " + listing.highBidderName + + (isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : "")); + } else { + // No bids - just return item + AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim( + listing.sellerUUID, listing.sellerName, listing.id, listing.item); + addClaimToPlayer(listing.sellerUUID, itemClaim); + + logAuction(EnumAuctionLogAction.CANCELLED, listing.sellerName, listing.item.getDisplayName(), listing.startingPrice, + "No bids" + (isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : "")); + } + + // Remove from seller's active listings + removeFromPlayerListings(listing.sellerUUID, listing.id); + + listing.status = EnumAuctionStatus.CANCELLED; + markDirty(); } - // Handle penalty if there are bids - if (listing.hasBids()) { - long penalty = (long) (listing.currentBid * ConfigMarket.CancellationPenaltyPercent); - - // Refund bidder (no item - can't rebid on cancelled auction) - AuctionClaim refundClaim = AuctionClaim.createRefundClaim( - listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid, - listing.item.getDisplayName(), listing.sellerName, null); - addClaimToPlayer(listing.highBidderUUID, refundClaim); - - // Remove from bidder's active bids - removeFromPlayerBids(listing.highBidderUUID, listing.id); - - sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id, - "The auction for " + listing.item.getDisplayName() + " was cancelled. Your bid has been refunded."); - - // Return item to seller - AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim( - listing.sellerUUID, listing.sellerName, listing.id, listing.item); - addClaimToPlayer(listing.sellerUUID, itemClaim); - - logAuction("CANCELLED", listing.sellerName, listing.item.getDisplayName(), listing.currentBid, - "Penalty: " + penalty + ", Bidder refunded: " + listing.highBidderName + - (isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : "")); - } else { - // No bids - just return item - AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim( - listing.sellerUUID, listing.sellerName, listing.id, listing.item); - addClaimToPlayer(listing.sellerUUID, itemClaim); - - logAuction("CANCELLED", listing.sellerName, listing.item.getDisplayName(), listing.startingPrice, - "No bids" + (isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : "")); - } - - // Remove from seller's active listings - removeFromPlayerListings(listing.sellerUUID, listing.id); - - listing.status = EnumAuctionStatus.CANCELLED; - markDirty(); - return null; // Success } @@ -368,6 +588,11 @@ public class AuctionController implements IAuctionHandler { return "Auction is disabled."; } + // Validate bid amount + if (bidAmount <= 0) { + return "Bid amount must be positive."; + } + UUID playerUUID = player.getUniqueID(); String playerName = player.getCommandSenderName(); @@ -376,84 +601,99 @@ public class AuctionController implements IAuctionHandler { return "Listing not found."; } - // Check status and expiry - if (!listing.status.canBid()) { - return "This auction has ended."; + synchronized (listing) { + // Check status and expiry + if (!listing.status.canBid()) { + return "This auction has ended."; + } + + if (listing.isExpired()) { + return "This auction has ended."; + } + + // CRITICAL: Prevent bidding on own items + if (listing.isSeller(playerUUID)) { + return "You cannot bid on your own auction."; + } + + // Prevent rebidding if already highest bidder + if (listing.isHighBidder(playerUUID)) { + return "You are already the highest bidder. Use buyout if you want to purchase immediately."; + } + + // Check minimum bid + long minBid = listing.getMinimumBid(ConfigMarket.MinBidIncrementPercent); + if (bidAmount < minBid) { + return "Bid must be at least " + minBid + " " + ConfigMarket.CurrencyName + "."; + } + + // Prevent bidding at or above buyout price + if (listing.hasBuyout() && bidAmount >= listing.buyoutPrice) { + return "Your bid meets or exceeds the buyout price. Use Buy Now instead."; + } + + // Check currency + PlayerData playerData = PlayerData.get(player); + if (playerData == null) { + return "Could not access player data."; + } + + PlayerTradeData currency = playerData.tradeData; + + // Store previous bidder info + UUID previousBidder = listing.highBidderUUID; + long previousBid = listing.currentBid; + + // Full bid amount charged since we don't allow rebidding + long amountToCharge = bidAmount; + + if (!currency.canAfford(amountToCharge)) { + return "You cannot afford this bid."; + } + + // Fire auction bid event (cancelable) + PlayerDataScript bidHandler = ScriptController.Instance.getPlayerScripts(player); + IPlayer iBidder = (IPlayer) NpcAPI.Instance().getIEntity(player); + AuctionEvent.BidEvent bidEvent = new AuctionEvent.BidEvent(iBidder, listing, bidAmount); + if (EventHooks.onAuctionBid(bidHandler, bidEvent)) { + return "Bid was cancelled."; + } + + // Deduct bid from new bidder FIRST + if (!currency.withdraw(amountToCharge)) { + return "Failed to deduct bid amount."; + } + + // Refund previous bidder (include item for rebid option) + if (listing.hasBids() && previousBidder != null) { + AuctionClaim refundClaim = AuctionClaim.createRefundClaim( + previousBidder, listing.highBidderName, listing.id, previousBid, + listing.item.getDisplayName(), playerName, listing.item); + addClaimToPlayer(previousBidder, refundClaim); + + // Remove from previous bidder's active bids + removeFromPlayerBids(previousBidder, listing.id); + + sendNotificationToPlayer(previousBidder, EnumNotificationType.AUCTION_OUTBID, listing.id, + "You were outbid on " + listing.item.getDisplayName() + "!"); + } + + // Update listing + listing.highBidderUUID = playerUUID; + listing.highBidderName = playerName; + listing.currentBid = bidAmount; + listing.bidCount++; + + // Add to new bidder's active bids + addToPlayerBids(playerUUID, listing.id); + + // Snipe protection (must be inside sync to prevent race with endAuction) + listing.extendForSnipeProtection(ConfigMarket.SnipeProtectionMinutes); } - if (listing.isExpired()) { - return "This auction has ended."; - } - - // CRITICAL: Prevent bidding on own items - if (listing.isSeller(playerUUID)) { - return "You cannot bid on your own auction."; - } - - // Prevent rebidding if already highest bidder - if (listing.isHighBidder(playerUUID)) { - return "You are already the highest bidder. Use buyout if you want to purchase immediately."; - } - - // Check minimum bid - long minBid = listing.getMinimumBid(ConfigMarket.MinBidIncrementPercent); - if (bidAmount < minBid) { - return "Bid must be at least " + minBid + " " + ConfigMarket.CurrencyName + "."; - } - - // Check currency - PlayerData playerData = PlayerData.get(player); - if (playerData == null) { - return "Could not access player data."; - } - - PlayerTradeData currency = playerData.tradeData; - - // Store previous bidder info - UUID previousBidder = listing.highBidderUUID; - long previousBid = listing.currentBid; - - // Full bid amount charged since we don't allow rebidding - long amountToCharge = bidAmount; - - if (!currency.canAfford(amountToCharge)) { - return "You cannot afford this bid."; - } - - // Deduct bid from new bidder FIRST - if (!currency.withdraw(amountToCharge)) { - return "Failed to deduct bid amount."; - } - - // Refund previous bidder (include item for rebid option) - if (listing.hasBids() && previousBidder != null) { - AuctionClaim refundClaim = AuctionClaim.createRefundClaim( - previousBidder, listing.highBidderName, listing.id, previousBid, - listing.item.getDisplayName(), playerName, listing.item); - addClaimToPlayer(previousBidder, refundClaim); - - // Remove from previous bidder's active bids - removeFromPlayerBids(previousBidder, listing.id); - - sendNotificationToPlayer(previousBidder, EnumNotificationType.AUCTION_OUTBID, listing.id, - "You were outbid on " + listing.item.getDisplayName() + "!"); - } - - // Update listing - listing.highBidderUUID = playerUUID; - listing.highBidderName = playerName; - listing.currentBid = bidAmount; - listing.bidCount++; - - // Add to new bidder's active bids - addToPlayerBids(playerUUID, listing.id); - - // Snipe protection - listing.extendForSnipeProtection(ConfigMarket.SnipeProtectionMinutes); - markDirty(); - logAuction("BID", playerName, listing.item.getDisplayName(), bidAmount, + logAuction(EnumAuctionLogAction.BID, playerName, listing.item.getDisplayName(), bidAmount, "Bids: " + listing.bidCount + ", Seller: " + listing.sellerName); return null; // Success @@ -472,97 +712,115 @@ public class AuctionController implements IAuctionHandler { return "Listing not found."; } - // Check status and expiry - if (!listing.status.canBid()) { - return "This auction has ended."; - } - - if (listing.isExpired()) { - return "This auction has ended."; - } - - if (!listing.hasBuyout()) { - return "This auction does not have a buyout price."; - } - - // CRITICAL: Prevent buying own items - if (listing.isSeller(playerUUID)) { - return "You cannot buy your own auction."; - } - - // Check currency - PlayerData playerData = PlayerData.get(player); - if (playerData == null) { - return "Could not access player data."; - } - - PlayerTradeData currency = playerData.tradeData; - - // If buyer is already the high bidder, only charge the difference - boolean isCurrentBidder = listing.isHighBidder(playerUUID); - long amountToCharge = isCurrentBidder - ? (listing.buyoutPrice - listing.currentBid) - : listing.buyoutPrice; - - if (!currency.canAfford(amountToCharge)) { - if (isCurrentBidder) { - return "You cannot afford the remaining " + amountToCharge + " " + ConfigMarket.CurrencyName + " for buyout."; + synchronized (listing) { + // Check status and expiry + if (!listing.status.canBid()) { + return "This auction has ended."; } - return "You cannot afford the buyout price."; + + if (listing.isExpired()) { + return "This auction has ended."; + } + + if (!listing.hasBuyout()) { + return "This auction does not have a buyout price."; + } + + // CRITICAL: Prevent buying own items + if (listing.isSeller(playerUUID)) { + return "You cannot buy your own auction."; + } + + // Check currency + PlayerData playerData = PlayerData.get(player); + if (playerData == null) { + return "Could not access player data."; + } + + PlayerTradeData currency = playerData.tradeData; + + // If buyer is already the high bidder, only charge the difference + boolean isCurrentBidder = listing.isHighBidder(playerUUID); + long amountToCharge = isCurrentBidder + ? (listing.buyoutPrice - listing.currentBid) + : listing.buyoutPrice; + + if (!currency.canAfford(amountToCharge)) { + if (isCurrentBidder) { + return "You cannot afford the remaining " + amountToCharge + " " + ConfigMarket.CurrencyName + " for buyout."; + } + return "You cannot afford the buyout price."; + } + + // Fire auction buyout event (cancelable) + PlayerDataScript buyoutHandler = ScriptController.Instance.getPlayerScripts(player); + IPlayer iBuyer = (IPlayer) NpcAPI.Instance().getIEntity(player); + AuctionEvent.BuyoutEvent buyoutEvent = new AuctionEvent.BuyoutEvent(iBuyer, listing); + if (EventHooks.onAuctionBuyout(buyoutHandler, buyoutEvent)) { + return "Buyout was cancelled."; + } + + // Deduct buyout amount + if (!currency.withdraw(amountToCharge)) { + return "Failed to deduct buyout amount."; + } + + // Refund previous bidder if any AND they're not the buyer (no item - auction ended via buyout) + if (listing.hasBids() && listing.highBidderUUID != null && !isCurrentBidder) { + AuctionClaim refundClaim = AuctionClaim.createRefundClaim( + listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid, + listing.item.getDisplayName(), playerName, null); + addClaimToPlayer(listing.highBidderUUID, refundClaim); + + // Remove from previous bidder's active bids + removeFromPlayerBids(listing.highBidderUUID, listing.id); + + sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id, + "The auction for " + listing.item.getDisplayName() + " was bought out. Your bid has been refunded."); + } else if (isCurrentBidder) { + // Current bidder is buying out - just remove from their active bids + removeFromPlayerBids(playerUUID, listing.id); + } + + // Create claims + AuctionClaim itemClaim = AuctionClaim.createItemWonClaim(playerUUID, playerName, listing.id, listing.item); + addClaimToPlayer(playerUUID, itemClaim); + + long saleAmount = listing.buyoutPrice; + long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent); + long sellerReceives = saleAmount - tax; + + AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim( + listing.sellerUUID, listing.sellerName, listing.id, sellerReceives, + listing.item.getDisplayName(), playerName); + if (listing.isGlobalListing) { + addGlobalClaim(currencyClaim); + } else { + addClaimToPlayer(listing.sellerUUID, currencyClaim); + } + + // Notifications + if (!listing.isGlobalListing && listing.sellerUUID != null) { + sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id, + "Your " + listing.item.getDisplayName() + " was bought out for " + saleAmount + " " + ConfigMarket.CurrencyName + "!"); + } + + // Remove from seller's active listings + if (!listing.isGlobalListing && listing.sellerUUID != null) { + removeFromPlayerListings(listing.sellerUUID, listing.id); + } + + listing.status = EnumAuctionStatus.ENDED; + listing.highBidderUUID = playerUUID; + listing.highBidderName = playerName; + listing.currentBid = listing.buyoutPrice; + + markDirty(); + + logAuction(EnumAuctionLogAction.BUYOUT, playerName, listing.item.getDisplayName(), listing.buyoutPrice, + "Seller: " + listing.sellerName + ", Tax: " + tax + (listing.isGlobalListing ? ", Global listing" : "")); } - // Deduct buyout amount - if (!currency.withdraw(amountToCharge)) { - return "Failed to deduct buyout amount."; - } - - // Refund previous bidder if any AND they're not the buyer (no item - auction ended via buyout) - if (listing.hasBids() && listing.highBidderUUID != null && !isCurrentBidder) { - AuctionClaim refundClaim = AuctionClaim.createRefundClaim( - listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid, - listing.item.getDisplayName(), playerName, null); - addClaimToPlayer(listing.highBidderUUID, refundClaim); - - // Remove from previous bidder's active bids - removeFromPlayerBids(listing.highBidderUUID, listing.id); - - sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id, - "The auction for " + listing.item.getDisplayName() + " was bought out. Your bid has been refunded."); - } else if (isCurrentBidder) { - // Current bidder is buying out - just remove from their active bids - removeFromPlayerBids(playerUUID, listing.id); - } - - // Create claims - AuctionClaim itemClaim = AuctionClaim.createItemWonClaim(playerUUID, playerName, listing.id, listing.item); - addClaimToPlayer(playerUUID, itemClaim); - - long saleAmount = listing.buyoutPrice; - long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent); - long sellerReceives = saleAmount - tax; - - AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim( - listing.sellerUUID, listing.sellerName, listing.id, sellerReceives, - listing.item.getDisplayName(), playerName); - addClaimToPlayer(listing.sellerUUID, currencyClaim); - - // Notifications - sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id, - "Your " + listing.item.getDisplayName() + " was bought out for " + saleAmount + " " + ConfigMarket.CurrencyName + "!"); - - // Remove from seller's active listings - removeFromPlayerListings(listing.sellerUUID, listing.id); - - listing.status = EnumAuctionStatus.ENDED; - listing.highBidderUUID = playerUUID; - listing.highBidderName = playerName; - listing.currentBid = listing.buyoutPrice; - - markDirty(); - - logAuction("BUYOUT", playerName, listing.item.getDisplayName(), listing.buyoutPrice, - "Seller: " + listing.sellerName + ", Tax: " + tax); - return null; // Success } @@ -592,6 +850,93 @@ public class AuctionController implements IAuctionHandler { return new ArrayList<>(); } + /** + * Paginated global claims used by the global auction admin GUI. + */ + public List getGlobalClaims(int page, int pageSize) { + List snapshot = getGlobalClaimsSnapshot(); + snapshot.sort((a, b) -> Long.compare(b.createdTime, a.createdTime)); + + int safePage = Math.max(0, page); + int safePageSize = Math.max(1, pageSize); + int start = safePage * safePageSize; + if (start >= snapshot.size()) { + return new ArrayList<>(); + } + int end = Math.min(start + safePageSize, snapshot.size()); + return new ArrayList<>(snapshot.subList(start, end)); + } + + public int getTotalGlobalClaims() { + return getGlobalClaimsSnapshot().size(); + } + + public boolean hasGlobalClaims() { + return getTotalGlobalClaims() > 0; + } + + public String claimGlobalItem(String claimId, EntityPlayer player) { + String listingId; + String itemName; + synchronized (globalClaims) { + AuctionClaim claim = getGlobalClaimInternal(claimId); + if (claim == null) { + return "Global claim not found."; + } + if (!claim.type.isItem()) { + return "This global claim is not an item claim."; + } + if (claim.item == null) { + return "Item data is missing."; + } + + // Check inventory space before adding (addItemStackToInventory mutates even on partial add) + if (!canFitInInventory(player, claim.item)) { + return "Not enough inventory space to claim this item."; + } + + // Add to inventory (safe - we verified space above) + player.inventory.addItemStackToInventory(claim.item.copy()); + + listingId = claim.listingId; + itemName = claim.item.getDisplayName(); + claimAndRemoveGlobal(claim.id); + } + cleanupListingIfComplete(listingId); + markDirty(); + + logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), itemName, 0, + "Global item claim"); + return null; + } + + /** + * Global currency claims are acknowledged/cleared and do not alter player balances. + */ + public String claimGlobalCurrency(String claimId, EntityPlayer player) { + String listingId; + long currency; + synchronized (globalClaims) { + AuctionClaim claim = getGlobalClaimInternal(claimId); + if (claim == null) { + return "Global claim not found."; + } + if (!claim.type.isCurrency()) { + return "This global claim is not a currency claim."; + } + + listingId = claim.listingId; + currency = claim.currency; + claimAndRemoveGlobal(claim.id); + } + cleanupListingIfComplete(listingId); + markDirty(); + + logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), ConfigMarket.CurrencyName, currency, + "Global currency claim acknowledged (no balance change)"); + return null; + } + public String claimItem(String claimId, EntityPlayer player) { PlayerData playerData = PlayerData.get(player); if (playerData == null) { @@ -615,11 +960,22 @@ public class AuctionController implements IAuctionHandler { return "Item data is missing."; } - // Check inventory space - if (!player.inventory.addItemStackToInventory(claim.item.copy())) { - return "Your inventory is full."; + // Fire auction claim event (cancelable) + PlayerDataScript itemClaimHandler = ScriptController.Instance.getPlayerScripts(player); + IPlayer iItemClaimer = (IPlayer) NpcAPI.Instance().getIEntity(player); + AuctionEvent.ClaimEvent itemClaimEvent = new AuctionEvent.ClaimEvent(iItemClaimer, claim); + if (EventHooks.onAuctionClaim(itemClaimHandler, itemClaimEvent)) { + return "Claim was prevented."; } + // Check inventory space before adding (addItemStackToInventory mutates even on partial add) + if (!canFitInInventory(player, claim.item)) { + return "Not enough inventory space to claim this item."; + } + + // Add to inventory (safe - we verified space above) + player.inventory.addItemStackToInventory(claim.item.copy()); + // Remove claim from player's auction data playerData.tradeData.claimAndRemove(claimId); playerData.updateClient = true; @@ -628,7 +984,7 @@ public class AuctionController implements IAuctionHandler { // Cleanup listing if no more claims cleanupListingIfComplete(claim.listingId); - logAuction("CLAIMED", player.getCommandSenderName(), claim.item.getDisplayName(), 0, "Item claimed"); + logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), claim.item.getDisplayName(), 0, "Item claimed"); return null; // Success } @@ -652,6 +1008,14 @@ public class AuctionController implements IAuctionHandler { return "This is not a currency claim."; } + // Fire auction claim event (cancelable) + PlayerDataScript currencyClaimHandler = ScriptController.Instance.getPlayerScripts(player); + IPlayer iCurrencyClaimer = (IPlayer) NpcAPI.Instance().getIEntity(player); + AuctionEvent.ClaimEvent currencyClaimEvent = new AuctionEvent.ClaimEvent(iCurrencyClaimer, claim); + if (EventHooks.onAuctionClaim(currencyClaimHandler, currencyClaimEvent)) { + return "Claim was prevented."; + } + if (!playerData.tradeData.deposit(claim.currency)) { return "Failed to deposit currency."; } @@ -664,12 +1028,40 @@ public class AuctionController implements IAuctionHandler { // Cleanup listing if no more claims cleanupListingIfComplete(claim.listingId); - logAuction("CLAIMED", player.getCommandSenderName(), ConfigMarket.CurrencyName, claim.currency, + logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), ConfigMarket.CurrencyName, claim.currency, claim.type == EnumClaimType.REFUND ? "Refund claimed" : "Sale proceeds claimed"); return null; // Success } + /** + * Check if a player's inventory can fit the entire ItemStack without partial adds. + * Unlike addItemStackToInventory, this does NOT mutate the inventory. + */ + private boolean canFitInInventory(EntityPlayer player, ItemStack stack) { + int remaining = stack.stackSize; + int maxStack = stack.getMaxStackSize(); + ItemStack[] mainInventory = player.inventory.mainInventory; + + for (int i = 0; i < mainInventory.length; i++) { + if (remaining <= 0) return true; + + ItemStack slot = mainInventory[i]; + if (slot == null) { + remaining -= Math.min(remaining, maxStack); + } else if (slot.getItem() == stack.getItem() + && slot.getItemDamage() == stack.getItemDamage() + && ItemStack.areItemStackTagsEqual(slot, stack)) { + int spaceInSlot = maxStack - slot.stackSize; + if (spaceInSlot > 0) { + remaining -= Math.min(remaining, spaceInSlot); + } + } + } + + return remaining <= 0; + } + /** * Clean up a listing if it's ended and no longer needed. * Now just removes ended listings after some delay since claims are in PlayerData. @@ -716,6 +1108,7 @@ public class AuctionController implements IAuctionHandler { for (AuctionListing listing : listings.values()) { if (listing.status != EnumAuctionStatus.ACTIVE) continue; + if (listing.isExpired()) continue; // Apply search filter (searches item name AND seller name) if (filter.hasSearchText()) { @@ -766,6 +1159,7 @@ public class AuctionController implements IAuctionHandler { int count = 0; for (AuctionListing listing : listings.values()) { if (listing.status != EnumAuctionStatus.ACTIVE) continue; + if (listing.isExpired()) continue; if (filter.hasSearchText()) { String itemName = listing.item != null ? listing.item.getDisplayName() : ""; String sellerName = listing.sellerName != null ? listing.sellerName : ""; @@ -993,7 +1387,7 @@ public class AuctionController implements IAuctionHandler { if (expired > 0) { playerData.updateClient = true; playerData.save(); - logAuction("CLAIM_EXPIRED", player.getCommandSenderName(), "Multiple", expired, + logAuction(EnumAuctionLogAction.CLAIM_EXPIRED, player.getCommandSenderName(), "Multiple", expired, expired + " claims expired on login"); } } @@ -1030,6 +1424,30 @@ public class AuctionController implements IAuctionHandler { player.addChatMessage(new ChatComponentText(msg.toString())); } + + // Notify admins with permission about pending global claims. + if (CustomNpcsPermissions.hasCustomPermission(player, "customnpcs.global.auction")) { + List global = getGlobalClaimsSnapshot(); + if (!global.isEmpty()) { + int itemClaims = 0; + int currencyClaims = 0; + for (AuctionClaim claim : global) { + if (claim.type.isItem()) { + itemClaims++; + } else { + currencyClaims++; + } + } + + StringBuilder msg = new StringBuilder(); + msg.append(EnumChatFormatting.GOLD).append("[Auction] "); + msg.append(EnumChatFormatting.AQUA).append("Global claims available: "); + msg.append(EnumChatFormatting.GREEN).append(itemClaims).append(" item claim(s)"); + msg.append(EnumChatFormatting.GRAY).append(", "); + msg.append(EnumChatFormatting.YELLOW).append(currencyClaims).append(" currency claim(s)"); + player.addChatMessage(new ChatComponentText(msg.toString())); + } + } } public void onPlayerLogout(UUID playerUUID) { @@ -1041,52 +1459,28 @@ public class AuctionController implements IAuctionHandler { // Logging // ========================================= - private void logAuction(String action, String playerName, String itemName, long amount, String details) { - if (!ConfigMarket.AuctionLoggingEnabled) return; + private void logAuction(EnumAuctionLogAction action, String playerName, String itemName, long amount, String details) { + if (!action.shouldLog()) return; - boolean shouldLog = false; - switch (action) { - case "CREATED": - shouldLog = ConfigMarket.LogAuctionCreated; - break; - case "BID": - shouldLog = ConfigMarket.LogAuctionBid; - break; - case "BUYOUT": - shouldLog = ConfigMarket.LogAuctionBuyout; - break; - case "SOLD": - shouldLog = ConfigMarket.LogAuctionSold; - break; - case "EXPIRED": - shouldLog = ConfigMarket.LogAuctionExpired; - break; - case "CANCELLED": - shouldLog = ConfigMarket.LogAuctionCancelled; - break; - case "CLAIMED": - case "CLAIM_EXPIRED": - shouldLog = ConfigMarket.LogAuctionClaimed; - break; - } - - if (shouldLog) { - String logMessage = String.format("[AUCTION:%s] Player: %s, Item: %s, Amount: %d, Details: %s", - action, playerName, itemName, amount, details); - LogWriter.info(logMessage); - } + String logMessage = String.format("[AUCTION:%s] Player: %s, Item: %s, Amount: %d, Details: %s", + action.name(), playerName, itemName, amount, details); + LogWriter.info(logMessage); } // ========================================= // Save / Load - Async on CNPC+ Thread // ========================================= - /** Mark data as dirty - will be saved on next save cycle */ + /** + * Mark data as dirty - will be saved on next save cycle + */ private void markDirty() { dirty.set(true); } - /** Save synchronously - used for server shutdown */ + /** + * Save synchronously - used for server shutdown + */ public void save() { if (!dirty.compareAndSet(true, false)) { return; // Nothing to save @@ -1094,7 +1488,9 @@ public class AuctionController implements IAuctionHandler { saveInternal(); } - /** Save asynchronously on CNPC+ thread */ + /** + * Save asynchronously on CNPC+ thread + */ public void saveAsync() { if (!dirty.compareAndSet(true, false)) { return; // Nothing to save @@ -1122,7 +1518,9 @@ public class AuctionController implements IAuctionHandler { }); } - /** Internal synchronous save */ + /** + * Internal synchronous save + */ private void saveInternal() { try { NBTTagCompound compound = writeToNBT(new NBTTagCompound()); @@ -1141,7 +1539,9 @@ public class AuctionController implements IAuctionHandler { File fileOld = new File(saveDir, "auction.dat_old"); File fileCurrent = new File(saveDir, "auction.dat"); - CompressedStreamTools.writeCompressed(compound, new FileOutputStream(fileNew)); + try (FileOutputStream fos = new FileOutputStream(fileNew)) { + CompressedStreamTools.writeCompressed(compound, fos); + } // Backup rotation if (fileOld.exists()) fileOld.delete(); @@ -1157,6 +1557,7 @@ public class AuctionController implements IAuctionHandler { public void load() { listings.clear(); + globalClaims.clear(); playerListingIds.clear(); playerBidIds.clear(); @@ -1189,7 +1590,9 @@ public class AuctionController implements IAuctionHandler { } } - /** Rebuild all indices from loaded data */ + /** + * Rebuild all indices from loaded data + */ private void rebuildIndices() { playerListingIds.clear(); playerBidIds.clear(); @@ -1197,7 +1600,9 @@ public class AuctionController implements IAuctionHandler { // Index listings for (AuctionListing listing : listings.values()) { if (listing.status == EnumAuctionStatus.ACTIVE) { - addToPlayerListings(listing.sellerUUID, listing.id); + if (!listing.isGlobalListing && listing.sellerUUID != null) { + addToPlayerListings(listing.sellerUUID, listing.id); + } if (listing.highBidderUUID != null) { addToPlayerBids(listing.highBidderUUID, listing.id); } @@ -1210,27 +1615,50 @@ public class AuctionController implements IAuctionHandler { } private void loadFromFile(File file) throws Exception { - NBTTagCompound compound = CompressedStreamTools.readCompressed(new FileInputStream(file)); + NBTTagCompound compound; + try (FileInputStream fis = new FileInputStream(file)) { + compound = CompressedStreamTools.readCompressed(fis); + } readFromNBT(compound); } public NBTTagCompound writeToNBT(NBTTagCompound compound) { - // Listings only - claims are stored in PlayerData + // Listings + global claims (player claims are stored in PlayerData) NBTTagList listingsList = new NBTTagList(); for (AuctionListing listing : listings.values()) { listingsList.appendTag(listing.writeToNBT(new NBTTagCompound())); } compound.setTag("Listings", listingsList); + NBTTagList globalClaimsList = new NBTTagList(); + for (AuctionClaim claim : globalClaims) { + if (claim != null && !claim.claimed) { + globalClaimsList.appendTag(claim.writeToNBT(new NBTTagCompound())); + } + } + compound.setTag("GlobalClaims", globalClaimsList); + return compound; } public void readFromNBT(NBTTagCompound compound) { + globalClaims.clear(); + NBTTagList listingsList = compound.getTagList("Listings", 10); for (int i = 0; i < listingsList.tagCount(); i++) { AuctionListing listing = AuctionListing.fromNBT(listingsList.getCompoundTagAt(i)); listings.put(listing.id, listing); } + + if (compound.hasKey("GlobalClaims")) { + NBTTagList claimsList = compound.getTagList("GlobalClaims", 10); + for (int i = 0; i < claimsList.tagCount(); i++) { + AuctionClaim claim = AuctionClaim.fromNBT(claimsList.getCompoundTagAt(i)); + if (!claim.claimed) { + globalClaims.add(claim); + } + } + } } // ========================================= @@ -1397,16 +1825,80 @@ public class AuctionController implements IAuctionHandler { return new ArrayList<>(listings.values()); } + /** + * Admin management flow for listings. + * cancelCompletely=false: stop listing and return assets to the original owners' claim pools. + * cancelCompletely=true: cancel listing and route assets to global claims. + */ + public String adminStopListingToGlobal(String listingId, EntityPlayer admin, boolean cancelCompletely) { + AuctionListing listing = listings.get(listingId); + if (listing == null) { + return "Listing not found."; + } + if (admin == null) { + return "Admin player is missing."; + } + + synchronized (listing) { + if (!listing.status.canCancel()) { + return "This auction cannot be managed."; + } + + String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item"; + + // Return active highest bid - always refund to the actual bidder + if (listing.hasBids() && listing.highBidderUUID != null) { + AuctionClaim refundClaim = AuctionClaim.createRefundClaim( + listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid, itemName, + listing.sellerName, null); + addClaimToPlayer(listing.highBidderUUID, refundClaim); + removeFromPlayerBids(listing.highBidderUUID, listing.id); + } + + // Return the listed item. + if (listing.item != null) { + AuctionClaim itemClaim; + if (cancelCompletely || listing.sellerUUID == null) { + itemClaim = AuctionClaim.createItemReturnedClaim( + null, "Global", listing.id, listing.item); + addGlobalClaim(itemClaim); + } else { + itemClaim = AuctionClaim.createItemReturnedClaim( + listing.sellerUUID, listing.sellerName, listing.id, listing.item); + addClaimToPlayer(listing.sellerUUID, itemClaim); + } + } + + if (!listing.isGlobalListing && listing.sellerUUID != null) { + removeFromPlayerListings(listing.sellerUUID, listing.id); + } + + listing.status = cancelCompletely ? EnumAuctionStatus.CANCELLED : EnumAuctionStatus.ENDED; + markDirty(); + + logAuction(EnumAuctionLogAction.CANCELLED, admin.getCommandSenderName(), itemName, listing.currentBid, + (cancelCompletely ? "Admin cancelled to global claims" : "Admin stopped to owner claims") + + ", OriginalSeller: " + listing.sellerName); + } + + return null; + } + public void adminCancelListing(String listingId, EntityPlayer admin, String reason) { - cancelListing(listingId, admin, true); + AuctionListing listing = listings.get(listingId); + String itemName = listing != null && listing.item != null ? listing.item.getDisplayName() : "Unknown"; + adminStopListingToGlobal(listingId, admin, true); + if (reason != null && !reason.isEmpty()) { + logAuction(EnumAuctionLogAction.CANCELLED, admin.getCommandSenderName(), itemName, 0, "Admin cancel - Reason: " + reason); + } } public void clearEndedListings() { // Remove ended/cancelled listings (claims are in PlayerData now) listings.entrySet().removeIf(entry -> entry.getValue().status == EnumAuctionStatus.CLAIMED || - entry.getValue().status == EnumAuctionStatus.ENDED || - entry.getValue().status == EnumAuctionStatus.CANCELLED); + entry.getValue().status == EnumAuctionStatus.ENDED || + entry.getValue().status == EnumAuctionStatus.CANCELLED); // Rebuild indices rebuildIndices(); diff --git a/src/main/java/noppes/npcs/controllers/CategoryManager.java b/src/main/java/noppes/npcs/controllers/CategoryManager.java new file mode 100644 index 000000000..80da9768d --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/CategoryManager.java @@ -0,0 +1,255 @@ +package noppes.npcs.controllers; + +import noppes.npcs.controllers.data.Category; + +import java.io.File; +import java.util.*; +import java.util.Arrays; + +/** + * Filesystem-based category manager for organizing items into named groups. + * Categories are subdirectories within the controller's base directory. + * Items without a category mapping are "Uncategorized" (root-level files). + * + * One instance per controller (Effect, Animation, LinkedItem, Form, Aura, Outline, etc.) + */ +public class CategoryManager { + public static final int UNCATEGORIZED_ID = 0; + public static final String UNCATEGORIZED_NAME = "Uncategorized"; + + private File baseDir; + private final HashMap categories = new HashMap<>(); + private final HashMap itemCategoryMap = new HashMap<>(); + private int lastUsedCatID = 0; + + /** + * Scan the base directory for subdirectories and create Category objects. + * Call at the start of controller loading, before loading items. + */ + public void loadCategories(File baseDir) { + loadCategories(baseDir, new String[0]); + } + + /** + * Scan the base directory for subdirectories and create Category objects, + * excluding any subdirectories whose names match excludeDirs. + */ + public void loadCategories(File baseDir, String... excludeDirs) { + this.baseDir = baseDir; + categories.clear(); + itemCategoryMap.clear(); + lastUsedCatID = 0; + + if (!baseDir.exists()) return; + + Set excludeSet = new HashSet<>(Arrays.asList(excludeDirs)); + File[] files = baseDir.listFiles(); + if (files == null) return; + for (File sub : files) { + if (!sub.isDirectory()) continue; + if (excludeSet.contains(sub.getName())) continue; + lastUsedCatID++; + categories.put(lastUsedCatID, new Category(lastUsedCatID, sub.getName())); + } + } + + /** + * Register an item as belonging to a category. + * Call when loading items from a subdirectory. + */ + public void registerItem(int itemId, int catId) { + if (catId > UNCATEGORIZED_ID) { + itemCategoryMap.put(itemId, catId); + } + } + + public void removeItem(int itemId) { + itemCategoryMap.remove(itemId); + } + + public boolean isLoaded() { + return baseDir != null; + } + + public File getItemDir(int itemId) { + int catId = itemCategoryMap.getOrDefault(itemId, UNCATEGORIZED_ID); + return getCategoryDir(catId); + } + + public File getCategoryDir(int catId) { + if (catId == UNCATEGORIZED_ID) return baseDir; + Category cat = categories.get(catId); + if (cat != null) return new File(baseDir, cat.title); + return baseDir; + } + + public HashMap getCategories() { + return categories; + } + + // ========== Category CRUD ========== + + public Category createCategory(String name) { + if (baseDir == null) return null; + while (hasCategoryName(name)) name += "_"; + lastUsedCatID++; + Category cat = new Category(lastUsedCatID, name); + categories.put(cat.id, cat); + File dir = new File(baseDir, name); + if (!dir.exists()) dir.mkdirs(); + return cat; + } + + public void saveCategory(Category cat) { + if (cat.id <= 0 || baseDir == null) return; + Category existing = categories.get(cat.id); + if (existing != null && !existing.title.equals(cat.title)) { + String newTitle = cat.title; + while (hasCategoryName(newTitle)) newTitle += "_"; + File oldDir = new File(baseDir, existing.title); + File newDir = new File(baseDir, newTitle); + if (oldDir.exists() && !newDir.exists()) { + oldDir.renameTo(newDir); + } + cat.title = newTitle; + } + categories.put(cat.id, cat); + } + + public boolean removeCategory(int catId) { + return removeCategory(catId, null); + } + + public boolean removeCategory(int catId, Set allItemIds) { + if (baseDir == null) return false; + if (catId <= UNCATEGORIZED_ID) return false; + Category cat = categories.get(catId); + if (cat == null) return false; + + // Server-side guard: refuse to delete if category has items + if (allItemIds != null) { + if (!isCategoryEmpty(catId, allItemIds)) return false; + } else { + // Without item set, check if any items are mapped to this category + if (itemCategoryMap.containsValue(catId)) return false; + } + + // Also check filesystem — directory must be empty or non-existent + File dir = new File(baseDir, cat.title); + if (dir.exists()) { + String[] contents = dir.list(); + if (contents != null && contents.length > 0) { + return false; + } + dir.delete(); + } + + categories.remove(catId); + Iterator> it = itemCategoryMap.entrySet().iterator(); + while (it.hasNext()) { + if (it.next().getValue() == catId) { + it.remove(); + } + } + return true; + } + + public void moveItem(int itemId, String fileName, int destCatId) { + if (baseDir == null) return; + int oldCatId = itemCategoryMap.getOrDefault(itemId, UNCATEGORIZED_ID); + if (oldCatId == destCatId) return; + + File oldDir = getCategoryDir(oldCatId); + File newDir = getCategoryDir(destCatId); + if (!newDir.exists()) newDir.mkdirs(); + + File oldFile = new File(oldDir, fileName); + File newFile = new File(newDir, fileName); + if (oldFile.exists()) { + oldFile.renameTo(newFile); + } + + if (destCatId == UNCATEGORIZED_ID) { + itemCategoryMap.remove(itemId); + } else { + itemCategoryMap.put(itemId, destCatId); + } + } + + // ========== Query ========== + + public boolean hasCategoryName(String name) { + for (Category cat : categories.values()) { + if (cat.title.equalsIgnoreCase(name)) return true; + } + return false; + } + + public boolean isCategoryEmpty(int catId, Set allItemIds) { + if (catId == UNCATEGORIZED_ID) { + for (int id : allItemIds) { + if (!itemCategoryMap.containsKey(id)) return false; + } + return true; + } + for (Map.Entry entry : itemCategoryMap.entrySet()) { + if (entry.getValue() == catId && allItemIds.contains(entry.getKey())) return false; + } + return true; + } + + public Category getCategory(int catId) { + return categories.get(catId); + } + + public int getItemCategory(int itemId) { + return itemCategoryMap.getOrDefault(itemId, UNCATEGORIZED_ID); + } + + public List getItemsInCategory(int catId, Set allItemIds) { + List result = new ArrayList<>(); + for (int itemId : allItemIds) { + int assignedCat = itemCategoryMap.getOrDefault(itemId, UNCATEGORIZED_ID); + if (assignedCat == catId) { + result.add(itemId); + } + } + return result; + } + + // ========== Scroll Data ========== + + public Map getCategoryScrollData() { + Map map = new HashMap<>(); + map.put(UNCATEGORIZED_NAME, UNCATEGORIZED_ID); + for (Category cat : categories.values()) { + map.put(cat.title, cat.id); + } + return map; + } + + /** + * Search all directories (root + subdirectories) for a file and delete it. + */ + public void deleteFile(String fileName) { + if (baseDir == null || !baseDir.exists()) return; + + File file = new File(baseDir, fileName); + if (file.exists()) { + file.delete(); + return; + } + + File[] subs = baseDir.listFiles(); + if (subs != null) { + for (File sub : subs) { + if (!sub.isDirectory()) continue; + File subFile = new File(sub, fileName); + if (subFile.exists()) { + subFile.delete(); + return; + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/controllers/CustomEffectController.java b/src/main/java/noppes/npcs/controllers/CustomEffectController.java index d1036dc70..6a465b0ee 100644 --- a/src/main/java/noppes/npcs/controllers/CustomEffectController.java +++ b/src/main/java/noppes/npcs/controllers/CustomEffectController.java @@ -1,7 +1,7 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.SyncController; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; @@ -25,7 +25,9 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -37,11 +39,13 @@ public class CustomEffectController implements ICustomEffectHandler { public static CustomEffectController Instance = new CustomEffectController(); public HashMap> indexMapper = new HashMap<>(); + private HashMap indexLabels = new HashMap<>(); public HashMap customEffectsSync = new HashMap<>(); public HashMap customEffectScriptHandlers = new HashMap<>(); private HashMap bootOrder; + public CategoryManager categoryManager = new CategoryManager(); private int lastUsedID = 0; public ConcurrentHashMap> playerEffects = new ConcurrentHashMap<>(); @@ -59,6 +63,14 @@ public class CustomEffectController implements ICustomEffectHandler { indexMapper.put(index, (HashMap) effectHashMap); } + public void registerEffectMapLabel(int index, String label) { + indexLabels.put(index, label); + } + + public HashMap getIndexLabels() { + return indexLabels; + } + public HashMap getCustomEffects() { return indexMapper.get(0); } @@ -110,16 +122,13 @@ public class CustomEffectController implements ICustomEffectHandler { CustomEffect foundEffect = getCustomEffects().remove(effect.getID()); customEffectScriptHandlers.remove(effect.getID()); if (foundEffect != null && foundEffect.name != null) { - File dir = this.getDir(); - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - if (file.getName().equalsIgnoreCase(foundEffect.name + ".json")) { - file.delete(); - SyncController.syncRemove(EnumSyncType.CUSTOM_EFFECTS, foundEffect.getID()); - break; - } + File dir = categoryManager.getItemDir(id); + File file = new File(dir, foundEffect.name + ".json"); + if (file.exists()) { + file.delete(); } + categoryManager.removeItem(id); + SyncController.syncRemove(SyncType.CUSTOM_EFFECTS, foundEffect.getID()); saveEffectLoadMap(); } } @@ -319,52 +328,66 @@ public class CustomEffectController implements ICustomEffectHandler { File dir = getDir(); if (!dir.exists()) { dir.mkdir(); - } else { - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - try { - CustomEffect effect = new CustomEffect(); - effect.readFromNBT(NBTJsonUtil.LoadFile(file)); - effect.name = file.getName().substring(0, file.getName().length() - 5); - if (effect.id == -1) { - effect.id = getUnusedId(); - } - int originalID = effect.id; - int setID = effect.id; - while (bootOrder.containsKey(setID) || getCustomEffects().containsKey(setID)) { - if (bootOrder.containsKey(setID)) - if (bootOrder.get(setID).equalsIgnoreCase(effect.name)) - break; - setID++; - } - effect.id = setID; - if (originalID != setID) { - LogWriter.info("Found Custom Effect ID Mismatch: " + effect.name + ", New ID: " + setID); - effect.save(); - } - getCustomEffects().put(effect.id, effect); - } catch (Exception e) { - LogWriter.error("Error loading: " + file.getAbsolutePath(), e); - } - } } + + categoryManager.loadCategories(dir); + + // Load uncategorized effects (root level .json files) + loadEffectsFromDir(dir, CategoryManager.UNCATEGORIZED_ID); + + // Load categorized effects (subdirectories) + for (Map.Entry entry : categoryManager.getCategories().entrySet()) { + File catDir = categoryManager.getCategoryDir(entry.getKey()); + loadEffectsFromDir(catDir, entry.getKey()); + } + this.registerEffectMap(0, getCustomEffects()); saveEffectLoadMap(); } - public HashMap getEffectMap(int index) { - if (indexMapper.containsKey(index)) { - return getEffectMap(index); + private void loadEffectsFromDir(File dir, int catId) { + File[] files = dir.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) + continue; + try { + CustomEffect effect = new CustomEffect(); + effect.readFromNBT(NBTJsonUtil.LoadFile(file)); + effect.name = file.getName().substring(0, file.getName().length() - 5); + if (effect.id == -1) { + effect.id = getUnusedId(); + } + int originalID = effect.id; + int setID = effect.id; + while (bootOrder.containsKey(setID) || getCustomEffects().containsKey(setID)) { + if (bootOrder.containsKey(setID)) + if (bootOrder.get(setID).equalsIgnoreCase(effect.name)) + break; + setID++; + } + effect.id = setID; + if (originalID != setID) { + LogWriter.info("Found Custom Effect ID Mismatch: " + effect.name + ", New ID: " + setID); + effect.save(); + } + getCustomEffects().put(effect.id, effect); + categoryManager.registerItem(effect.id, catId); + } catch (Exception e) { + LogWriter.error("Error loading: " + file.getAbsolutePath(), e); + } } - return null; + } + + public HashMap getEffectMap(int index) { + return indexMapper.get(index); } private File getDir() { return new File(CustomNpcs.getWorldSaveDirectory(), "customeffects"); } - private void saveEffectLoadMap() { + public void saveEffectLoadMap() { try { File saveDir = getMapDir(); File file = new File(saveDir, "customeffects.dat_new"); @@ -447,12 +470,7 @@ public class CustomEffectController implements ICustomEffectHandler { } public void deleteEffectFile(String prevName) { - File dir = this.getDir(); - if (!dir.exists()) - dir.mkdirs(); - File file2 = new File(dir, prevName + ".json"); - if (file2.exists()) - file2.delete(); + categoryManager.deleteFile(prevName + ".json"); } // API Versions @@ -484,21 +502,7 @@ public class CustomEffectController implements ICustomEffectHandler { public void deleteEffect(String name) { ICustomEffect effect = getEffect(name); if (effect != null) { - CustomEffect foundEffect = getCustomEffects().remove(effect.getID()); - customEffectScriptHandlers.remove(effect.getID()); - if (foundEffect != null && foundEffect.name != null) { - File dir = this.getDir(); - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - if (file.getName().equalsIgnoreCase(foundEffect.name + ".json")) { - file.delete(); - SyncController.syncRemove(EnumSyncType.CUSTOM_EFFECTS, foundEffect.getID()); - break; - } - } - saveEffectLoadMap(); - } + delete(effect.getID()); } } @@ -626,6 +630,45 @@ public class CustomEffectController implements ICustomEffectHandler { return get(id, index); } + //////////////////////////////////////////////////////// + // CATEGORY HELPERS + //////////////////////////////////////////////////////// + + public Map getCategoryScrollData() { + return categoryManager.getCategoryScrollData(); + } + + public void moveItemToCategory(int itemId, int catId) { + CustomEffect effect = getCustomEffects().get(itemId); + if (effect == null) return; + categoryManager.moveItem(itemId, effect.name + ".json", catId); + saveEffectLoadMap(); + } + + public Map getItemsByCategoryScrollData(int catId) { + Map map = new HashMap<>(); + List itemIds = categoryManager.getItemsInCategory(catId, getCustomEffects().keySet()); + for (int itemId : itemIds) { + CustomEffect effect = getCustomEffects().get(itemId); + if (effect != null) { + map.put(effect.name, effect.id); + } + } + return map; + } + + public HashMap> getItemTagMapForCategory(int catId) { + HashMap> tagMap = new HashMap<>(); + List itemIds = categoryManager.getItemsInCategory(catId, getCustomEffects().keySet()); + for (int itemId : itemIds) { + CustomEffect effect = getCustomEffects().get(itemId); + if (effect != null && !effect.tagUUIDs.isEmpty()) { + tagMap.put(effect.name, effect.tagUUIDs); + } + } + return tagMap; + } + @Override public ICustomEffect saveEffect(ICustomEffect customEffect) { if (customEffect.getID() < 0) { @@ -637,12 +680,13 @@ public class CustomEffectController implements ICustomEffectHandler { while (hasOther(customEffect.getName(), customEffect.getID())) customEffect.setName(customEffect.getName() + "_"); + TagController.validateTagUUIDs(((CustomEffect) customEffect).tagUUIDs); getCustomEffects().remove(customEffect.getID()); getCustomEffects().put(customEffect.getID(), (CustomEffect) customEffect); saveEffectLoadMap(); - File dir = this.getDir(); + File dir = categoryManager.getItemDir(customEffect.getID()); if (!dir.exists()) dir.mkdirs(); @@ -656,11 +700,36 @@ public class CustomEffectController implements ICustomEffectHandler { file2.delete(); file.renameTo(file2); nbtTagCompound.removeTag("ScriptData"); - SyncController.syncUpdate(EnumSyncType.CUSTOM_EFFECTS, -1, nbtTagCompound); + SyncController.syncUpdate(SyncType.CUSTOM_EFFECTS, -1, nbtTagCompound); } catch (Exception e) { LogWriter.except(e); } return getCustomEffects().get(customEffect.getID()); } + public CustomEffect cloneEffect(int originalId) { + CustomEffect original = getCustomEffects().get(originalId); + if (original == null) return null; + + int originalCatId = categoryManager.getItemCategory(originalId); + + NBTTagCompound nbt = original.writeToNBT(true); + int newId = getUnusedId(); + nbt.setInteger("ID", newId); + + CustomEffect clone = new CustomEffect(); + clone.readFromNBT(nbt); + + String name = clone.getName(); + while (has(name)) name += "_"; + clone.name = name; + + if (originalCatId > CategoryManager.UNCATEGORIZED_ID) { + categoryManager.registerItem(newId, originalCatId); + } + + saveEffect(clone); + return clone; + } + } diff --git a/src/main/java/noppes/npcs/controllers/DialogController.java b/src/main/java/noppes/npcs/controllers/DialogController.java index 3490735f3..b65e1ef5e 100644 --- a/src/main/java/noppes/npcs/controllers/DialogController.java +++ b/src/main/java/noppes/npcs/controllers/DialogController.java @@ -1,7 +1,8 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.SyncController; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.controllers.sync.handlers.DialogCategorySyncHandler; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -75,6 +76,7 @@ public class DialogController implements IDialogHandler { if (!file.isDirectory()) continue; DialogCategory category = loadCategoryDir(file); + List

reassigned = new ArrayList(); Iterator ite = category.dialogs.keySet().iterator(); while (ite.hasNext()) { int id = ite.next(); @@ -82,12 +84,48 @@ public class DialogController implements IDialogHandler { lastUsedDialogID = id; Dialog dialog = category.dialogs.get(id); if (dialogs.containsKey(id)) { - LogWriter.error("Duplicate id " + dialog.id + " from category " + category.title); + // Dialog IDs live in the filename, not inside the JSON body, + // so a simple rename permanently resolves the conflict. + File catDir = new File(getDir(), category.title); + + // Find the next free ID. It has to clear three things: the ids already + // registered globally, the ids this category still holds but has not + // reached yet, and any file already on disk - renameTo overwrites + // silently on POSIX, so landing on an existing file would destroy it. + int newId = lastUsedDialogID; + do { + newId++; + } while (dialogs.containsKey(newId) + || category.dialogs.containsKey(newId) + || new File(catDir, newId + ".json").exists()); + lastUsedDialogID = newId; + + File oldFile = new File(catDir, id + ".json"); + File newFile = new File(catDir, newId + ".json"); + boolean renamed = oldFile.renameTo(newFile); + + dialog.id = newId; ite.remove(); + reassigned.add(dialog); + + if (renamed) { + LogWriter.info("Dialog ID conflict: reassigned \"" + dialog.title + + "\" from id " + id + " to " + newId + + " in category \"" + category.title + "\""); + } else { + LogWriter.error("Dialog ID conflict: could not rename file for \"" + + dialog.title + "\" (id " + id + + " in category \"" + category.title + "\") to " + newId); + } } else { dialogs.put(id, dialog); } } + // Re-register reassigned dialogs under their new IDs. + for (Dialog dialog : reassigned) { + dialogs.put(dialog.id, dialog); + category.dialogs.put(dialog.id, dialog); + } lastUsedCatID++; category.id = lastUsedCatID; categories.put(category.id, category); @@ -239,7 +277,7 @@ public class DialogController implements IDialogHandler { dir.mkdirs(); } categories.put(category.id, category); - SyncController.syncUpdate(EnumSyncType.DIALOG_CATEGORY, -1, SyncController.updateDialogCat(category)); + SyncController.syncUpdate(SyncType.DIALOG_CATEGORY, -1, DialogCategorySyncHandler.serializeCategory(category)); } public void removeCategory(int category) { @@ -252,7 +290,7 @@ public class DialogController implements IDialogHandler { for (int dia : cat.dialogs.keySet()) dialogs.remove(dia); categories.remove(category); - SyncController.syncRemove(EnumSyncType.DIALOG_CATEGORY, category); + SyncController.syncRemove(SyncType.DIALOG_CATEGORY, category); } private boolean containsCategoryName(String name) { @@ -302,7 +340,7 @@ public class DialogController implements IDialogHandler { if (file2.exists()) file2.delete(); file.renameTo(file2); - SyncController.syncUpdate(EnumSyncType.DIALOG, category.id, dialog.writeToNBT(new NBTTagCompound())); + SyncController.syncUpdate(SyncType.DIALOG, category.id, dialog.writeToNBT(new NBTTagCompound())); } catch (Exception e) { LogWriter.except(e); } @@ -316,7 +354,7 @@ public class DialogController implements IDialogHandler { return; category.dialogs.remove(dialog.id); dialogs.remove(dialog.id); - SyncController.syncRemove(EnumSyncType.DIALOG, dialog.id); + SyncController.syncRemove(SyncType.DIALOG, dialog.id); } private File getDir() { diff --git a/src/main/java/noppes/npcs/controllers/FactionController.java b/src/main/java/noppes/npcs/controllers/FactionController.java index 9ddf860ea..7da2ebe67 100644 --- a/src/main/java/noppes/npcs/controllers/FactionController.java +++ b/src/main/java/noppes/npcs/controllers/FactionController.java @@ -1,7 +1,7 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.SyncController; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -159,7 +159,7 @@ public class FactionController implements IFactionHandler { NBTTagCompound facCompound = new NBTTagCompound(); faction.writeNBT(facCompound); - SyncController.syncUpdate(EnumSyncType.FACTION, -1, facCompound); + SyncController.syncUpdate(SyncType.FACTION, -1, facCompound); saveFactions(); } @@ -195,7 +195,7 @@ public class FactionController implements IFactionHandler { } else { this.saveFactions(); faction.id = -1; - SyncController.syncRemove(EnumSyncType.FACTION, id); + SyncController.syncRemove(SyncType.FACTION, id); return faction; } } else { diff --git a/src/main/java/noppes/npcs/controllers/HookDefinition.java b/src/main/java/noppes/npcs/controllers/HookDefinition.java index 864e37ee3..be6c09397 100644 --- a/src/main/java/noppes/npcs/controllers/HookDefinition.java +++ b/src/main/java/noppes/npcs/controllers/HookDefinition.java @@ -148,9 +148,9 @@ public class HookDefinition implements IHookDefinition { } // Build required imports from event type - String importName = getImportForClass(eventType); - if (importName != null) { - builder.requiredImports(importName); + String[] importNames = getImportsForClass(eventType); + if (importNames.length > 0) { + builder.requiredImports(importNames); } } @@ -185,26 +185,31 @@ public class HookDefinition implements IHookDefinition { } /** - * Get the import statement needed for a class. - * For nested classes, returns the enclosing class. + * Get the import statements needed for a class. + * For nested classes, includes both enclosing and nested names. */ - private static String getImportForClass(Class clazz) { + private static String[] getImportsForClass(Class clazz) { if (clazz == null || clazz.isPrimitive()) { - return null; + return new String[0]; + } + + String fullName = clazz.getName(); + if (fullName.startsWith("java.lang.")) { + return new String[0]; } - // For nested classes, get the top-level enclosing class Class enclosing = clazz; while (enclosing.getEnclosingClass() != null) { enclosing = enclosing.getEnclosingClass(); } - String name = enclosing.getName(); - if (name.startsWith("java.lang.")) { - return null; + String enclosingName = enclosing.getName(); + String nestedName = fullName.replace('$', '.'); + if (!nestedName.equals(enclosingName)) { + return new String[]{enclosingName, nestedName}; } - return name; + return new String[]{enclosingName}; } // ==================== Builder ==================== @@ -231,9 +236,9 @@ public class HookDefinition implements IHookDefinition { if (clazz != null) { this.eventClassName = clazz.getName(); - String importName = getImportForClass(clazz); - if (importName != null) { - this.requiredImports = new String[]{importName}; + String[] importNames = getImportsForClass(clazz); + if (importNames.length > 0) { + this.requiredImports = importNames; } if (clazz.isAnnotationPresent(Cancelable.class)) { diff --git a/src/main/java/noppes/npcs/controllers/LinkedItemController.java b/src/main/java/noppes/npcs/controllers/LinkedItemController.java index 78534a82f..f4e994c2c 100644 --- a/src/main/java/noppes/npcs/controllers/LinkedItemController.java +++ b/src/main/java/noppes/npcs/controllers/LinkedItemController.java @@ -5,6 +5,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import noppes.npcs.CustomNpcs; import noppes.npcs.LogWriter; +import noppes.npcs.api.handler.ILinkedItemHandler; import noppes.npcs.api.handler.data.ILinkedItem; import noppes.npcs.api.item.IItemStack; import noppes.npcs.controllers.data.IScriptHandler; @@ -19,9 +20,13 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.zip.GZIPInputStream; -public class LinkedItemController { +public class LinkedItemController implements ILinkedItemHandler { private static LinkedItemController Instance; private int lastUsedID = 0; @@ -29,6 +34,7 @@ public class LinkedItemController { public HashMap linkedItemsScripts = new HashMap<>(); private HashMap bootOrder; + public CategoryManager categoryManager = new CategoryManager(); private LinkedItemController() { } @@ -40,25 +46,28 @@ public class LinkedItemController { return Instance; } - public LinkedItem createItem(String name) { + @Override + public ILinkedItem createItem(String name) { return new LinkedItem(name); } + @Override public IItemStack createItemStack(int id) { - LinkedItem linkedItem = this.get(id); + LinkedItem linkedItem = (LinkedItem) this.get(id); if (linkedItem != null) { return linkedItem.createStack(); } return null; } - public void add(LinkedItem linkedItem) { + @Override + public void add(ILinkedItem linkedItem) { if (linkedItem != null) { String name = linkedItem.getName(); if (name != null && !name.isEmpty()) { int linkedItemId = linkedItem.getId(); int id = this.linkedItems.containsKey(linkedItemId) ? linkedItemId : this.getUnusedId(); - this.linkedItems.put(id, linkedItem); + this.linkedItems.put(id, (LinkedItem) linkedItem); linkedItem.setId(id); this.addScript(id); } @@ -69,6 +78,7 @@ public class LinkedItemController { this.linkedItemsScripts.put(id, new LinkedItemScript()); } + @Override public LinkedItem remove(int id) { this.removeScript(id); return this.linkedItems.remove(id); @@ -78,16 +88,19 @@ public class LinkedItemController { this.linkedItemsScripts.remove(id); } + @Override public LinkedItem get(int id) { - return this.linkedItems.get(id); + return (LinkedItem) this.linkedItems.get(id); } + @Override public boolean contains(int id) { return this.linkedItems.containsKey(id); } - public boolean contains(LinkedItem linkedItem) { - return this.linkedItems.containsValue(linkedItem); + @Override + public boolean contains(ILinkedItem linkedItem) { + return this.linkedItems.containsValue((LinkedItem) linkedItem); } public IScriptHandler getScriptHandler(int id) { @@ -113,45 +126,61 @@ public class LinkedItemController { File dir = getDir(); if (!dir.exists()) { dir.mkdir(); - } else { - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - try { - LinkedItem linkedItem = new LinkedItem(); - linkedItem.readFromNBT(NBTJsonUtil.LoadFile(file)); - linkedItem.name = file.getName().substring(0, file.getName().length() - 5); + } - if (linkedItem.id == -1) { - linkedItem.id = getUnusedId(); - } + categoryManager.loadCategories(dir); - int originalID = linkedItem.id; - int setID = linkedItem.id; - while (bootOrder.containsKey(setID) || linkedItems.containsKey(setID)) { - if (bootOrder.containsKey(setID)) - if (bootOrder.get(setID).equals(linkedItem.name)) - break; + // Load uncategorized items (root level .json files) + loadItemsFromDir(dir, CategoryManager.UNCATEGORIZED_ID); - setID++; - } - - linkedItem.id = setID; - if (originalID != setID) { - LogWriter.info("Found Linked Item ID Mismatch: " + linkedItem.name + ", New ID: " + setID); - linkedItem.save(); - } - - linkedItems.put(linkedItem.id, linkedItem); - } catch (Exception e) { - LogWriter.error("Error loading: " + file.getAbsolutePath(), e); - } - } + // Load categorized items (subdirectories) + for (Map.Entry entry : categoryManager.getCategories().entrySet()) { + File catDir = categoryManager.getCategoryDir(entry.getKey()); + loadItemsFromDir(catDir, entry.getKey()); } saveLinkedItemsMap(); } + private void loadItemsFromDir(File dir, int catId) { + File[] files = dir.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) + continue; + try { + LinkedItem linkedItem = new LinkedItem(); + linkedItem.readFromNBT(NBTJsonUtil.LoadFile(file)); + linkedItem.name = file.getName().substring(0, file.getName().length() - 5); + + if (linkedItem.id == -1) { + linkedItem.id = getUnusedId(); + } + + int originalID = linkedItem.id; + int setID = linkedItem.id; + while (bootOrder.containsKey(setID) || linkedItems.containsKey(setID)) { + if (bootOrder.containsKey(setID)) + if (bootOrder.get(setID).equals(linkedItem.name)) + break; + + setID++; + } + + linkedItem.id = setID; + if (originalID != setID) { + LogWriter.info("Found Linked Item ID Mismatch: " + linkedItem.name + ", New ID: " + setID); + linkedItem.save(); + } + + linkedItems.put(linkedItem.id, linkedItem); + categoryManager.registerItem(linkedItem.id, catId); + } catch (Exception e) { + LogWriter.error("Error loading: " + file.getAbsolutePath(), e); + } + } + } + private File getDir() { return new File(CustomNpcs.getWorldSaveDirectory(), "linkeditems"); } @@ -187,12 +216,13 @@ public class LinkedItemController { while (hasOther(linkedItem.getName(), linkedItem.getId())) linkedItem.setName(linkedItem.getName() + "_"); + TagController.validateTagUUIDs(((LinkedItem) linkedItem).tagUUIDs); linkedItems.remove(linkedItem.getId()); linkedItems.put(linkedItem.getId(), (LinkedItem) linkedItem); saveLinkedItemsMap(); // Save Linked Item File - File dir = this.getDir(); + File dir = categoryManager.getItemDir(linkedItem.getId()); if (!dir.exists()) dir.mkdirs(); @@ -210,6 +240,31 @@ public class LinkedItemController { return linkedItems.get(linkedItem.getId()); } + public LinkedItem cloneLinkedItem(int originalId) { + LinkedItem original = linkedItems.get(originalId); + if (original == null) return null; + + int originalCatId = categoryManager.getItemCategory(originalId); + + NBTTagCompound nbt = original.writeToNBT(true); + int newId = getUnusedId(); + nbt.setInteger("Id", newId); + + LinkedItem clone = new LinkedItem(); + clone.readFromNBT(nbt); + + String name = clone.getName(); + while (hasName(name)) name += "_"; + clone.name = name; + + if (originalCatId > CategoryManager.UNCATEGORIZED_ID) { + categoryManager.registerItem(newId, originalCatId); + } + + saveLinkedItem(clone); + return clone; + } + private boolean hasOther(String name, int id) { for (LinkedItem linkedItem : linkedItems.values()) { if (linkedItem.getId() != id && linkedItem.getName().equalsIgnoreCase(name)) @@ -219,31 +274,23 @@ public class LinkedItemController { } public void delete(int id) { - LinkedItem linkedItem = get(id); + LinkedItem linkedItem = (LinkedItem) get(id); if (linkedItem != null) { LinkedItem foundItem = remove(id); if (foundItem != null && foundItem.name != null) { - File dir = this.getDir(); - for (File file : dir.listFiles()) { - if (!file.isFile() || !file.getName().endsWith(".json")) - continue; - if (file.getName().equalsIgnoreCase(foundItem.name + ".json")) { - file.delete(); - break; - } + File dir = categoryManager.getItemDir(id); + File file = new File(dir, foundItem.name + ".json"); + if (file.exists()) { + file.delete(); } + categoryManager.removeItem(id); saveLinkedItemsMap(); } } } public void deleteLinkedItemFile(String prevName) { - File dir = this.getDir(); - if (!dir.exists()) - dir.mkdirs(); - File file2 = new File(dir, prevName + ".json"); - if (file2.exists()) - file2.delete(); + categoryManager.deleteFile(prevName + ".json"); } @@ -342,5 +389,41 @@ public class LinkedItemController { } //////////////////////////////////////////////////////// + // CATEGORY HELPERS //////////////////////////////////////////////////////// + + public Map getCategoryScrollData() { + return categoryManager.getCategoryScrollData(); + } + + public void moveItemToCategory(int itemId, int catId) { + LinkedItem item = linkedItems.get(itemId); + if (item == null) return; + categoryManager.moveItem(itemId, item.name + ".json", catId); + saveLinkedItemsMap(); + } + + public Map getItemsByCategoryScrollData(int catId) { + Map map = new HashMap<>(); + List itemIds = categoryManager.getItemsInCategory(catId, linkedItems.keySet()); + for (int itemId : itemIds) { + LinkedItem item = linkedItems.get(itemId); + if (item != null) { + map.put(item.name, item.id); + } + } + return map; + } + + public HashMap> getItemTagMapForCategory(int catId) { + HashMap> tagMap = new HashMap<>(); + List itemIds = categoryManager.getItemsInCategory(catId, linkedItems.keySet()); + for (int itemId : itemIds) { + LinkedItem item = linkedItems.get(itemId); + if (item != null && !item.tagUUIDs.isEmpty()) { + tagMap.put(item.name, item.tagUUIDs); + } + } + return tagMap; + } } diff --git a/src/main/java/noppes/npcs/controllers/LinkedNpcController.java b/src/main/java/noppes/npcs/controllers/LinkedNpcController.java index 8873f256f..768b8d375 100644 --- a/src/main/java/noppes/npcs/controllers/LinkedNpcController.java +++ b/src/main/java/noppes/npcs/controllers/LinkedNpcController.java @@ -136,6 +136,7 @@ public class LinkedNpcController { npc.ais.readToNBT(compound); npc.transform.readToNBT(compound); + npc.abilities.readFromNBT(compound); npc.ais.setMovingPath(points); npc.updateClient = true; } @@ -161,6 +162,7 @@ public class LinkedNpcController { npc.ais.writeToNBT(compound); npc.advanced.writeToNBT(compound); npc.transform.writeToNBT(compound); + npc.abilities.writeToNBT(compound); compound.setTag("ModelData", ((EntityCustomNpc) npc).modelData.writeToNBT()); return compound; } diff --git a/src/main/java/noppes/npcs/controllers/MagicController.java b/src/main/java/noppes/npcs/controllers/MagicController.java index 40febf172..dff89d015 100644 --- a/src/main/java/noppes/npcs/controllers/MagicController.java +++ b/src/main/java/noppes/npcs/controllers/MagicController.java @@ -1,7 +1,7 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.SyncController; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; @@ -275,7 +275,7 @@ public class MagicController implements IMagicHandler { NBTTagCompound magicCompound = new NBTTagCompound(); mag.writeNBT(magicCompound); - SyncController.syncUpdate(EnumSyncType.MAGIC, -1, magicCompound); + SyncController.syncUpdate(SyncType.MAGIC, -1, magicCompound); saveMagicData(); } @@ -283,7 +283,7 @@ public class MagicController implements IMagicHandler { public void removeMagic(int magicID) { if (magics.containsKey(magicID)) { magics.remove(magicID); - SyncController.syncRemove(EnumSyncType.MAGIC, magicID); + SyncController.syncRemove(SyncType.MAGIC, magicID); saveMagicData(); } } @@ -345,7 +345,7 @@ public class MagicController implements IMagicHandler { NBTTagCompound cycleCompound = new NBTTagCompound(); cycle.writeNBT(cycleCompound); - SyncController.syncUpdate(EnumSyncType.MAGIC_CYCLE, -1, cycleCompound); + SyncController.syncUpdate(SyncType.MAGIC_CYCLE, -1, cycleCompound); saveMagicData(); } @@ -353,7 +353,7 @@ public class MagicController implements IMagicHandler { public void removeCycle(int categoryId) { if (cycles.containsKey(categoryId)) { cycles.remove(categoryId); - SyncController.syncRemove(EnumSyncType.MAGIC_CYCLE, categoryId); + SyncController.syncRemove(SyncType.MAGIC_CYCLE, categoryId); saveMagicData(); } } diff --git a/src/main/java/noppes/npcs/controllers/PlayerQuestController.java b/src/main/java/noppes/npcs/controllers/PlayerQuestController.java index 7b99f40d8..cb3fce39f 100644 --- a/src/main/java/noppes/npcs/controllers/PlayerQuestController.java +++ b/src/main/java/noppes/npcs/controllers/PlayerQuestController.java @@ -1,6 +1,7 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.ProfileController; +import noppes.npcs.client.ProfileClientConfig; import kamkeel.npcs.network.packets.data.AchievementPacket; import kamkeel.npcs.network.packets.data.ChatAlertPacket; import net.minecraft.entity.player.EntityPlayer; @@ -91,7 +92,9 @@ public class PlayerQuestController { questData.finishedQuests.put(quest.id, completeTime); } - if (ConfigMain.ProfilesEnabled && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) + if (ConfigMain.ProfilesEnabled && quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) ProfileController.Instance.shareQuestCompletion(player, quest.id, completeTime); } @@ -125,27 +128,27 @@ public class PlayerQuestController { if (data.activeQuests.containsKey(quest.id)) return false; - if (!data.finishedQuests.containsKey(quest.id) || quest.repeat == EnumQuestRepeat.REPEATABLE) + boolean finishedLocally = data.finishedQuests.containsKey(quest.id); + boolean completedShared = false; + boolean hasCooldownShared = false; + if (ProfileClientConfig.isProfilesEnabled() && quest.profileOptions.enableOptions + && ProfileClientConfig.hasSharedQuest(player, quest.id)) { + if (quest.profileOptions.completeControl == EnumProfileSync.Shared) + completedShared = true; + if (quest.profileOptions.cooldownControl == EnumProfileSync.Shared) + hasCooldownShared = true; + } + + boolean isFinished = finishedLocally || completedShared; + + if (!isFinished && !hasCooldownShared) + return true; + if (quest.repeat == EnumQuestRepeat.REPEATABLE) return true; if (quest.repeat == EnumQuestRepeat.NONE) - return false; + return !isFinished; - long questTime = data.finishedQuests.get(quest.id); - - if (quest.repeat == EnumQuestRepeat.MCDAILY) { - return player.worldObj.getTotalWorldTime() - questTime >= 24000; - } else if (quest.repeat == EnumQuestRepeat.MCWEEKLY) { - return player.worldObj.getTotalWorldTime() - questTime >= 168000; - } else if (quest.repeat == EnumQuestRepeat.MCCUSTOM) { - return player.worldObj.getTotalWorldTime() - questTime >= quest.customCooldown; - } else if (quest.repeat == EnumQuestRepeat.RLDAILY) { - return System.currentTimeMillis() - questTime >= 86400000; - } else if (quest.repeat == EnumQuestRepeat.RLWEEKLY) { - return System.currentTimeMillis() - questTime >= 604800000; - } else if (quest.repeat == EnumQuestRepeat.RLCUSTOM) { - return System.currentTimeMillis() - questTime >= quest.customCooldown; - } - return false; + return quest.getTimeUntilRepeat(player) <= 0; } public static Vector getActiveQuests(EntityPlayer player) { diff --git a/src/main/java/noppes/npcs/controllers/ProfileConfigSync.java b/src/main/java/noppes/npcs/controllers/ProfileConfigSync.java new file mode 100644 index 000000000..5291ff1fd --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/ProfileConfigSync.java @@ -0,0 +1,34 @@ +package noppes.npcs.controllers; + +import kamkeel.npcs.controllers.ProfileController; +import kamkeel.npcs.controllers.data.profile.Profile; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.config.ConfigMain; + +import java.util.Map; + +public class ProfileConfigSync { + public static NBTTagCompound writeToNBT(EntityPlayer player) { + NBTTagCompound compound = new NBTTagCompound(); + if (!ConfigMain.ProfilesEnabled || ProfileController.Instance == null) { + return compound; + } + + Profile profile = ProfileController.Instance.getProfile(player); + if (profile == null) { + return compound; + } + + NBTTagList questList = new NBTTagList(); + for (Map.Entry entry : profile.sharedQuestTimestamps.entrySet()) { + NBTTagCompound questEntry = new NBTTagCompound(); + questEntry.setInteger("Quest", entry.getKey()); + questEntry.setLong("Date", entry.getValue()); + questList.appendTag(questEntry); + } + compound.setTag("SharedQuestTimestamps", questList); + return compound; + } +} diff --git a/src/main/java/noppes/npcs/controllers/QuestController.java b/src/main/java/noppes/npcs/controllers/QuestController.java index 72688b7e5..3d9b707b3 100644 --- a/src/main/java/noppes/npcs/controllers/QuestController.java +++ b/src/main/java/noppes/npcs/controllers/QuestController.java @@ -1,7 +1,8 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.SyncController; -import kamkeel.npcs.network.enums.EnumSyncType; +import kamkeel.npcs.controllers.sync.handlers.QuestCategorySyncHandler; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -69,6 +70,7 @@ public class QuestController implements IQuestHandler { if (!file.isDirectory()) continue; QuestCategory category = loadCategoryDir(file); + List reassigned = new ArrayList(); Iterator ite = category.quests.keySet().iterator(); while (ite.hasNext()) { int id = ite.next(); @@ -76,15 +78,58 @@ public class QuestController implements IQuestHandler { lastUsedQuestID = id; Quest quest = category.quests.get(id); if (quests.containsKey(id)) { - LogWriter.error("Duplicate id " + quest.id + " from category " + category.title); + // Quest IDs live in the filename, not inside the JSON body, + // so a simple rename permanently resolves the conflict. + File catDir = new File(getDir(), category.title); + + // Find the next free ID. It has to clear three things: the ids already + // registered globally, the ids this category still holds but has not + // reached yet, and any file already on disk - renameTo overwrites + // silently on POSIX, so landing on an existing file would destroy it. + int newId = lastUsedQuestID; + do { + newId++; + } while (quests.containsKey(newId) + || category.quests.containsKey(newId) + || new File(catDir, newId + ".json").exists()); + lastUsedQuestID = newId; + + File oldFile = new File(catDir, id + ".json"); + File newFile = new File(catDir, newId + ".json"); + boolean renamed = oldFile.renameTo(newFile); + + quest.id = newId; ite.remove(); + reassigned.add(quest); + + if (renamed) { + LogWriter.info("Quest ID conflict: reassigned \"" + quest.title + + "\" from id " + id + " to " + newId + + " in category \"" + category.title + "\""); + } else { + LogWriter.error("Quest ID conflict: could not rename file for \"" + + quest.title + "\" (id " + id + + " in category \"" + category.title + "\") to " + newId); + } } else { quests.put(id, quest); - if (quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) { + if (quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) { sharedQuests.put(id, quest); } } } + // Re-register reassigned quests under their new IDs. + for (Quest quest : reassigned) { + quests.put(quest.id, quest); + category.quests.put(quest.id, quest); + if (quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) { + sharedQuests.put(quest.id, quest); + } + } lastUsedCatID++; category.id = lastUsedCatID; categories.put(category.id, category); @@ -156,7 +201,7 @@ public class QuestController implements IQuestHandler { for (int dia : cat.quests.keySet()) quests.remove(dia); categories.remove(category); - SyncController.syncRemove(EnumSyncType.QUEST_CATEGORY, category); + SyncController.syncRemove(SyncType.QUEST_CATEGORY, category); } public void saveCategory(QuestCategory category) { @@ -186,7 +231,7 @@ public class QuestController implements IQuestHandler { dir.mkdirs(); } categories.put(category.id, category); - SyncController.syncUpdate(EnumSyncType.QUEST_CATEGORY, -1, SyncController.updateQuestCat(category)); + SyncController.syncUpdate(SyncType.QUEST_CATEGORY, -1, QuestCategorySyncHandler.serializeCategory(category)); } private boolean containsCategoryName(String name) { @@ -225,7 +270,9 @@ public class QuestController implements IQuestHandler { category.quests.put(quest.id, quest); sharedQuests.remove(quest.id); - if (quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) { + if (quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) { sharedQuests.put(quest.id, quest); } @@ -241,7 +288,7 @@ public class QuestController implements IQuestHandler { if (file2.exists()) file2.delete(); file.renameTo(file2); - SyncController.syncUpdate(EnumSyncType.QUEST, category.id, quest.writeToNBT(new NBTTagCompound())); + SyncController.syncUpdate(SyncType.QUEST, category.id, quest.writeToNBT(new NBTTagCompound())); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/noppes/npcs/controllers/RecipeController.java b/src/main/java/noppes/npcs/controllers/RecipeController.java index 7fccdec93..621726927 100644 --- a/src/main/java/noppes/npcs/controllers/RecipeController.java +++ b/src/main/java/noppes/npcs/controllers/RecipeController.java @@ -1,6 +1,7 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.network.enums.SyncType; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; @@ -282,12 +283,12 @@ public class RecipeController implements IRecipeHandler { return null; RecipeCarpentry globalRecipe = globalRecipes.remove(recipe.id); if (globalRecipe != null) - SyncController.syncAllWorkbenchRecipes(); + SyncController.syncAll(SyncType.WORKBENCH_RECIPES); RecipeCarpentry carpentry = carpentryRecipes.remove(recipe.id); if (carpentry != null) { carpentryScripts.remove(recipe.id); - SyncController.syncAllCarpentryRecipes(); + SyncController.syncAll(SyncType.CARPENTRY_RECIPES); } saveCategories(); @@ -302,7 +303,7 @@ public class RecipeController implements IRecipeHandler { RecipeAnvil anvilRecipe = anvilRecipes.remove(recipe.id); if (anvilRecipe != null) - SyncController.syncAllAnvilRecipes(); + SyncController.syncAll(SyncType.ANVIL_RECIPES); saveCategories(); return recipe; diff --git a/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java b/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java index 5a9d32ed3..9e322ea10 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java +++ b/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java @@ -5,7 +5,7 @@ import noppes.npcs.config.ConfigScript; /** * Server-side utility for syncing script configuration to clients. - * + *

* This class is SERVER-SIDE ONLY. Client reads via ScriptClientConfig. */ public class ScriptConfigSync { diff --git a/src/main/java/noppes/npcs/controllers/ScriptContainer.java b/src/main/java/noppes/npcs/controllers/ScriptContainer.java index 9674c8b04..88e54ec0a 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptContainer.java +++ b/src/main/java/noppes/npcs/controllers/ScriptContainer.java @@ -11,6 +11,7 @@ import noppes.npcs.controllers.data.IScriptHandler; import noppes.npcs.controllers.data.IScriptUnit; import noppes.npcs.scripted.NpcAPI; +import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptContext; @@ -45,11 +46,48 @@ public class ScriptContainer implements IScriptUnit { private static Method luaCall; private CompiledScript compScript = null; private final HashMap cachedFunctions = new HashMap<>(); + private long lastGlobalsVersion = -1; + + /** + * Persisted per-container language. Null means inherit from handler default. + * Separate from currentScriptLanguage which is the engine cache. + */ + private String language = null; + + /** + * Per-instance bindings for variable isolation. When non-null, this container + * is an instance scope sharing a template's engine. All eval/lookup uses these + * bindings instead of the engine's default ENGINE_SCOPE. + */ + private Bindings instanceBindings = null; public ScriptContainer(IScriptHandler handler) { this.handler = handler; } + /** + * Create a lightweight instance scope that shares this container's engine + * but has its own isolated Bindings for variable state. + * The template's engine is initialized if needed. + * + * @param instanceHandler the script handler for the instance + */ + @Override + public IScriptUnit createInstanceScope(IScriptHandler instanceHandler) { + if (this.engine == null) { + this.setEngine(this.getLanguage()); + } + ScriptContainer instance = new ScriptContainer(instanceHandler); + instance.script = this.script; + instance.scripts = new ArrayList<>(this.scripts); + instance.console = this.console; + instance.language = this.language; + instance.engine = this.engine; + instance.currentScriptLanguage = this.currentScriptLanguage; + instance.instanceBindings = this.engine.createBindings(); + return instance; + } + public void readFromNBT(NBTTagCompound compound) { String prevScript = this.script; this.script = compound.getString("Script"); @@ -68,6 +106,12 @@ public class ScriptContainer implements IScriptUnit { this.console = NBTTags.GetLongStringMap(compound.getTagList("Console", 10)); this.scripts = NBTTags.getStringList(compound.getTagList("ScriptList", 10)); this.lastCreated = 0L; + + // Read per-container language (empty string or missing = inherit from handler) + if (compound.hasKey("ContainerLanguage")) { + String lang = compound.getString("ContainerLanguage"); + this.language = lang.isEmpty() ? null : lang; + } } public NBTTagCompound writeToNBT(NBTTagCompound compound) { @@ -98,6 +142,11 @@ public class ScriptContainer implements IScriptUnit { //compound.setString("Type", this.type); compound.setTag("Console", NBTTags.NBTLongStringMap(this.console)); compound.setTag("ScriptList", NBTTags.nbtStringList(this.scripts)); + + // Persist per-container language if explicitly set + if (this.language != null) { + compound.setString("ContainerLanguage", this.language); + } return compound; } @@ -169,13 +218,14 @@ public class ScriptContainer implements IScriptUnit { if (!CustomNpcs.proxy.isScriptingEnabled() || errored || !hasCode() || unknownFunctions.contains(type)) return; - this.setEngine(handler.getLanguage()); + this.setEngine(this.getLanguage()); if (engine == null) return; if (ScriptController.Instance.lastLoaded > this.lastCreated) { this.lastCreated = ScriptController.Instance.lastLoaded; evaluated = false; + lastGlobalsVersion = -1; } synchronized (lock) { @@ -188,20 +238,39 @@ public class ScriptContainer implements IScriptUnit { engine.getContext().setWriter(pw); engine.getContext().setErrorWriter(pw); - engine.put("API", NpcAPI.Instance()); - HashMap engineEntries = new HashMap<>(NpcAPI.engineObjects); - for (Map.Entry objectEntry : engineEntries.entrySet()) { - engine.put(objectEntry.getKey(), objectEntry.getValue()); + // Populate bindings with API objects (skip if globals unchanged) + long currentGlobalsVersion = NpcAPI.engineObjectsVersion; + boolean globalsChanged = lastGlobalsVersion != currentGlobalsVersion; + if (instanceBindings != null) { + if (globalsChanged) { + instanceBindings.put("API", NpcAPI.Instance()); + for (Map.Entry objectEntry : NpcAPI.engineObjects.entrySet()) { + instanceBindings.put(objectEntry.getKey(), objectEntry.getValue()); + } + lastGlobalsVersion = currentGlobalsVersion; + } + } else { + if (globalsChanged) { + engine.put("API", NpcAPI.Instance()); + for (Map.Entry objectEntry : NpcAPI.engineObjects.entrySet()) { + engine.put(objectEntry.getKey(), objectEntry.getValue()); + } + lastGlobalsVersion = currentGlobalsVersion; + } } try { if (!evaluated) { this.cachedFunctions.clear(); - engine.eval(getFullCode()); + if (instanceBindings != null) { + engine.eval(getFullCode(), instanceBindings); + } else { + engine.eval(getFullCode()); + } evaluated = true; } if (engine.getFactory().getLanguageName().equals("lua")) { - Object ob = engine.get(type); + Object ob = instanceBindings != null ? instanceBindings.get(type) : engine.get(type); if (ob != null) { if (luaCoerce == null) { luaCoerce = Class.forName("org.luaj.vm2.lib.jse.CoerceJavaToLua").getMethod("coerce", Object.class); @@ -213,8 +282,14 @@ public class ScriptContainer implements IScriptUnit { } } else { if (!this.cachedFunctions.containsKey(type)) { - ScriptObjectMirror global = (ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE); - ScriptObjectMirror func = (ScriptObjectMirror) global.get(type); + ScriptObjectMirror func; + if (instanceBindings != null) { + Object val = instanceBindings.get(type); + func = val instanceof ScriptObjectMirror ? (ScriptObjectMirror) val : null; + } else { + ScriptObjectMirror global = (ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE); + func = (ScriptObjectMirror) global.get(type); + } this.cachedFunctions.put(type, func); } ScriptObjectMirror func = this.cachedFunctions.get(type); @@ -261,14 +336,22 @@ public class ScriptContainer implements IScriptUnit { return !this.getFullCode().isEmpty(); } + @Override + public boolean isUnknownFunction(String type) { + return unknownFunctions.contains(type); + } + public void setEngine(String scriptLanguage) { if (!Objects.equals(scriptLanguage, this.currentScriptLanguage)) { + // Instance scopes share the template's engine — never create a new one + if (instanceBindings != null) return; this.currentScriptLanguage = scriptLanguage; if (ConfigScript.ScriptingECMA6 && scriptLanguage.equals("ECMAScript")) { System.setProperty("nashorn.args", "--language=es6"); } this.engine = ScriptController.Instance.getEngineByName(scriptLanguage.toLowerCase()); this.evaluated = false; + this.lastGlobalsVersion = -1; } } @@ -308,18 +391,15 @@ public class ScriptContainer implements IScriptUnit { @Override public String getLanguage() { - // If a specific language is set for this container, use it - // Otherwise fall back to the handler's language - if (currentScriptLanguage != null) { - return currentScriptLanguage; - } - return handler != null ? handler.getLanguage() : "ECMAScript"; + // Return persisted per-container language, defaulting to ECMAScript. + // This is separate from currentScriptLanguage which is the engine cache. + return this.language != null ? this.language : "ECMAScript"; } @Override public void setLanguage(String language) { - if (!Objects.equals(this.currentScriptLanguage, language)) { - this.currentScriptLanguage = language; + if (!Objects.equals(this.language, language)) { + this.language = language; this.evaluated = false; } } diff --git a/src/main/java/noppes/npcs/controllers/ScriptHookController.java b/src/main/java/noppes/npcs/controllers/ScriptHookController.java index f3bad8e9d..332d2f1e9 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptHookController.java +++ b/src/main/java/noppes/npcs/controllers/ScriptHookController.java @@ -1,11 +1,15 @@ package noppes.npcs.controllers; import noppes.npcs.api.event.IAbilityEvent; +import noppes.npcs.api.event.IChainEvent; import noppes.npcs.api.event.IAnimationEvent; +import noppes.npcs.api.event.IAuctionEvent; 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.IEnergyBarrierEvent; +import noppes.npcs.api.event.IEnergyProjectileEvent; import noppes.npcs.api.event.IFactionEvent; import noppes.npcs.api.event.IForgeEvent; import noppes.npcs.api.event.IItemEvent; @@ -37,6 +41,8 @@ import static noppes.npcs.constants.ScriptContext.ITEM; import static noppes.npcs.constants.ScriptContext.LINKED_ITEM; import static noppes.npcs.constants.ScriptContext.NPC; import static noppes.npcs.constants.ScriptContext.PLAYER; +import static noppes.npcs.constants.ScriptContext.ABILITY; +import static noppes.npcs.constants.ScriptContext.CHAINED_ABILITY; import static noppes.npcs.constants.ScriptContext.RECIPE; /** @@ -77,6 +83,7 @@ public class ScriptHookController implements IScriptHookHandler { initializeLinkedItemHooks(); initializeRecipeHooks(); initializeEffectHooks(); + initializeAbilityHooks(); initializeForgeHooks(); } @@ -106,13 +113,41 @@ 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); hook(NPC, ABILITY_HIT, IAbilityEvent.HitEvent.class); + hook(NPC, ABILITY_DEFEND, IAbilityEvent.DefendEvent.class); hook(NPC, ABILITY_TICK, IAbilityEvent.TickEvent.class); hook(NPC, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); hook(NPC, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + hook(NPC, ABILITY_TOGGLE, IAbilityEvent.ToggleEvent.class); + hook(NPC, ABILITY_TOGGLE_TICK, IAbilityEvent.ToggleUpdateEvent.class); + + // Chain + hook(NPC, CHAIN_START, IChainEvent.StartEvent.class); + hook(NPC, CHAIN_NEXT, IChainEvent.NextEvent.class); + hook(NPC, CHAIN_COMPLETE, IChainEvent.CompleteEvent.class); + hook(NPC, CHAIN_INTERRUPT, IChainEvent.InterruptEvent.class); + + // Energy Barrier + hook(NPC, ENERGY_BARRIER_SPAWNED, IEnergyBarrierEvent.SpawnedEvent.class); + hook(NPC, ENERGY_BARRIER_TICK, IEnergyBarrierEvent.UpdateEvent.class); + hook(NPC, ENERGY_BARRIER_HIT, IEnergyBarrierEvent.HitEvent.class); + hook(NPC, ENERGY_BARRIER_DESTROYED, IEnergyBarrierEvent.DestroyedEvent.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 +243,43 @@ 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); + + // Energy Barrier + hook(PLAYER, ENERGY_BARRIER_SPAWNED, IEnergyBarrierEvent.SpawnedEvent.class); + hook(PLAYER, ENERGY_BARRIER_TICK, IEnergyBarrierEvent.UpdateEvent.class); + hook(PLAYER, ENERGY_BARRIER_HIT, IEnergyBarrierEvent.HitEvent.class); + hook(PLAYER, ENERGY_BARRIER_DESTROYED, IEnergyBarrierEvent.DestroyedEvent.class); + + // Ability + hook(PLAYER, ABILITY_START, IAbilityEvent.StartEvent.class); + hook(PLAYER, ABILITY_EXECUTE, IAbilityEvent.ExecuteEvent.class); + hook(PLAYER, ABILITY_HIT, IAbilityEvent.HitEvent.class); + hook(PLAYER, ABILITY_DEFEND, IAbilityEvent.DefendEvent.class); + hook(PLAYER, ABILITY_TICK, IAbilityEvent.TickEvent.class); + hook(PLAYER, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); + hook(PLAYER, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + hook(PLAYER, ABILITY_TOGGLE, IAbilityEvent.ToggleEvent.class); + hook(PLAYER, ABILITY_TOGGLE_TICK, IAbilityEvent.ToggleUpdateEvent.class); + + // Chain + hook(PLAYER, CHAIN_START, IChainEvent.StartEvent.class); + hook(PLAYER, CHAIN_NEXT, IChainEvent.NextEvent.class); + hook(PLAYER, CHAIN_COMPLETE, IChainEvent.CompleteEvent.class); + hook(PLAYER, CHAIN_INTERRUPT, IChainEvent.InterruptEvent.class); + + // Auction + hook(PLAYER, AUCTION_CREATE, IAuctionEvent.CreateEvent.class); + hook(PLAYER, AUCTION_BID, IAuctionEvent.BidEvent.class); + hook(PLAYER, AUCTION_BUYOUT, IAuctionEvent.BuyoutEvent.class); + hook(PLAYER, AUCTION_CANCEL, IAuctionEvent.CancelEvent.class); + hook(PLAYER, AUCTION_CLAIM, IAuctionEvent.ClaimEvent.class); + // Profile hook(PLAYER, PROFILE_CHANGE, IPlayerEvent.ProfileEvent.Changed.class); hook(PLAYER, PROFILE_REMOVE, IPlayerEvent.ProfileEvent.Removed.class); @@ -282,6 +354,25 @@ public class ScriptHookController implements IScriptHookHandler { hook(EFFECT, ON_EFFECT_REMOVE, IPlayerEvent.EffectEvent.Removed.class); } + private void initializeAbilityHooks() { + // Ability context (internal per-ability scripts) + hook(ABILITY, ABILITY_START, IAbilityEvent.StartEvent.class); + hook(ABILITY, ABILITY_EXECUTE, IAbilityEvent.ExecuteEvent.class); + hook(ABILITY, ABILITY_HIT, IAbilityEvent.HitEvent.class); + hook(ABILITY, ABILITY_DEFEND, IAbilityEvent.DefendEvent.class); + hook(ABILITY, ABILITY_TICK, IAbilityEvent.TickEvent.class); + hook(ABILITY, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); + hook(ABILITY, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + hook(ABILITY, ABILITY_TOGGLE, IAbilityEvent.ToggleEvent.class); + hook(ABILITY, ABILITY_TOGGLE_TICK, IAbilityEvent.ToggleUpdateEvent.class); + + // Chained ability context (chain-level lifecycle hooks) + hook(CHAINED_ABILITY, CHAIN_START, IChainEvent.StartEvent.class); + hook(CHAINED_ABILITY, CHAIN_NEXT, IChainEvent.NextEvent.class); + hook(CHAINED_ABILITY, CHAIN_COMPLETE, IChainEvent.CompleteEvent.class); + hook(CHAINED_ABILITY, CHAIN_INTERRUPT, IChainEvent.InterruptEvent.class); + } + private void initializeForgeHooks() { hook(FORGE, INIT, IForgeEvent.InitEvent.class); hook(FORGE, FORGE_WORLD, IForgeEvent.WorldEvent.class); diff --git a/src/main/java/noppes/npcs/controllers/SpawnController.java b/src/main/java/noppes/npcs/controllers/SpawnController.java index 7a04d788d..ce9d784e4 100644 --- a/src/main/java/noppes/npcs/controllers/SpawnController.java +++ b/src/main/java/noppes/npcs/controllers/SpawnController.java @@ -223,11 +223,14 @@ public class SpawnController implements INaturalSpawnsHandler { } public INaturalSpawn[] getSpawns(String biome) { - return getSpawnList(biome).toArray(new INaturalSpawn[]{}); + List biomeSpawns = getSpawnList(biome); + if (biomeSpawns == null) + return new INaturalSpawn[]{}; + return biomeSpawns.toArray(new INaturalSpawn[]{}); } public void addSpawn(INaturalSpawn spawn) { - ((SpawnData) spawn).id = 0; + ((SpawnData) spawn).id = -1; this.saveSpawnData((SpawnData) spawn); } diff --git a/src/main/java/noppes/npcs/controllers/TagController.java b/src/main/java/noppes/npcs/controllers/TagController.java index cbd2ed006..738418a13 100644 --- a/src/main/java/noppes/npcs/controllers/TagController.java +++ b/src/main/java/noppes/npcs/controllers/TagController.java @@ -1,5 +1,8 @@ package noppes.npcs.controllers; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -9,6 +12,9 @@ import noppes.npcs.api.handler.ITagHandler; import noppes.npcs.api.handler.data.ITag; import noppes.npcs.controllers.data.Tag; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; + import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; @@ -18,6 +24,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; @@ -234,4 +241,69 @@ public class TagController implements ITagHandler { public HashSet getAllTags() { return new HashSet(this.tags.values()); } + + /** + * Write a set of tag UUIDs to an NBT compound under the given key. + */ + public static void writeTagUUIDs(NBTTagCompound compound, String key, HashSet tagUUIDs) { + if (tagUUIDs != null && !tagUUIDs.isEmpty()) { + NBTTagList list = new NBTTagList(); + for (UUID uuid : tagUUIDs) { + list.appendTag(new NBTTagString(uuid.toString())); + } + compound.setTag(key, list); + } + } + + /** + * Read a set of tag UUIDs from an NBT compound under the given key. + */ + public static HashSet readTagUUIDs(NBTTagCompound compound, String key) { + HashSet uuids = new HashSet<>(); + if (compound.hasKey(key)) { + NBTTagList list = compound.getTagList(key, 8); + for (int i = 0; i < list.tagCount(); i++) { + try { + uuids.add(UUID.fromString(list.getStringTagAt(i))); + } catch (IllegalArgumentException ignored) {} + } + } + return uuids; + } + + /** + * Remove invalid tag UUIDs (those not in the tag registry). + */ + public static void validateTagUUIDs(HashSet tagUUIDs) { + TagController tc = getInstance(); + if (tc == null) return; + tagUUIDs.removeIf(uuid -> tc.getTagFromUUID(uuid) == null); + } + + /** + * Build and send a CategoryTagMap GuiData packet for a set of items. + * @param player the target player + * @param itemTags map of item name -> tag UUIDs (only validated tags are sent) + */ + public static void sendCategoryTagMap(EntityPlayerMP player, HashMap> itemTags) { + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList entries = new NBTTagList(); + TagController tc = getInstance(); + for (Map.Entry> entry : itemTags.entrySet()) { + HashSet valid = new HashSet<>(); + for (UUID uuid : entry.getValue()) { + if (tc != null && tc.getTagFromUUID(uuid) != null) { + valid.add(uuid); + } + } + if (!valid.isEmpty()) { + NBTTagCompound itemEntry = new NBTTagCompound(); + itemEntry.setString("Name", entry.getKey()); + writeTagUUIDs(itemEntry, "Tags", valid); + entries.appendTag(itemEntry); + } + } + compound.setTag("CategoryTagMap", entries); + GuiDataPacket.sendGuiData(player, compound); + } } diff --git a/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java b/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java new file mode 100644 index 000000000..7941c81f1 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java @@ -0,0 +1,47 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class AbilityHotbarData { + public static final String CHAIN_PREFIX = "chain:"; + public static final int TOTAL_SLOTS = 12; + + public int slot = -1; + public String abilityKey = ""; + + public AbilityHotbarData() { + } + + public AbilityHotbarData(int slot) { + this.slot = slot; + } + + public boolean isChainKey() { + return abilityKey != null && abilityKey.startsWith(CHAIN_PREFIX); + } + + public String getResolveKey() { + if (isChainKey()) return abilityKey.substring(CHAIN_PREFIX.length()); + return abilityKey; + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("slot", slot); + tag.setString("abilityKey", abilityKey != null ? abilityKey : ""); + compound.setTag("AbilityHotbar" + slot, tag); + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + abilityKey = compound.getString("abilityKey"); + } + + public void reset() { + abilityKey = ""; + } + + public boolean isEmpty() { + return abilityKey == null || abilityKey.isEmpty(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AbilityScript.java b/src/main/java/noppes/npcs/controllers/data/AbilityScript.java new file mode 100644 index 000000000..785dc009a --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AbilityScript.java @@ -0,0 +1,60 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.network.packets.request.script.AbilityScriptPacket; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; + +/** + * Script handler for ability scripts. + * Manages a single script container for ability hooks (abilityStart, abilityTick, abilityComplete, etc.). + */ +public class AbilityScript extends SingleScriptHandler implements IScriptHandlerPacket { + + /** + * The ability ID (UUID) for packet communication. Empty if not bound. + */ + private String abilityId = ""; + + /** + * Create an unbound AbilityScript (for server-side use). + */ + public AbilityScript() { + } + + /** + * Create an AbilityScript bound to a specific ability (for GUI use). + * + * @param abilityId The UUID of the ability + */ + public AbilityScript(String abilityId) { + this.abilityId = abilityId != null ? abilityId : ""; + } + + @Override + public ScriptContext getContext() { + return ScriptContext.ABILITY; + } + + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.ABILITY); + } + + @Override + public String noticeString() { + return !abilityId.isEmpty() ? "Ability[" + abilityId + "]" : "Ability"; + } + + @Override + public void requestData() { + if (!abilityId.isEmpty()) + AbilityScriptPacket.Get(abilityId); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (!abilityId.isEmpty()) + AbilityScriptPacket.Save(abilityId, index, totalCount, nbt); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java b/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java index 75a1a714a..1f4d331a4 100644 --- a/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java +++ b/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java @@ -10,15 +10,16 @@ import noppes.npcs.config.ConfigMarket; import java.util.ArrayList; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.regex.Pattern; public class AuctionBlacklist { - private static Set blacklistedItems = new HashSet<>(); - private static Set wildcardPatterns = new HashSet<>(); - private static Set blacklistedMods = new HashSet<>(); - private static Set blacklistedNBTTags = new HashSet<>(); + private static volatile Set blacklistedItems = new HashSet<>(); + private static volatile Set wildcardPatterns = new HashSet<>(); + private static volatile Set blacklistedMods = new HashSet<>(); + private static volatile Set blacklistedNBTTags = new HashSet<>(); // Built-in bound item requirement keys (always blocked) private static final String SOULBIND_KEY = "cnpc_soulbind"; @@ -28,10 +29,10 @@ public class AuctionBlacklist { private static final String BYPASS_PERMISSION = "customnpcs.auction.blacklist.bypass"; public static void reload() { - blacklistedItems.clear(); - wildcardPatterns.clear(); - blacklistedMods.clear(); - blacklistedNBTTags.clear(); + Set newItems = new HashSet<>(); + Set newWildcards = new HashSet<>(); + Set newMods = new HashSet<>(); + Set newNBTTags = new HashSet<>(); // Load blacklisted items for (String item : ConfigMarket.BlacklistedItems) { @@ -40,23 +41,29 @@ public class AuctionBlacklist { if (item.contains("*")) { String regex = "^" + item.replace(".", "\\.").replace("*", ".*") + "$"; - wildcardPatterns.add(Pattern.compile(regex)); + newWildcards.add(Pattern.compile(regex)); } else { - blacklistedItems.add(item); + newItems.add(item); } } // Load blacklisted mods for (String mod : ConfigMarket.BlacklistedMods) { if (mod == null || mod.isEmpty()) continue; - blacklistedMods.add(mod.toLowerCase().trim()); + newMods.add(mod.toLowerCase().trim()); } // Load blacklisted NBT tags for (String tag : ConfigMarket.BlacklistedNBTTags) { if (tag == null || tag.isEmpty()) continue; - blacklistedNBTTags.add(tag.trim()); + newNBTTags.add(tag.trim()); } + + // Atomic swap + blacklistedItems = newItems; + wildcardPatterns = newWildcards; + blacklistedMods = newMods; + blacklistedNBTTags = newNBTTags; } /** @@ -78,7 +85,6 @@ public class AuctionBlacklist { * Check if item is blacklisted (without bypass check) */ public static boolean isBlacklisted(ItemStack item) { - if (!ConfigMarket.BlacklistEnabled) return false; if (item == null || item.getItem() == null) return true; // Check bound items (always blocked, even if blacklist is "disabled") @@ -86,6 +92,8 @@ public class AuctionBlacklist { return true; } + if (!ConfigMarket.BlacklistEnabled) return false; + // Get registry name GameRegistry.UniqueIdentifier uid = GameRegistry.findUniqueIdentifierFor(item.getItem()); if (uid == null) return true; @@ -172,9 +180,13 @@ public class AuctionBlacklist { if (registryName.contains("*")) { String regex = "^" + registryName.replace(".", "\\.").replace("*", ".*") + "$"; - wildcardPatterns.add(Pattern.compile(regex)); + Set newWildcards = new HashSet<>(wildcardPatterns); + newWildcards.add(Pattern.compile(regex)); + wildcardPatterns = newWildcards; } else { - blacklistedItems.add(registryName); + Set newItems = new HashSet<>(blacklistedItems); + newItems.add(registryName); + blacklistedItems = newItems; } return true; } @@ -185,30 +197,55 @@ public class AuctionBlacklist { if (registryName.contains("*")) { String regex = "^" + registryName.replace(".", "\\.").replace("*", ".*") + "$"; - return wildcardPatterns.removeIf(p -> p.pattern().equals(regex)); + Set newWildcards = new HashSet<>(wildcardPatterns); + boolean removed = false; + Iterator it = newWildcards.iterator(); + while (it.hasNext()) { + if (it.next().pattern().equals(regex)) { + it.remove(); + removed = true; + } + } + wildcardPatterns = newWildcards; + return removed; } else { - return blacklistedItems.remove(registryName); + Set newItems = new HashSet<>(blacklistedItems); + boolean removed = newItems.remove(registryName); + blacklistedItems = newItems; + return removed; } } public static boolean addMod(String modId) { if (modId == null || modId.isEmpty()) return false; - return blacklistedMods.add(modId.toLowerCase().trim()); + Set newMods = new HashSet<>(blacklistedMods); + boolean added = newMods.add(modId.toLowerCase().trim()); + blacklistedMods = newMods; + return added; } public static boolean removeMod(String modId) { if (modId == null || modId.isEmpty()) return false; - return blacklistedMods.remove(modId.toLowerCase().trim()); + Set newMods = new HashSet<>(blacklistedMods); + boolean removed = newMods.remove(modId.toLowerCase().trim()); + blacklistedMods = newMods; + return removed; } public static boolean addNBTTag(String tag) { if (tag == null || tag.isEmpty()) return false; - return blacklistedNBTTags.add(tag.trim()); + Set newTags = new HashSet<>(blacklistedNBTTags); + boolean added = newTags.add(tag.trim()); + blacklistedNBTTags = newTags; + return added; } public static boolean removeNBTTag(String tag) { if (tag == null || tag.isEmpty()) return false; - return blacklistedNBTTags.remove(tag.trim()); + Set newTags = new HashSet<>(blacklistedNBTTags); + boolean removed = newTags.remove(tag.trim()); + blacklistedNBTTags = newTags; + return removed; } // ========================================= diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java b/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java index ad4ae3238..534e7ae6d 100644 --- a/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java +++ b/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java @@ -2,6 +2,7 @@ package noppes.npcs.controllers.data; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.handler.data.IAuctionClaim; import noppes.npcs.api.item.IItemStack; import noppes.npcs.config.ConfigMarket; @@ -33,7 +34,9 @@ public class AuctionClaim implements IAuctionClaim { this.otherPlayerName = ""; } - /** Create claim for winning an item (buyer won auction or buyout) */ + /** + * Create claim for winning an item (buyer won auction or buyout) + */ public static AuctionClaim createItemWonClaim(UUID playerUUID, String playerName, String listingId, ItemStack item) { AuctionClaim claim = new AuctionClaim(); claim.playerUUID = playerUUID; @@ -46,7 +49,9 @@ public class AuctionClaim implements IAuctionClaim { return claim; } - /** Create claim for returned item (seller's expired/cancelled listing) */ + /** + * Create claim for returned item (seller's expired/cancelled listing) + */ public static AuctionClaim createItemReturnedClaim(UUID playerUUID, String playerName, String listingId, ItemStack item) { AuctionClaim claim = new AuctionClaim(); claim.playerUUID = playerUUID; @@ -59,7 +64,9 @@ public class AuctionClaim implements IAuctionClaim { return claim; } - /** Create claim for seller's proceeds (stores item name for tooltip, not full item) */ + /** + * Create claim for seller's proceeds (stores item name for tooltip, not full item) + */ public static AuctionClaim createCurrencyClaim(UUID playerUUID, String playerName, String listingId, long currency, String itemName, String buyerName) { AuctionClaim claim = new AuctionClaim(); claim.playerUUID = playerUUID; @@ -74,7 +81,9 @@ public class AuctionClaim implements IAuctionClaim { return claim; } - /** Create claim for outbid refund (stores item for display and rebid option) */ + /** + * Create claim for outbid refund (stores item for display and rebid option) + */ public static AuctionClaim createRefundClaim(UUID playerUUID, String playerName, String listingId, long currency, String itemName, String outbidderName, ItemStack item) { AuctionClaim claim = new AuctionClaim(); claim.playerUUID = playerUUID; @@ -140,7 +149,7 @@ public class AuctionClaim implements IAuctionClaim { @Override public boolean isCurrencyClaim() { - return type == EnumClaimType.CURRENCY; + return type.isCurrency(); } @Override @@ -201,9 +210,7 @@ public class AuctionClaim implements IAuctionClaim { compound.setInteger("Type", type.ordinal()); if (item != null) { - NBTTagCompound itemTag = new NBTTagCompound(); - item.writeToNBT(itemTag); - compound.setTag("Item", itemTag); + compound.setTag("Item", NoppesUtilServer.writeItem(item, new NBTTagCompound())); } compound.setString("ItemName", itemName != null ? itemName : ""); @@ -227,7 +234,7 @@ public class AuctionClaim implements IAuctionClaim { type = EnumClaimType.fromOrdinal(compound.getInteger("Type")); if (compound.hasKey("Item")) { - item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); + item = NoppesUtilServer.readItem(compound.getCompoundTag("Item")); } else { item = null; } diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java b/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java index 95bf2ed24..e6841fcea 100644 --- a/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java +++ b/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java @@ -4,16 +4,12 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import noppes.npcs.constants.EnumAuctionSort; -import java.util.regex.Pattern; - /** * Filter for auction listings. * Supports search by item name or seller name and sorting options. */ public class AuctionFilter { - private static final Pattern COLOR_CODE_PATTERN = Pattern.compile("§[0-9a-fk-or]", Pattern.CASE_INSENSITIVE); - - public String searchText; + private String searchText; public EnumAuctionSort sortBy; // Cached normalized search for efficiency @@ -29,15 +25,18 @@ public class AuctionFilter { return searchText != null && !searchText.trim().isEmpty(); } - /** Normalize string for search (strip colors, lowercase, trim) */ + /** + * Normalize string for search (strip colors, lowercase, trim) + */ public static String normalizeForSearch(String input) { if (input == null || input.isEmpty()) return ""; - String stripped = COLOR_CODE_PATTERN.matcher(input).replaceAll(""); - stripped = EnumChatFormatting.getTextWithoutFormattingCodes(stripped); - return stripped.toLowerCase().trim(); + String stripped = EnumChatFormatting.getTextWithoutFormattingCodes(input); + return stripped != null ? stripped.toLowerCase().trim() : input.toLowerCase().trim(); } - /** Check if item name or seller name matches search text */ + /** + * Check if item name or seller name matches search text + */ public boolean matchesSearch(String itemName, String sellerName) { if (!hasSearchText()) return true; String normalizedItem = normalizeForSearch(itemName); @@ -46,12 +45,16 @@ public class AuctionFilter { return normalizedItem.contains(normalizedSearch) || normalizedSeller.contains(normalizedSearch); } - /** Legacy method - only checks item name */ + /** + * Legacy method - only checks item name + */ public boolean matchesSearch(String itemName) { return matchesSearch(itemName, ""); } - /** Advanced search - all words must be present in item name OR seller name */ + /** + * Advanced search - all words must be present in item name OR seller name + */ public boolean matchesSearchAdvanced(String itemName, String sellerName) { if (!hasSearchText()) return true; String normalizedItem = normalizeForSearch(itemName); @@ -68,7 +71,9 @@ public class AuctionFilter { return true; } - /** Legacy method - only checks item name */ + /** + * Legacy method - only checks item name + */ public boolean matchesSearchAdvanced(String itemName) { return matchesSearchAdvanced(itemName, ""); } @@ -106,13 +111,20 @@ public class AuctionFilter { } // Getters and setters - public String getSearchText() { return searchText; } + public String getSearchText() { + return searchText; + } public void setSearchText(String searchText) { this.searchText = searchText; this.normalizedSearch = normalizeForSearch(searchText); } - public EnumAuctionSort getSortBy() { return sortBy; } - public void setSortBy(EnumAuctionSort sortBy) { this.sortBy = sortBy; } + public EnumAuctionSort getSortBy() { + return sortBy; + } + + public void setSortBy(EnumAuctionSort sortBy) { + this.sortBy = sortBy; + } } diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionListing.java b/src/main/java/noppes/npcs/controllers/data/AuctionListing.java index 6d57942c1..0c021174c 100644 --- a/src/main/java/noppes/npcs/controllers/data/AuctionListing.java +++ b/src/main/java/noppes/npcs/controllers/data/AuctionListing.java @@ -2,6 +2,7 @@ package noppes.npcs.controllers.data; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.handler.data.IAuctionListing; import noppes.npcs.api.item.IItemStack; import noppes.npcs.config.ConfigMarket; @@ -24,6 +25,7 @@ public class AuctionListing implements IAuctionListing { public long createdTime; public long endTime; public EnumAuctionStatus status; + public boolean isGlobalListing; public AuctionListing() { this.id = UUID.randomUUID().toString(); @@ -31,6 +33,7 @@ public class AuctionListing implements IAuctionListing { this.bidCount = 0; this.currentBid = 0; this.createdTime = System.currentTimeMillis(); + this.isGlobalListing = false; } public AuctionListing(UUID sellerUUID, String sellerName, ItemStack item, long startingPrice, long buyoutPrice, long durationMs) { @@ -212,9 +215,7 @@ public class AuctionListing implements IAuctionListing { compound.setString("SellerName", sellerName != null ? sellerName : ""); if (item != null) { - NBTTagCompound itemTag = new NBTTagCompound(); - item.writeToNBT(itemTag); - compound.setTag("Item", itemTag); + compound.setTag("Item", NoppesUtilServer.writeItem(item, new NBTTagCompound())); } compound.setLong("StartingPrice", startingPrice); @@ -228,6 +229,7 @@ public class AuctionListing implements IAuctionListing { compound.setLong("CreatedTime", createdTime); compound.setLong("EndTime", endTime); compound.setInteger("Status", status.ordinal()); + compound.setBoolean("IsGlobalListing", isGlobalListing); return compound; } @@ -240,7 +242,7 @@ public class AuctionListing implements IAuctionListing { sellerName = compound.getString("SellerName"); if (compound.hasKey("Item")) { - item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); + item = NoppesUtilServer.readItem(compound.getCompoundTag("Item")); } startingPrice = compound.getLong("StartingPrice"); @@ -255,6 +257,7 @@ public class AuctionListing implements IAuctionListing { createdTime = compound.getLong("CreatedTime"); endTime = compound.getLong("EndTime"); status = EnumAuctionStatus.fromOrdinal(compound.getInteger("Status")); + isGlobalListing = compound.getBoolean("IsGlobalListing"); } public static AuctionListing fromNBT(NBTTagCompound compound) { diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionNotification.java b/src/main/java/noppes/npcs/controllers/data/AuctionNotification.java deleted file mode 100644 index 01ebd1e47..000000000 --- a/src/main/java/noppes/npcs/controllers/data/AuctionNotification.java +++ /dev/null @@ -1,64 +0,0 @@ -package noppes.npcs.controllers.data; - -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.constants.EnumNotificationType; - -import java.util.UUID; - -public class AuctionNotification { - public String id; - public UUID playerUUID; - public EnumNotificationType type; - public String listingId; - public String message; - public long timestamp; - public boolean sent; - - public AuctionNotification() { - this.id = UUID.randomUUID().toString(); - this.timestamp = System.currentTimeMillis(); - this.sent = false; - } - - public AuctionNotification(UUID playerUUID, EnumNotificationType type, String listingId, String message) { - this(); - this.playerUUID = playerUUID; - this.type = type; - this.listingId = listingId; - this.message = message; - } - - public boolean isForPlayer(UUID uuid) { - return playerUUID != null && playerUUID.equals(uuid); - } - - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setString("ID", id); - compound.setString("PlayerUUID", playerUUID != null ? playerUUID.toString() : ""); - compound.setInteger("Type", type.ordinal()); - compound.setString("ListingID", listingId != null ? listingId : ""); - compound.setString("Message", message != null ? message : ""); - compound.setLong("Timestamp", timestamp); - compound.setBoolean("Sent", sent); - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - id = compound.getString("ID"); - - String playerUUIDStr = compound.getString("PlayerUUID"); - playerUUID = playerUUIDStr.isEmpty() ? null : UUID.fromString(playerUUIDStr); - - type = EnumNotificationType.fromOrdinal(compound.getInteger("Type")); - listingId = compound.getString("ListingID"); - message = compound.getString("Message"); - timestamp = compound.getLong("Timestamp"); - sent = compound.getBoolean("Sent"); - } - - public static AuctionNotification fromNBT(NBTTagCompound compound) { - AuctionNotification notification = new AuctionNotification(); - notification.readFromNBT(compound); - return notification; - } -} diff --git a/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java b/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java index a30923eac..50ef13c0e 100644 --- a/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java +++ b/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java @@ -23,6 +23,7 @@ public class BuiltInAnimation extends Animation { /** * Built-in animations cannot be saved. + * * @return this animation unchanged */ @Override @@ -33,6 +34,7 @@ public class BuiltInAnimation extends Animation { /** * Built-in animations have no valid ID. + * * @return always -1 */ @Override @@ -50,6 +52,7 @@ public class BuiltInAnimation extends Animation { /** * Check if this is a built-in animation. + * * @return always true for BuiltInAnimation */ public boolean isBuiltIn() { diff --git a/src/main/java/noppes/npcs/controllers/data/Category.java b/src/main/java/noppes/npcs/controllers/data/Category.java new file mode 100644 index 000000000..cbab80085 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/Category.java @@ -0,0 +1,31 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * Simple category data class for the generic category system. + * Used by CategoryManager to organize items into named groups. + */ +public class Category { + public int id = -1; + public String title = ""; + + public Category() { + } + + public Category(int id, String title) { + this.id = id; + this.title = title; + } + + public void readNBT(NBTTagCompound compound) { + id = compound.getInteger("CatID"); + title = compound.getString("CatTitle"); + } + + public NBTTagCompound writeNBT(NBTTagCompound compound) { + compound.setInteger("CatID", id); + compound.setString("CatTitle", title); + return compound; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/ChainedAbilityScript.java b/src/main/java/noppes/npcs/controllers/data/ChainedAbilityScript.java new file mode 100644 index 000000000..eee2308c8 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/ChainedAbilityScript.java @@ -0,0 +1,60 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.network.packets.request.script.ChainedAbilityScriptPacket; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; + +/** + * Script handler for chained ability scripts. + * Manages a single script container for chained ability hooks. + */ +public class ChainedAbilityScript extends SingleScriptHandler implements IScriptHandlerPacket { + + /** + * The chained ability ID (UUID) for packet communication. Empty if not bound. + */ + private String chainId = ""; + + /** + * Create an unbound ChainedAbilityScript (for server-side use). + */ + public ChainedAbilityScript() { + } + + /** + * Create a ChainedAbilityScript bound to a specific chained ability (for GUI use). + * + * @param chainId The UUID of the chained ability + */ + public ChainedAbilityScript(String chainId) { + this.chainId = chainId != null ? chainId : ""; + } + + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.CHAINED_ABILITY); + } + + @Override + public ScriptContext getContext() { + return ScriptContext.CHAINED_ABILITY; + } + + @Override + public String noticeString() { + return !chainId.isEmpty() ? "ChainedAbility[" + chainId + "]" : "ChainedAbility"; + } + + @Override + public void requestData() { + if (!chainId.isEmpty()) + ChainedAbilityScriptPacket.Get(chainId); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (!chainId.isEmpty()) + ChainedAbilityScriptPacket.Save(chainId, index, totalCount, nbt); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/CustomEffect.java b/src/main/java/noppes/npcs/controllers/data/CustomEffect.java index 7a5db74de..582098c87 100644 --- a/src/main/java/noppes/npcs/controllers/data/CustomEffect.java +++ b/src/main/java/noppes/npcs/controllers/data/CustomEffect.java @@ -9,8 +9,11 @@ import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.handler.data.ICustomEffect; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.TagController; import noppes.npcs.scripted.event.player.PlayerEvent; +import java.util.HashSet; +import java.util.UUID; import java.util.function.Consumer; public class CustomEffect implements ICustomEffect { @@ -26,17 +29,18 @@ public class CustomEffect implements ICustomEffect { public String icon = ""; public int iconX = 0, iconY = 0; - /** - * Experimental script stuff. - */ - public Consumer onAddedConsumer; - public Consumer onTickConsumer; - public Consumer onRemovedConsumer; public String menuName = "§aNEW EFFECT"; public int width = 16, height = 16; + // Animation + public boolean animated = false; + public int frameCount = 1; + public int frametime = 2; + public int index = 0; + public HashSet tagUUIDs = new HashSet<>(); + public CustomEffect() { } @@ -143,6 +147,36 @@ public class CustomEffect implements ICustomEffect { this.height = height; } + @Override + public boolean isAnimated() { + return animated; + } + + @Override + public void setAnimated(boolean animated) { + this.animated = animated; + } + + @Override + public int getFrameCount() { + return frameCount; + } + + @Override + public void setFrameCount(int frameCount) { + this.frameCount = Math.max(1, frameCount); + } + + @Override + public int getFrameTime() { + return frametime; + } + + @Override + public void setFrameTime(int frametime) { + this.frametime = Math.max(1, frametime); + } + @Override public boolean isLossOnDeath() { return lossOnDeath; @@ -169,26 +203,10 @@ public class CustomEffect implements ICustomEffect { } - public void onAdded(Consumer function) { - onAddedConsumer = function; - } - - public void onTick(Consumer function) { - onTickConsumer = function; - } - - public void onRemoved(Consumer function) { - onRemovedConsumer = function; - } - public void onAdded(EntityPlayer player, PlayerEffect playerEffect) { IPlayer iPlayer = NoppesUtilServer.getIPlayer(player); if (playerEffect.index == 0) { PlayerEvent.EffectEvent.Added event = new PlayerEvent.EffectEvent.Added(iPlayer, playerEffect); - - if (onAddedConsumer != null) - onAddedConsumer.accept(event); - EffectScript script = getScriptHandler(); if (script == null) { return; @@ -204,11 +222,6 @@ public class CustomEffect implements ICustomEffect { IPlayer iPlayer = NoppesUtilServer.getIPlayer(player); if (playerEffect.index == 0) { PlayerEvent.EffectEvent.Ticked event = new PlayerEvent.EffectEvent.Ticked(iPlayer, playerEffect); - - if (onTickConsumer != null) { - onTickConsumer.accept(event); - } - EffectScript script = getScriptHandler(); if (script == null) { return; @@ -225,11 +238,6 @@ public class CustomEffect implements ICustomEffect { if (playerEffect.index == 0) { PlayerEvent.EffectEvent.Removed event = new PlayerEvent.EffectEvent.Removed(iPlayer, playerEffect, type); - - if (onRemovedConsumer != null) { - onRemovedConsumer.accept(event); - } - EffectScript script = getScriptHandler(); if (script == null) { return; @@ -254,6 +262,11 @@ public class CustomEffect implements ICustomEffect { compound.setInteger("iconHeight", height); compound.setString("icon", icon); compound.setBoolean("lossOnDeath", lossOnDeath); + compound.setBoolean("iconAnimated", animated); + compound.setInteger("iconFrameCount", frameCount); + compound.setInteger("iconFrameTime", frametime); + + TagController.writeTagUUIDs(compound, "TagUUIDs", tagUUIDs); if (saveScripts) { NBTTagCompound scriptData = new NBTTagCompound(); @@ -296,6 +309,15 @@ public class CustomEffect implements ICustomEffect { icon = compound.getString("icon"); lossOnDeath = compound.getBoolean("lossOnDeath"); + if (compound.hasKey("iconAnimated")) + animated = compound.getBoolean("iconAnimated"); + if (compound.hasKey("iconFrameCount")) + frameCount = Math.max(1, compound.getInteger("iconFrameCount")); + if (compound.hasKey("iconFrameTime")) + frametime = Math.max(1, compound.getInteger("iconFrameTime")); + + tagUUIDs = TagController.readTagUUIDs(compound, "TagUUIDs"); + if (compound.hasKey("ScriptData", Constants.NBT.TAG_COMPOUND)) { EffectScript handler = new EffectScript(); handler.readFromNBT(compound.getCompoundTag("ScriptData")); diff --git a/src/main/java/noppes/npcs/controllers/data/DataScript.java b/src/main/java/noppes/npcs/controllers/data/DataScript.java index b112bf470..14f5544da 100644 --- a/src/main/java/noppes/npcs/controllers/data/DataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/DataScript.java @@ -20,6 +20,7 @@ import noppes.npcs.constants.EnumScriptType; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; +import noppes.npcs.controllers.ScriptHookController; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.janino.EventJaninoScript; import noppes.npcs.scripted.NpcAPI; @@ -28,15 +29,10 @@ import noppes.npcs.scripted.constants.EntityType; import noppes.npcs.scripted.constants.JobType; import noppes.npcs.scripted.constants.RoleType; import noppes.npcs.scripted.entity.ScriptNpc; +import noppes.npcs.api.handler.IHookDefinition; import javax.script.ScriptEngine; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; public class DataScript implements IScriptHandlerPacket { public List eventScripts = new ArrayList<>(); @@ -49,6 +45,7 @@ public class DataScript implements IScriptHandlerPacket { public String scriptLanguage = "ECMAScript"; private EntityNPCInterface npc; public boolean enabled = false; + private final Map engineGlobalsVersion = new IdentityHashMap<>(); public ICustomNpc dummyNpc; public IWorld dummyWorld; @@ -56,6 +53,17 @@ public class DataScript implements IScriptHandlerPacket { public boolean aiNeedsUpdate = false; public boolean hasInited = false; + // Editor/runtime globals descriptor used for a single source of truth. + private static final class GlobalDefinition { + private final String typeName; + private final Object value; + + private GlobalDefinition(String typeName, Object value) { + this.typeName = typeName; + this.value = value; + } + } + public DataScript(EntityNPCInterface npc) { for (int i = 0; i < 15; i++) { this.setNPCScript(i, new ScriptContainer(this)); @@ -180,21 +188,12 @@ public class DataScript implements IScriptHandlerPacket { LogWriter.postScriptLog(npc.field_110179_h, type, String.format("[%s] NPC %s (%s, %s, %s) | Objects: %s", ((String) type.function).toUpperCase(), npc.display.name, (int) npc.posX, (int) npc.posY, (int) npc.posZ, Arrays.toString(obs))); } } - return callScript(script, event); + return callScript(script, type.function, event); } - private boolean callScript(ScriptContainer script, Event event) { + private boolean callScript(ScriptContainer script, String hookName, Event event) { ScriptEngine engine = script.engine; - engine.put("npc", dummyNpc); - engine.put("world", dummyWorld); - engine.put("event", event); - engine.put("API", NpcAPI.Instance()); - engine.put("EntityType", entities); - engine.put("RoleType", roles); - engine.put("JobType", jobs); - for (Map.Entry engineObjects : NpcAPI.engineObjects.entrySet()) { - engine.put(engineObjects.getKey(), engineObjects.getValue()); - } + applyGlobalsToEngine(engine, hookName, event); script.run(engine); if (clientNeedsUpdate) { @@ -254,6 +253,66 @@ public class DataScript implements IScriptHandlerPacket { } } + public Map getEditorGlobals(String hookName) { + Map definitions = getGlobalDefinitions(hookName, null); + Map globals = new LinkedHashMap<>(); + for (Map.Entry entry : definitions.entrySet()) { + String typeName = entry.getValue().typeName; + if (typeName != null && !typeName.isEmpty()) { + globals.put(entry.getKey(), typeName); + } + } + return globals; + } + + // Apply runtime globals plus engine-only bindings. + private void applyGlobalsToEngine(ScriptEngine engine, String hookName, Event event) { + Map definitions = getGlobalDefinitions(hookName, event); + for (Map.Entry entry : definitions.entrySet()) { + engine.put(entry.getKey(), entry.getValue().value); + } + + long currentGlobalsVersion = NpcAPI.engineObjectsVersion; + Long lastVersion = engineGlobalsVersion.get(engine); + if (lastVersion == null || lastVersion != currentGlobalsVersion) { + engine.put("API", NpcAPI.Instance()); + for (Map.Entry engineObjects : NpcAPI.engineObjects.entrySet()) { + engine.put(engineObjects.getKey(), engineObjects.getValue()); + } + engineGlobalsVersion.put(engine, currentGlobalsVersion); + } + } + + // Build shared globals (editor types + runtime values). + private Map getGlobalDefinitions(String hookName, Event event) { + Map globals = new LinkedHashMap<>(); + globals.put("npc", new GlobalDefinition("ICustomNpc", dummyNpc)); + globals.put("world", new GlobalDefinition("IWorld", dummyWorld)); + globals.put("event", new GlobalDefinition(resolveEditorEventTypeName(hookName), event)); + globals.put("EntityType", new GlobalDefinition("noppes.npcs.scripted.constants.EntityType", entities)); + globals.put("RoleType", new GlobalDefinition("noppes.npcs.scripted.constants.RoleType", roles)); + globals.put("JobType", new GlobalDefinition("noppes.npcs.scripted.constants.JobType", jobs)); + + return globals; + } + + // Resolve editor-only event type from hook name with a single fallback. + private String resolveEditorEventTypeName(String hookName) { + final String fallback = "INpcEvent"; + if (hookName == null || hookName.isEmpty()) + return fallback; + + IHookDefinition definition = ScriptHookController.Instance.getHookDefinition(getContext().hookContext, hookName); + if (definition == null) + return fallback; + + String typeName = definition.getUsableTypeName(); + if (typeName == null || typeName.isEmpty()) + return fallback; + + return typeName; + } + public boolean isClient() { return this.npc.isRemote(); } diff --git a/src/main/java/noppes/npcs/controllers/data/EffectScript.java b/src/main/java/noppes/npcs/controllers/data/EffectScript.java index 457eb11d6..06b38af89 100644 --- a/src/main/java/noppes/npcs/controllers/data/EffectScript.java +++ b/src/main/java/noppes/npcs/controllers/data/EffectScript.java @@ -3,6 +3,7 @@ package noppes.npcs.controllers.data; import kamkeel.npcs.network.packets.request.script.EffectScriptPacket; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; /** * Script handler for CustomEffect scripts. @@ -35,6 +36,11 @@ public class EffectScript extends SingleScriptHandler implements IScriptHandlerP return ScriptContext.EFFECT; } + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.EFFECT); + } + @Override public String noticeString() { return effectId >= 0 ? "CustomEffect[" + effectId + "]" : "CustomEffect"; diff --git a/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java b/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java index f8c961db7..067474a0f 100644 --- a/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java @@ -18,12 +18,14 @@ import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.ScriptHookController; +import noppes.npcs.janino.EventJaninoScript; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; public class ForgeDataScript extends MultiScriptHandler { @@ -31,6 +33,7 @@ public class ForgeDataScript extends MultiScriptHandler { private static List cachedHooks; private long lastForgeUpdate = -1L; + private final HashSet globalUnknownEvents = new HashSet<>(); public ForgeDataScript() { } @@ -58,6 +61,7 @@ public class ForgeDataScript extends MultiScriptHandler { protected void reInitScripts() { lastInited = ScriptController.Instance.lastLoaded; lastForgeUpdate = ScriptController.Instance.lastForgeUpdate; + globalUnknownEvents.clear(); for (IScriptUnit script : this.scripts) { if (script instanceof ScriptContainer) @@ -78,10 +82,25 @@ public class ForgeDataScript extends MultiScriptHandler { } } + // Skip events that no script tab handles + if (globalUnknownEvents.contains(type)) { + return; + } + + boolean anyHandled = false; for (IScriptUnit script : this.scripts) { if (script == null || script.hasErrored() || !script.hasCode()) continue; + boolean wasUnknown = script.isUnknownFunction(type); script.run(type, event); + if (!wasUnknown || !script.isUnknownFunction(type)) { + anyHandled = true; + } + } + + // If no script tab handled this event type, cache it globally + if (!anyHandled) { + globalUnknownEvents.add(type); } } @@ -161,6 +180,11 @@ public class ForgeDataScript extends MultiScriptHandler { ForgeScriptPacket.Save(index, totalCount, nbt); } + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.FORGE); + } + @Override public boolean isClient() { return false; diff --git a/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java b/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java index 4654ff68f..6f8a057cd 100644 --- a/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java @@ -8,6 +8,7 @@ import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.janino.EventJaninoScript; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.util.ScriptToStringHelper; @@ -47,6 +48,11 @@ public class GlobalNPCDataScript extends MultiScriptHandler { lastNpcUpdate = ScriptController.Instance.lastGlobalNpcUpdate; } + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.NPC); + } + @Override public void requestData() { GlobalNPCScriptPacket.Get(); diff --git a/src/main/java/noppes/npcs/controllers/data/HitboxData.java b/src/main/java/noppes/npcs/controllers/data/HitboxData.java index 4d2f0263b..4ccf9f823 100644 --- a/src/main/java/noppes/npcs/controllers/data/HitboxData.java +++ b/src/main/java/noppes/npcs/controllers/data/HitboxData.java @@ -1,9 +1,10 @@ package noppes.npcs.controllers.data; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.entity.data.IHitboxData; import noppes.npcs.config.ConfigMain; -public class HitboxData { +public class HitboxData implements IHitboxData { private float widthScale = 1f; private float heightScale = 1f; diff --git a/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java b/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java index 88ff5fb94..fdc3e3202 100644 --- a/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java +++ b/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java @@ -53,6 +53,12 @@ public interface IScriptHandlerPacket extends IScriptHandler { return new GuiDataResult(GuiDataKind.LOAD_COMPLETE, -1); } + // Ignore unrelated packets (e.g. ScriptInfoPacket config data) + // that don't contain any expected keys for this handler + if (!compound.hasKey("Tab") && !compound.hasKey("ScriptLanguage") && !compound.hasKey("ScriptEnabled")) { + return null; + } + if (!compound.hasKey("Tab")) { setLanguage(compound.getString("ScriptLanguage")); setEnabled(compound.getBoolean("ScriptEnabled")); diff --git a/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java b/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java index b439d7d0a..5cdd58e04 100644 --- a/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java +++ b/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java @@ -157,6 +157,24 @@ public interface IScriptUnit { */ void setErrored(boolean errored); + // ==================== INSTANCE SCOPE ==================== + + /** + * Create an instance-scoped copy of this script unit for isolated execution. + * The instance shares compiled code with the template but has isolated state. + * + * @param instanceHandler the script handler for the new instance + * @return a new IScriptUnit with isolated variable state + */ + IScriptUnit createInstanceScope(IScriptHandler instanceHandler); + + /** + * Check if the given function name is known to be absent from this script unit. + */ + default boolean isUnknownFunction(String type) { + return false; + } + // ==================== EXECUTION ==================== /** diff --git a/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java b/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java index e40452bfc..c26edbf0c 100644 --- a/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java +++ b/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java @@ -12,6 +12,11 @@ public class ItemDisplayData { public Boolean durabilityShow = false; public Integer durabilityColor = -1; + // Animation + public Boolean animated = false; + public Integer frameCount = 1; + public Integer frametime = 2; + public NBTTagCompound writeToNBT() { NBTTagCompound compound = new NBTTagCompound(); this.writeToNBT(compound); @@ -42,6 +47,10 @@ public class ItemDisplayData { this.setFloat(compound, "TranslateY", this.translateY); this.setFloat(compound, "TranslateZ", this.translateZ); + this.setBoolean(compound, "Animated", this.animated); + this.setInteger(compound, "FrameCount", this.frameCount); + this.setInteger(compound, "FrameTime", this.frametime); + return compound; } @@ -97,6 +106,16 @@ public class ItemDisplayData { if (compound.hasKey("TranslateZ")) { this.translateZ = compound.getFloat("TranslateZ"); } + + if (compound.hasKey("Animated")) { + this.animated = compound.getBoolean("Animated"); + } + if (compound.hasKey("FrameCount")) { + this.frameCount = Math.max(1, compound.getInteger("FrameCount")); + } + if (compound.hasKey("FrameTime")) { + this.frametime = Math.max(1, compound.getInteger("FrameTime")); + } } private void setBoolean(NBTTagCompound compound, String key, Boolean value) { diff --git a/src/main/java/noppes/npcs/controllers/data/JaninoScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/JaninoScriptHandler.java index cbe1230e0..4c9731880 100644 --- a/src/main/java/noppes/npcs/controllers/data/JaninoScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/JaninoScriptHandler.java @@ -56,11 +56,17 @@ public class JaninoScriptHandler> extends ScriptHandle public void readFromNBT(NBTTagCompound compound) { // JaninoScriptable's helper generics assume JaninoScript, but most of our scripts are JaninoScript. // Keep it simple and safe: treat it as raw. - script = (S) JaninoScript.readFromNBT(compound, (JaninoScript) script, (Supplier) factory); + NBTTagCompound tag = compound.getCompoundTag("Script"); + enabled = tag.getBoolean("enabled"); + script = (S) JaninoScript.readFromNBT(tag, (JaninoScript) script, (Supplier) factory); } public void writeToNBT(NBTTagCompound compound) { - JaninoScript.writeToNBT(compound, (JaninoScript) script); + NBTTagCompound tag = new NBTTagCompound(); + tag.setBoolean("enabled", enabled); + JaninoScript.writeToNBT(tag, (JaninoScript) script); + compound.setTag("Script", tag); + } // -------------------- IScriptHandler -------------------- diff --git a/src/main/java/noppes/npcs/controllers/data/LinkedItem.java b/src/main/java/noppes/npcs/controllers/data/LinkedItem.java index 961c570f9..14081a85a 100644 --- a/src/main/java/noppes/npcs/controllers/data/LinkedItem.java +++ b/src/main/java/noppes/npcs/controllers/data/LinkedItem.java @@ -8,9 +8,13 @@ import noppes.npcs.EventHooks; import noppes.npcs.api.handler.data.ILinkedItem; import noppes.npcs.api.item.IItemStack; import noppes.npcs.controllers.LinkedItemController; +import noppes.npcs.controllers.TagController; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.item.ScriptLinkedItem; +import java.util.HashSet; +import java.util.UUID; + public class LinkedItem implements ILinkedItem { public static final String LINKED_VERSION_VERSION_TAG = "LinkedVersion"; public static final String LINKED_DATA_NBT_TAG = "LinkedData"; @@ -33,6 +37,8 @@ public class LinkedItem implements ILinkedItem { public int armorType = -2; //-2: Fits in no armor slot, -1: Fits in all slots, 0 - 3: Fits in Head -> Boots slot respectively public int enchantability; + public HashSet tagUUIDs = new HashSet<>(); + public LinkedItem() { this("New"); } @@ -67,6 +73,8 @@ public class LinkedItem implements ILinkedItem { compound.setInteger("MaxItemUseDuration", this.maxItemUseDuration); compound.setInteger("ItemUseAction", this.itemUseAction); + TagController.writeTagUUIDs(compound, "TagUUIDs", tagUUIDs); + if (saveScripts) { NBTTagCompound scriptData = new NBTTagCompound(); LinkedItemScript handler = getScriptHandler(); @@ -97,6 +105,8 @@ public class LinkedItem implements ILinkedItem { this.maxItemUseDuration = compound.getInteger("MaxItemUseDuration"); this.itemUseAction = compound.getInteger("ItemUseAction"); + tagUUIDs = TagController.readTagUUIDs(compound, "TagUUIDs"); + if (compound.hasKey("ScriptData", Constants.NBT.TAG_COMPOUND)) { LinkedItemScript handler = new LinkedItemScript(); handler.readFromNBT(compound.getCompoundTag("ScriptData")); diff --git a/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java b/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java index a54c20727..841f6b063 100644 --- a/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java +++ b/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java @@ -3,6 +3,7 @@ package noppes.npcs.controllers.data; import kamkeel.npcs.network.packets.request.script.item.LinkedItemScriptPacket; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; /** * Script handler for LinkedItem scripts. @@ -35,6 +36,11 @@ public class LinkedItemScript extends SingleScriptHandler implements IScriptHand return ScriptContext.LINKED_ITEM; } + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.LINKED_ITEM); + } + @Override public String noticeString() { return "LinkedItem"; diff --git a/src/main/java/noppes/npcs/controllers/data/MagicData.java b/src/main/java/noppes/npcs/controllers/data/MagicData.java index fa81eb61e..f70e6ec75 100644 --- a/src/main/java/noppes/npcs/controllers/data/MagicData.java +++ b/src/main/java/noppes/npcs/controllers/data/MagicData.java @@ -76,4 +76,15 @@ public class MagicData implements IMagicData { MagicEntry entry = magics.get(id); return entry == null ? 0 : entry.split; } + + public MagicData copy() { + MagicData copy = new MagicData(); + for (java.util.Map.Entry e : magics.entrySet()) { + MagicEntry entryCopy = new MagicEntry(); + entryCopy.damage = e.getValue().damage; + entryCopy.split = e.getValue().split; + copy.magics.put(e.getKey(), entryCopy); + } + return copy; + } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 6d265de27..1da16a3af 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -1,10 +1,18 @@ package noppes.npcs.controllers.data; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper; 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.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; +import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.UpdateAnimationsPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; +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; import net.minecraft.entity.EntityLivingBase; @@ -14,18 +22,20 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.DamageSource; +import noppes.npcs.AbstractDataAbilities; +import noppes.npcs.EventHooks; +import noppes.npcs.LogWriter; import noppes.npcs.api.ability.IPlayerAbilityData; -import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.data.Animation; - -import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; +import java.util.Map; /** * Manages player ability data - unlocked abilities, selection, cooldowns, and execution. * Players reference abilities by key (built-in keys or preset names), never customized copies. + * Extends AbstractDataAbilities for shared ability lifecycle logic. *

* Key differences from NPC DataAbilities: * - Universal cooldown (shared across all abilities) @@ -33,7 +43,7 @@ import java.util.List; * - Conditions requiring a target are skipped * - Uses ability's base cooldownTicks only */ -public class PlayerAbilityData implements IPlayerAbilityData { +public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerAbilityData { private final PlayerData playerData; @@ -52,19 +62,16 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private int selectedIndex = 0; - // ═══════════════════════════════════════════════════════════════════ - // RUNTIME STATE (not saved) - // ═══════════════════════════════════════════════════════════════════ - /** - * Universal cooldown end time (shared across all abilities). + * 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 transient long cooldownEndTime = 0; + private boolean playingAbilityAnimation = false; - /** - * Currently executing ability instance (null if none). - */ - private transient Ability currentAbility; + // ═══════════════════════════════════════════════════════════════════ + // PLAYER-SPECIFIC RUNTIME STATE (not saved) + // ═══════════════════════════════════════════════════════════════════ /** * Current ability's key (for cooldown tracking after completion). @@ -76,6 +83,36 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private transient EntityLivingBase currentTarget; + /** + * Last synced state flags byte for change detection (avoids spamming packets). + */ + private transient byte lastSyncedFlags = 0; + + /** + * World time when the last ability was activated (for double-press cancel detection). + */ + private transient long lastAbilityActivationTime = -1; + + /** + * Ticks after activation during which a second key press will cancel the ability. + */ + private static final int CANCEL_WINDOW_TICKS = 10; + + /** + * Position tracking for teleport detection during ability execution. + * If the player moves more than {@link #TELEPORT_THRESHOLD_SQ} in a single tick, + * the ability is interrupted as if the player changed dimensions. + */ + private transient double lastAbilityTickX, lastAbilityTickY, lastAbilityTickZ; + private transient boolean trackingAbilityPosition = false; + + /** + * Squared distance threshold for teleport detection (48 blocks). + * Normal sprint speed is ~5.6 blocks/tick; this threshold is well above + * any legitimate per-tick movement including ability-driven dashes. + */ + private static final double TELEPORT_THRESHOLD_SQ = 48.0 * 48.0; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -84,6 +121,169 @@ public class PlayerAbilityData implements IPlayerAbilityData { this.playerData = playerData; } + // ═══════════════════════════════════════════════════════════════════ + // ABSTRACT METHOD IMPLEMENTATIONS + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected EntityLivingBase getEntity() { + return playerData.player; + } + + @Override + protected EntityLivingBase getTarget() { + return currentTarget; + } + + @Override + protected long getWorldTime() { + EntityPlayer player = playerData.player; + return player != null ? player.worldObj.getTotalWorldTime() : 0; + } + + @Override + protected void spawnTelegraph(Ability ability, EntityLivingBase target) { + EntityPlayer player = playerData.player; + List telegraphs = ability.createTelegraphs(player, target); + if (!telegraphs.isEmpty()) { + ability.setTelegraphInstances(telegraphs); + if (player instanceof EntityPlayerMP) { + for (TelegraphInstance telegraph : telegraphs) { + TelegraphSpawnPacket.sendToTracking(telegraph, player); + } + } + } + } + + @Override + protected void removeTelegraph(Ability ability) { + EntityPlayer player = playerData.player; + List telegraphs = ability.getTelegraphInstances(); + for (TelegraphInstance telegraph : telegraphs) { + if (player instanceof EntityPlayerMP) { + TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), player); + } + } + ability.setTelegraphInstances(null); + } + + @Override + protected void setAnimationData(Animation animation) { + playerData.animationData.setEnabled(true); + playerData.animationData.setAnimation(animation); + playerData.animationData.updateClient(); + playingAbilityAnimation = true; + } + + @Override + protected void clearAnimationData() { + playerData.animationData.setAnimation(null); + playerData.animationData.updateClient(); + + // Directly send animation clear to the owning player. updateClient() uses + // getEntitiesWithinAABB to find recipients, but during teleport the player + // entity hasn't migrated to the new chunk yet — so the AABB search centered + // on the new position won't find them, and the clear packet is never delivered. + // This guarantees the player's client always receives the clear. + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + NBTTagCompound data = new NBTTagCompound(); + data.setBoolean("AllowAnimation", playerData.animationData.enabled()); + PacketHandler.Instance.sendToPlayer( + new UpdateAnimationsPacket(data, player.getCommandSenderName()), + (EntityPlayerMP) player + ); + } + + playingAbilityAnimation = false; + } + + @Override + protected void playAbilitySound(String sound) { + if (sound != null && !sound.isEmpty()) { + EntityPlayer player = playerData.player; + if (player != null) { + player.worldObj.playSoundAtEntity(player, sound, 1.0f, 1.0f); + } + } + } + + @Override + protected void captureLockedRotation() { + EntityPlayer player = playerData.player; + lockedYaw = player.rotationYaw; + lockedPitch = player.rotationPitch; + rotationLocked = true; + } + + @Override + protected void rollCooldown(Ability ability) { + if (ability.isIgnoreCooldown()) return; + + int duration = ability.getCooldownTicks(); + long endTime = getWorldTime() + duration; + + if (ability.isPerAbilityCooldown()) { + // Per-ability: only this ability goes on cooldown + if (currentAbilityKey != null) { + setPerAbilityCooldown(currentAbilityKey, endTime, duration); + } + } else { + // Global: all global-cooldown abilities share this cooldown + cooldownEndTime = endTime; + globalCooldownDuration = duration; + } + } + + @Override + protected void rollChainCooldown(ChainedAbility chain) { + if (chain.isIgnoreCooldown()) return; + + int duration = chain.getCooldownTicks(); + long endTime = getWorldTime() + duration; + + if (chain.isPerAbilityCooldown()) { + if (currentAbilityKey != null) { + setPerAbilityCooldown(currentAbilityKey, endTime, duration); + } + } else { + cooldownEndTime = endTime; + globalCooldownDuration = duration; + } + } + + @Override + protected void onAbilityComplete() { + currentAbility = null; + currentAbilityKey = null; + currentTarget = null; + lastAbilityActivationTime = -1; + syncAbilityStateClear(playerData.player); + } + + // ═══════════════════════════════════════════════════════════════════ + // HOOK OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void onInterruptComplete() { + // Player clears state immediately (unlike NPC which ticks through DAZED) + // Roll cooldown before clearing state — NPC rolls during handleAbilityCompletion + // after ticking through DAZED, but the player skips DAZED entirely. + if (!interruptCooldownRolled && currentAbility != null) { + rollCooldown(currentAbility); + } + interruptCooldownRolled = false; + + // Stop the dazed animation that was started in interruptCurrentAbility() + stopAbilityAnimation(); + currentAbility = null; + currentAbilityKey = null; + currentTarget = null; + lastAbilityActivationTime = -1; + syncAbilityStateClear(playerData.player); + } + // ═══════════════════════════════════════════════════════════════════ // TICK - Called from player tick handler // ═══════════════════════════════════════════════════════════════════ @@ -97,85 +297,53 @@ public class PlayerAbilityData implements IPlayerAbilityData { return; } - if (currentAbility != null && currentAbility.isExecuting()) { - tickCurrentAbility(player); - } - } + // Tick active toggles (independent of currentAbility) + tickActiveToggles(); - /** - * Tick the currently executing ability. - */ - private void tickCurrentAbility(EntityPlayer player) { - AbilityPhase oldPhase = currentAbility.getPhase(); + boolean hasActiveAbility = chainDelayRemaining > 0 || (currentAbility != null && currentAbility.isExecuting()); - // Tick advances time and possibly changes phase - boolean phaseChanged = currentAbility.tick(); - - switch (currentAbility.getPhase()) { - case WINDUP: - currentAbility.onWindUpTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); - break; - - case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { - // Just entered ACTIVE phase - TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); - if (telegraph != null) { - telegraph.lockPosition(); - } - removeTelegraph(currentAbility, player); - - // Play active sound and animation - playAbilitySound(player, currentAbility.getActiveSound()); - playAbilityAnimation(currentAbility.getActiveAnimation()); - - // Call onExecute - currentAbility.onExecute(player, currentTarget, player.worldObj); - - if (currentAbility.getPhase() == AbilityPhase.IDLE) { - handleAbilityCompletion(player); - return; - } - } - currentAbility.onActiveTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); - - if (currentAbility.getPhase() == AbilityPhase.IDLE) { - handleAbilityCompletion(player); + if (hasActiveAbility) { + // Detect large position jump (teleport) while ability is executing. + // Must run BEFORE tickCurrentAbility / applyPositionLock so the raw + // teleported position is visible before any lock snaps it back. + if (trackingAbilityPosition) { + double dx = player.posX - lastAbilityTickX; + double dy = player.posY - lastAbilityTickY; + double dz = player.posZ - lastAbilityTickZ; + if (dx * dx + dy * dy + dz * dz > TELEPORT_THRESHOLD_SQ) { + // Player was teleported — clear ability state (same as dimension change) + trackingAbilityPosition = false; + resetOnTeleport(); return; } - break; + } - case DAZED: - // Player is dazed - just wait - break; + // Update tracked position for next tick's comparison + lastAbilityTickX = player.posX; + lastAbilityTickY = player.posY; + lastAbilityTickZ = player.posZ; + trackingAbilityPosition = true; - case IDLE: - handleAbilityCompletion(player); - break; + tickCurrentAbility(); + + // 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 { + trackingAbilityPosition = false; + + // Safety: release orphaned locks if no ability is executing + if (rotationLocked || positionLocked) { + releaseRotationControl(); + releaseLockedPosition(); + syncAbilityStateClear(player); + } } } - /** - * Handle ability completion. - */ - private void handleAbilityCompletion(EntityPlayer player) { - if (currentAbility == null) return; - - currentAbility.onComplete(player, currentTarget); - - // Apply universal cooldown (using base cooldownTicks only, not min/max random) - if (!currentAbility.isIgnoreCooldown()) { - cooldownEndTime = player.worldObj.getTotalWorldTime() + currentAbility.getCooldownTicks(); - } - - // Stop animation - stopAbilityAnimation(); - - currentAbility = null; - currentAbilityKey = null; - currentTarget = null; - } - // ═══════════════════════════════════════════════════════════════════ // ABILITY ACTIVATION - Called on Special Key press // ═══════════════════════════════════════════════════════════════════ @@ -197,84 +365,161 @@ public class PlayerAbilityData implements IPlayerAbilityData { } /** - * Activate a specific ability by key. + * Prefix used to identify chained ability keys in the unlocked list. + */ + public static final String CHAIN_PREFIX = "chain:"; + + /** + * Resolve an action key to an IAbilityAction. + * Handles "chain:" prefix for chained abilities, otherwise resolves from AbilityController. + */ + private IAbilityAction resolveActionKey(String key) { + if (key.startsWith(CHAIN_PREFIX)) { + return AbilityController.Instance.resolveChainedAbility(key.substring(CHAIN_PREFIX.length())); + } + return AbilityController.Instance.resolveAbility(key); + } + + /** + * Activate a specific ability by key. Keys prefixed with "chain:" are + * treated as chained abilities and resolved from {@link AbilityController}. * * @param player The player - * @param key The ability key (built-in or preset name) + * @param key The ability key (built-in or preset name), or "chain:name" for chains * @return true if the ability was started */ public boolean activateAbility(EntityPlayer player, String key) { if (player.worldObj.isRemote || key == null || key.isEmpty()) return false; + // Global activation check (e.g., addon-registered restrictions) + if (!AbilityController.Instance.canPlayerActivate(player)) return false; + // Can't activate if already executing if (currentAbility != null && currentAbility.isExecuting()) return false; + if (isExecutingChain()) return false; - // Resolve ability from controller - if (AbilityController.Instance == null) return false; - Ability ability = AbilityController.Instance.resolveAbility(key); - if (ability == null) return false; + // Resolve via unified resolver + IAbilityAction action = resolveActionKey(key); + if (action == null) return false; // Check user type allows player - if (!ability.getAllowedBy().allowsPlayer()) return false; - - // Check universal cooldown - if (!ability.isIgnoreCooldown() && isOnCooldown(player)) return false; + if (!action.getAllowedBy().allowsPlayer()) return false; // Check conditions (skip target-requiring ones) - if (!ability.checkConditionsForPlayer(player)) return false; + if (!action.checkConditionsForPlayer(player)) return false; + + // Check player requirement (visibility/availability gate) + if (!action.isAvailableFor(player)) return false; + + // Dispatch: chain vs ability + if (action.isChain()) { + ChainedAbility chain = (ChainedAbility) action; + if (!chain.isIgnoreCooldown()) { + if (chain.isPerAbilityCooldown()) { + if (isOnPerAbilityCooldown(key)) return false; + } else { + if (isOnCooldown()) return false; + } + } + + currentAbilityKey = key; + currentTarget = null; + lastAbilityActivationTime = getWorldTime(); + return startChain((ChainedAbility) action, null); + } + + // Regular ability activation + Ability ability = (Ability) action; + + // Toggle abilities cycle state instead of executing + if (ability.isToggleable()) { + toggleAbility(key); + return true; + } + + // Check cooldown (per-ability cooldowns are independent from global) + if (!ability.isIgnoreCooldown()) { + if (ability.isPerAbilityCooldown()) { + if (isOnPerAbilityCooldown(key)) return false; + } else { + if (isOnCooldown()) 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 (EventHooks.onAbilityStart(ability, player, null)) { + return false; // Cancelled + } // Start the ability currentAbility = ability; currentAbilityKey = key; currentTarget = null; // Players don't have auto-targets + lastAbilityActivationTime = getWorldTime(); ability.start(null); if (ability.getPhase() == AbilityPhase.ACTIVE) { - // Windup was 0 — skip telegraph/windup and go straight to active - executeImmediate(ability, player); + // Windup was 0 — capture locks for immediate active phase, then execute + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } + executeImmediate(ability, currentTarget); } else { // Normal windup flow - spawnTelegraph(ability, player, null); - playAbilitySound(player, ability.getWindUpSound()); + if (ability.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(ability, null); + playAbilitySound(ability.getWindUpSound()); playAbilityAnimation(ability.getWindUpAnimation()); } + // Immediate sync on ability use + syncToClient(); return true; } - /** - * Execute an ability immediately (no windup). - * Called when windUpTicks is 0. - */ - private void executeImmediate(Ability ability, EntityPlayer player) { - // Play active sound and animation - playAbilitySound(player, ability.getActiveSound()); - playAbilityAnimation(ability.getActiveAnimation()); - - // Call onExecute - ability.onExecute(player, currentTarget, player.worldObj); - - // Check if ability completed during onExecute - if (ability.getPhase() == AbilityPhase.IDLE) { - handleAbilityCompletion(player); - } - } - // ═══════════════════════════════════════════════════════════════════ // CLIENT SYNC // ═══════════════════════════════════════════════════════════════════ /** - * Sync ability data to the client. - * Called when abilities change (unlock/lock/select) and on login. + * Full sync of all ability state to the client. + * Delegates to {@link PlayerAbilitySyncHelper#syncAbilities(EntityPlayerMP)}. */ public void syncToClient() { EntityPlayer player = playerData.player; if (player instanceof EntityPlayerMP) { - PlayerAbilitySyncPacket.sendToPlayer((EntityPlayerMP) player); + PlayerAbilitySyncHelper.syncAbilities((EntityPlayerMP) player); } } + /** + * Lightweight sync of cooldown state only to the client. + * Delegates to {@link PlayerAbilitySyncHelper#syncAbilityCooldowns(EntityPlayerMP)}. + */ + public void syncCooldownToClient() { + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + PlayerAbilitySyncHelper.syncAbilityCooldowns((EntityPlayerMP) player); + } + } + + @Override + protected void onToggleStateChanged(String key, boolean active, int state) { + } + // ═══════════════════════════════════════════════════════════════════ // SELECTION // ═══════════════════════════════════════════════════════════════════ @@ -284,22 +529,19 @@ public class PlayerAbilityData implements IPlayerAbilityData { } public void setSelectedIndex(int index) { - if (index >= 0 && index < unlockedAbilities.size()) { + if (index == -1 || (index >= 0 && index < unlockedAbilities.size())) { this.selectedIndex = index; - syncToClient(); } } public void selectNext() { if (unlockedAbilities.isEmpty()) return; selectedIndex = (selectedIndex + 1) % unlockedAbilities.size(); - syncToClient(); } public void selectPrevious() { if (unlockedAbilities.isEmpty()) return; selectedIndex = (selectedIndex - 1 + unlockedAbilities.size()) % unlockedAbilities.size(); - syncToClient(); } public String getSelectedAbilityKey() { @@ -328,13 +570,11 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (selectedIndex >= unlockedAbilities.size()) { selectedIndex = Math.max(0, unlockedAbilities.size() - 1); } - syncToClient(); } public void unlockAbility(String key) { if (key != null && !key.isEmpty() && !unlockedAbilities.contains(key)) { unlockedAbilities.add(key); - syncToClient(); } } @@ -343,7 +583,6 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (selectedIndex >= unlockedAbilities.size()) { selectedIndex = Math.max(0, unlockedAbilities.size() - 1); } - syncToClient(); } public boolean hasUnlockedAbility(String key) { @@ -351,18 +590,27 @@ public class PlayerAbilityData implements IPlayerAbilityData { } // ═══════════════════════════════════════════════════════════════════ - // COOLDOWNS + // COOLDOWNS (Player-specific overloads) // ═══════════════════════════════════════════════════════════════════ + /** + * Check if on cooldown using player reference. + */ public boolean isOnCooldown(EntityPlayer player) { return player.worldObj.getTotalWorldTime() < cooldownEndTime; } /** * Check if a specific ability key is on cooldown. - * Currently uses universal cooldown (same for all abilities). + * Respects per-ability cooldown if the ability has it enabled. */ public boolean isOnCooldown(String key, EntityPlayer player) { + if (AbilityController.Instance != null) { + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability != null && ability.isPerAbilityCooldown()) { + return isOnPerAbilityCooldown(key); + } + } return isOnCooldown(player); } @@ -373,19 +621,25 @@ public class PlayerAbilityData implements IPlayerAbilityData { /** * Reset cooldown for a specific ability key. - * Currently resets the universal cooldown. + * Resets per-ability cooldown if applicable, and global cooldown. */ public void resetCooldown(String key) { + resetPerAbilityCooldown(key); cooldownEndTime = 0; } /** - * Reset all cooldowns. + * Reset all cooldowns (global + all per-ability). */ public void resetAllCooldowns() { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); } + // ═══════════════════════════════════════════════════════════════════ + // IPlayerAbilityData INTERFACE + // ═══════════════════════════════════════════════════════════════════ + @Override public boolean activateAbility() { return activateAbility(playerData.player); @@ -396,28 +650,6 @@ public class PlayerAbilityData implements IPlayerAbilityData { return activateAbility(playerData.player, key); } - // ═══════════════════════════════════════════════════════════════════ - // STATE QUERIES - // ═══════════════════════════════════════════════════════════════════ - - public boolean isExecutingAbility() { - return currentAbility != null && currentAbility.isExecuting(); - } - - public Ability getCurrentAbility() { - return currentAbility; - } - - public void interruptCurrentAbility() { - if (currentAbility != null && currentAbility.isExecuting()) { - currentAbility.interrupt(); - stopAbilityAnimation(); - currentAbility = null; - currentAbilityKey = null; - currentTarget = null; - } - } - @Override public boolean isOnCooldown() { EntityPlayer player = playerData.player; @@ -435,8 +667,228 @@ public class PlayerAbilityData implements IPlayerAbilityData { @Override public void resetCooldown() { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); } + // ═══════════════════════════════════════════════════════════════════ + // INTERRUPTION (convenience overload) + // ═══════════════════════════════════════════════════════════════════ + + public void interruptCurrentAbility() { + interruptCurrentAbility(null, 0); + } + + /** + * Try to cancel the current ability via double-press. + * Only succeeds if within the cancel window and not in DAZED phase. + * Also handles cancellation during chain delay (between chain entries). + * + * @return true if the ability was cancelled + */ + public boolean tryCancelAbility() { + boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting(); + boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0; + + if (!hasExecutingAbility && !isInChainDelay) return false; + + // Only allow cancel during WINDUP phase + if (hasExecutingAbility) { + AbilityPhase phase = currentAbility.getPhase(); + if (phase != AbilityPhase.WINDUP) return false; + } + + long worldTime = getWorldTime(); + if (lastAbilityActivationTime < 0 || (worldTime - lastAbilityActivationTime) > CANCEL_WINDOW_TICKS) { + // Outside cancel window — update time so a quick follow-up press can cancel + lastAbilityActivationTime = worldTime; + return false; + } + + cancelCurrentAbility(); + return true; + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTITY RECONSTRUCTION RESET + // ═══════════════════════════════════════════════════════════════════ + + /** + * Handle entity reconstruction events (dimension change, death/respawn, etc.). + * Cleans up any executing ability state without firing script events (those were + * already fired on the original entity), clears transient runtime state, and + * re-syncs ability data to the client on the new entity. + *

+ * This should be called whenever the player's entity object is recreated by Forge, + * since the client-side entity loses all synced ability state. + * + * @param clearCooldowns true to fully reset cooldowns (dimension change), + * false to preserve cooldowns (death/respawn — interrupt already rolled them) + * @param clearToggles true to clear active toggles (death/respawn), + * false to keep them (dimension change) + */ + public void onEntityReconstructed(boolean clearCooldowns, boolean clearToggles) { + // Clean up any executing ability silently (no script events — already fired on old entity) + if (currentAbility != null && currentAbility.isExecuting()) { + removeTelegraph(currentAbility); + currentAbility.interrupt(); + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + } + + // Clear chain and concurrent state + if (currentChain != null) currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + interruptConcurrentSlots(); + + // Clear all transient state + currentAbility = null; + currentAbilityKey = null; + currentTarget = null; + lastAbilityActivationTime = -1; + + if (clearCooldowns) { + cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + } + interruptCooldownRolled = false; + + if (clearToggles) { + clearActiveToggles(); + } + + // Force-send cleared lock state to client. We must always send this + // (not gated by lastSyncedFlags != 0) because the NEW entity's client + // may have stale lock state from before the reconstruction. + lastSyncedFlags = 0; + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0); + } + + // Re-sync full ability data (unlocked list, selection, toggles) to client + syncToClient(); + } + + /** + * Fully reset transient ability execution state when changing dimensions. + * Cooldowns are preserved so dimension changes cannot bypass them. + * Keeps active toggles (dimension change shouldn't reset ongoing effects). + */ + public void resetOnDimensionChange() { + trackingAbilityPosition = false; + onEntityReconstructed(false, false); + } + + /** + * Reset ability state when a large-distance teleport is detected during execution. + * Same behavior as dimension change: silent cleanup, preserve cooldowns, keep toggles. + */ + public void resetOnTeleport() { + onEntityReconstructed(false, false); + } + + /** + * Reset ability state after death/respawn. + * Preserves cooldowns (the death handler interrupted the ability which rolled cooldown + * via onInterruptComplete) but clears active toggles (death should end ongoing effects). + */ + public void resetOnRespawn() { + onEntityReconstructed(false, true); + } + + /** + * Reset ability state on login. Clears all transient execution state (current ability, + * locks, chains, cooldowns) that may have leaked from a previous session via the + * PlayerData cache. Toggles are NOT cleared — they are restored from NBT by readFromNBT. + *

+ * Does NOT send packets — called before the client's sync state is initialized. + * The caller must trigger a full ability sync afterwards (e.g. via syncToClient). + */ + public void resetOnLogin() { + trackingAbilityPosition = false; + + // Silently clean up any stale executing ability + if (currentAbility != null && currentAbility.isExecuting()) { + removeTelegraph(currentAbility); + currentAbility.interrupt(); + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + } + + // Clear chain and concurrent state + if (currentChain != null) currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + interruptConcurrentSlots(); + + // Clear all transient state + currentAbility = null; + currentAbilityKey = null; + currentTarget = null; + lastAbilityActivationTime = -1; + + // Cooldowns are absolute world-time deadlines and are restored from NBT, so relogging + // must not clear them or it becomes a way to bypass them. + interruptCooldownRolled = false; + + // Reset sync tracking so next sync sends fresh state + lastSyncedFlags = 0; + } + + /** + * Clean up ability state on disconnect. Interrupts any executing ability (fires events, + * rolls cooldown) before the player entity goes away, then clears all transient state. + * This ensures scripts receive proper interrupt/complete events and prevents stale state + * from leaking into the next session via the PlayerData cache. + */ + public void resetOnDisconnect() { + // Interrupt with events so scripts know the ability ended + if (currentAbility != null && currentAbility.isExecuting()) { + interruptCurrentAbility(null, 0); + } + // Clear any remaining transient state (chains, locks) + // Don't clear toggles — they were already saved to NBT by this point + // Don't clear cooldowns — they persist across sessions + onEntityReconstructed(false, false); + } + + // ═══════════════════════════════════════════════════════════════════ + // DAMAGE HANDLING + // ═══════════════════════════════════════════════════════════════════ + + /** + * 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; + } + if (currentAbility.isInvulnerableForCurrentPhase()) { + return 0; + } + + if (currentAbility != null && currentAbility.canInterrupt(source)) { + interruptCurrentAbility(source, amount); + } + + return amount; + } + + // ═══════════════════════════════════════════════════════════════════ + // STATE QUERIES (Player-specific) + // ═══════════════════════════════════════════════════════════════════ + /** * Check if the player's movement should be locked due to an executing ability. * Used by the tick handler to restrict player movement during ability phases. @@ -446,65 +898,131 @@ public class PlayerAbilityData implements IPlayerAbilityData { && currentAbility.isMovementLockedForCurrentPhase(); } + /** + * 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(); + } + // ═══════════════════════════════════════════════════════════════════ - // TELEGRAPH + // ROTATION CONTROL (Player-specific application) // ═══════════════════════════════════════════════════════════════════ - private void spawnTelegraph(Ability ability, EntityPlayer player, EntityLivingBase target) { - TelegraphInstance telegraph = ability.createTelegraph(player, target); - if (telegraph != null) { - ability.setTelegraphInstance(telegraph); + /** + * 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) { - TelegraphSpawnPacket.sendToTracking(telegraph, player); + player.rotationYawHead = lockedYaw; } } } - private void removeTelegraph(Ability ability, EntityPlayer player) { - TelegraphInstance telegraph = ability.getTelegraphInstance(); - if (telegraph != null) { - if (player instanceof EntityPlayerMP) { - TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), player); - } - ability.setTelegraphInstance(null); + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING (Player-specific application) + // ═══════════════════════════════════════════════════════════════════ + + /** + * 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; + 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 || currentAbility.getPhase() == AbilityPhase.WINDUP)) { + flags |= PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT; + } + if (positionLocked) { + flags |= PlayerAbilityStatePacket.FLAG_POSITION_LOCKED; + } + if (wasFlyingAtLock) { + flags |= PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK; + } + if (currentAbility.getPhase() == AbilityPhase.ACTIVE) { + flags |= PlayerAbilityStatePacket.FLAG_ACTIVE_PHASE; + } + 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); } } - // ═══════════════════════════════════════════════════════════════════ - // ANIMATION - // ═══════════════════════════════════════════════════════════════════ - - public void playAbilityAnimation(Animation animation) { - if (animation == null || AnimationController.Instance == null) return; - playerData.animationData.setEnabled(true); - playerData.animationData.setAnimation(animation); - playerData.animationData.updateClient(); + /** + * 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); + } } - public void playAbilityAnimation(int animation) { - if (animation < 0) return; - if (AnimationController.Instance == null) return; - if (AnimationController.Instance.get(animation) == null) return; - - playAbilityAnimation((Animation) AnimationController.Instance.get(animation)); - } - - public void playAbilityAnimation(String animation) { - if (animation.isEmpty()) return; - if (AnimationController.Instance == null) return; - if (AnimationController.Instance.get(animation, true) == null) return; - - playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true)); - } - - private void stopAbilityAnimation() { - playerData.animationData.setAnimation(null); - playerData.animationData.updateClient(); - } - - private void playAbilitySound(EntityPlayer player, String sound) { - if (sound != null && !sound.isEmpty()) { - player.worldObj.playSoundAtEntity(player, sound, 1.0f, 1.0f); + /** + * Periodic safety check: if no ability is executing but the client may have + * stale lock flags, send a clear. Prevents stuck clients from missed packets. + */ + public void ensureLockStateClear() { + if (isExecutingAbility() || isExecutingChain()) return; + EntityPlayer player = playerData.player; + if (!(player instanceof EntityPlayerMP)) return; + if (lastSyncedFlags != 0) { + lastSyncedFlags = 0; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0); } } @@ -519,6 +1037,33 @@ public class PlayerAbilityData implements IPlayerAbilityData { } compound.setTag("PlayerAbilities", list); compound.setInteger("PlayerAbilitySelected", selectedIndex); + compound.setBoolean("AbilityAnimating", playingAbilityAnimation); + + // Active toggles (compound format with state) + NBTTagList toggleList = new NBTTagList(); + for (Map.Entry entry : activeToggles.entrySet()) { + NBTTagCompound toggleNbt = new NBTTagCompound(); + toggleNbt.setString("Key", entry.getKey()); + toggleNbt.setInteger("State", entry.getValue().getState()); + toggleList.appendTag(toggleNbt); + } + compound.setTag("ActiveToggles", toggleList); + + // Cooldowns are absolute world-time deadlines, so they stay meaningful across sessions + NBTTagCompound cooldowns = new NBTTagCompound(); + cooldowns.setLong("GlobalEnd", cooldownEndTime); + cooldowns.setInteger("GlobalDuration", globalCooldownDuration); + NBTTagList perAbilityList = new NBTTagList(); + for (Map.Entry entry : perAbilityCooldownEndTimes.entrySet()) { + NBTTagCompound cooldownNbt = new NBTTagCompound(); + cooldownNbt.setString("Key", entry.getKey()); + cooldownNbt.setLong("End", entry.getValue()); + Integer duration = perAbilityCooldownDurations.get(entry.getKey()); + cooldownNbt.setInteger("Duration", duration == null ? 0 : duration); + perAbilityList.appendTag(cooldownNbt); + } + cooldowns.setTag("PerAbility", perAbilityList); + compound.setTag("AbilityCooldowns", cooldowns); } public void readFromNBT(NBTTagCompound compound) { @@ -533,8 +1078,67 @@ 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"); + + // Active toggles - restore state directly (no onToggle callback during load) + activeToggles.clear(); + if (compound.hasKey("ActiveToggles")) { + NBTTagList toggleNbt = compound.getTagList("ActiveToggles", 10); // 10 = TAG_COMPOUND + for (int i = 0; i < toggleNbt.tagCount(); i++) { + NBTTagCompound entry = toggleNbt.getCompoundTagAt(i); + String key = entry.getString("Key"); + int state = entry.hasKey("State") ? entry.getInteger("State") : 1; + setToggleEntryDirect(key, state); + } + } + + if (compound.hasKey("AbilityCooldowns")) { + cooldownEndTime = 0; + globalCooldownDuration = 0; + resetAllPerAbilityCooldowns(); + + NBTTagCompound cooldowns = compound.getCompoundTag("AbilityCooldowns"); + cooldownEndTime = cooldowns.getLong("GlobalEnd"); + globalCooldownDuration = cooldowns.getInteger("GlobalDuration"); + NBTTagList perAbilityList = cooldowns.getTagList("PerAbility", 10); // 10 = TAG_COMPOUND + for (int i = 0; i < perAbilityList.tagCount(); i++) { + NBTTagCompound entry = perAbilityList.getCompoundTagAt(i); + String key = entry.getString("Key"); + if (key == null || key.isEmpty()) continue; + perAbilityCooldownEndTimes.put(key, entry.getLong("End")); + perAbilityCooldownDurations.put(key, entry.getInteger("Duration")); + } + } + } + + /** + * Remove any unlocked ability keys that can no longer be resolved or + * are no longer allowed for players (e.g. NPC-only abilities). + * Called during load to clean up references to deleted/restricted abilities. + * Supports both regular ability keys and "chain:" prefixed chained ability keys. + */ + private void validateUnlockedAbilities() { + if (AbilityController.Instance == null) return; + if (playerData == null || !(playerData.player instanceof EntityPlayerMP)) return; + + Iterator it = unlockedAbilities.iterator(); + while (it.hasNext()) { + String key = it.next(); + IAbilityAction resolved = resolveActionKey(key); + if (resolved == null) { + it.remove(); + LogWriter.info("Removed invalid ability reference from player data: " + key); + } else if (!resolved.getAllowedBy().allowsPlayer()) { + it.remove(); + LogWriter.info("Removed non-player ability from player data: " + key); + } + } } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java new file mode 100644 index 000000000..6ff49c4b6 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java @@ -0,0 +1,90 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.FMLCommonHandler; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +public class PlayerAbilityHotbarData { + public AbilityHotbarData[] slots = new AbilityHotbarData[AbilityHotbarData.TOTAL_SLOTS]; + + public PlayerAbilityHotbarData() { + for (int i = 0; i < slots.length; i++) { + slots[i] = new AbilityHotbarData(i); + } + } + + public AbilityHotbarData getSlot(int index) { + if (index < 0 || index >= slots.length) return null; + return slots[index]; + } + + public void setSlot(int index, String abilityKey) { + if (index < 0 || index >= slots.length) return; + slots[index].abilityKey = abilityKey != null ? abilityKey : ""; + } + + public void clearSlot(int index) { + if (index < 0 || index >= slots.length) return; + slots[index].reset(); + } + + public boolean hasAnyAbilities() { + for (AbilityHotbarData slot : slots) { + if (!slot.isEmpty()) return true; + } + return false; + } + + public void writeToNBT(NBTTagCompound compound) { + for (int i = 0; i < slots.length; i++) { + slots[i].writeToNBT(compound); + } + } + + public void readFromNBT(NBTTagCompound compound) { + for (int i = 0; i < slots.length; i++) { + NBTTagCompound slotTag = compound.getCompoundTag("AbilityHotbar" + i); + slots[i].readFromNBT(slotTag); + } + validateSlots(); + } + + public void validateSlots() { + if (AbilityController.Instance == null) return; + // Only validate on the server - the client trusts server-sent data. + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; + for (AbilityHotbarData slot : slots) { + if (slot.isEmpty()) continue; + boolean valid; + if (slot.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slot.abilityKey); + // Also check that resolved ability allows player usage + if (valid) { + Ability ability = AbilityController.Instance.resolveAbility(slot.abilityKey); + if (ability != null && !ability.getAllowedBy().allowsPlayer()) { + valid = false; + } + } + } + if (!valid) { + slot.reset(); + } + } + } + + /** + * Sync hotbar data only to the client. + * Used after server confirms a client hotbar edit. + */ + public void syncToClient(EntityPlayer player) { + if (player instanceof EntityPlayerMP) { + AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player); + } + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index fa4e7d961..0c575eb77 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -18,13 +18,13 @@ import noppes.npcs.LogWriter; import noppes.npcs.api.ability.IPlayerAbilityData; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.handler.IPlayerBankData; -import noppes.npcs.api.handler.IPlayerTradeData; import noppes.npcs.api.handler.IPlayerData; import noppes.npcs.api.handler.IPlayerDialogData; import noppes.npcs.api.handler.IPlayerFactionData; import noppes.npcs.api.handler.IPlayerItemGiverData; import noppes.npcs.api.handler.IPlayerMailData; import noppes.npcs.api.handler.IPlayerQuestData; +import noppes.npcs.api.handler.IPlayerTradeData; import noppes.npcs.api.handler.IPlayerTransportData; import noppes.npcs.config.ConfigMain; import noppes.npcs.constants.EnumRoleType; @@ -47,8 +47,6 @@ import java.io.FileOutputStream; import java.util.HashSet; import java.util.UUID; -import static noppes.npcs.util.CustomNPCsThreader.customNPCThread; - public class PlayerData implements IExtendedEntityProperties, IPlayerData { public PlayerDialogData dialogData = new PlayerDialogData(this); public PlayerBankData bankData = new PlayerBankData(this); @@ -67,6 +65,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { public PlayerTradeData tradeData = new PlayerTradeData(this); public PlayerAbilityData abilityData = new PlayerAbilityData(this); + public PlayerAbilityHotbarData hotbarData = new PlayerAbilityHotbarData(); public ActionManager actionManager = new ActionManager(); public PlayerDataScript scriptData; @@ -95,13 +94,25 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { private boolean specialKeyDown = false; public void onLogin() { - // Continue playing animation for self when re-logging + // Clear any stale transient ability state that leaked via the PlayerData cache. + // Must happen before the animation check since it may clear ability animation state. + abilityData.resetOnLogin(); + + // 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(); @@ -110,12 +121,12 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { if (!controller.playerEffects.containsKey(playerID)) { controller.playerEffects.put(playerID, effectData.getEffects()); } - - // Sync player ability data to client - abilityData.syncToClient(); } public void onLogout() { + // Interrupt executing ability (fires events, rolls cooldown), then clear + // all transient state so nothing leaks via the PlayerData cache. + abilityData.resetOnDisconnect(); this.partyInvites.clear(); this.actionManager.clear(); } @@ -143,6 +154,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { magicData.readToNBT(data); tradeData.readFromNBT(data); abilityData.readFromNBT(data); + hotbarData.readFromNBT(data); if (player != null) { playername = player.getCommandSenderName(); @@ -187,6 +199,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { magicData.writeToNBT(compound); tradeData.writeToNBT(compound); abilityData.writeToNBT(compound); + hotbarData.writeToNBT(compound); compound.setString("PlayerName", playername); compound.setString("UUID", uuid); @@ -240,6 +253,8 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { factionData.saveNBTData(compound); mailData.saveNBTData(compound); tradeData.writeToNBT(compound); + abilityData.writeToNBT(compound); + hotbarData.writeToNBT(compound); compound.setString("PlayerName", playername); compound.setString("UUID", uuid); DBCAddon.instance.writeToNBT(this, compound); @@ -254,6 +269,8 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { factionData.loadNBTData(data); mailData.loadNBTData(data); tradeData.readFromNBT(data); + abilityData.readFromNBT(data); + hotbarData.readFromNBT(data); if (player != null) { playername = player.getCommandSenderName(); uuid = player.getPersistentID().toString(); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java b/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java index 95f8bcb8e..7307333e0 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java @@ -167,6 +167,12 @@ public class PlayerDataScript extends MultiScriptHandler { return ScriptController.Instance.playerScripts.scriptLanguage; } + @Override + public void setLanguage(String lang) { + ScriptController.Instance.playerScripts.scriptLanguage = lang; + this.scriptLanguage = lang; + } + @Override public String noticeString() { if (this.player == null) { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java b/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java index a0a8e0bb7..f2c0d19d6 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java @@ -8,7 +8,6 @@ import noppes.npcs.api.handler.data.IAuctionClaim; import noppes.npcs.config.ConfigMarket; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -129,12 +128,13 @@ public class PlayerTradeData implements IPlayerTradeData { // Built-in currency long newBalance = this.balance + amount; - if (newBalance > ConfigMarket.MaxBalance) { - return false; - } + // Overflow protection if (newBalance < this.balance) { - // Overflow protection - return false; + newBalance = ConfigMarket.MaxBalance; + } + // Cap at MaxBalance instead of rejecting + if (newBalance > ConfigMarket.MaxBalance) { + newBalance = ConfigMarket.MaxBalance; } this.balance = newBalance; this.lifetimeEarned += amount; @@ -245,8 +245,14 @@ public class PlayerTradeData implements IPlayerTradeData { * Add a claim to this player's pending claims. * Thread-safe - can be called from any thread. */ - public void addClaim(AuctionClaim claim) { + public synchronized void addClaim(AuctionClaim claim) { if (claim != null && !claim.claimed) { + // Prevent duplicate claim IDs + for (AuctionClaim existing : claims) { + if (existing.id.equals(claim.id)) { + return; + } + } claims.add(claim); } } @@ -276,8 +282,9 @@ public class PlayerTradeData implements IPlayerTradeData { /** * Get a specific claim by ID (internal use). + * Synchronized to pair with claimAndRemove for thread safety. */ - public AuctionClaim getClaimInternal(String claimId) { + public synchronized AuctionClaim getClaimInternal(String claimId) { for (AuctionClaim claim : claims) { if (claim.id.equals(claimId) && !claim.claimed) { return claim; @@ -296,8 +303,9 @@ public class PlayerTradeData implements IPlayerTradeData { /** * Mark a claim as claimed and remove it. + * Synchronized to prevent double-claim from concurrent threads. */ - public boolean claimAndRemove(String claimId) { + public synchronized boolean claimAndRemove(String claimId) { for (AuctionClaim claim : claims) { if (claim.id.equals(claimId) && !claim.claimed) { claim.claimed = true; @@ -341,18 +349,16 @@ public class PlayerTradeData implements IPlayerTradeData { */ public int processExpiredClaims() { int expirationDays = ConfigMarket.ClaimExpirationDays; - int removed = 0; - - Iterator iterator = claims.iterator(); - while (iterator.hasNext()) { - AuctionClaim claim = iterator.next(); + List expired = new ArrayList<>(); + for (AuctionClaim claim : claims) { if (!claim.claimed && claim.isExpired(expirationDays)) { - claims.remove(claim); - removed++; + expired.add(claim); } } - - return removed; + if (!expired.isEmpty()) { + claims.removeAll(expired); + } + return expired.size(); } // ========================================= diff --git a/src/main/java/noppes/npcs/controllers/data/Quest.java b/src/main/java/noppes/npcs/controllers/data/Quest.java index 1f9097d8a..c7e63ec1f 100644 --- a/src/main/java/noppes/npcs/controllers/data/Quest.java +++ b/src/main/java/noppes/npcs/controllers/data/Quest.java @@ -1,7 +1,6 @@ package noppes.npcs.controllers.data; -import kamkeel.npcs.controllers.ProfileController; -import kamkeel.npcs.controllers.data.profile.Profile; +import noppes.npcs.client.ProfileClientConfig; import kamkeel.npcs.network.packets.data.QuestCompletionPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -22,7 +21,6 @@ import noppes.npcs.api.handler.data.IQuestCategory; import noppes.npcs.api.handler.data.IQuestInterface; import noppes.npcs.api.handler.data.IQuestObjective; import noppes.npcs.api.handler.data.ISlot; -import noppes.npcs.config.ConfigMain; import noppes.npcs.constants.EnumProfileSync; import noppes.npcs.constants.EnumQuestCompletion; import noppes.npcs.constants.EnumQuestRepeat; @@ -176,21 +174,52 @@ public class Quest implements ICompatibilty, IQuest { } public long getTimeUntilRepeat(EntityPlayer player) { - if (ConfigMain.ProfilesEnabled && profileOptions.enableOptions && profileOptions.cooldownControl == EnumProfileSync.Shared) { - Profile profile = ProfileController.Instance.getProfile(player); - IPlayer iPlayer = NoppesUtilServer.getIPlayer(player); - long timeRemaining = 0L; - for (ISlot slot : profile.getSlots().values()) { - IPlayerData playerData = ProfileController.Instance.getSlotPlayerData(iPlayer, slot.getId()); - IPlayerQuestData iPlayerQuestData = playerData.getQuestData(); - timeRemaining = Math.max(timeRemaining, getTimeUntilRepeatQuestData(player, iPlayerQuestData)); + if (ProfileClientConfig.isProfilesEnabled() && profileOptions.enableOptions + && profileOptions.cooldownControl == EnumProfileSync.Shared) { + Long questTime = ProfileClientConfig.getSharedQuestTimestamp(player, this.id); + if (questTime != null) { + return calculateRemainingCooldown(player, questTime); } - return timeRemaining; + return 0L; } IPlayerQuestData questData = PlayerData.get(player).getQuestData(); return getTimeUntilRepeatQuestData(player, questData); } + public long calculateRemainingCooldown(EntityPlayer player, long questTime) { + switch (repeat) { + case MCDAILY: { + long now = player.worldObj.getTotalWorldTime(); + long remainingTicks = questTime + 24000 - now; + return Math.max(0, remainingTicks * 50); + } + case MCWEEKLY: { + long now = player.worldObj.getTotalWorldTime(); + long remainingTicks = questTime + 168000 - now; + return Math.max(0, remainingTicks * 50); + } + case MCCUSTOM: { + long now = player.worldObj.getTotalWorldTime(); + long remainingTicks = questTime + this.customCooldown - now; + return Math.max(0, remainingTicks * 50); + } + case RLDAILY: { + long remainingMillis = questTime + 86400000 - System.currentTimeMillis(); + return Math.max(0, remainingMillis); + } + case RLWEEKLY: { + long remainingMillis = questTime + 604800000 - System.currentTimeMillis(); + return Math.max(0, remainingMillis); + } + case RLCUSTOM: { + long remainingMillis = questTime + this.customCooldown - System.currentTimeMillis(); + return Math.max(0, remainingMillis); + } + default: + return 0L; + } + } + public long getTimeUntilRepeatQuestData(EntityPlayer player, IPlayerQuestData questData) { long questTime = questData.getLastCompletedTime(this.id); diff --git a/src/main/java/noppes/npcs/controllers/data/QuestCategory.java b/src/main/java/noppes/npcs/controllers/data/QuestCategory.java index c35c41dff..7dcca4cb5 100644 --- a/src/main/java/noppes/npcs/controllers/data/QuestCategory.java +++ b/src/main/java/noppes/npcs/controllers/data/QuestCategory.java @@ -2,6 +2,7 @@ package noppes.npcs.controllers.data; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; import noppes.npcs.api.handler.data.IQuest; import noppes.npcs.api.handler.data.IQuestCategory; @@ -21,8 +22,8 @@ public class QuestCategory implements IQuestCategory { public void readNBT(NBTTagCompound nbttagcompound) { id = nbttagcompound.getInteger("Slot"); title = nbttagcompound.getString("Title"); - NBTTagList questList = nbttagcompound.getTagList("Quests", 10); - if (questList != null) { + NBTTagList questList = getFirstValidList(nbttagcompound, Constants.NBT.TAG_COMPOUND, "Quests", "Dialogs"); + if (questList.tagCount() > 0) { for (int ii = 0; ii < questList.tagCount(); ii++) { NBTTagCompound nbttagcompound2 = questList.getCompoundTagAt(ii); Quest quest = new Quest(); @@ -33,6 +34,18 @@ public class QuestCategory implements IQuestCategory { } } + private NBTTagList getFirstValidList(NBTTagCompound nbt, int type, String... keys) { + for (String key : keys) { + if (nbt.hasKey(key, Constants.NBT.TAG_LIST)) { + NBTTagList list = nbt.getTagList(key, type); + if (list.tagCount() > 0) { + return list; + } + } + } + return new NBTTagList(); + } + public NBTTagCompound writeNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setInteger("Slot", id); nbttagcompound.setString("Title", title); diff --git a/src/main/java/noppes/npcs/controllers/data/RecipeScript.java b/src/main/java/noppes/npcs/controllers/data/RecipeScript.java index 97f81df90..c2b8ba551 100644 --- a/src/main/java/noppes/npcs/controllers/data/RecipeScript.java +++ b/src/main/java/noppes/npcs/controllers/data/RecipeScript.java @@ -3,6 +3,7 @@ package noppes.npcs.controllers.data; import kamkeel.npcs.network.packets.request.script.RecipeScriptPacket; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; /** * Script handler for Recipe scripts (both carpentry and anvil). @@ -42,6 +43,11 @@ public class RecipeScript extends SingleScriptHandler implements IScriptHandlerP return ScriptContext.RECIPE; } + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.RECIPE); + } + @Override public String noticeString() { return "RecipeScript"; diff --git a/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java index 096f8f381..d35c6bc9c 100644 --- a/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java @@ -10,7 +10,7 @@ import java.util.List; public abstract class ScriptHandler implements IScriptHandler { public List scripts = new ArrayList<>(); protected String scriptLanguage = "ECMAScript"; - protected boolean enabled = false; + protected boolean enabled = true; protected long lastInited = -1; protected boolean canRunScripts() { diff --git a/src/main/java/noppes/npcs/controllers/data/SkinOverlay.java b/src/main/java/noppes/npcs/controllers/data/SkinOverlay.java index 4b0cde375..43a13a074 100644 --- a/src/main/java/noppes/npcs/controllers/data/SkinOverlay.java +++ b/src/main/java/noppes/npcs/controllers/data/SkinOverlay.java @@ -10,8 +10,10 @@ public class SkinOverlay implements ISkinOverlay { public boolean glow = true; public boolean blend = true; + public float alpha = 1.0F; public float size = 1.0F; + public int color = 0xFFFFFF; public float speedX = 0.0F; public float speedY = 0.0F; @@ -78,6 +80,15 @@ public class SkinOverlay implements ISkinOverlay { return size; } + public void setColor(int color) { + this.color = Math.max(0, color); + this.updateClient(); + } + + public int getColor() { + return color; + } + public void setTextureScale(float scaleX, float scaleY) { this.scaleX = scaleX; this.scaleY = scaleY; @@ -131,6 +142,11 @@ public class SkinOverlay implements ISkinOverlay { this.blend = compound.getBoolean("SkinOverlayBlend"); this.alpha = compound.getFloat("SkinOverlayAlpha"); this.size = compound.getFloat("SkinOverlaySize"); + if(compound.hasKey("SkinOverlayColor")){ + this.color = compound.getInteger("SkinOverlayColor"); + } else { + this.color = 0xFFFFFF; + } this.speedX = compound.getFloat("SkinOverlaySpeedX"); this.speedY = compound.getFloat("SkinOverlaySpeedY"); this.scaleX = compound.getFloat("SkinOverlayScaleX"); @@ -146,6 +162,7 @@ public class SkinOverlay implements ISkinOverlay { compound.setBoolean("SkinOverlayBlend", this.getBlend()); compound.setFloat("SkinOverlayAlpha", this.getAlpha()); compound.setFloat("SkinOverlaySize", this.getSize()); + compound.setInteger("SkinOverlayColor", this.getColor()); compound.setFloat("SkinOverlaySpeedX", this.getSpeedX()); compound.setFloat("SkinOverlaySpeedY", this.getSpeedY()); compound.setFloat("SkinOverlayScaleX", this.getTextureScaleX()); @@ -166,6 +183,7 @@ public class SkinOverlay implements ISkinOverlay { private void updateClient() { if (this.parent != null) { this.parent.updateClient(); + this.parent.save(); } } } diff --git a/src/main/java/noppes/npcs/controllers/data/SpawnData.java b/src/main/java/noppes/npcs/controllers/data/SpawnData.java index f82d9b225..164f451da 100644 --- a/src/main/java/noppes/npcs/controllers/data/SpawnData.java +++ b/src/main/java/noppes/npcs/controllers/data/SpawnData.java @@ -21,6 +21,10 @@ import java.util.Map; import java.util.Set; public class SpawnData extends WeightedRandom.Item implements INaturalSpawn { + public static final int DESPAWN_FORCE_NATURAL = INaturalSpawn.DESPAWN_FORCE_NATURAL; + public static final int DESPAWN_PRESERVE_TEMPLATE = INaturalSpawn.DESPAWN_PRESERVE_TEMPLATE; + public static final int DESPAWN_FORCE_PERSISTENT = INaturalSpawn.DESPAWN_FORCE_PERSISTENT; + public List biomes = new ArrayList<>(); public HashSet dimensions = new HashSet<>(); public int id = -1; @@ -35,6 +39,11 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn { public int spawnHeightMin; public int spawnHeightMax = 100; + public int maxAlive = 0; + public int cooldownTicks = 0; + public int attemptsPerCycle = 1; + public int playerMinDistance = 24; + public int despawnMode = DESPAWN_FORCE_NATURAL; public SpawnData() { super(10); @@ -74,6 +83,19 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn { } else { spawnHeightMax = compound.getInteger("HeightMax"); } + + maxAlive = compound.hasKey("MaxAlive") ? Math.max(0, compound.getInteger("MaxAlive")) : 0; + cooldownTicks = compound.hasKey("CooldownTicks") ? Math.max(0, compound.getInteger("CooldownTicks")) : 0; + attemptsPerCycle = compound.hasKey("AttemptsPerCycle") ? Math.max(1, compound.getInteger("AttemptsPerCycle")) : 1; + playerMinDistance = compound.hasKey("PlayerMinDistance") ? Math.max(0, compound.getInteger("PlayerMinDistance")) : 24; + if (compound.hasKey("DespawnMode")) { + despawnMode = compound.getInteger("DespawnMode"); + } else { + despawnMode = DESPAWN_FORCE_NATURAL; + } + if (despawnMode < DESPAWN_FORCE_NATURAL || despawnMode > DESPAWN_FORCE_PERSISTENT) { + despawnMode = DESPAWN_FORCE_NATURAL; + } } public NBTTagCompound writeNBT(NBTTagCompound compound) { @@ -98,6 +120,11 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn { compound.setInteger("HeightMin", spawnHeightMin); compound.setInteger("HeightMax", spawnHeightMax); + compound.setInteger("MaxAlive", maxAlive); + compound.setInteger("CooldownTicks", cooldownTicks); + compound.setInteger("AttemptsPerCycle", attemptsPerCycle); + compound.setInteger("PlayerMinDistance", playerMinDistance); + compound.setInteger("DespawnMode", despawnMode); return compound; } @@ -204,4 +231,46 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn { public void setBiomes(String[] biomes) { this.biomes = new ArrayList<>(Arrays.asList(biomes)); } + + public void setMaxAlive(int maxAlive) { + this.maxAlive = Math.max(0, maxAlive); + } + + public int getMaxAlive() { + return this.maxAlive; + } + + public void setCooldownTicks(int ticks) { + this.cooldownTicks = Math.max(0, ticks); + } + + public int getCooldownTicks() { + return this.cooldownTicks; + } + + public void setAttemptsPerCycle(int attempts) { + this.attemptsPerCycle = Math.max(1, attempts); + } + + public int getAttemptsPerCycle() { + return this.attemptsPerCycle; + } + + public void setPlayerMinDistance(int distance) { + this.playerMinDistance = Math.max(0, distance); + } + + public int getPlayerMinDistance() { + return this.playerMinDistance; + } + + public void setDespawnMode(int mode) { + if (mode < DESPAWN_FORCE_NATURAL || mode > DESPAWN_FORCE_PERSISTENT) + mode = DESPAWN_FORCE_NATURAL; + this.despawnMode = mode; + } + + public int getDespawnMode() { + return this.despawnMode; + } } diff --git a/src/main/java/noppes/npcs/controllers/data/TintData.java b/src/main/java/noppes/npcs/controllers/data/TintData.java index 104600daf..1471d967a 100644 --- a/src/main/java/noppes/npcs/controllers/data/TintData.java +++ b/src/main/java/noppes/npcs/controllers/data/TintData.java @@ -1,8 +1,9 @@ package noppes.npcs.controllers.data; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.entity.data.ITintData; -public class TintData { +public class TintData implements ITintData { private boolean tintEnabled = false; private boolean hurtTintEnabled = true; private boolean generalTintEnabled = false; 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..cfa80afc6 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..035003cfe 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/EntityCustomNpc.java b/src/main/java/noppes/npcs/entity/EntityCustomNpc.java index b47179edf..336f778ce 100644 --- a/src/main/java/noppes/npcs/entity/EntityCustomNpc.java +++ b/src/main/java/noppes/npcs/entity/EntityCustomNpc.java @@ -86,7 +86,8 @@ public class EntityCustomNpc extends EntityNPCFlying { worldObj.MAX_ENTITY_RADIUS = newWidth / 2; } - setSize(newWidth, newHeight); + this.width = newWidth; + this.height = newHeight; this.setPosition(posX, posY, posZ); } } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCFlying.java b/src/main/java/noppes/npcs/entity/EntityNPCFlying.java index 18c730dd3..c41e0e843 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCFlying.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCFlying.java @@ -62,26 +62,27 @@ public abstract class EntityNPCFlying extends EntityNPCInterface { } else if (heightOffGround > this.ais.flyHeightLimit) { aboveLimit = true; } - if (aboveLimit && this.ais.hasFlyLimit || (heightOffGround < Math.ceil(this.height) && this.motionY == 0)) { + if (aboveLimit && this.ais.hasFlyLimit) { this.flyLimitAllow = false; - if (!this.getNavigator().noPath() && this.motionY > 0) { + if (this.motionY > 0) { this.motionY = 0; - } else { - setNpcFlyingState(false); - super.moveEntityWithHeading(p_70612_1_, p_70612_2_); - return; } + } else if (heightOffGround < Math.ceil(this.height) && this.motionY == 0) { + this.flyLimitAllow = false; + setNpcFlyingState(false); + super.moveEntityWithHeading(p_70612_1_, p_70612_2_); + return; } this.flyLimitAllow = true; setNpcFlyingState(true); - double d3 = this.motionY; - super.moveEntityWithHeading(p_70612_1_, p_70612_2_); - this.motionY = d3; - + double desiredMotionY = this.motionY; if (this.getNavigator().noPath()) { - this.motionY = -Math.abs(this.ais.flyGravity); + desiredMotionY = -Math.abs(this.ais.flyGravity); } + this.motionY = desiredMotionY; + super.moveEntityWithHeading(p_70612_1_, p_70612_2_); + this.motionY = desiredMotionY; this.updateLimbSwing(); } @@ -120,15 +121,16 @@ public abstract class EntityNPCFlying extends EntityNPCInterface { } else if (heightOffGround > this.ais.flyHeightLimit) { aboveLimit = true; } - if (aboveLimit && this.ais.hasFlyLimit || (heightOffGround < Math.ceil(this.height) && this.motionY == 0)) { + if (aboveLimit && this.ais.hasFlyLimit) { this.flyLimitAllow = false; - if (!this.getNavigator().noPath() && this.motionY > 0) { + if (this.motionY > 0) { this.motionY = 0; - } else { - setNpcFlyingState(false); - super.performMountedMovement(strafe, forward, moveSpeed); - return; } + } else if (heightOffGround < Math.ceil(this.height) && this.motionY == 0) { + this.flyLimitAllow = false; + setNpcFlyingState(false); + super.performMountedMovement(strafe, forward, moveSpeed); + return; } this.flyLimitAllow = true; setNpcFlyingState(true); @@ -138,13 +140,13 @@ public abstract class EntityNPCFlying extends EntityNPCInterface { return; } - double d3 = this.motionY; - super.performMountedMovement(strafe, forward, moveSpeed); - this.motionY = d3; - + double desiredMotionY = this.motionY; if (this.getNavigator().noPath()) { - this.motionY = -Math.abs(this.ais.flyGravity); + desiredMotionY = -Math.abs(this.ais.flyGravity); } + this.motionY = desiredMotionY; + super.performMountedMovement(strafe, forward, moveSpeed); + this.motionY = desiredMotionY; this.updateLimbSwing(); } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCGolem.java b/src/main/java/noppes/npcs/entity/EntityNPCGolem.java index bb6544071..5eb111e4d 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCGolem.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCGolem.java @@ -37,7 +37,9 @@ public class EntityNPCGolem extends EntityNPCInterface { newWidth = 1.4f; newHeight = 2.5f; } - setSize(newWidth, newHeight); + this.width = newWidth; + this.height = newHeight; + this.setPosition(posX, posY, posZ); if (width / 2 > World.MAX_ENTITY_RADIUS) { World.MAX_ENTITY_RADIUS = width / 2; } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 6e4b40884..ae4aba781 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -6,6 +6,9 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import kamkeel.npcs.addon.DBCAddon; +import kamkeel.npcs.controllers.data.ability.type.AbilityCounter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; +import kamkeel.npcs.controllers.data.ability.type.AbilityDodge; import kamkeel.npcs.addon.client.DBCClient; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; @@ -68,6 +71,7 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.ServerChatEvent; import noppes.npcs.CustomItems; @@ -250,7 +254,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti setFaction(faction.id); setSize(1, 1); this.updateTasks(); - this.func_110163_bv(); + this.syncDespawnPersistence(); if (!this.isRemote() && this.wrappedNPC == null) { this.wrappedNPC = new ScriptNpc<>(this); @@ -297,7 +301,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti @Override public boolean getLeashed() { - return false; //Prevents npcs from being leashed + return false; // Prevents npcs from being leashed } @Override @@ -384,11 +388,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; } @@ -473,7 +479,14 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti } if (wasKilled != isKilled() && wasKilled) { - reset(); + if (!worldObj.isRemote) { + reset(); + } else { + // Client-side full reset can create health oscillation when spawn data is being repaired. + deathTime = 0; + currentAnimation = EnumAnimation.NONE; + updateHitbox(); + } } wasKilled = isKilled(); @@ -652,6 +665,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti if (damagesource.damageType != null && damagesource.damageType.equals("outOfWorld") && isKilled()) { reset(); } + if (this.abilities != null && this.abilities.isCurrentAbilityInvulnerable()) { + return false; + } // Check for custom weapon attack speed - bypass immunity if enough time has passed Entity sourceEntity = damagesource.getEntity(); @@ -699,6 +715,21 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti // Resistances i = stats.resistances.applyResistance(damagesource, i); + // Defend abilities + AbilityDefend defend = this.abilities != null ? this.abilities.getActiveDefend() : null; + if (defend != null) { + // Dodge & Counter: cancel attack entirely + if (defend instanceof AbilityDodge || defend instanceof AbilityCounter) { + float result = defend.onDefend(attackingEntity, damagesource, i); + if (result != i) { + return false; + } + } else { + // Guard: reduce damage + i = defend.onDefend(attackingEntity, damagesource, i); + } + } + NpcEvent.DamagedEvent event = new NpcEvent.DamagedEvent(this.wrappedNPC, attackingEntity, i, damagesource); if (EventHooks.onNPCDamaged(this, event) || isKilled()) return false; @@ -1043,29 +1074,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) { @@ -1216,7 +1224,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(ConfigMain.NpcNavRange); this.updateTasks(); - this.func_110163_bv(); + this.syncDespawnPersistence(); } @Override @@ -1277,7 +1285,8 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti World.MAX_ENTITY_RADIUS = newWidth / 2; } - setSize(newWidth, newHeight); + this.width = newWidth; + this.height = newHeight; this.setPosition(posX, posY, posZ); } @@ -1417,6 +1426,26 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti field_20062_v += d1 * 0.25D; } + @Override + protected void despawnEntity() { + syncDespawnPersistence(); + super.despawnEntity(); + } + + public void syncDespawnPersistence() { + if (stats == null) { + if (!this.persistenceRequired) { + this.func_110163_bv(); + } + return; + } + if (stats.canDespawn) { + this.persistenceRequired = false; + } else if (!this.persistenceRequired) { + this.func_110163_bv(); + } + } + @Override protected boolean canDespawn() { return stats.canDespawn; @@ -1819,6 +1848,11 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti compound.setBoolean("DeadBody", stats.hideKilledBody); compound.setInteger("StandingState", ais.standingType.ordinal()); compound.setInteger("MovingState", ais.movingType.ordinal()); + compound.setInteger("MovingType", ais.movementType); + compound.setDouble("FlySpeed", ais.flySpeed); + compound.setDouble("FlyGravity", ais.flyGravity); + compound.setBoolean("HasFlyLimit", ais.hasFlyLimit); + compound.setInteger("FlyHeightLimit", ais.flyHeightLimit); compound.setInteger("Orientation", ais.orientation); compound.setFloat("OffsetY", ais.bodyOffsetY); compound.setInteger("Role", advanced.role.ordinal()); @@ -1850,6 +1884,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti try { readSpawnData(ByteBufUtils.readNBT(buf)); } catch (IOException e) { + e.printStackTrace(); } } @@ -1859,6 +1894,21 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti stats.hideKilledBody = compound.getBoolean("DeadBody"); ais.standingType = EnumStandingType.values()[compound.getInteger("StandingState") % EnumStandingType.values().length]; ais.movingType = EnumMovingType.values()[compound.getInteger("MovingState") % EnumMovingType.values().length]; + if (compound.hasKey("MovingType", Constants.NBT.TAG_INT)) { + ais.movementType = compound.getInteger("MovingType"); + } + if (compound.hasKey("FlySpeed", Constants.NBT.TAG_DOUBLE)) { + ais.flySpeed = compound.getDouble("FlySpeed"); + } + if (compound.hasKey("FlyGravity", Constants.NBT.TAG_DOUBLE)) { + ais.flyGravity = compound.getDouble("FlyGravity"); + } + if (compound.hasKey("HasFlyLimit", Constants.NBT.TAG_BYTE)) { + ais.hasFlyLimit = compound.getBoolean("HasFlyLimit"); + } + if (compound.hasKey("FlyHeightLimit", Constants.NBT.TAG_INT)) { + ais.flyHeightLimit = compound.getInteger("FlyHeightLimit"); + } ais.orientation = compound.getInteger("Orientation"); ais.bodyOffsetY = compound.getFloat("OffsetY"); diff --git a/src/main/java/noppes/npcs/entity/EntityNpcDragon.java b/src/main/java/noppes/npcs/entity/EntityNpcDragon.java index a9df9da99..c5952fa3c 100644 --- a/src/main/java/noppes/npcs/entity/EntityNpcDragon.java +++ b/src/main/java/noppes/npcs/entity/EntityNpcDragon.java @@ -115,7 +115,9 @@ public class EntityNpcDragon extends EntityNPCInterface { // } @Override public void updateHitbox() { - setSize(1.8f, 1.4f); + this.width = 1.8f; + this.height = 1.4f; + this.setPosition(posX, posY, posZ); if (width / 2 > World.MAX_ENTITY_RADIUS) { World.MAX_ENTITY_RADIUS = width / 2; } diff --git a/src/main/java/noppes/npcs/entity/EntityNpcSlime.java b/src/main/java/noppes/npcs/entity/EntityNpcSlime.java index 9794de069..93bdc5a7d 100644 --- a/src/main/java/noppes/npcs/entity/EntityNpcSlime.java +++ b/src/main/java/noppes/npcs/entity/EntityNpcSlime.java @@ -17,7 +17,9 @@ public class EntityNpcSlime extends EntityNPCInterface { @Override public void updateHitbox() { - setSize(0.8f, 0.8f); + this.width = 0.8f; + this.height = 0.8f; + this.setPosition(posX, posY, posZ); if (width / 2 > World.MAX_ENTITY_RADIUS) { World.MAX_ENTITY_RADIUS = width / 2; } 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/entity/data/DataSkinOverlays.java b/src/main/java/noppes/npcs/entity/data/DataSkinOverlays.java index 38f48c944..569dafeb2 100644 --- a/src/main/java/noppes/npcs/entity/data/DataSkinOverlays.java +++ b/src/main/java/noppes/npcs/entity/data/DataSkinOverlays.java @@ -49,6 +49,12 @@ public class DataSkinOverlays implements IOverlayHandler { return nbttagcompound; } + public void save() { + if (parent instanceof PlayerData) { + ((PlayerData) parent).save(); + } + } + public void updateClient() { if (parent != null) { if (parent instanceof PlayerData && ((PlayerData) parent).player != null) { @@ -69,6 +75,7 @@ public class DataSkinOverlays implements IOverlayHandler { ((SkinOverlay) data).parent = this; this.overlayList.put(id, data); updateClient(); + save(); } public ISkinOverlay get(int id) { @@ -82,6 +89,7 @@ public class DataSkinOverlays implements IOverlayHandler { public boolean remove(int id) { boolean removed = this.overlayList.remove(id) != null; updateClient(); + save(); return removed; } @@ -92,5 +100,6 @@ public class DataSkinOverlays implements IOverlayHandler { public void clear() { this.overlayList.clear(); updateClient(); + save(); } } diff --git a/src/main/java/noppes/npcs/entity/old/EntityNPCEnderman.java b/src/main/java/noppes/npcs/entity/old/EntityNPCEnderman.java index 958237c17..6479f90c7 100644 --- a/src/main/java/noppes/npcs/entity/old/EntityNPCEnderman.java +++ b/src/main/java/noppes/npcs/entity/old/EntityNPCEnderman.java @@ -40,7 +40,9 @@ public class EntityNPCEnderman extends EntityNpcEnderchibi { newHeight = (newHeight / 5f) * display.modelSize; newWidth = Math.max(newWidth, 0.00001f); newHeight = Math.max(newHeight, 0.00001f); - setSize(newWidth, newHeight); + this.width = newWidth; + this.height = newHeight; + this.setPosition(posX, posY, posZ); if (width / 2 > World.MAX_ENTITY_RADIUS) { World.MAX_ENTITY_RADIUS = width / 2; } diff --git a/src/main/java/noppes/npcs/items/ItemLinked.java b/src/main/java/noppes/npcs/items/ItemLinked.java index 8392beaf6..161547526 100644 --- a/src/main/java/noppes/npcs/items/ItemLinked.java +++ b/src/main/java/noppes/npcs/items/ItemLinked.java @@ -33,7 +33,7 @@ public class ItemLinked extends ItemCustomizable { IItemStack itemStack = NpcAPI.Instance().getIItemStack(stack); if (itemStack instanceof ScriptLinkedItem) { ScriptLinkedItem scriptLinkedItem = (ScriptLinkedItem) itemStack; - LinkedItem linkedItem = LinkedItemController.getInstance().get(scriptLinkedItem.linkedItem.getId()); + LinkedItem linkedItem = (LinkedItem) LinkedItemController.getInstance().get(scriptLinkedItem.linkedItem.getId()); int prevVersion = scriptLinkedItem.linkedVersion; if (linkedItem != null && scriptLinkedItem.linkedVersion != linkedItem.version) { scriptLinkedItem.linkedItem = linkedItem.clone(); diff --git a/src/main/java/noppes/npcs/items/ItemNpcWand.java b/src/main/java/noppes/npcs/items/ItemNpcWand.java index d36a81fce..858fba1ae 100644 --- a/src/main/java/noppes/npcs/items/ItemNpcWand.java +++ b/src/main/java/noppes/npcs/items/ItemNpcWand.java @@ -48,7 +48,7 @@ public class ItemNpcWand extends Item { EntityCustomNpc npc = new EntityCustomNpc(par3World); npc.ais.startPos = new int[]{par4, par5, par6}; - npc.setLocationAndAngles((float) par4 + 0.5F, npc.getStartYPos(), (float) par6 + 0.5F, player.rotationYaw, player.rotationPitch); + npc.setLocationAndAngles((float) par4 + 0.5F, npc.getStartYPos(), (float) par6 + 0.5F, player.rotationYaw, 0); par3World.spawnEntityInWorld(npc); npc.setHealth(npc.getMaxHealth()); diff --git a/src/main/java/noppes/npcs/items/ItemStaff.java b/src/main/java/noppes/npcs/items/ItemStaff.java index 2a54c49a3..39de82e37 100644 --- a/src/main/java/noppes/npcs/items/ItemStaff.java +++ b/src/main/java/noppes/npcs/items/ItemStaff.java @@ -1,7 +1,12 @@ package noppes.npcs.items; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData; +import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; import kamkeel.npcs.entity.EntityAbilityOrb; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -22,7 +27,7 @@ import noppes.npcs.entity.EntityProjectile; import noppes.npcs.util.IProjectileCallback; import org.lwjgl.opengl.GL11; -import java.awt.*; +import java.awt.Color; public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { @@ -33,7 +38,8 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { public ItemStaff(int par1, EnumNpcToolMaterial material) { super(par1); this.material = material; - this.color = OrbColor.get(material.ordinal());; + this.color = OrbColor.get(material.ordinal()); + ; setCreativeTab(CustomItems.tabWeapon); } @@ -59,6 +65,11 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { EntityAbilityOrb orb = (EntityAbilityOrb) entity; + if (orb.getChargeProgress() < 1.0f) { + orb.setDead(); + return; + } + orb.startMoving(null); world.playSoundAtEntity( @@ -73,12 +84,39 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { public void onUsingTick(ItemStack stack, EntityPlayer player, int count) { int tick = getMaxItemUseDuration(stack) - count; + int chargeTime = 20 + material.getHarvestLevel() * 8; + if (player.worldObj.isRemote) { spawnParticle(stack, player); + + // Reset charge tick on client to prevent client-side timeout + // (resetChargeTick is not synced via DataWatcher, so the client's + // chargeTick would keep climbing and falsely trigger CHARGE_TIMEOUT_GRACE) + if (tick > chargeTime && stack.stackTagCompound != null) { + Entity existing = player.worldObj + .getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); + if (existing instanceof EntityAbilityOrb) { + EntityAbilityOrb orb = (EntityAbilityOrb) existing; + if (orb.isCharging()) { + orb.resetChargeTick(); + } + } + } return; } - int chargeTime = 20 + material.getHarvestLevel() * 8; + // Keep a fully-charged orb alive while the player is still holding + if (tick > chargeTime && stack.stackTagCompound != null) { + Entity existing = ((WorldServer) player.worldObj) + .getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); + if (existing instanceof EntityAbilityOrb) { + EntityAbilityOrb orb = (EntityAbilityOrb) existing; + if (orb.isCharging()) { + orb.resetChargeTick(); + } + } + return; + } if (tick == chargeTime) { @@ -110,8 +148,6 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { EnergyLightningData lightning = new EnergyLightningData(); EnergyLifespanData lifespan = new EnergyLifespanData(100, 72000); EnergyHomingData homing = new EnergyHomingData(); - EnergyTrajectoryData trajectory = new EnergyTrajectoryData(); - homing.speed = 0.5f; homing.homingStrength = 0.35f; homing.homingRange = 20f; @@ -119,11 +155,11 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { EntityAbilityOrb orb = new EntityAbilityOrb( player.worldObj, player, null, player.posX, player.posY + player.getEyeHeight(), player.posZ, - 1.0f, colorData, combat, homing, lightning, lifespan, trajectory + 1.0f, colorData, combat, homing, lightning, lifespan ); orb.setupCharging( - new EnergyAnchorData(AnchorPoint.FRONT, 0, -1, 0), + new EnergyAnchorData(AnchorPoint.EYE, 0, 0, 1), chargeTime ); diff --git a/src/main/java/noppes/npcs/janino/JaninoScript.java b/src/main/java/noppes/npcs/janino/JaninoScript.java index 2afe8052f..afa55033c 100644 --- a/src/main/java/noppes/npcs/janino/JaninoScript.java +++ b/src/main/java/noppes/npcs/janino/JaninoScript.java @@ -11,6 +11,7 @@ import noppes.npcs.constants.EnumScriptType; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.ScriptHookController; +import noppes.npcs.controllers.data.IScriptHandler; import noppes.npcs.controllers.data.IScriptUnit; import noppes.npcs.janino.annotations.ParamName; import org.codehaus.commons.compiler.InternalCompilerException; @@ -21,14 +22,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.Permissions; import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; +import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -49,7 +43,9 @@ public abstract class JaninoScript implements IScriptUnit { private final JaninoHookResolver hookResolver = new JaninoHookResolver(); private final String[] defaultImports; - + // Cache of imports used in the last compilation + private String[] cachedImports; + private Map hookDefCache; private int lastHookRevision = -1; private int lastSeenGlobalRevision; @@ -123,13 +119,21 @@ public abstract class JaninoScript implements IScriptUnit { public void unload() { } + @Override + public IScriptUnit createInstanceScope(IScriptHandler instanceHandler) { + IScriptUnit instance = instanceHandler.createJaninoScriptUnit(); + if (instance == null) return null; + instance.setScript(this.script); + instance.setExternalScripts(new ArrayList<>(this.externalScripts)); + return instance; + } + // ==================== COMPILATION ==================== public void compileScript(String code) { try { - String[] imports = collectImportsForCode(code); - builder.setDefaultImports(imports); + builder.setDefaultImports(cachedImports = collectImportsForCode(code)); this.scriptBody = builder.build(); scriptBody.setScript(code); } catch (InternalCompilerException e) { @@ -396,6 +400,56 @@ public abstract class JaninoScript implements IScriptUnit { return sb.toString(); } + /** + * Get the default imports configured for this script type. + * These are packages/classes that are automatically available without explicit import statements. + * + * @return Array of default import patterns (e.g., "noppes.npcs.api.*") + */ + public String[] getDefaultImports() { + return defaultImports; + } + + private String[] getCachedImports() { + if (cachedImports == null) { + cachedImports = collectImportsForCode(getFullCode()); + } + return cachedImports; + } + + /** + * Get all types used in hook method signatures (parameters and return types). + * This includes event types like INpcEvent.InitEvent, INpcEvent.DamagedEvent, etc., + * as well as return types like Color, String, etc. + * Useful for syntax highlighting to know what types are implicitly available. + * + * @return Set of fully qualified class names for all hook parameter and return types + */ + public Set getHookTypes() { + Set types = new HashSet<>(); + Collections.addAll(types, getCachedImports()); + return types; + } + + /** + * Add a type and all its enclosing types to the set. + * For nested classes like INpcEvent.InitEvent, this adds both INpcEvent and INpcEvent$InitEvent. + */ + private void addTypeAndEnclosingTypes(Set types, Class clazz) { + if (clazz == null || clazz.isPrimitive()) + return; + + // Add the type itself + types.add(clazz.getName()); + + // Add enclosing/declaring class if it's a nested type + Class enclosing = clazz.getDeclaringClass(); + while (enclosing != null) { + types.add(enclosing.getName()); + enclosing = enclosing.getDeclaringClass(); + } + } + // ==================== IScriptUnit ==================== @Override @@ -407,6 +461,7 @@ public abstract class JaninoScript implements IScriptUnit { public void setScript(String script) { this.script = script; this.evaluated = false; + this.cachedImports = null; hookResolver.clearResolutionCaches(); } @@ -419,6 +474,7 @@ public abstract class JaninoScript implements IScriptUnit { public void setExternalScripts(List scripts) { this.externalScripts = scripts; this.evaluated = false; + this.cachedImports = null; hookResolver.clearResolutionCaches(); } @@ -488,15 +544,13 @@ public abstract class JaninoScript implements IScriptUnit { } public static > S readFromNBT(NBTTagCompound compound, S script, Supplier factory) { - if (compound.hasKey("Script")) { - if (script == null) script = factory.get(); - script.readFromNBT(compound.getCompoundTag("Script")); - } + if (script == null) script = factory.get(); + script.readFromNBT(compound); return script; } public static NBTTagCompound writeToNBT(NBTTagCompound compound, JaninoScript script) { - if (script != null) compound.setTag("Script", script.writeToNBT(new NBTTagCompound())); + if (script != null) script.writeToNBT(compound); return compound; } } diff --git a/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java b/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java index 9b09759c0..3848edcd4 100644 --- a/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java +++ b/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java @@ -57,6 +57,14 @@ public class CustomNPCsMixinPlugin implements IMixinConfigPlugin { mixins.add("MixinItemStack"); } + + // Server Only Mixins + if (!client) { + if (ConfigMixin.EntitySpawnFixMixin) { + mixins.add("MixinEntityTrackerEntry"); + } + } + return mixins; } diff --git a/src/main/java/noppes/npcs/mixin/MixinEntityTrackerEntry.java b/src/main/java/noppes/npcs/mixin/MixinEntityTrackerEntry.java new file mode 100644 index 000000000..a66297040 --- /dev/null +++ b/src/main/java/noppes/npcs/mixin/MixinEntityTrackerEntry.java @@ -0,0 +1,77 @@ +package noppes.npcs.mixin; + +import cpw.mods.fml.common.network.internal.FMLMessage; +import cpw.mods.fml.common.network.internal.FMLProxyPacket; +import cpw.mods.fml.common.registry.EntityRegistry; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityTrackerEntry; +import net.minecraft.network.Packet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +import java.lang.reflect.Method; + +/** + * Fixes a race condition in Forge's FMLNetworkHandler.getEntitySpawningPacket. + * + * Forge uses a single static shared EmbeddedChannel to serialize all mod entity + * spawn packets. The channel's generatePacketFrom method does a non-atomic + * write-then-poll, so concurrent calls can swap, lose, or misdeliver packets. + * + * This mixin bypasses the shared channel by serializing directly into a fresh + * ByteBuf per call, eliminating the race condition entirely. + */ +@Mixin(EntityTrackerEntry.class) +public abstract class MixinEntityTrackerEntry { + private static final Logger LOGGER = LogManager.getLogger("CustomNPCs-SpawnFix"); + private static Method toBytesMethod; + + static { + try { + toBytesMethod = FMLMessage.EntitySpawnMessage.class.getDeclaredMethod("toBytes", ByteBuf.class); + toBytesMethod.setAccessible(true); + } catch (NoSuchMethodException e) { + LOGGER.fatal("Failed to find FMLMessage.EntitySpawnMessage.toBytes - entity spawn fix will not work", e); + } + } + + @Shadow + public Entity myEntity; + + @Redirect( + method = "func_151260_c", + at = @At( + value = "INVOKE", + target = "Lcpw/mods/fml/common/network/internal/FMLNetworkHandler;getEntitySpawningPacket(Lnet/minecraft/entity/Entity;)Lnet/minecraft/network/Packet;" + ), + remap = false + ) + private Packet cnpcplus$getEntitySpawningPacket(Entity entity) { + if (toBytesMethod == null) { + return null; + } + + EntityRegistry.EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entity.getClass(), false); + if (er == null || er.usesVanillaSpawning()) { + return null; + } + + FMLMessage.EntitySpawnMessage message = new FMLMessage.EntitySpawnMessage(er, entity, er.getContainer()); + ByteBuf buf = Unpooled.buffer(); + buf.writeByte(2); + try { + toBytesMethod.invoke(message, buf); + } catch (Throwable e) { + LOGGER.warn("Failed to serialize entity spawn packet for {}", entity.getClass().getName(), e); + buf.release(); + return null; + } + return new FMLProxyPacket(buf, "FML"); + } +} diff --git a/src/main/java/noppes/npcs/mixin/MixinItemStack.java b/src/main/java/noppes/npcs/mixin/MixinItemStack.java index 8615573c0..051bc4b46 100644 --- a/src/main/java/noppes/npcs/mixin/MixinItemStack.java +++ b/src/main/java/noppes/npcs/mixin/MixinItemStack.java @@ -1,9 +1,12 @@ package noppes.npcs.mixin; import kamkeel.npcs.util.AttributeItemUtil; +import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.global.GuiNpcManageAuction; +import noppes.npcs.client.gui.player.GuiAuctionInterface; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -28,9 +31,14 @@ public abstract class MixinItemStack { @Inject(method = "getTooltip", at = @At("TAIL"), cancellable = true) public void getAttributeTooltip(EntityPlayer player, boolean advanced, CallbackInfoReturnable> cir) { + boolean override = false; + if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface || Minecraft.getMinecraft().currentScreen instanceof GuiNpcManageAuction) { + override = true; + } + List tooltip = cir.getReturnValue(); if (hasTagCompound() && getTagCompound().hasKey(TAG_RPGCORE)) { - cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound())); + cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound(), override)); } } } diff --git a/src/main/java/noppes/npcs/mixin/MixinModelRenderer.java b/src/main/java/noppes/npcs/mixin/MixinModelRenderer.java index e38805870..603b856b6 100644 --- a/src/main/java/noppes/npcs/mixin/MixinModelRenderer.java +++ b/src/main/java/noppes/npcs/mixin/MixinModelRenderer.java @@ -86,6 +86,9 @@ public abstract class MixinModelRenderer { float prevAngleX = this.rotateAngleX; float prevAngleY = this.rotateAngleY; float prevAngleZ = this.rotateAngleZ; + float prevOffsetX = this.offsetX; + float prevOffsetY = this.offsetY; + float prevOffsetZ = this.offsetZ; boolean changedAngles = false; try { @@ -149,6 +152,11 @@ public abstract class MixinModelRenderer { GL11.glPopMatrix(); } + // Mirror vanilla ModelRenderer behavior: always undo offset translation. + // Without this, models that animate via offsetX/Y/Z (e.g. witch nose while drinking) + // leak transforms into subsequent renders. + GL11.glTranslatef(-this.offsetX, -this.offsetY, -this.offsetZ); + if (changedAngles) { this.rotationPointX = prevPointX; this.rotationPointY = prevPointY; @@ -156,6 +164,9 @@ public abstract class MixinModelRenderer { this.rotateAngleX = prevAngleX; this.rotateAngleY = prevAngleY; this.rotateAngleZ = prevAngleZ; + this.offsetX = prevOffsetX; + this.offsetY = prevOffsetY; + this.offsetZ = prevOffsetZ; } } } diff --git a/src/main/java/noppes/npcs/roles/JobSpawner.java b/src/main/java/noppes/npcs/roles/JobSpawner.java index 42a509e5a..11e71bc20 100644 --- a/src/main/java/noppes/npcs/roles/JobSpawner.java +++ b/src/main/java/noppes/npcs/roles/JobSpawner.java @@ -47,6 +47,7 @@ public class JobSpawner extends JobInterface { private EntityLivingBase target; + private boolean isResetting = false; public JobSpawner(EntityNPCInterface npc) { super(npc); @@ -314,16 +315,25 @@ public class JobSpawner extends JobInterface { @Override public void reset() { - number = 0; - if (spawned.isEmpty()) - spawned = getNearbySpawned(); + if (isResetting) + return; + isResetting = true; + try { + number = 0; + if (spawned.isEmpty()) + spawned = getNearbySpawned(); - target = null; - checkSpawns(); + target = null; + checkSpawns(); + } finally { + isResetting = false; + } } @Override public void delete() { + if (isResetting) + return; if (spawnType == 3 && npc.stats.spawnCycle == 3) { spawnEntity(compound1); spawnEntity(compound2); diff --git a/src/main/java/noppes/npcs/roles/RoleTrader.java b/src/main/java/noppes/npcs/roles/RoleTrader.java index 6aa69d357..717754abf 100644 --- a/src/main/java/noppes/npcs/roles/RoleTrader.java +++ b/src/main/java/noppes/npcs/roles/RoleTrader.java @@ -94,6 +94,15 @@ public class RoleTrader extends RoleInterface { @Override public void readFromNBT(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound, true); + } + + /** + * @param loadFromMarket pull the linked market's stored data over the compound just read. + * False when the compound is an admin edit, which is authoritative and + * would otherwise be overwritten by the market it is about to be saved to. + */ + public void readFromNBT(NBTTagCompound nbttagcompound, boolean loadFromMarket) { String oldMarket = marketName; marketName = nbttagcompound.getString("TraderMarket"); readNBT(nbttagcompound); @@ -101,6 +110,9 @@ public class RoleTrader extends RoleInterface { // Register with MarketRegistry for linked market sync MarketRegistry.updateTraderMarket(oldMarket, marketName, this); + if (!loadFromMarket) + return; + try { Market.getMarket(this, marketName); } catch (Exception ex) { diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index c80c18d28..1a0b7edf1 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -3,10 +3,22 @@ package noppes.npcs.scripted; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.eventhandler.EventBus; import foxz.command.ScriptedCommand; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.AttributeController; +import kamkeel.npcs.controllers.EnergyController; 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.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityEnergySweeper; +import kamkeel.npcs.entity.EntityEnergyExplosion; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.block.Block; import net.minecraft.command.CommandHandler; import net.minecraft.entity.Entity; @@ -51,35 +63,19 @@ import noppes.npcs.api.IBlock; import noppes.npcs.api.ICommand; import noppes.npcs.api.IContainer; import noppes.npcs.api.IDamageSource; +import noppes.npcs.api.IEnergyHandler; import noppes.npcs.api.INbt; import noppes.npcs.api.IParticle; -import noppes.npcs.api.ITelegraph; import noppes.npcs.api.IPos; import noppes.npcs.api.ISkinOverlay; +import noppes.npcs.api.ITelegraph; import noppes.npcs.api.ITileEntity; import noppes.npcs.api.IWorld; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.gui.ICustomGui; -import noppes.npcs.api.handler.IAbilityHandler; -import noppes.npcs.api.handler.IActionManager; -import noppes.npcs.api.handler.IAnimationHandler; -import noppes.npcs.api.handler.IAuctionHandler; -import noppes.npcs.api.handler.IAttributeHandler; -import noppes.npcs.api.handler.ICloneHandler; -import noppes.npcs.api.handler.ICustomEffectHandler; -import noppes.npcs.api.handler.IDialogHandler; -import noppes.npcs.api.handler.IFactionHandler; -import noppes.npcs.api.handler.IMagicHandler; -import noppes.npcs.api.handler.INaturalSpawnsHandler; -import noppes.npcs.api.handler.IPartyHandler; -import noppes.npcs.api.handler.IProfileHandler; -import noppes.npcs.api.handler.IQuestHandler; -import noppes.npcs.api.handler.IRecipeHandler; -import noppes.npcs.api.handler.IScriptHookHandler; -import noppes.npcs.api.handler.ITelegraphHandler; -import noppes.npcs.api.handler.ITransportHandler; +import noppes.npcs.api.handler.*; import noppes.npcs.api.handler.data.IAnimation; import noppes.npcs.api.handler.data.IFrame; import noppes.npcs.api.handler.data.IFramePart; @@ -90,22 +86,7 @@ import noppes.npcs.compat.PixelmonHelper; import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumAnimationPart; import noppes.npcs.containers.ContainerNpcInterface; -import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.AuctionController; -import noppes.npcs.controllers.ChunkController; -import noppes.npcs.controllers.CustomEffectController; -import noppes.npcs.controllers.DialogController; -import noppes.npcs.controllers.FactionController; -import noppes.npcs.controllers.MagicController; -import noppes.npcs.controllers.PartyController; -import noppes.npcs.controllers.QuestController; -import noppes.npcs.controllers.RecipeController; -import noppes.npcs.controllers.ScriptController; -import noppes.npcs.controllers.ScriptEntityData; -import noppes.npcs.controllers.ScriptHookController; -import noppes.npcs.controllers.ServerCloneController; -import noppes.npcs.controllers.SpawnController; -import noppes.npcs.controllers.TransportController; +import noppes.npcs.controllers.*; import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.Frame; import noppes.npcs.controllers.data.FramePart; @@ -119,6 +100,17 @@ 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.ScriptEnergyDome; +import noppes.npcs.scripted.entity.ScriptEnergyExplosion; +import noppes.npcs.scripted.entity.ScriptEnergyLaser; +import noppes.npcs.scripted.entity.ScriptEnergyOrb; +import noppes.npcs.scripted.entity.ScriptEnergyPanel; +import noppes.npcs.scripted.entity.ScriptEnergyProjectile; +import noppes.npcs.scripted.entity.ScriptEnergySlicer; +import noppes.npcs.scripted.entity.ScriptEnergySweeper; +import noppes.npcs.scripted.entity.ScriptEnergyZone; import noppes.npcs.scripted.entity.ScriptEntity; import noppes.npcs.scripted.entity.ScriptEntityItem; import noppes.npcs.scripted.entity.ScriptFishHook; @@ -168,6 +160,7 @@ public class NpcAPI extends AbstractNpcAPI { private static final Map worldCache = new LRUHashMap<>(10); private static final CacheHashMap> scriptItemCache = new CacheHashMap<>(60 * 1000); public static final HashMap engineObjects = new HashMap<>(); + public static volatile long engineObjectsVersion = 0; public static final EventBus EVENT_BUS = new EventBus(); private static AbstractNpcAPI instance = null; @@ -263,10 +256,12 @@ public class NpcAPI extends AbstractNpcAPI { public void addGlobalObject(String key, Object obj) { NpcAPI.engineObjects.put(key, obj); + NpcAPI.engineObjectsVersion++; } public void removeGlobalObject(String key) { NpcAPI.engineObjects.remove(key); + NpcAPI.engineObjectsVersion++; } public boolean hasGlobalObject(String key) { @@ -365,6 +360,10 @@ public class NpcAPI extends AbstractNpcAPI { return AnimationController.Instance; } + public ILinkedItemHandler getLinkedItems() { + return LinkedItemController.getInstance(); + } + public IScriptHookHandler getScriptHooks() { return ScriptHookController.Instance; } @@ -454,6 +453,28 @@ 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 if (entity instanceof EntityEnergySlicer) + data = new ScriptEntityData(new ScriptEnergySlicer<>((EntityEnergySlicer) entity)); + else if (entity instanceof EntityEnergyProjectile) + data = new ScriptEntityData(new ScriptEnergyProjectile((EntityEnergyProjectile) entity)); + else if (entity instanceof EntityEnergyDome) + data = new ScriptEntityData(new ScriptEnergyDome<>((EntityEnergyDome) entity)); + else if (entity instanceof EntityEnergyPanel) + data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityEnergyPanel) entity)); + else if (entity instanceof EntityEnergySweeper) + data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityEnergySweeper) entity)); + else if (entity instanceof EntityEnergyExplosion) + data = new ScriptEntityData(new ScriptEnergyExplosion<>((EntityEnergyExplosion) entity)); + else if (entity instanceof EntityAbilityZone) + data = new ScriptEntityData(new ScriptEnergyZone<>((EntityAbilityZone) entity)); else data = new ScriptEntityData(new ScriptEntity<>(entity)); entity.registerExtendedProperties("ScriptedObject", data); @@ -604,6 +625,11 @@ public class NpcAPI extends AbstractNpcAPI { return instance; } + @Override + public IEnergyHandler getEnergyHandler() { + return EnergyController.Instance; + } + public EventBus events() { return EVENT_BUS; } diff --git a/src/main/java/noppes/npcs/scripted/ScriptWorld.java b/src/main/java/noppes/npcs/scripted/ScriptWorld.java index c9b806ca9..5bbe3909a 100644 --- a/src/main/java/noppes/npcs/scripted/ScriptWorld.java +++ b/src/main/java/noppes/npcs/scripted/ScriptWorld.java @@ -1,5 +1,9 @@ package noppes.npcs.scripted; +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.block.BlockAir; import net.minecraft.entity.Entity; @@ -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..e92babb24 100644 --- a/src/main/java/noppes/npcs/scripted/constants/EntityType.java +++ b/src/main/java/noppes/npcs/scripted/constants/EntityType.java @@ -15,4 +15,13 @@ 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; + public static final int ENERGY_SLICER = 18; + public static final int ENERGY_BARRIER = 19; + public static final int ENERGY_DOME = 20; + public static final int ENERGY_PANEL = 21; + public static final int ENERGY_EXPLOSION = 22; } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptDBCPlayer.java b/src/main/java/noppes/npcs/scripted/entity/ScriptDBCPlayer.java index c1f4f9bb2..fb596b677 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptDBCPlayer.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptDBCPlayer.java @@ -789,7 +789,7 @@ public class ScriptDBCPlayer extends ScriptPlayer i } public void setRace(byte race) { - if (race < 0 || race > 1) + if (race < 0 || race > 5) return; player.getEntityData().getCompoundTag("PlayerPersisted").setByte("jrmcRace", race); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyAbility.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyAbility.java new file mode 100644 index 000000000..54bc7fd42 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyAbility.java @@ -0,0 +1,166 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergyAbility; +import net.minecraft.entity.Entity; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.INbt; +import noppes.npcs.api.entity.IEnergyAbility; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.handler.data.IMagicData; +import noppes.npcs.controllers.data.MagicData; +import noppes.npcs.scripted.NpcAPI; + +/** + * Base script wrapper for all energy ability entities. + * Implements shared display, lightning, owner, and charging methods. + */ +public abstract class ScriptEnergyAbility extends ScriptEntity implements IEnergyAbility { + + public ScriptEnergyAbility(T entity) { + super(entity); + } + + // ==================== OWNER ==================== + + public int getOwnerEntityId() { + return entity.getOwnerEntityId(); + } + + public IEntity getOwner() { + Entity owner = entity.getOwnerEntity(); + return owner != null ? NpcAPI.Instance().getIEntity(owner) : null; + } + + // ==================== DISPLAY ==================== + + public int getInnerColor() { + return entity.getInnerColor(); + } + + public void setInnerColor(int color) { + entity.setInnerColor(color); + } + + public float getInnerAlpha() { + return entity.getInnerAlpha(); + } + + public void setInnerAlpha(float alpha) { + entity.setInnerAlpha(alpha); + } + + 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); + } + + // ==================== 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); + } + + // ==================== STATE ==================== + + public boolean isCharging() { + return entity.isCharging(); + } + + public float getChargeProgress() { + return entity.getChargeProgress(); + } + + public boolean isIgnoreIFrames() { + return entity.isIgnoreIFrames(); + } + + public void setIgnoreIFrames(boolean ignore) { + entity.setIgnoreIFrames(ignore); + } + + // ==================== CUSTOM DAMAGE DATA ==================== + + public INbt getDamageData() { + NBTTagCompound data = entity.getCustomDamageData(); + if (data == null) { + data = new NBTTagCompound(); + entity.setCustomDamageData(data); + } + return NpcAPI.Instance().getINbt(data); + } + + public void setDamageData(INbt data) { + if (data == null) { + entity.setCustomDamageData(null); + } else { + entity.setCustomDamageData((NBTTagCompound) data.getMCNBT()); + } + } + + // ==================== MAGIC DATA ==================== + + public IMagicData getMagicData() { + return entity.getMagicData(); + } + + public void setMagicData(IMagicData data) { + if (data instanceof MagicData) { + entity.setMagicData((MagicData) data); + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java new file mode 100644 index 000000000..16d96ddc1 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java @@ -0,0 +1,159 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; +import noppes.npcs.api.entity.IEnergyBarrier; +import noppes.npcs.scripted.constants.EntityType; + +/** + * Base script wrapper for energy barrier entities (Dome, Panel). + * All shared methods delegate directly to EntityEnergyBarrier base. + */ +public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { + + public ScriptEnergyBarrier(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_BARRIER; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_BARRIER || super.typeOf(type); + } + + // ==================== HEALTH ==================== + + public float getCurrentHealth() { + return entity.getCurrentHealth(); + } + + public void setCurrentHealth(float health) { + entity.setCurrentHealth(health); + } + + public float getHealthPercent() { + return entity.getHealthPercent(); + } + + public float getMaxHealth() { + return entity.getBarrierData().maxHealth; + } + + public void setMaxHealth(float maxHealth) { + entity.getBarrierData().setMaxHealth(maxHealth); + } + + public boolean isUseHealth() { + return entity.getBarrierData().useHealth; + } + + public void setUseHealth(boolean useHealth) { + entity.getBarrierData().useHealth = useHealth; + } + + // ==================== DURATION ==================== + + public int getDuration() { + return entity.getBarrierData().durationTicks; + } + + public void setDuration(int ticks) { + entity.getBarrierData().setDurationTicks(ticks); + } + + public boolean isUseDuration() { + return entity.getBarrierData().useDuration; + } + + public void setUseDuration(boolean useDuration) { + entity.getBarrierData().useDuration = useDuration; + } + + // ==================== STATE (BARRIER-SPECIFIC) ==================== + + public int getTicksAlive() { + return entity.getTicksAlive(); + } + + // ==================== BARRIER ==================== + + public float getDefaultMultiplier() { + return entity.getBarrierData().defaultMultiplier; + } + + public void setDefaultMultiplier(float multiplier) { + entity.getBarrierData().defaultMultiplier = multiplier; + } + + public boolean isSolid() { + return entity.getBarrierData().solid; + } + + public void setSolid(boolean solid) { + entity.getBarrierData().solid = solid; + } + + public boolean isKnockbackEnabled() { + return entity.getBarrierData().knockbackEnabled; + } + + public void setKnockbackEnabled(boolean enabled) { + entity.getBarrierData().knockbackEnabled = enabled; + } + + public float getKnockbackStrength() { + return entity.getBarrierData().knockbackStrength; + } + + public void setKnockbackStrength(float strength) { + entity.getBarrierData().knockbackStrength = strength; + } + + public boolean isAbsorbing() { + return entity.getBarrierData().absorbing; + } + + public void setAbsorbing(boolean absorbing) { + entity.getBarrierData().absorbing = absorbing; + } + + public float getAbsorbRadius() { + return entity.getBarrierData().absorbRadius; + } + + public void setAbsorbRadius(float radius) { + entity.getBarrierData().absorbRadius = radius; + } + + public boolean isReflect() { + return entity.getBarrierData().reflect; + } + + public void setReflect(boolean reflect) { + entity.getBarrierData().reflect = reflect; + } + + public float getReflectStrengthPct() { + return entity.getBarrierData().reflectStrengthPct; + } + + public void setReflectStrengthPct(float strengthPct) { + entity.getBarrierData().setReflectStrengthPct(strengthPct); + } + + public int getBarrierType() { + return entity instanceof EntityEnergyDome ? 0 : 1; + } + + // ==================== SYNC ==================== + + public void syncClient() { + if (entity.addedToChunk) { + entity.sendClientSync(); + } + } +} 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..f937663e0 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java @@ -0,0 +1,84 @@ +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 + protected void launchFromOwner(EntityLivingBase target) { + entity.startFiring(target); + } + + @Override + public void fireAt(IEntity target) { + entity.setAttachedToOwner(false); + super.fireAt(target); + } + + @Override + public void fireAt(double x, double y, double z) { + entity.setAttachedToOwner(false); + super.fireAt(x, y, z); + } + + @Override + public void fireDirection(float yaw, float pitch) { + entity.setAttachedToOwner(false); + super.fireDirection(yaw, pitch); + } +} 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..66244c2fd --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java @@ -0,0 +1,81 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityDisc; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyDisc; +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 + protected void launchFromOwner(EntityLivingBase target) { + entity.startMoving(target); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java new file mode 100644 index 000000000..e022118f7 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java @@ -0,0 +1,37 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergyDome; +import noppes.npcs.api.entity.IEnergyDome; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { + + public ScriptEnergyDome(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_DOME; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_DOME || super.typeOf(type); + } + + @Override + public int getBarrierType() { + return 0; + } + + // ==================== DOME-SPECIFIC ==================== + + public float getDomeRadius() { + return entity.getDomeRadius(); + } + + public void setDomeRadius(float radius) { + entity.setDomeRadius(radius); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyExplosion.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyExplosion.java new file mode 100644 index 000000000..8ce2e359f --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyExplosion.java @@ -0,0 +1,109 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergyExplosion; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.energyexplosion.EnergyExplosionSpawnPacket; +import noppes.npcs.api.entity.IEnergyExplosion; +import noppes.npcs.scripted.constants.EntityType; + +import java.util.UUID; + +/** + * Script wrapper for standalone energy explosion entities. + */ +public class ScriptEnergyExplosion extends ScriptEnergyAbility implements IEnergyExplosion { + + public ScriptEnergyExplosion(T entity) { + super(entity); + } + + // ==================== TYPE ==================== + + @Override + public int getType() { + return EntityType.ENERGY_EXPLOSION; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_EXPLOSION || super.typeOf(type); + } + + // ==================== RADIUS & DURATION ==================== + + @Override + public float getRadius() { + return entity.getExplosionRadius(); + } + + @Override + public void setRadius(float radius) { + entity.setExplosionRadius(radius); + } + + @Override + public int getDuration() { + return entity.getDurationTicks(); + } + + // ==================== DAMAGE ==================== + + @Override + public float getDamage() { + return entity.getDamage(); + } + + @Override + public void setDamage(float damage) { + entity.setDamage(damage); + } + + @Override + public float getKnockback() { + return entity.getKnockback(); + } + + @Override + public void setKnockback(float knockback) { + entity.setKnockback(knockback); + } + + @Override + public float getKnockbackUp() { + return entity.getKnockbackUp(); + } + + @Override + public void setKnockbackUp(float knockbackUp) { + entity.setKnockbackUp(knockbackUp); + } + + @Override + public float getDamageFalloff() { + return entity.getDamageFalloff(); + } + + @Override + public void setDamageFalloff(float falloff) { + entity.setDamageFalloff(falloff); + } + + // ==================== SPAWNING ==================== + + @Override + public void spawn() { + if (entity.addedToChunk || entity.worldObj == null) return; + + if (!entity.worldObj.isRemote) { + // Send visual to clients via packet (explosion is packet-driven, not a tracked entity) + String instanceId = "energy_explosion_" + UUID.randomUUID(); + PacketHandler.Instance.sendToAll(new EnergyExplosionSpawnPacket( + instanceId, entity.exportSpawnNBT())); + + // Spawn server-side for damage logic (if damage enabled) + if (entity.isDamageEnabled()) { + entity.worldObj.spawnEntityInWorld(entity); + } + } + } +} 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..4f8bcbcd5 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java @@ -0,0 +1,130 @@ +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 float getMaxLength() { + return entity.getMaxLength(); + } + + public void setMaxLength(float maxLength) { + entity.setMaxLength(maxLength); + } + + 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(); + } + + // ==================== FIRE ==================== + + @Override + protected void launchFromOwner(EntityLivingBase target) { + entity.startMoving(target); + } + + @Override + public void fireAt(IEntity target) { + entity.setTrackOwnerOrigin(false); + super.fireAt(target); + } + + @Override + public void fireAt(double x, double y, double z) { + entity.setTrackOwnerOrigin(false); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.setDirection(dx / len, dy / len, dz / len); + } + ensureSpawned(); + } + + @Override + public void fireDirection(float yaw, float pitch) { + entity.setTrackOwnerOrigin(false); + float yawRad = (float) Math.toRadians(yaw); + float pitchRad = (float) Math.toRadians(pitch); + entity.setDirection( + -Math.sin(yawRad) * Math.cos(pitchRad), + -Math.sin(pitchRad), + Math.cos(yawRad) * Math.cos(pitchRad) + ); + ensureSpawned(); + } +} 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..af290b8b3 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java @@ -0,0 +1,33 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityOrb; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyOrb; +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 + protected void launchFromOwner(EntityLivingBase target) { + entity.startMoving(target); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java new file mode 100644 index 000000000..edcf90795 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java @@ -0,0 +1,76 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergyPanel; +import noppes.npcs.api.entity.IEnergyPanel; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { + + public ScriptEnergyPanel(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_PANEL; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_PANEL || super.typeOf(type); + } + + @Override + public int getBarrierType() { + return 1; + } + + // ==================== PANEL-SPECIFIC ==================== + + public float getPanelWidth() { + return entity.getPanelData().panelWidth; + } + + public void setPanelWidth(float width) { + entity.getPanelData().setPanelWidth(width); + } + + public float getPanelHeight() { + return entity.getPanelData().panelHeight; + } + + public void setPanelHeight(float height) { + entity.getPanelData().setPanelHeight(height); + } + + public float getPanelYaw() { + return entity.getPanelYaw(); + } + + public int getPanelMode() { + return entity.getMode().ordinal(); + } + + public boolean isLaunched() { + return entity.getMode() == EntityEnergyPanel.PanelMode.LAUNCHED; + } + + public void setPanelYaw(float yaw) { + entity.setPanelYaw(yaw); + } + + public void setPanelMode(int mode) { + EntityEnergyPanel.PanelMode[] values = EntityEnergyPanel.PanelMode.values(); + if (mode >= 0 && mode < values.length) { + entity.setMode(values[mode]); + } + } + + // ==================== SPAWNING ==================== + + public void spawn() { + if (!entity.addedToChunk && entity.worldObj != null) { + entity.worldObj.spawnEntityInWorld(entity); + } + } +} 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..4ff8f8699 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java @@ -0,0 +1,373 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergyProjectile; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.EventHooks; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyProjectile extends ScriptEnergyAbility implements IEnergyProjectile { + + public ScriptEnergyProjectile(T entity) { + super(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 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 (PROJECTILE-SPECIFIC) ==================== + + 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); + } + + // ==================== 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); + } + + public int getHitType() { + return entity.getHitType(); + } + + public void setHitType(int hitType) { + entity.setHitType(hitType); + } + + public int getMultiHitDelayTicks() { + return entity.getMultiHitDelayTicks(); + } + + public void setMultiHitDelayTicks(int delayTicks) { + entity.setMultiHitDelayTicks(delayTicks); + } + + public int getMaxHits() { + return entity.getMaxHits(); + } + + public void setMaxHits(int maxHits) { + entity.setMaxHits(maxHits); + } + + // ==================== 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(); + } + + // ==================== FIRE ==================== + + public void fireAt(IEntity target) { + if (target != null) { + EntityLivingBase living = resolveLivingTarget(target); + if (living != null) { + entity.setTargetEntityId(living.getEntityId()); + setMotionToward(living.posX, living.posY + living.getEyeHeight(), living.posZ); + } else { + net.minecraft.entity.Entity mcTarget = target.getMCEntity(); + setMotionToward(mcTarget.posX, mcTarget.posY + mcTarget.getEyeHeight(), mcTarget.posZ); + } + } + ensureSpawned(); + } + + public void fireAt(double x, double y, double z) { + setMotionToward(x, y, z); + ensureSpawned(); + } + + public void fireDirection(float yaw, float pitch) { + setMotionFromDirection(yaw, pitch); + ensureSpawned(); + } + + public void fireFrom(IEntityLivingBase caster) { + if (caster == null) return; + initFromCaster(caster); + launchFromOwner(null); + ensureSpawned(); + } + + public void fireFrom(IEntityLivingBase caster, IEntity target) { + if (caster == null) return; + initFromCaster(caster); + launchFromOwner(resolveLivingTarget(target)); + ensureSpawned(); + } + + /** + * 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); + } + + /** + * Hook for subclasses to call their entity's full launch sequence (startMoving/startFiring). + * Called by fireFrom methods — handles look-vector snap, charge exit, homing init, etc. + * Default: sets motion toward target, or along owner's look direction if target is null. + */ + protected void launchFromOwner(EntityLivingBase target) { + if (target != null) { + setMotionToward(target.posX, target.posY + target.getEyeHeight(), target.posZ); + } else { + net.minecraft.entity.Entity owner = entity.getOwnerEntity(); + if (owner != null) { + setMotionFromDirection(owner.rotationYaw, owner.rotationPitch); + } + } + } + + private void setMotionFromDirection(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(); + } + + protected static EntityLivingBase resolveLivingTarget(IEntity target) { + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + return (EntityLivingBase) target.getMCEntity(); + } + return null; + } + + /** + * 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(); + } + } + + public void syncClient() { + if (entity.addedToChunk) { + entity.sendClientSync(); + } + } + + protected void ensureSpawned() { + if (!entity.addedToChunk && entity.worldObj != null) { + entity.worldObj.spawnEntityInWorld(entity); + if (!entity.worldObj.isRemote) { + EventHooks.onEnergyProjectileFired(entity); + } + } else if (entity.addedToChunk) { + entity.sendClientSync(); + } + } + +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySlicer.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySlicer.java new file mode 100644 index 000000000..42ea79203 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySlicer.java @@ -0,0 +1,53 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergySlicer; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergySlicer; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergySlicer extends ScriptEnergyProjectile implements IEnergySlicer { + + public ScriptEnergySlicer(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_SLICER; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_SLICER || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 4; + } + + // ==================== SLICER-SPECIFIC ==================== + + public float getSliceWidth() { + return entity.getSliceWidth(); + } + + public void setSliceWidth(float width) { + entity.setSliceWidth(width); + } + + public float getSliceThickness() { + return entity.getSliceThickness(); + } + + public void setSliceThickness(float thickness) { + entity.setSliceThickness(thickness); + } + + // ==================== FIRE ==================== + + @Override + protected void launchFromOwner(EntityLivingBase target) { + entity.startMoving(target); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java new file mode 100644 index 000000000..021bcafb5 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java @@ -0,0 +1,116 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityEnergySweeper; +import noppes.npcs.api.entity.IEnergySweeper; + +public class ScriptEnergySweeper extends ScriptEnergyAbility implements IEnergySweeper { + + public ScriptEnergySweeper(T entity) { + super(entity); + } + + // ==================== BEAM DIMENSIONS ==================== + + @Override + public float getBeamLength() { + return entity.getBeamLength(); + } + + @Override + public void setBeamLength(float length) { + entity.setBeamLength(length); + } + + @Override + public float getBeamWidth() { + return entity.getBeamWidth(); + } + + @Override + public void setBeamWidth(float width) { + entity.setBeamWidth(width); + } + + @Override + public float getBeamHeight() { + return entity.getBeamHeight(); + } + + @Override + public void setBeamHeight(float height) { + entity.setBeamHeight(height); + } + + // ==================== ROTATION ==================== + + @Override + public float getSweepSpeed() { + return entity.getSweepSpeed(); + } + + @Override + public void setSweepSpeed(float degreesPerTick) { + entity.setSweepSpeed(degreesPerTick); + } + + @Override + public int getNumberOfRotations() { + return entity.getNumberOfRotations(); + } + + @Override + public void setNumberOfRotations(int rotations) { + entity.setNumberOfRotations(rotations); + } + + @Override + public boolean isLockOnTarget() { + return entity.isLockOnTarget(); + } + + @Override + public void setLockOnTarget(boolean lock) { + entity.setLockOnTarget(lock); + } + + // ==================== DAMAGE ==================== + + @Override + public float getDamage() { + return entity.getDamage(); + } + + @Override + public void setDamage(float damage) { + entity.setDamage(damage); + } + + @Override + public int getDamageInterval() { + return entity.getDamageInterval(); + } + + @Override + public void setDamageInterval(int ticks) { + entity.setDamageInterval(ticks); + } + + @Override + public boolean isPiercing() { + return entity.isPiercing(); + } + + @Override + public void setPiercing(boolean piercing) { + entity.setPiercing(piercing); + } + + // ==================== SPAWNING ==================== + + @Override + public void spawn() { + if (!entity.addedToChunk && entity.worldObj != null) { + entity.worldObj.spawnEntityInWorld(entity); + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyZone.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyZone.java new file mode 100644 index 000000000..9368a2475 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyZone.java @@ -0,0 +1,277 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityZone; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.INbt; +import noppes.npcs.api.entity.IEnergyZone; +import noppes.npcs.scripted.NpcAPI; + +/** + * Script wrapper for EntityAbilityZone (Hazard and Trap zones). + */ +public class ScriptEnergyZone extends ScriptEntity implements IEnergyZone { + + public ScriptEnergyZone(T entity) { + super(entity); + } + + // ==================== ZONE TYPE ==================== + + @Override + public int getZoneType() { + return entity.getZoneType().ordinal(); + } + + // ==================== COMMON ZONE PROPERTIES ==================== + + @Override + public int getZoneShape() { + return entity.getShape().ordinal(); + } + + @Override + public void setZoneShape(int shape) { + EntityAbilityZone.ZoneShape[] values = EntityAbilityZone.ZoneShape.values(); + if (shape >= 0 && shape < values.length) { + entity.setShape(values[shape]); + } + } + + @Override + public float getRadius() { + return entity.getRadius(); + } + + @Override + public void setRadius(float radius) { + entity.setRadius(radius); + } + + @Override + public float getZoneHeight() { + return entity.getZoneHeight(); + } + + @Override + public void setZoneHeight(float height) { + entity.setZoneHeight(height); + } + + @Override + public int getDuration() { + return entity.getDurationTicks(); + } + + @Override + public void setDuration(int ticks) { + entity.setDurationTicks(ticks); + } + + // ==================== COLORS ==================== + + @Override + public int getInnerColor() { + return entity.getInnerColor(); + } + + @Override + public void setInnerColor(int color) { + entity.setInnerColor(color); + } + + @Override + public int getOuterColor() { + return entity.getOuterColor(); + } + + @Override + public void setOuterColor(int color) { + entity.setOuterColor(color); + } + + @Override + public boolean isOuterColorEnabled() { + return entity.isOuterColorEnabled(); + } + + @Override + public void setOuterColorEnabled(boolean enabled) { + entity.setOuterColorEnabled(enabled); + } + + // ==================== VISUALS ==================== + + @Override + public float getParticleDensity() { + return entity.getParticleDensity(); + } + + @Override + public void setParticleDensity(float density) { + entity.setParticleDensity(density); + } + + @Override + public float getParticleScale() { + return entity.getParticleScale(); + } + + @Override + public void setParticleScale(float scale) { + entity.setParticleScale(scale); + } + + @Override + public float getAnimSpeed() { + return entity.getAnimSpeed(); + } + + @Override + public void setAnimSpeed(float speed) { + entity.setAnimSpeed(speed); + } + + @Override + public boolean isIgnoreIFrames() { + return entity.isIgnoreIFrames(); + } + + @Override + public void setIgnoreIFrames(boolean ignore) { + entity.setIgnoreIFrames(ignore); + } + + // ==================== HAZARD-SPECIFIC ==================== + + @Override + public float getDamagePerSecond() { + return entity.getDamagePerSecond(); + } + + @Override + public void setDamagePerSecond(float dps) { + entity.setDamagePerSecond(dps); + } + + @Override + public int getDamageInterval() { + return entity.getDamageInterval(); + } + + @Override + public void setDamageInterval(int ticks) { + entity.setDamageInterval(ticks); + } + + @Override + public boolean isAffectsCaster() { + return entity.isAffectsCaster(); + } + + @Override + public void setAffectsCaster(boolean affects) { + entity.setAffectsCaster(affects); + } + + // ==================== TRAP-SPECIFIC ==================== + + @Override + public float getTriggerRadius() { + return entity.getTriggerRadius(); + } + + @Override + public void setTriggerRadius(float radius) { + entity.setTriggerRadius(radius); + } + + @Override + public int getArmTime() { + return entity.getArmTime(); + } + + @Override + public void setArmTime(int ticks) { + entity.setArmTime(ticks); + } + + @Override + public int getMaxTriggers() { + return entity.getMaxTriggers(); + } + + @Override + public void setMaxTriggers(int max) { + entity.setMaxTriggers(max); + } + + @Override + public int getTriggerCooldown() { + return entity.getTriggerCooldown(); + } + + @Override + public void setTriggerCooldown(int ticks) { + entity.setTriggerCooldown(ticks); + } + + @Override + public float getDamage() { + return entity.getDamage(); + } + + @Override + public void setDamage(float damage) { + entity.setDamage(damage); + } + + @Override + public float getKnockback() { + return entity.getKnockback(); + } + + @Override + public void setKnockback(float knockback) { + entity.setKnockback(knockback); + } + + @Override + public boolean isVisible() { + return entity.isVisible(); + } + + @Override + public void setVisible(boolean visible) { + entity.setVisible(visible); + } + + // ==================== CUSTOM DAMAGE DATA ==================== + + @Override + public INbt getDamageData() { + NBTTagCompound data = entity.getCustomDamageData(); + if (data == null) { + data = new NBTTagCompound(); + entity.setCustomDamageData(data); + } + return NpcAPI.Instance().getINbt(data); + } + + @Override + public void setDamageData(INbt data) { + if (data == null) { + entity.setCustomDamageData(null); + } else { + entity.setCustomDamageData((NBTTagCompound) data.getMCNBT()); + } + } + + // ==================== SPAWNING ==================== + + @Override + public void spawn() { + if (!entity.addedToChunk && entity.worldObj != null) { + entity.worldObj.spawnEntityInWorld(entity); + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java index 6c8bc9e3a..9115dc170 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.EntityEnergyProjectile; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -527,6 +532,16 @@ public class ScriptEntity implements IEntity { cls = EntityMob.class; else if (type == EntityType.NPC) cls = EntityNPCInterface.class; + else if (type == EntityType.ENERGY_PROJECTILE) + cls = EntityEnergyProjectile.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..27621f125 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java @@ -1,5 +1,7 @@ package noppes.npcs.scripted.entity; +import kamkeel.npcs.entity.EntityEnergyProjectile; +import net.minecraft.entity.EnumCreatureAttribute; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import noppes.npcs.NoppesUtilServer; @@ -7,9 +9,12 @@ 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.IHitboxData; import noppes.npcs.api.entity.data.IModelData; +import noppes.npcs.api.entity.data.ITintData; import noppes.npcs.api.handler.IActionManager; import noppes.npcs.api.handler.IOverlayHandler; import noppes.npcs.api.handler.data.IAnimationData; @@ -419,6 +424,62 @@ public class ScriptNpc extends ScriptLiving imp return this.npc.advanced.killLines; } + public boolean getOrderedLines() { + return npc.advanced.orderedLines; + } + + public void setOrderedLines(boolean ordered) { + npc.advanced.orderedLines = ordered; + } + + public String getIdleSound() { + return npc.advanced.idleSound; + } + + public void setIdleSound(String sound) { + npc.advanced.idleSound = sound; + } + + public String getAngrySound() { + return npc.advanced.angrySound; + } + + public void setAngrySound(String sound) { + npc.advanced.angrySound = sound; + } + + public String getHurtSound() { + return npc.advanced.hurtSound; + } + + public void setHurtSound(String sound) { + npc.advanced.hurtSound = sound; + } + + public String getDeathSound() { + return npc.advanced.deathSound; + } + + public void setDeathSound(String sound) { + npc.advanced.deathSound = sound; + } + + public String getStepSound() { + return npc.advanced.stepSound; + } + + public void setStepSound(String sound) { + npc.advanced.stepSound = sound; + } + + public boolean getDisablePitch() { + return npc.advanced.disablePitch; + } + + public void setDisablePitch(boolean disablePitch) { + npc.advanced.disablePitch = disablePitch; + } + /** * Kill the npc, doesnt't despawn it */ @@ -846,6 +907,171 @@ public class ScriptNpc extends ScriptLiving imp return npc.ais.tacticalRadius; } + public int getTacticalChance() { + return npc.ais.tacticalChance; + } + + public void setTacticalChance(int chance) { + npc.ais.tacticalChance = chance; + } + + public boolean getCanSwim() { + return npc.ais.canSwim; + } + + public void setCanSwim(boolean canSwim) { + npc.ais.canSwim = canSwim; + } + + public boolean getReactsToFire() { + return npc.ais.reactsToFire; + } + + public void setReactsToFire(boolean reactsToFire) { + npc.ais.reactsToFire = reactsToFire; + } + + public boolean getAvoidsWater() { + return npc.ais.avoidsWater; + } + + public void setAvoidsWater(boolean avoidsWater) { + npc.ais.avoidsWater = avoidsWater; + } + + public boolean getAvoidsSun() { + return npc.ais.avoidsSun; + } + + public void setAvoidsSun(boolean avoidsSun) { + npc.ais.avoidsSun = avoidsSun; + } + + public boolean getDirectLOS() { + return npc.ais.directLOS; + } + + public void setDirectLOS(boolean directLOS) { + npc.ais.directLOS = directLOS; + } + + public int getLeapType() { + return npc.ais.leapType; + } + + public void setLeapType(int leapType) { + npc.ais.leapType = leapType; + } + + public boolean getCanSprint() { + return npc.ais.canSprint; + } + + public void setCanSprint(boolean canSprint) { + npc.ais.canSprint = canSprint; + } + + public boolean getStopAndInteract() { + return npc.ais.stopAndInteract; + } + + public void setStopAndInteract(boolean stopAndInteract) { + npc.ais.stopAndInteract = stopAndInteract; + } + + public int getDoorInteract() { + return npc.ais.doorInteract; + } + + public void setDoorInteract(int doorInteract) { + npc.ais.doorInteract = doorInteract; + } + + public int getWalkingRange() { + return npc.ais.walkingRange; + } + + public void setWalkingRange(int range) { + npc.ais.walkingRange = range; + } + + public boolean getNpcInteracting() { + return npc.ais.npcInteracting; + } + + public void setNpcInteracting(boolean npcInteracting) { + npc.ais.npcInteracting = npcInteracting; + } + + public boolean getMovingPause() { + return npc.ais.movingPause; + } + + public void setMovingPause(boolean movingPause) { + npc.ais.movingPause = movingPause; + } + + public int getMovingPattern() { + return npc.ais.movingPattern; + } + + public void setMovingPattern(int pattern) { + if (pattern < 0) pattern = 0; + if (pattern > 1) pattern = 1; + npc.ais.movingPattern = pattern; + } + + public int getCanFireIndirect() { + return npc.ais.canFireIndirect; + } + + public void setCanFireIndirect(int canFireIndirect) { + npc.ais.canFireIndirect = canFireIndirect; + } + + public int getUseRangeMelee() { + return npc.ais.useRangeMelee; + } + + public void setUseRangeMelee(int useRangeMelee) { + npc.ais.useRangeMelee = useRangeMelee; + } + + public int getDistanceToMelee() { + return npc.ais.distanceToMelee; + } + + public void setDistanceToMelee(int distance) { + npc.ais.distanceToMelee = distance; + } + + public float getBodyOffsetX() { + return npc.ais.bodyOffsetX; + } + + public void setBodyOffsetX(float offsetX) { + npc.ais.bodyOffsetX = offsetX; + npc.script.clientNeedsUpdate = true; + } + + public float getBodyOffsetY() { + return npc.ais.bodyOffsetY; + } + + public void setBodyOffsetY(float offsetY) { + npc.ais.bodyOffsetY = offsetY; + npc.script.clientNeedsUpdate = true; + } + + public float getBodyOffsetZ() { + return npc.ais.bodyOffsetZ; + } + + public void setBodyOffsetZ(float offsetZ) { + npc.ais.bodyOffsetZ = offsetZ; + npc.script.clientNeedsUpdate = true; + } + public void setIgnoreCobweb(boolean ignore) { npc.stats.ignoreCobweb = ignore; } @@ -1107,6 +1333,7 @@ public class ScriptNpc extends ScriptLiving imp public void setNaturallyDespawns(boolean canDespawn) { npc.stats.canDespawn = canDespawn; npc.stats.playerSetCanDespawn = canDespawn; + npc.syncDespawnPersistence(); } public boolean spawnedFromSoulStone() { @@ -1149,6 +1376,14 @@ public class ScriptNpc extends ScriptLiving imp return npc instanceof EntityCustomNpc ? ((EntityCustomNpc) npc).modelData : null; } + public IHitboxData getHitboxData() { + return npc.display.hitboxData; + } + + public ITintData getTintData() { + return npc.display.tintData; + } + public void setHeadScale(float x, float y, float z) { if (npc instanceof EntityCustomNpc) { ((EntityCustomNpc) this.npc).modelData.modelScale.head.scaleX = ValueUtil.clamp(x, 0.5f, 1.5f); @@ -1247,6 +1482,66 @@ public class ScriptNpc extends ScriptLiving imp return npc.stats.resistances.knockback; } + public boolean getDamageDisabled() { + return npc.stats.resistances.disableDamage; + } + + public void setDamageDisabled(boolean disabled) { + npc.stats.resistances.disableDamage = disabled; + } + + public boolean getNoFallDamage() { + return npc.stats.noFallDamage; + } + + public void setNoFallDamage(boolean noFallDamage) { + npc.stats.noFallDamage = noFallDamage; + } + + public boolean getImmuneToFire() { + return npc.stats.immuneToFire; + } + + public void setImmuneToFire(boolean immuneToFire) { + npc.stats.immuneToFire = immuneToFire; + npc.setImmuneToFire(immuneToFire); + } + + public boolean getPotionImmune() { + return npc.stats.potionImmune; + } + + public void setPotionImmune(boolean potionImmune) { + npc.stats.potionImmune = potionImmune; + } + + public boolean getBurnInSun() { + return npc.stats.burnInSun; + } + + public void setBurnInSun(boolean burnInSun) { + npc.stats.burnInSun = burnInSun; + } + + public boolean getAttackInvisible() { + return npc.stats.attackInvisible; + } + + public void setAttackInvisible(boolean attackInvisible) { + npc.stats.attackInvisible = attackInvisible; + } + + public int getCreatureType() { + return npc.stats.creatureType.ordinal(); + } + + public void setCreatureType(int type) { + EnumCreatureAttribute[] values = EnumCreatureAttribute.values(); + if (type >= 0 && type < values.length) { + npc.stats.creatureType = values[type]; + } + } + /** * @param type Retaliation type. 0:normal, 1:panic, 2:retreat, 3:nothing */ @@ -1429,6 +1724,15 @@ public class ScriptNpc extends ScriptLiving imp return npc.display.skinOverlayData.overlayList.get(0).getTexture(); } + public String getGlowTexture() { + return npc.display.glowTexture; + } + + public void setGlowTexture(String texture) { + npc.display.glowTexture = texture; + npc.script.clientNeedsUpdate = true; + } + public IOverlayHandler getOverlays() { return npc.display.skinOverlayData; } @@ -1463,4 +1767,13 @@ public class ScriptNpc extends ScriptLiving imp public IDataAbilities getAbilityData() { return new ScriptDataAbilities(npc); } + + public IEnergyProjectile[] getActiveEnergyProjectiles() { + java.util.List entities = EntityEnergyProjectile.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..2b626ddae 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.EntityEnergyProjectile; 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; @@ -315,9 +317,7 @@ public class ScriptPlayer extends ScriptLivingBase Quest quest = QuestController.Instance.quests.get(id); if (quest == null) return; - PlayerData data = PlayerData.get(player); - PlayerQuestController.setQuestFinishedUtil(player, quest, data.questData); - data.updateClient = true; + PlayerQuestController.setQuestFinished(quest, player); } /** @@ -933,4 +933,13 @@ public class ScriptPlayer extends ScriptLivingBase public String getFormattedCurrencyBalance() { return getData().tradeData.formatBalance(); } + + public IEnergyProjectile[] getActiveEnergyProjectiles() { + List entities = EntityEnergyProjectile.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/AbilityEvent.java b/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java index 9bf7719d5..f71cb8b2a 100644 --- a/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java +++ b/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java @@ -8,26 +8,56 @@ import noppes.npcs.api.IDamageSource; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.scripted.NpcAPI; /** - * Events fired during NPC ability execution lifecycle. + * Unified ability events for both NPCs and Players. */ -public class AbilityEvent extends NpcEvent implements IAbilityEvent { +public class AbilityEvent extends CustomNPCsEvent implements IAbilityEvent { + protected final IEntityLivingBase entity; + public final IPlayer player; + public final ICustomNpc npc; protected final Ability ability; protected final IEntityLivingBase target; + private transient IAbility abilityCopy; - public AbilityEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc); + public AbilityEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + this.entity = entity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(entity) : null; this.ability = ability; this.target = target != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(target) : null; + this.player = (this.entity instanceof IPlayer) ? (IPlayer) this.entity : null; + this.npc = (this.entity instanceof ICustomNpc) ? (ICustomNpc) this.entity : null; + } + + @Override + public IEntityLivingBase getEntity() { + return entity; + } + + @Override + public IPlayer getPlayer() { + return player; + } + + @Override + public ICustomNpc getNpc() { + return npc; + } + + @Override + public boolean isNPC() { + return entity instanceof ICustomNpc; } @Override public IAbility getAbility() { - return ability; + if (abilityCopy == null && ability != null) { + abilityCopy = ability.deepCopy(); + } + return abilityCopy; } @Override @@ -40,13 +70,10 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { return "abilityEvent"; } - /** - * Fired when an ability starts executing (enters WINDUP phase). - */ @Cancelable public static class StartEvent extends AbilityEvent implements IAbilityEvent.StartEvent { - public StartEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc, ability, target); + public StartEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); } @Override @@ -55,13 +82,10 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability enters the ACTIVE phase and performs its effect. - */ @Cancelable public static class ExecuteEvent extends AbilityEvent implements IAbilityEvent.ExecuteEvent { - public ExecuteEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc, ability, target); + public ExecuteEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); } @Override @@ -70,16 +94,13 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability is interrupted by damage. - */ public static class InterruptEvent extends AbilityEvent implements IAbilityEvent.InterruptEvent { private final IDamageSource damageSource; private final float damage; - public InterruptEvent(ICustomNpc npc, Ability ability, EntityLivingBase target, DamageSource source, float damage) { - super(npc, ability, target); - this.damageSource = NpcAPI.Instance().getIDamageSource(source); + public InterruptEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, DamageSource source, float damage) { + super(entity, ability, target); + this.damageSource = source != null ? NpcAPI.Instance().getIDamageSource(source) : null; this.damage = damage; } @@ -99,12 +120,9 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability completes its full execution cycle. - */ public static class CompleteEvent extends AbilityEvent implements IAbilityEvent.CompleteEvent { - public CompleteEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc, ability, target); + public CompleteEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); } @Override @@ -113,10 +131,6 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability hits an entity with damage. - * This is a cancelable event - canceling prevents the damage from being applied. - */ @Cancelable public static class HitEvent extends AbilityEvent implements IAbilityEvent.HitEvent { private final IEntityLivingBase hitEntity; @@ -124,9 +138,9 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { private float knockback; private float knockbackUp; - public HitEvent(ICustomNpc npc, Ability ability, EntityLivingBase target, + public HitEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp) { - super(npc, ability, target); + super(entity, ability, target); this.hitEntity = hitEntity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(hitEntity) : null; this.damage = damage; this.knockback = knockback; @@ -174,16 +188,12 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired every tick while an ability is executing. - * Provides information about the current phase and tick. - */ public static class TickEvent extends AbilityEvent implements IAbilityEvent.TickEvent { private final int abilityPhase; private final int tick; - public TickEvent(ICustomNpc npc, Ability ability, EntityLivingBase target, int phase, int tick) { - super(npc, ability, target); + public TickEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, int phase, int tick) { + super(entity, ability, target); this.abilityPhase = phase; this.tick = tick; } @@ -203,4 +213,113 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { return EnumScriptType.ABILITY_TICK.function; } } + + @Cancelable + public static class DefendEvent extends AbilityEvent implements IAbilityEvent.DefendEvent { + private final IEntityLivingBase attacker; + private final IEntityLivingBase lastAttacker; + private float damage; + + public DefendEvent(EntityLivingBase entity, Ability ability, EntityLivingBase attacker, + EntityLivingBase lastAttacker, float damage) { + super(entity, ability, null); + this.attacker = attacker != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(attacker) : null; + this.lastAttacker = lastAttacker != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(lastAttacker) : null; + this.damage = damage; + } + + @Override + public IEntityLivingBase getAttacker() { + return attacker; + } + + @Override + public IEntityLivingBase getLastAttacker() { + return lastAttacker; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_DEFEND.function; + } + } + + @Cancelable + public static class ToggleEvent extends AbilityEvent implements IAbilityEvent.ToggleEvent { + private final int oldState; + private final int newState; + + public ToggleEvent(EntityLivingBase entity, Ability ability, int oldState, int newState) { + super(entity, ability, null); + this.oldState = oldState; + this.newState = newState; + } + + @Override + public boolean isTogglingOn() { + return newState > 0; + } + + @Override + public int getOldState() { + return oldState; + } + + @Override + public int getNewState() { + return newState; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_TOGGLE.function; + } + } + + public static class ToggleUpdateEvent extends AbilityEvent implements IAbilityEvent.ToggleUpdateEvent { + private final int tick; + private final int state; + private boolean enabled = true; + + public ToggleUpdateEvent(EntityLivingBase entity, Ability ability, int tick, int state) { + super(entity, ability, null); + this.tick = tick; + this.state = state; + } + + @Override + public int getTick() { + return tick; + } + + @Override + public int getState() { + return state; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + @Override + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_TOGGLE_TICK.function; + } + } } diff --git a/src/main/java/noppes/npcs/scripted/event/ChainEvent.java b/src/main/java/noppes/npcs/scripted/event/ChainEvent.java new file mode 100644 index 000000000..2c0852e6c --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/ChainEvent.java @@ -0,0 +1,134 @@ +package noppes.npcs.scripted.event; + +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.IDamageSource; +import noppes.npcs.api.ability.IChainedAbility; +import noppes.npcs.api.entity.ICustomNpc; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.api.entity.IPlayer; +import noppes.npcs.api.event.IChainEvent; +import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.scripted.NpcAPI; + +/** + * Unified chain events for both NPCs and Players. + */ +public class ChainEvent extends CustomNPCsEvent implements IChainEvent { + protected final IEntityLivingBase entity; + public final IPlayer player; + public final ICustomNpc npc; + protected final ChainedAbility chain; + protected final IEntityLivingBase target; + protected final int entryIndex; + + public ChainEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + this.entity = entity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(entity) : null; + this.chain = chain; + this.entryIndex = entryIndex; + this.target = target != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(target) : null; + this.player = (this.entity instanceof IPlayer) ? (IPlayer) this.entity : null; + this.npc = (this.entity instanceof ICustomNpc) ? (ICustomNpc) this.entity : null; + } + + @Override + public IEntityLivingBase getEntity() { + return entity; + } + + @Override + public IPlayer getPlayer() { + return player; + } + + @Override + public ICustomNpc getNpc() { + return npc; + } + + @Override + public boolean isNPC() { + return entity instanceof ICustomNpc; + } + + @Override + public IChainedAbility getChain() { + return chain; + } + + @Override + public IEntityLivingBase getTarget() { + return target; + } + + @Override + public int getEntryIndex() { + return entryIndex; + } + + @Override + public String getHookName() { + return "chainEvent"; + } + + public static class StartEvent extends ChainEvent implements IChainEvent.StartEvent { + public StartEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + super(entity, chain, entryIndex, target); + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_START.function; + } + } + + public static class NextEvent extends ChainEvent implements IChainEvent.NextEvent { + public NextEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + super(entity, chain, entryIndex, target); + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_NEXT.function; + } + } + + public static class CompleteEvent extends ChainEvent implements IChainEvent.CompleteEvent { + public CompleteEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + super(entity, chain, entryIndex, target); + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_COMPLETE.function; + } + } + + public static class InterruptEvent extends ChainEvent implements IChainEvent.InterruptEvent { + private final IDamageSource damageSource; + private final float damage; + + public InterruptEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target, + DamageSource source, float damage) { + super(entity, chain, entryIndex, 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.CHAIN_INTERRUPT.function; + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/event/EnergyBarrierEvent.java b/src/main/java/noppes/npcs/scripted/event/EnergyBarrierEvent.java new file mode 100644 index 000000000..a64948a6c --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/EnergyBarrierEvent.java @@ -0,0 +1,98 @@ +package noppes.npcs.scripted.event; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import noppes.npcs.api.entity.IEnergyBarrier; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.event.IEnergyBarrierEvent; +import noppes.npcs.constants.EnumScriptType; + +public class EnergyBarrierEvent extends CustomNPCsEvent implements IEnergyBarrierEvent { + public final IEnergyBarrier barrier; + public final IEntity owner; + + public EnergyBarrierEvent(IEnergyBarrier barrier) { + this.barrier = barrier; + this.owner = barrier.getOwner(); + } + + @Override + public IEnergyBarrier getBarrier() { + return barrier; + } + + @Override + public IEntity getOwner() { + return owner; + } + + @Override + public String getHookName() { + return "energyBarrierEvent"; + } + + public static class SpawnedEvent extends EnergyBarrierEvent implements IEnergyBarrierEvent.SpawnedEvent { + public SpawnedEvent(IEnergyBarrier barrier) { + super(barrier); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_BARRIER_SPAWNED.function; + } + } + + public static class UpdateEvent extends EnergyBarrierEvent implements IEnergyBarrierEvent.UpdateEvent { + public UpdateEvent(IEnergyBarrier barrier) { + super(barrier); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_BARRIER_TICK.function; + } + } + + @Cancelable + public static class HitEvent extends EnergyBarrierEvent implements IEnergyBarrierEvent.HitEvent { + private final IEnergyProjectile projectile; + private float damage; + + public HitEvent(IEnergyBarrier barrier, IEnergyProjectile projectile, float damage) { + super(barrier); + this.projectile = projectile; + this.damage = damage; + } + + @Override + public IEnergyProjectile getProjectile() { + return projectile; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_BARRIER_HIT.function; + } + } + + public static class DestroyedEvent extends EnergyBarrierEvent implements IEnergyBarrierEvent.DestroyedEvent { + public DestroyedEvent(IEnergyBarrier barrier) { + super(barrier); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_BARRIER_DESTROYED.function; + } + } +} 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..024376103 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java @@ -0,0 +1,138 @@ +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 { + private final int tick; + + public UpdateEvent(IEnergyProjectile projectile, int tick) { + super(projectile); + this.tick = tick; + } + + @Override + public int getTick() { return this.tick; } + + @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/AuctionEvent.java b/src/main/java/noppes/npcs/scripted/event/player/AuctionEvent.java new file mode 100644 index 000000000..fc3a121e1 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/player/AuctionEvent.java @@ -0,0 +1,149 @@ +package noppes.npcs.scripted.event.player; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import noppes.npcs.api.entity.IPlayer; +import noppes.npcs.api.event.IAuctionEvent; +import noppes.npcs.api.handler.data.IAuctionClaim; +import noppes.npcs.api.handler.data.IAuctionListing; +import noppes.npcs.api.item.IItemStack; +import noppes.npcs.constants.EnumScriptType; + +public class AuctionEvent extends PlayerEvent implements IAuctionEvent { + + public AuctionEvent(IPlayer player) { + super(player); + } + + @Override + public String getHookName() { + return "auctionEvent"; + } + + @Cancelable + public static class CreateEvent extends AuctionEvent implements IAuctionEvent.CreateEvent { + public final IItemStack item; + public final long startingPrice; + public final long buyoutPrice; + + public CreateEvent(IPlayer player, IItemStack item, long startingPrice, long buyoutPrice) { + super(player); + this.item = item; + this.startingPrice = startingPrice; + this.buyoutPrice = buyoutPrice; + } + + @Override + public String getHookName() { + return EnumScriptType.AUCTION_CREATE.function; + } + + @Override + public IItemStack getItem() { + return item; + } + + @Override + public long getStartingPrice() { + return startingPrice; + } + + @Override + public long getBuyoutPrice() { + return buyoutPrice; + } + } + + @Cancelable + public static class BidEvent extends AuctionEvent implements IAuctionEvent.BidEvent { + public final IAuctionListing listing; + public final long bidAmount; + + public BidEvent(IPlayer player, IAuctionListing listing, long bidAmount) { + super(player); + this.listing = listing; + this.bidAmount = bidAmount; + } + + @Override + public String getHookName() { + return EnumScriptType.AUCTION_BID.function; + } + + @Override + public IAuctionListing getListing() { + return listing; + } + + @Override + public long getBidAmount() { + return bidAmount; + } + } + + @Cancelable + public static class BuyoutEvent extends AuctionEvent implements IAuctionEvent.BuyoutEvent { + public final IAuctionListing listing; + + public BuyoutEvent(IPlayer player, IAuctionListing listing) { + super(player); + this.listing = listing; + } + + @Override + public String getHookName() { + return EnumScriptType.AUCTION_BUYOUT.function; + } + + @Override + public IAuctionListing getListing() { + return listing; + } + } + + @Cancelable + public static class CancelEvent extends AuctionEvent implements IAuctionEvent.CancelEvent { + public final IAuctionListing listing; + public final boolean admin; + + public CancelEvent(IPlayer player, IAuctionListing listing, boolean isAdmin) { + super(player); + this.listing = listing; + this.admin = isAdmin; + } + + @Override + public String getHookName() { + return EnumScriptType.AUCTION_CANCEL.function; + } + + @Override + public IAuctionListing getListing() { + return listing; + } + + @Override + public boolean isAdmin() { + return admin; + } + } + + @Cancelable + public static class ClaimEvent extends AuctionEvent implements IAuctionEvent.ClaimEvent { + public final IAuctionClaim claim; + + public ClaimEvent(IPlayer player, IAuctionClaim claim) { + super(player); + this.claim = claim; + } + + @Override + public String getHookName() { + return EnumScriptType.AUCTION_CLAIM.function; + } + + @Override + public IAuctionClaim getClaim() { + return claim; + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java b/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java deleted file mode 100644 index cb7def405..000000000 --- a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java +++ /dev/null @@ -1,101 +0,0 @@ -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 noppes.npcs.api.ability.IAbility; -import noppes.npcs.api.entity.IEntityLivingBase; -import noppes.npcs.api.entity.IPlayer; -import noppes.npcs.api.event.IPlayerAbilityEvent; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.scripted.NpcAPI; - -/** - * Events fired during player ability execution lifecycle. - */ -public class PlayerAbilityEvent extends PlayerEvent implements IPlayerAbilityEvent { - protected final Ability ability; - protected final IEntityLivingBase target; - - public PlayerAbilityEvent(IPlayer player, Ability ability, EntityLivingBase target) { - super(player); - this.ability = ability; - this.target = target != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(target) : null; - } - - @Override - public IAbility getAbility() { - return ability; - } - - @Override - public IEntityLivingBase getTarget() { - return target; - } - - @Override - public String getHookName() { - return "playerAbilityEvent"; - } - - /** - * Fired when a player's ability hits an entity with damage. - * Canceling prevents the damage from being applied. - */ - @Cancelable - public static class HitEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.HitEvent { - private final IEntityLivingBase hitEntity; - private float damage; - private float knockback; - private float knockbackUp; - - public HitEvent(IPlayer player, Ability ability, EntityLivingBase target, - EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp) { - super(player, ability, target); - this.hitEntity = hitEntity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(hitEntity) : null; - this.damage = damage; - this.knockback = knockback; - this.knockbackUp = knockbackUp; - } - - @Override - public IEntityLivingBase getHitEntity() { - return hitEntity; - } - - @Override - public float getDamage() { - return damage; - } - - @Override - public void setDamage(float damage) { - this.damage = damage; - } - - @Override - public float getKnockback() { - return knockback; - } - - @Override - public void setKnockback(float knockback) { - this.knockback = knockback; - } - - @Override - public float getKnockbackUp() { - return knockbackUp; - } - - @Override - public void setKnockbackUp(float knockbackUp) { - this.knockbackUp = knockbackUp; - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_HIT.function; - } - } -} diff --git a/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java b/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java index 4b9ead83e..05da1d779 100644 --- a/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java +++ b/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java @@ -11,6 +11,11 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur float scale; String texture; + // Animation + boolean animated = false; + int frameCount = 1; + int frametime = 2; + public ScriptGuiTexturedRect() { this.textureY = -1; this.scale = 1.0F; @@ -76,6 +81,25 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur return this; } + public boolean isAnimated() { + return this.animated && this.frameCount > 1; + } + + public int getFrameCount() { + return this.frameCount; + } + + public int getFrameTime() { + return this.frametime; + } + + public ITexturedRect setAnimation(int frameCount, int frametime) { + this.animated = frameCount > 1; + this.frameCount = Math.max(1, frameCount); + this.frametime = Math.max(1, frametime); + return this; + } + public int getType() { return 2; } @@ -89,6 +113,12 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur nbt.setIntArray("texPos", new int[]{this.textureX, this.textureY}); } + if (this.animated) { + nbt.setBoolean("animated", true); + nbt.setInteger("frameCount", this.frameCount); + nbt.setInteger("frameTime", this.frametime); + } + return nbt; } @@ -101,6 +131,13 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur this.setTextureOffset(nbt.getIntArray("texPos")[0], nbt.getIntArray("texPos")[1]); } + if (nbt.hasKey("animated") && nbt.getBoolean("animated")) { + this.setAnimation( + nbt.hasKey("frameCount") ? Math.max(1, nbt.getInteger("frameCount")) : 1, + nbt.hasKey("frameTime") ? Math.max(1, nbt.getInteger("frameTime")) : 2 + ); + } + return this; } } diff --git a/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java b/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java index 77e51df2c..a029b4ba4 100644 --- a/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java +++ b/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java @@ -147,6 +147,33 @@ public abstract class ScriptCustomizableItem extends ScriptItemStack implements return this.itemDisplay.translateZ != null ? this.itemDisplay.translateZ : 0; } + public Boolean isTextureAnimated() { + return this.itemDisplay.animated != null ? this.itemDisplay.animated : false; + } + + public void setTextureAnimated(Boolean animated) { + this.itemDisplay.animated = animated; + saveItemData(); + } + + public Integer getFrameCount() { + return this.itemDisplay.frameCount != null ? this.itemDisplay.frameCount : 1; + } + + public void setFrameCount(Integer frameCount) { + this.itemDisplay.frameCount = frameCount != null ? Math.max(1, frameCount) : 1; + saveItemData(); + } + + public Integer getFrameTime() { + return this.itemDisplay.frametime != null ? this.itemDisplay.frametime : 2; + } + + public void setFrameTime(Integer frametime) { + this.itemDisplay.frametime = frametime != null ? Math.max(1, frametime) : 2; + saveItemData(); + } + public NBTTagCompound getMCNbt() { NBTTagCompound compound = super.getMCNbt(); compound.setTag("ItemData", this.getItemNBT(new NBTTagCompound())); diff --git a/src/main/java/noppes/npcs/scripted/item/ScriptLinkedItem.java b/src/main/java/noppes/npcs/scripted/item/ScriptLinkedItem.java index 1c4a2ac91..f86d5c113 100644 --- a/src/main/java/noppes/npcs/scripted/item/ScriptLinkedItem.java +++ b/src/main/java/noppes/npcs/scripted/item/ScriptLinkedItem.java @@ -87,6 +87,11 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin return this.durabilityValue; } + public void setDurabilityValue(float value) { + this.durabilityValue = (double) value; + saveItemData(); + } + @Override public int getMaxItemUseDuration() { return this.linkedItem.maxItemUseDuration; @@ -217,6 +222,7 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin this.itemDisplay.writeToNBT(compound); compound.setTag(LinkedItem.LINKED_DATA_NBT_TAG, this.linkedItem.writeToNBT(false)); compound.setInteger(LinkedItem.LINKED_VERSION_VERSION_TAG, this.linkedVersion); + compound.setDouble("DurabilityValue", this.durabilityValue); return compound; } @@ -224,5 +230,7 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin this.itemDisplay.readFromNBT(compound); this.linkedItem.readFromNBT(compound.getCompoundTag(LinkedItem.LINKED_DATA_NBT_TAG)); this.linkedVersion = compound.getInteger(LinkedItem.LINKED_VERSION_VERSION_TAG); + if (compound.hasKey("DurabilityValue")) + this.durabilityValue = compound.getDouble("DurabilityValue"); } } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java index e27f6e075..9fb509761 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java @@ -1,8 +1,8 @@ package noppes.npcs.scripted.wrapper; +import kamkeel.npcs.controllers.AbilityController; 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.AbilityAction; import net.minecraft.entity.EntityLivingBase; import noppes.npcs.DataAbilities; import noppes.npcs.api.ability.IAbility; @@ -36,7 +36,12 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public IAbility[] getAbilities() { - return data.getAbilities().toArray(new IAbility[0]); + List live = data.getAbilities(); + IAbility[] copies = new IAbility[live.size()]; + for (int i = 0; i < live.size(); i++) { + copies[i] = live.get(i).deepCopy(); + } + return copies; } @Override @@ -53,15 +58,17 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public void addAbilityReference(String key) { - // Validate ability exists and allows NPCs - Ability ability = AbilityController.Instance.resolveAbility(key); + // Validate ability exists and allows NPCs (peek avoids deep copy) + Ability ability = AbilityController.Instance.peekAbility(key); if (ability == null) { return; // Ability doesn't exist } if (!ability.getAllowedBy().allowsNpc()) { return; // Ability is PLAYER_ONLY } - data.addAbilityReference(key); + // Store by UUID/registry key for stable reference + String canonicalKey = ability.getId() != null ? ability.getId() : key; + data.addAbilityReference(canonicalKey); } @Override @@ -71,7 +78,8 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public IAbility getAbility(String abilityId) { - return data.getAbility(abilityId); + Ability a = data.getAbility(abilityId); + return a != null ? a.deepCopy() : null; } @Override @@ -81,14 +89,14 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public boolean isAbilityReference(String abilityId) { - List slots = data.getAbilitySlots(); + List slots = data.getAbilityActions(); for (int i = 0; i < slots.size(); i++) { - kamkeel.npcs.controllers.data.ability.AbilitySlot slot = slots.get(i); - if (slot.isReference()) { + AbilityAction slot = slots.get(i); + if (slot.isAbilityReference()) { if (slot.getReferenceId().equals(abilityId)) return true; - } else { + } else if (!slot.isReference()) { Ability a = slot.getAbility(); - if (a != null && a.getId().equals(abilityId)) return false; + if (a != null && abilityId.equals(a.getId())) return false; } } return false; @@ -96,10 +104,10 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public boolean convertToInline(String abilityId) { - List slots = data.getAbilitySlots(); + List slots = data.getAbilityActions(); for (int i = 0; i < slots.size(); i++) { - kamkeel.npcs.controllers.data.ability.AbilitySlot slot = slots.get(i); - if (slot.isReference() && slot.getReferenceId().equals(abilityId)) { + AbilityAction slot = slots.get(i); + if (slot.isAbilityReference() && slot.getReferenceId().equals(abilityId)) { return data.convertToInline(i); } } @@ -113,6 +121,17 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public IAbility getCurrentAbility() { + Ability a = data.getCurrentAbility(); + return a != null ? a.deepCopy() : null; + } + + @Override + public IAbility getSourceAbility(String abilityId) { + return data.getAbility(abilityId); + } + + @Override + public IAbility getSourceCurrentAbility() { return data.getCurrentAbility(); } @@ -126,6 +145,11 @@ public class ScriptDataAbilities implements IDataAbilities { data.interruptCurrentAbility(null, 0); } + @Override + public void completeCurrentAbility() { + data.completeCurrentAbility(); + } + @Override public int getGlobalCooldown() { return (int) data.getRemainingCooldown(); @@ -133,10 +157,11 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public void setGlobalCooldown(int ticks) { - // Set the cooldown by manipulating the internal cooldown end time - // Not directly exposed, but we can reset and let it tick down - data.resetCooldown(); - // This is a best-effort implementation + if (ticks <= 0) { + data.resetCooldown(); + } else { + data.setCooldownEndTime(npc.worldObj.getTotalWorldTime() + ticks); + } } @Override @@ -171,8 +196,8 @@ 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); + // Validate ability exists and allows NPCs (peek avoids deep copy) + Ability ability = AbilityController.Instance.peekAbility(key); if (ability == null) { return false; // Ability doesn't exist } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java index 42ed3372e..bb6b1b930 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java @@ -1,7 +1,7 @@ package noppes.npcs.scripted.wrapper; +import kamkeel.npcs.controllers.AbilityController; 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; @@ -28,8 +28,8 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public void unlockAbility(String key) { - // Validate ability exists and allows players - Ability ability = AbilityController.Instance.resolveAbility(key); + // Validate ability exists and allows players (peek avoids deep copy) + Ability ability = AbilityController.Instance.peekAbility(key); if (ability == null) { return; // Ability doesn't exist } @@ -43,12 +43,14 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public void lockAbility(String key) { - data.lockAbility(key); + String canonicalKey = resolveCanonicalKey(key); + data.lockAbility(canonicalKey); } @Override public boolean hasUnlockedAbility(String key) { - return data.hasUnlockedAbility(key); + String canonicalKey = resolveCanonicalKey(key); + return data.hasUnlockedAbility(canonicalKey); } @Override @@ -83,7 +85,8 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public IAbility getCurrentAbility() { - return data.getCurrentAbility(); + Ability a = data.getCurrentAbility(); + return a != null ? a.deepCopy() : null; } @Override @@ -91,6 +94,11 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { data.interruptCurrentAbility(); } + @Override + public void completeCurrentAbility() { + data.completeCurrentAbility(); + } + @Override public boolean isOnCooldown() { return data.isOnCooldown(); @@ -131,4 +139,38 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { if (player == null) return false; return data.activateAbility(player, key); } + + // Toggle system + + @Override + public int toggleAbility(String key) { + return data.toggleAbility(key); + } + + @Override + public int getToggleState(String key) { + return data.getToggleState(key); + } + + @Override + public void setToggleState(String key, int state) { + data.setToggleState(key, state); + } + + @Override + public boolean isAbilityToggled(String key) { + return data.isAbilityToggled(key); + } + + /** + * Resolve a user-provided key to the canonical storage key. + * Uses the same resolution as unlockAbility: registry key for built-in, UUID for custom. + */ + private String resolveCanonicalKey(String key) { + Ability ability = AbilityController.Instance.peekAbility(key); + if (ability != null && ability.getId() != null) { + return ability.getId(); + } + return key; + } } diff --git a/src/main/java/noppes/npcs/util/AuctionFormatUtil.java b/src/main/java/noppes/npcs/util/AuctionFormatUtil.java new file mode 100644 index 000000000..a92193815 --- /dev/null +++ b/src/main/java/noppes/npcs/util/AuctionFormatUtil.java @@ -0,0 +1,68 @@ +package noppes.npcs.util; + +import net.minecraft.util.StatCollector; +import noppes.npcs.client.AuctionClientConfig; + +/** + * Shared formatting utilities for the auction system. + * Consolidates duplicated format methods from GUI classes. + */ +public class AuctionFormatUtil { + // Time constants in milliseconds + public static final long MS_PER_SECOND = 1000L; + public static final long MS_PER_MINUTE = 60L * MS_PER_SECOND; + public static final long MS_PER_HOUR = 60L * MS_PER_MINUTE; + public static final long MS_PER_DAY = 24L * MS_PER_HOUR; + + /** + * Format currency amount with commas (e.g., 1000 -> "1,000"). + * Does NOT append currency name. + */ + public static String formatCurrency(long amount) { + if (amount < 1000) return "" + amount; + StringBuilder sb = new StringBuilder(); + String str = "" + amount; + int count = 0; + for (int i = str.length() - 1; i >= 0; i--) { + if (count > 0 && count % 3 == 0) sb.insert(0, ','); + sb.insert(0, str.charAt(i)); + count++; + } + return sb.toString(); + } + + /** + * Format currency amount with commas and append currency name. + * (e.g., 1000 -> "1,000 Gold") + */ + public static String formatCurrencyWithName(long amount) { + return formatCurrency(amount) + " " + AuctionClientConfig.getCurrencyName(); + } + + /** + * Format time remaining as a compact string (e.g., "2d 5h 30m"). + * Uses localized "Ended" text when time is <= 0. + */ + public static String formatTimeRemaining(long ms) { + if (ms <= 0) return StatCollector.translateToLocal("auction.ended"); + + long seconds = (ms / MS_PER_SECOND) % 60; + long minutes = (ms / MS_PER_MINUTE) % 60; + long hours = (ms / MS_PER_HOUR) % 24; + long days = ms / MS_PER_DAY; + + StringBuilder sb = new StringBuilder(); + if (days > 0) sb.append(days).append("d "); + if (hours > 0 || days > 0) sb.append(hours).append("h "); + if (minutes > 0 || hours > 0 || days > 0) sb.append(minutes).append("m"); + else sb.append(seconds).append("s"); + return sb.toString(); + } + + /** + * Check if time remaining is urgent (less than 1 hour). + */ + public static boolean isTimeUrgent(long ms) { + return ms > 0 && ms < MS_PER_HOUR; + } +} diff --git a/src/main/java/noppes/npcs/util/MathUtil.java b/src/main/java/noppes/npcs/util/MathUtil.java new file mode 100644 index 000000000..cfaec4e2a --- /dev/null +++ b/src/main/java/noppes/npcs/util/MathUtil.java @@ -0,0 +1,24 @@ +package noppes.npcs.util; + +import net.minecraft.util.Vec3; + +public class MathUtil { + + public static float getYaw(Vec3 vector) { + double x = vector.xCoord; + double z = vector.zCoord; + double yawRad = Math.atan2(z, x); + + return 90F - (float) Math.toDegrees(yawRad); + } + + public static float getPitch(Vec3 vector) { + double x = vector.xCoord; + double y = vector.yCoord; + double z = vector.zCoord; + double horizontalMag = Math.sqrt(x * x + z * z); + double pitchRad = Math.atan2(y, horizontalMag); + + return (float) -Math.toDegrees(pitchRad); + } +} diff --git a/src/main/java/somehussar/gui/AnnotatedGui.java b/src/main/java/somehussar/gui/AnnotatedGui.java index 8cdf224d5..7a1244f89 100644 --- a/src/main/java/somehussar/gui/AnnotatedGui.java +++ b/src/main/java/somehussar/gui/AnnotatedGui.java @@ -33,7 +33,7 @@ public class AnnotatedGui extends SubGuiInterface { int i = 0; for (EditableField field : metadata.getParent().getDeclaredFields()) { - addLabel(new GuiNpcLabel(i++, field.getName(), guiLeft+8, guiTop+i*15+5)); + addLabel(new GuiNpcLabel(i++, field.getName(), guiLeft + 8, guiTop + i * 15 + 5)); } } diff --git a/src/main/java/somehussar/gui/ImmediateTextField.java b/src/main/java/somehussar/gui/ImmediateTextField.java index 5f49a9d84..fba3c5a4d 100644 --- a/src/main/java/somehussar/gui/ImmediateTextField.java +++ b/src/main/java/somehussar/gui/ImmediateTextField.java @@ -5,7 +5,7 @@ import net.minecraft.client.gui.FontRenderer; import noppes.npcs.client.gui.util.GuiNpcTextField; import somehussar.gui.annotationHandling.field.EditableField; -public class ImmediateTextField extends GuiNpcTextField{ +public class ImmediateTextField extends GuiNpcTextField { private final EditableField editableField; // // private final GuiNpcTextField encapsulatedField; @@ -13,6 +13,7 @@ public class ImmediateTextField extends GuiNpcTextField{ public ImmediateTextField(int id, EditableField field, int xPos, int yPos) { this(id, field, Minecraft.getMinecraft().fontRenderer, xPos, yPos); } + public ImmediateTextField(int id, EditableField field, FontRenderer fontRenderer, int xPos, int yPos) { super(id, null, fontRenderer, xPos, yPos, 0, 0, null); diff --git a/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java b/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java index 596f3ab2f..95a74658e 100644 --- a/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java +++ b/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java @@ -27,6 +27,7 @@ public @interface GuiEditable { @Retention(RetentionPolicy.RUNTIME) @interface Size { int labelWidth() default 60; + int fieldWidth() default 50; GuiEditable.Size DEFAULT_SIZE = new GuiEditable.Size() { @@ -39,7 +40,11 @@ public @interface GuiEditable { public int fieldWidth() { return 50; } - @Override public Class annotationType() { return GuiEditable.Size.class; } + + @Override + public Class annotationType() { + return GuiEditable.Size.class; + } }; } diff --git a/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java b/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java index c6b7f3625..b54e70e52 100644 --- a/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java +++ b/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java @@ -26,7 +26,8 @@ public final class GuiFieldHandler { } - private GuiFieldHandler() {} + private GuiFieldHandler() { + } public static ClassMetadata getMetadata(Class type) { return CACHE.computeIfAbsent(type, GuiFieldHandler::scanClass); @@ -69,7 +70,8 @@ public final class GuiFieldHandler { if (Modifier.isFinal(field.getModifiers())) return null; GuiEditable.Size size = field.getAnnotation(GuiEditable.Size.class); - if (size == null) size = GuiEditable.Size.DEFAULT_SIZE;; + if (size == null) size = GuiEditable.Size.DEFAULT_SIZE; + ; field.setAccessible(true); EditableField.Builder builder = new EditableField.Builder() diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java index 3b9268a30..faccc6418 100644 --- a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java @@ -9,5 +9,6 @@ import java.lang.annotation.Target; @Target(ElementType.FIELD) public @interface NumericConstraint { double min() default Double.NEGATIVE_INFINITY; + double max() default Double.POSITIVE_INFINITY; } diff --git a/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java b/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java index 73172ef42..97e8500f1 100644 --- a/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java +++ b/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java @@ -46,7 +46,9 @@ public final class EditableField { return this.constraints; } - public int getOrder() { return this.order; } + public int getOrder() { + return this.order; + } EditableField(Builder b) { this.name = b.name; @@ -69,14 +71,45 @@ public final class EditableField { private String group = null; private GuiEditable.Size size; - public Builder name(String v) { this.name = v; return this; } - public Builder type(Class v) { this.type = v; return this; } - public Builder getter(MethodHandle v) { this.getter = v; return this; } - public Builder setter(MethodHandle v) { this.setter = v; return this; } - public Builder constraints(FieldConstraints v) { this.constraints = v; return this; } - public Builder order(int order) { this.order = order; return this; } - public Builder group(String value) { this.group = value; return this; } - public Builder size(GuiEditable.Size size) { this.size = size; return this; } + public Builder name(String v) { + this.name = v; + return this; + } + + public Builder type(Class v) { + this.type = v; + return this; + } + + public Builder getter(MethodHandle v) { + this.getter = v; + return this; + } + + public Builder setter(MethodHandle v) { + this.setter = v; + return this; + } + + public Builder constraints(FieldConstraints v) { + this.constraints = v; + return this; + } + + public Builder order(int order) { + this.order = order; + return this; + } + + public Builder group(String value) { + this.group = value; + return this; + } + + public Builder size(GuiEditable.Size size) { + this.size = size; + return this; + } public EditableField build() { return new EditableField<>(this); diff --git a/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java b/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java index e52742812..8c3fcde4c 100644 --- a/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java +++ b/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java @@ -4,6 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import noppes.npcs.CustomItems; +import noppes.npcs.client.gui.player.inventory.GuiAbilities; import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory; import noppes.npcs.client.gui.player.inventory.GuiFaction; import noppes.npcs.client.gui.player.inventory.GuiParty; @@ -58,5 +59,8 @@ public class InventoryTabCustomNpc extends AbstractTab { if (tab == -104) { mc.displayGuiScreen(new GuiProfiles()); } + if (tab == -105) { + mc.displayGuiScreen(new GuiAbilities()); + } } } diff --git a/src/main/resources/META-INF/customnpcs_at.cfg b/src/main/resources/META-INF/customnpcs_at.cfg index dbcb46481..a41eb23c9 100644 --- a/src/main/resources/META-INF/customnpcs_at.cfg +++ b/src/main/resources/META-INF/customnpcs_at.cfg @@ -18,6 +18,8 @@ public net.minecraft.client.renderer.entity.RenderPlayer func_77043_a(Lnet/minec #EntityLivingBase public net.minecraft.entity.EntityLivingBase func_82166_i()I # getArmSwingAnimationEnd public net.minecraft.entity.EntityLivingBase field_70703_bu # isJumping +#EntityLiving +public net.minecraft.entity.EntityLiving field_82179_bU # persistenceRequired # Minecraft public net.minecraft.client.Minecraft field_147126_aw # mcMusicTicker # MusicTicker diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json deleted file mode 100644 index 15d49bce6..000000000 --- a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json +++ /dev/null @@ -1,1274 +0,0 @@ -{ - "Loop": -1, - "Speed": 1.0f, - "Frames": [ - { - "ColorMarker": 16777215, - "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", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "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", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -37.0f, - "Rotation0": -37.0f, - "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, - "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 - }, - { - "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": 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", - "Rotation1": -25.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "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", - "Rotation1": -25.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 4.0f, - "Part": "LEFT_ARM", - "Rotation1": -63.0f, - "Rotation0": -31.0f, - "Pivot0": -2.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 2 - } - ], - "CurrentFrameTime": 0, - "CurrentFrame": 19, - "Smooth": 0b, - "ID": 15, - "WhileAttacking": 1b, - "WhileWalking": 1b, - "Name": "Ability_HeavyHit_Windup", - "WhileStanding": 1b -} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_BeamDual_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_BeamDual_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_BeamDual_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_BeamDual_Windup.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Beam_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Beam_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Beam_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Beam_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Beam_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Beam_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Beam_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Beam_Windup.json diff --git a/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Charge_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Charge_Active.json new file mode 100644 index 000000000..82b2294ca --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_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/cnpc_animations/Ability_Charge_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Charge_Windup.json new file mode 100644 index 000000000..c627007e3 --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_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_Cutter_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Cutter_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Cutter_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Cutter_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Cutter_Windup.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_DiscDual_Active.json similarity index 65% rename from src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json rename to src/main/resources/assets/customnpcs/cnpc_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/cnpc_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/cnpc_animations/Ability_DiscDual_Windup.json similarity index 99% rename from src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_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/cnpc_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_Disc_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Disc_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Disc_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Disc_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Disc_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Disc_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Disc_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Disc_Windup.json diff --git a/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Generic_Dazed.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Generic_Dazed.json new file mode 100644 index 000000000..38e42bd1e --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_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_Guard_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Guard_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Guard_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Guard_Counter.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Guard_Counter.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_HeavyHit_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_HeavyHit_Active.json diff --git a/src/main/resources/assets/customnpcs/cnpc_animations/Ability_HeavyHit_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_HeavyHit_Windup.json new file mode 100644 index 000000000..a276742ba --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_HeavyHit_Windup.json @@ -0,0 +1,203 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.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": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -37.0f, + "Rotation0": -37.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 31.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.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, + "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 + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 15 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": -25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -63.0f, + "Rotation0": -31.0f, + "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, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 1, + "Smooth": 0b, + "ID": 15, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_HeavyHit_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Laser_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Laser_Active.json new file mode 100644 index 000000000..f3117602a --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Laser_Active.json @@ -0,0 +1,203 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -82.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": 2.0f, + "Rotation0": -88.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 86.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -82.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -92.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 94.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -82.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": -2.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 80.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 3, + "Smooth": 0b, + "ID": 10, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Laser_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Laser_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Laser_Windup.json similarity index 71% rename from src/main/resources/assets/customnpcs/animations/Ability_Laser_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Laser_Windup.json index 5cb4fc3be..c12700304 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Laser_Active.json +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Laser_Windup.json @@ -1,5 +1,5 @@ { - "Loop": 0, + "Loop": -1, "Speed": 1.0f, "Frames": [ { @@ -11,67 +11,67 @@ "Pivot2": 0.0f, "Part": "LEFT_LEG", "Rotation1": 0.0f, - "Rotation0": 0.0f, + "Rotation0": 12.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": -18.0f }, { - "Pivot2": 5.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": -25.0f, + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -82.0f, "Pivot0": 0.0f, - "Pivot1": 2.0f, + "Pivot1": 0.0f, "Rotation2": 0.0f }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", "Rotation1": 0.0f, - "Rotation0": 0.0f, + "Rotation0": 12.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 18.0f }, { - "Pivot2": 2.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": -195.0f, - "Pivot0": -1.0f, - "Pivot1": -1.0f, - "Rotation2": -56.0f - }, - { - "Pivot2": 4.0f, + "Pivot2": 0.0f, "Part": "RIGHT_ARM", - "Rotation1": 90.0f, + "Rotation1": 0.0f, "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": -1.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, "Rotation2": 90.0f }, { - "Pivot2": 5.0f, + "Pivot2": 3.0f, "Part": "HEAD", "Rotation1": 0.0f, - "Rotation0": -37.0f, + "Rotation0": 0.0f, "Pivot0": 0.0f, - "Pivot1": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, "Rotation2": 0.0f } ], "Smooth": 0b, - "Duration": 3 + "Duration": 15 } ], "CurrentFrameTime": 0, - "CurrentFrame": 3, + "CurrentFrame": 4, "Smooth": 0b, - "ID": 10, + "ID": 12, "WhileAttacking": 1b, "WhileWalking": 1b, - "Name": "Ability_Laser_Active", + "Name": "Ability_Laser_Windup", "WhileStanding": 1b } diff --git a/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbBarrage_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbBarrage_Active.json new file mode 100644 index 000000000..e34dd5d21 --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbBarrage_Active.json @@ -0,0 +1,203 @@ +{ + "Loop": 2, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "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": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.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 + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "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": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 25.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 25.0f + }, + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.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 + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "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": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.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 + } + ], + "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/cnpc_animations/Ability_OrbBarrage_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbBarrage_Windup.json new file mode 100644 index 000000000..dfe8f601b --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_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_OrbDual_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbDual_Active.json similarity index 99% rename from src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbDual_Active.json index 58a305e78..c632afc9c 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbDual_Active.json @@ -1,5 +1,5 @@ { - "Loop": 3, + "Loop": -1, "Speed": 1.0f, "Frames": [ { @@ -252,7 +252,7 @@ } ], "Smooth": 0b, - "Duration": 3 + "Duration": 20 } ], "CurrentFrameTime": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbDual_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_OrbDual_Windup.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Orb_Active.json similarity index 96% rename from src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Orb_Active.json index 994e2190c..cb8973971 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Orb_Active.json @@ -1,11 +1,11 @@ { - "Loop": 0, + "Loop": -1, "Speed": 1.0f, "Frames": [ { "ColorMarker": 16777215, "Comment": "", - "Speed": 0.5f, + "Speed": 1.0f, "FrameParts": [ { "Pivot2": 0.0f, @@ -63,7 +63,7 @@ } ], "Smooth": 0b, - "Duration": 30 + "Duration": 20 } ], "CurrentFrameTime": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Orb_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Orb_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Orb_Windup.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Shockwave_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Shockwave_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Shockwave_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Shockwave_Windup.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Slam_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Slam_Active.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Slam_Active.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Slam_Active.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Slam_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Slam_Windup.json similarity index 100% rename from src/main/resources/assets/customnpcs/animations/Ability_Slam_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Slam_Windup.json diff --git a/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Zone_Active.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Zone_Active.json new file mode 100644 index 000000000..747f73860 --- /dev/null +++ b/src/main/resources/assets/customnpcs/cnpc_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_Laser_Windup.json b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Zone_Windup.json similarity index 56% rename from src/main/resources/assets/customnpcs/animations/Ability_Laser_Windup.json rename to src/main/resources/assets/customnpcs/cnpc_animations/Ability_Zone_Windup.json index c445faca9..40a6abef7 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Laser_Windup.json +++ b/src/main/resources/assets/customnpcs/cnpc_animations/Ability_Zone_Windup.json @@ -5,312 +5,375 @@ { "ColorMarker": 16777215, "Comment": "", - "Speed": 3.0f, + "Speed": 2.0f, "FrameParts": [ { - "Pivot2": 3.0f, - "Part": "HEAD", + "Pivot2": -3.0f, + "Part": "BODY", "Rotation1": 0.0f, - "Rotation0": 0.0f, + "Rotation0": 12.0f, "Pivot0": 0.0f, - "Pivot1": 1.0f, + "Pivot1": 0.0f, "Rotation2": 0.0f }, { "Pivot2": 0.0f, "Part": "LEFT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, + "Rotation1": 12.0f, + "Rotation0": 6.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, - "Rotation2": -18.0f + "Rotation2": -6.0f }, { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": 0.0f, + "Pivot2": -3.0f, "Part": "LEFT_ARM", - "Rotation1": 50.0f, - "Rotation0": -82.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 1.0f, - "Pivot1": 2.0f, - "Rotation2": 90.0f - }, - { - "Pivot2": 3.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 3 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 50.0f, - "Rotation0": -82.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_ARM", - "Rotation1": 2.0f, - "Rotation0": -88.0f, - "Pivot0": 1.0f, - "Pivot1": 2.0f, - "Rotation2": 86.0f - }, - { - "Pivot2": 3.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 3 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 50.0f, - "Rotation0": -82.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -92.0f, - "Pivot0": 1.0f, - "Pivot1": 2.0f, - "Rotation2": 94.0f - }, - { - "Pivot2": 3.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 3 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": 0.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 50.0f, - "Rotation0": -82.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_ARM", - "Rotation1": -2.0f, - "Rotation0": -90.0f, - "Pivot0": 1.0f, - "Pivot1": 2.0f, - "Rotation2": 80.0f - }, - { - "Pivot2": 3.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 3 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": 5.0f, - "Part": "HEAD", - "Rotation1": 0.0f, + "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": 2.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": 0.0f, - "Rotation0": 0.0f, + "Rotation1": 18.0f, + "Rotation0": 6.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, - "Rotation2": -18.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": 0.0f, - "Rotation0": 0.0f, + "Rotation1": -18.0f, + "Rotation0": 6.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": 2.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": -195.0f, - "Pivot0": -1.0f, - "Pivot1": -1.0f, - "Rotation2": -56.0f + "Rotation2": 12.0f }, { "Pivot2": 4.0f, "Part": "RIGHT_ARM", - "Rotation1": 90.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": -1.0f, - "Rotation2": 90.0f - }, + "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": 5.0f, + "Pivot2": 3.0f, "Part": "BODY", "Rotation1": 0.0f, - "Rotation0": -25.0f, + "Rotation0": -18.0f, "Pivot0": 0.0f, - "Pivot1": 2.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 } ], @@ -319,11 +382,11 @@ } ], "CurrentFrameTime": 0, - "CurrentFrame": 3, + "CurrentFrame": 5, "Smooth": 0b, - "ID": 12, + "ID": 23, "WhileAttacking": 1b, "WhileWalking": 1b, - "Name": "Ability_Laser_Windup", + "Name": "Ability_Zone_Windup", "WhileStanding": 1b } diff --git a/src/main/resources/assets/customnpcs/colorscheme/script_editor_scheme.json b/src/main/resources/assets/customnpcs/colorscheme/script_editor_scheme.json new file mode 100644 index 000000000..6a0da80b8 --- /dev/null +++ b/src/main/resources/assets/customnpcs/colorscheme/script_editor_scheme.json @@ -0,0 +1,128 @@ +{ + "background": { + "backgroundColor": "#FF000000", + "gutterColor": "#FF000000", + "gutterSeparatorColor": "#FF3C3F41", + "lineNumberColor": "#FF606366", + "lineNumberActiveColor": "#FFB9C7D6", + "scrollbarColor": "#FFE0E0E0", + "borderColor": "#FFA0A0A0", + "caretColor": "#FFFFFFFF" + + }, + "COMMENT": { + "color": "#FF777777", + "bold": false, + "italic": false + }, + "STRING": { + "color": "#FF16c57d", + "bold": false, + "italic": false + }, + "JSDOC_TAG": { + "color": "#FF8E8070", + "bold": true, + "italic": false + }, + "JSDOC_TYPE": { + "color": "#FF9A8C7C", + "bold": false, + "italic": false + }, + "UNUSED_IMPORT": { + "color": "#FF666666", + "bold": false, + "italic": false + }, + "KEYWORD": { + "color": "#FFFF5555", + "bold": false, + "italic": false + }, + "INTERFACE_DECL": { + "color": "#FF80F2F6", + "bold": false, + "italic": false + }, + "ENUM_DECL": { + "color": "#FFFF55FF", + "bold": false, + "italic": false + }, + "ENUM_CONSTANT": { + "color": "#FF55FFFF", + "bold": true, + "italic": true + }, + "CLASS_DECL": { + "color": "#FF00AAAA", + "bold": false, + "italic": false + }, + "IMPORTED_CLASS": { + "color": "#FF00AAAA", + "bold": false, + "italic": false + }, + "GENERIC_TYPE_PARAM": { + "color": "#FF00FA9A", + "bold": false, + "italic": false + }, + "TYPE_DECL": { + "color": "#FF00AAAA", + "bold": false, + "italic": false + }, + "METHOD_DECL": { + "color": "#FF00AA00", + "bold": false, + "italic": false + }, + "METHOD_CALL": { + "color": "#FF55FF55", + "bold": false, + "italic": false + }, + "UNDEFINED_VAR": { + "color": "#FFAA0000", + "bold": false, + "italic": false + }, + "PARAMETER": { + "color": "#FF5555FF", + "bold": false, + "italic": false + }, + "GLOBAL_FIELD": { + "color": "#FF55FFFF", + "bold": false, + "italic": false + }, + "LOCAL_FIELD": { + "color": "#FFFFFF55", + "bold": false, + "italic": false + }, + "STATIC_FINAL_FIELD": { + "color": "#FF8DDAF8", + "bold": true, + "italic": true + }, + "LITERAL": { + "color": "#FF79C0FF", + "bold": false, + "italic": false + }, + "VARIABLE": { + "color": "#FFFFFFFF", + "bold": false, + "italic": false + }, + "DEFAULT": { + "color": "#FFFFFFFF", + "bold": false, + "italic": false + } +} diff --git a/src/main/resources/assets/customnpcs/lang/de_DE.lang b/src/main/resources/assets/customnpcs/lang/de_DE.lang index 32170875b..3ae606484 100644 --- a/src/main/resources/assets/customnpcs/lang/de_DE.lang +++ b/src/main/resources/assets/customnpcs/lang/de_DE.lang @@ -432,6 +432,7 @@ script.interact=interagieren script.update=Update script.console=Konsole script.language=Sprache +script.default=Standard script.damaged=Schaden script.killed=Sterben script.attack=Angriff diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 3bc0fa119..3f46be5a3 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2,6 +2,9 @@ customnpcs.defaultTextColor=404040 key.categories.customnpc=CustomNPC+ key.customnpcs.special=Special Key +key.customnpcs.abilityHudKey=HUD Key +key.customnpcs.abilityNext=Ability Next +key.customnpcs.abilityPrev=Ability Previous key.npcInventory=NPC Inventory entity.CustomNpc.name=Custom Npc @@ -122,6 +125,7 @@ gui.copy=Copy gui.clear=Clear gui.builtin=Built-in gui.custom=Custom +gui.chained=Chained gui.builtinAnimations=Built-in Animations gui.customAnimations=Custom Animations gui.done=Done @@ -153,6 +157,9 @@ gui.deselectAll=Deselect All gui.loading=Loading gui.off=Off gui.on=On +gui.fullscreen=FULL +gui.fullscreen.tooltip=Designed for Fullscreen Mode +gui.addCategory=Add Category gui.sure=Are you sure? gui.available=Requirements Met gui.items=Items @@ -165,7 +172,14 @@ gui.unused=Unused gui.apply=Apply gui.cancel=Cancel gui.continue=Continue +gui.back=Back gui.yes=Yes +gui.abilities=Abilities +gui.toggles=Toggles +gui.toggle=Toggle +gui.toggle.active=Active +gui.toggle.inactive=Inactive +gui.abilityHotbar=Ability Hotbar gui.lineColor1=Upper line color gui.lineColor2=Middle line color @@ -173,6 +187,10 @@ gui.lineColor3=Lower line color gui.slotColour=Slots color gui.buttonAcceptColour=Accept button color gui.buttonRejectColour=Reject button color +gui.animated=Animated +gui.animated.hover=Textures with a .mcmeta file animate automatically.\nEnable this for manual animation of sprite sheet textures. +gui.frameCount=Frame Count +gui.frameTime=Frame Time questgui.doyouaccept=Do you accept the quest? questgui.bringitems=Bring items questgui.readdialog=Read dialog @@ -233,7 +251,7 @@ party.partying=Partying! party.messageNoParty=You're not in a party! Either wait for an invite or create one. party.partyRequirements=Required by party.setQuestConfirm=Setting a Quest to a party will clear its progress! -party.dropQuestConfirm=Are you sure you want to drop the party quest?` +party.dropQuestConfirm=Are you sure you want to drop the party quest? settings.chatBubbles=Chat Bubbles settings.trackAlignment=Tracking Alignment @@ -416,7 +434,37 @@ spawning.liquidSpawning=Spawns in Liquid spawning.airSpawning=Spawns in Air spawning.minHeight=Minimum Height spawning.maxHeight=Maximum Height +spawning.maxAlive=Max Alive (0 = Unlimited) +spawning.cooldownTicks=Cooldown (Ticks) +spawning.attemptsPerCycle=Attempts Per Cycle +spawning.playerMinDistance=Min Player Distance +spawning.despawnMode=Despawn Mode +spawning.despawn.forceNatural=Force Natural +spawning.despawn.preserve=Preserve Template +spawning.despawn.forcePersistent=Force Persistent spawning.naturalInfo=Add at least one spawn entry and configure spawn options for the NPC to spawn naturally +spawning.naturalInfoPerformance=Natural Spawn Setup\nBest performance baseline:\n- maxAlive: 20-60\n- cooldownTicks: 200-600\n- attemptsPerCycle: 1-2\n- playerMinDistance: 32-48\n- despawnMode: Force Natural +tooltip.naturalspawns.main.addProfile=Create a new natural spawn profile.\nBest performance: Keep profile count focused by biome/theme. +tooltip.naturalspawns.main.removeProfile=Delete the selected natural spawn profile.\nBest performance: Remove unused profiles to reduce selection overhead. +tooltip.naturalspawns.main.search=Filter spawn profiles by name.\nTip: Use biome/type prefixes for faster maintenance. +tooltip.naturalspawns.main.biomes=Choose biomes this profile can spawn in.\nBest performance: Use only needed biomes. +tooltip.naturalspawns.main.dimensions=Choose dimensions this profile can spawn in.\nBest performance: Limit to required dimensions. +tooltip.naturalspawns.main.options=Open advanced spawn controls.\nBest performance: Configure cap, cooldown, attempts, and despawn mode. +tooltip.naturalspawns.main.addEntry=Add an entry slot to this profile.\nBest performance: Keep only active entries. +tooltip.naturalspawns.main.removeEntry=Remove selected entry slot.\nBest performance: Remove empty/duplicate entries. +tooltip.naturalspawns.main.slot=Entry slot index.\nTip: Keep numbering organized for easier debugging. +tooltip.naturalspawns.main.selectEntry=Select which clone/NPC this slot spawns.\nBest performance: Avoid very heavy scripted clones in high-frequency profiles. +tooltip.naturalspawns.options.animal=Spawn Rule: Animal\nUses animal-style spawn checks (surface + creature-valid blocks).\nUse for passive/overworld mobs.\nPerformance: Disable if not needed. +tooltip.naturalspawns.options.monster=Spawn Rule: Monster\nUses monster-style spawn checks (surface + monster-valid blocks).\nUse for hostile/night/cave mobs.\nPerformance: Disable if not needed. +tooltip.naturalspawns.options.liquid=Spawn Rule: Liquid\nAllows spawn validation in liquid/water spaces.\nUse only for aquatic entries.\nPerformance: Keep OFF unless required. +tooltip.naturalspawns.options.air=Spawn Rule: Air\nAllows spawn validation in open-air columns.\nUse only for flying/airborne entries.\nPerformance: Keep OFF unless required. +tooltip.naturalspawns.options.minHeight=Minimum Spawn Y\nLower vertical bound for this profile.\nUse with Max Height to narrow valid layers.\nPerformance: Tighter ranges = fewer failed checks. +tooltip.naturalspawns.options.maxHeight=Maximum Spawn Y\nUpper vertical bound for this profile.\nUse with Min Height to target a specific layer.\nPerformance: Tighter ranges = fewer failed checks. +tooltip.naturalspawns.options.maxAlive=Max Alive (Per Profile)\nCounts loaded entities tagged to this natural spawn profile.\n0 = Unlimited (not recommended).\nPerformance baseline: 20-60. +tooltip.naturalspawns.options.cooldownTicks=Cooldown (Ticks)\nWait time after a successful spawn before this profile can spawn again.\n20 ticks = 1 second.\nPerformance baseline: 200-600 (10-30 seconds). +tooltip.naturalspawns.options.attemptsPerCycle=Attempts Per Cycle\nHow many nearby positions this profile tests each cycle.\nHigher values increase spawn pressure and CPU checks.\nPerformance baseline: 1-2. +tooltip.naturalspawns.options.playerMinDistance=Min Player Distance\nBlocks from nearest player where spawning is blocked.\nHigher values reduce pop-in near players.\nPerformance baseline: 32-48. +tooltip.naturalspawns.options.despawnMode=Despawn Mode (CNPC entries)\nForce Natural: sets canDespawn=true on spawn. Recommended for natural ecosystems.\nPreserve Template: keeps clone/template despawn setting.\nForce Persistent: sets canDespawn=false (NPC stays loaded longer).\nPerformance recommendation: Force Natural. role.name=Role role.none=No Role @@ -482,9 +530,9 @@ stock.reset.never=Never stock.reset.mcdaily=MC Daily stock.reset.mcweekly=MC Weekly stock.reset.mccustom=MC Custom -stock.reset.rldaily=Real Daily -stock.reset.rlweekly=Real Weekly -stock.reset.rlcustom=Real Custom +stock.reset.rldaily=RL Daily +stock.reset.rlweekly=RL Weekly +stock.reset.rlcustom=RL Custom stock.options.hover=Configure stock limits and reset timers stock.enable.hover=Enable limited stock for trade slots @@ -533,7 +581,7 @@ stats.respawn=Respawn stats.deadbody=HideDeadBody stats.fireimmune=ImmuneToFire stats.candrown=Drowns -stats.firesound:=SoundFX +stats.firesound=SoundFX stats.creaturetype=CreatureType stats.normal=Normal stats.reverse=Reverse @@ -806,8 +854,7 @@ quest.tracking=Tracking quest.alerts=Alerts quest.noAlerts=No Alerts -script.apidoc=API Docs -script.apisrc=API Source +gui.api=API script.scripts=Scripts script.hooks=Hooks @@ -818,6 +865,7 @@ script.interact=Interact script.update=Update script.console=Console script.language=Language +script.default=Default script.damaged=Damaged script.killed=Killed script.attack=Attack @@ -1517,17 +1565,13 @@ ability.globalCooldown=Global Cooldown ability.minCooldown=Min CD ability.maxCooldown=Max CD ability.edit=Edit Ability -ability.weight=Weight ability.targeting=Targeting -ability.minRange=Min Range -ability.maxRange=Max Range ability.timing=Timing (ticks) ability.cooldown=Cooldown ability.windup=Wind Up ability.syncOn=Sync: On ability.syncOff=Sync: Off ability.dazed=Dazed Ticks -ability.interruptible=Interruptible ability.threshold=Threshold ability.lockMove=Lock Move ability.lockMove.windup=Windup @@ -1549,6 +1593,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 @@ -1557,15 +1602,69 @@ ability.sweep.spin=Spin # Dash Mode ability.dash.aggressive=Aggressive ability.dash.defensive=Defensive +ability.dash.directional=Directional + +# Dash Direction +ability.dash.forward=Forward +ability.dash.diagonalForwardLeft=Diagonal Forward Left +ability.dash.diagonalForwardRight=Diagonal Forward Right +ability.dash.left=Left +ability.dash.right=Right +ability.dash.diagonalBackLeft=Diagonal Back Left +ability.dash.diagonalBackRight=Diagonal Back Right +ability.dash.back=Back +ability.dash.custom=Custom # Counter Type 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.ignoreIFrames=Ignore I-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 @@ -1588,21 +1687,25 @@ telegraph.ring=Ring telegraph.line=Line telegraph.cone=Cone telegraph.point=Point +telegraph.square=Square +telegraph.none=None ability.tab.timing=Timing ability.tab.effects=Effects ability.tab.telegraph=Telegraph ability.tab.visual=Visual -ability.showTelegraph=Show Telegraph ability.telegraphColor=Color ability.telegraphSizeNote=Size is based on ability parameters # Ability Effects Tab -ability.windUpSound=Wind Up Sound -ability.activeSound=Active Sound -ability.windUpAnim=Wind Up Anim -ability.activeAnim=Active Anim +ability.cnpc.custom=Custom +ability.telegraphShape=Telegraph Shape +ability.toggleEnabled=Toggle +ability.toggleStates=Toggle States +ability.hasActiveToggle=Active Toggle Tick +ability.section.toggle=Toggle +ability.section.execution=Execution ability.cnpc.slam=Slam ability.cnpc.heavy_hit=Heavy Hit ability.cnpc.cutter=Cutter @@ -1615,11 +1718,13 @@ ability.cnpc.teleport=Teleport ability.cnpc.vortex=Vortex ability.cnpc.shockwave=Shockwave ability.cnpc.guard=Guard -ability.cnpc.heal=Heal +ability.cnpc.counter=Counter +ability.cnpc.dodge=Dodge +ability.cnpc.effect=Effect ability.cnpc.hazard=Hazard ability.cnpc.trap=Trap ability.cnpc.disc=Disc -ability.cnpc.laser_shot=Laser Shot +ability.cnpc.laser_shot=Laser ability.cnpc.sweeper=Sweeper # ═══════════════════════════════════════════════════════════════ @@ -1630,6 +1735,12 @@ ability.cnpc.sweeper=Sweeper ability.weight=Weight ability.windUpTicks=Wind Up ability.cooldownTicks=Cooldown +ability.perAbilityCooldown=Per-Ability +ability.ignoreCooldown=Ignore Cooldown +ability.freeOnCast=Free on Cast +ability.hover.freeOnCast=Ability enters cooldown immediately after entities are spawned, allowing the caster to use other abilities while summoned entities remain active +ability.freeAim=Free Aim +ability.hover.freeAim=Players Only. Allows the player to steer the beam direction with their mouse during the active phase. Requires: Lock Movement set to Active or Both, Rotation Mode set to Free, Free on Cast disabled. ability.lockMovement=Lock Movement ability.rotationMode=Rotation ability.rotationPhase=Phase @@ -1645,22 +1756,42 @@ ability.minRange=Min Range ability.maxRange=Max Range ability.conditions=Conditions +# Chained Ability +ability.select=Select Ability +ability.entries=Entries +ability.delay=Delay +ability.windUpAll=Wind Up All +ability.allowedBy=Allowed By + # Effects Tab ability.windUpSound=Wind Up Sound ability.activeSound=Active Sound ability.counterSound=Counter Sound ability.windUpAnimation=Wind Up Animation ability.activeAnimation=Active Animation +ability.dazedAnimation=Dazed Animation ability.counterAnimation=Counter Animation +ability.dodgeAnimation1=Dodge Animation 1 +ability.dodgeAnimation2=Dodge Animation 2 +ability.dodgeAnimation3=Dodge Animation 3 ability.showTelegraph=Show Telegraph ability.windUpColor=Wind Up Color ability.activeColor=Active Color +ability.telegraphHeight=Height Offset +ability.telegraphRadius=Radius +ability.telegraphInnerRadius=Inner Radius +ability.telegraphLength=Length +ability.telegraphWidth=Width +ability.telegraphAngle=Angle +ability.telegraphActiveTicks=Active Ticks +ability.syncTelegraph=Sync Duration # Section Headers 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 @@ -1673,6 +1804,14 @@ ability.section.explosive=Explosive ability.section.colors=Colors ability.section.effects=Effects ability.section.burst=Burst +ability.section.magic=Magic +ability.magic.note=Magic Note +ability.magic.usesCaster=Uses the Caster's Magic Data +ability.magic.editor=Magic Editor +ability.preview.damage=Damage +ability.preview.health=Health +ability.preview.magic.casters=Magic: Caster's +ability.section.dodgeAnimations=Dodge Animations ability.section.visual=Visual ability.section.projectile1=Projectile 1 ability.section.projectile2=Projectile 2 @@ -1697,7 +1836,6 @@ gui.radius=Radius gui.thickness=Thickness gui.rotationSpeed=Rotation Speed gui.strength=Strength -gui.range=Range gui.delay=Delay gui.density=Density gui.length=Length @@ -1710,24 +1848,47 @@ 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 ability.knockback=Knockback ability.knockbackUp=Knockback Up +ability.hitType=Hit Type +ability.hitType.single=Single +ability.hitType.pierce=Pierce +ability.hitType.multi=Multi +ability.multiHitDelay=Multi-Hit Delay +ability.maxHits=Max Hits ability.distance=Distance ability.maxDistance=Max Distance +ability.maxLength=Max Length ability.lifetime=Lifetime 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.launchFromAnchor=Launch From Anchor +ability.hover.launchFromAnchor=When enabled, the projectile launches from its anchor position instead of snapping to the default eye/look-vector position. ability.vertical=Vertical ability.rotationSpeed=Rotation Speed @@ -1745,6 +1906,10 @@ ability.innerRadius=Inner Radius # Projectile ability.projectileType=Projectile Type +# Heavy Hit +ability.hitDelayTicks=Hit Delay +ability.activeDisplayTicks=End Delay + # Orb Settings ability.homing=Homing ability.explosive=Explosive @@ -1757,8 +1922,10 @@ ability.chargeSpeed=Charge Speed # Dash ability.dashMode=Dash Mode -ability.dashDistance=Dash Distance -ability.dashSpeed=Dash Speed +ability.dashDistance=Distance +ability.dashDirection=Direction +ability.dashSpeed=Speed +ability.dashAngle=Angle # Teleport ability.blinkRadius=Blink Radius @@ -1777,22 +1944,34 @@ ability.maxTargets=Max Targets # Shockwave ability.pushStrength=Push Strength -# Guard +# Defend (Guard / Counter / Dodge) +ability.maxHitAmount=Max Hit Amount ability.damageReduction=Damage Reduction -ability.counterWindow=Counter Ticks -# Heal -ability.instantHeal=Instant Heal +# Effect +ability.instantHeal=Instant ability.healAmount=Heal Amount ability.healPercent=Heal Percent -ability.healRadius=Heal Radius -ability.healSelf=Heal Self -ability.healAllies=Heal Allies +ability.targetFilter=Target Filter +ability.targetFilter.allies=Allies +ability.targetFilter.enemies=Enemies +ability.targetFilter.all=All +ability.includeSelf=Include Self +ability.section.targeting=Targeting +ability.concurrent=Concurrent +ability.customScriptInfo=This ability is for scripting purposes +ability.concurrentInfo=This ability allows Concurrency in Chains +ability.hover.concurrent=When enabled, this ability fires at the same time as the ability above it in the chain +ability.customEffects=Custom Effects +ability.effectActions=Effect Actions +ability.noCustomEffects=No custom effects defined +ability.variant.selfHeal=Self Heal +ability.variant.healingAura=Healing Aura +ability.variant.poisonDebuff=Poison Debuff # Hazard ability.shape=Shape ability.placement=Placement -ability.damagePerSecond=Damage/Sec ability.damageInterval=Damage Interval ability.slownessLevel=Slowness Level ability.debuffDuration=Debuff Duration @@ -1801,8 +1980,6 @@ ability.affectsCaster=Affects Caster # Trap ability.armTime=Arm Time -ability.maxTriggers=Max Triggers -ability.triggerCooldown=Trigger Cooldown # Sweeper ability.sweepSpeed=Sweep Speed @@ -1825,12 +2002,10 @@ ability.outerEnabled=Outer Glow ability.outerWidth=Outer Width ability.outerAlpha=Outer Alpha ability.lightning=Lightning -ability.lightningDensity=Density ability.lightningRadius=Radius # Projectile Count / Settings ability.projectileCount=Count -ability.dualFireDelay=Fire Delay ability.fireDelay=Fire Delay ability.colorOverride=Color Override @@ -1847,6 +2022,12 @@ ability.hover.burstReplay=Replay windup and active animations for each burst ite ability.save.confirm=Save ability preset ability.save.overwrite=Overwrite existing preset ability.duplicate.name=A preset with this name already exists +ability.invulnerable=Invulnerable +ability.invulnerable.none=None +ability.invulnerable.windup=Windup +ability.invulnerable.active=Active +ability.invulnerable.both=Both +ability.hover.invulnerable=Ignores all incoming damage and hit reactions during selected phases. Windup/Both also disable interrupts. ability.load.select=Select ability to load: ability.load.mode=How should this ability be loaded? ability.clone=Clone @@ -1861,6 +2042,7 @@ 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 @@ -1889,7 +2071,10 @@ ability.hover.weight=Higher weight = more likely to be chosen when multiple abil 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.trackSpeed=Track Speed +ability.hover.trackSpeed=Tracking speed in blocks/sec. 0 = instant. Sprint speed is ~5.6. Default 4 for lasers (dodgeable while sprinting). ability.hover.interruptible=If enabled, ability can be interrupted by taking damage +ability.hover.ignoreIFrames=Temporarily clears target hurt resistance before applying ability damage, then restores it. 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) ability.hover.cooldown=Time before ability can be used again (20 ticks = 1 second) @@ -1903,8 +2088,13 @@ ability.hover.windUpColor=Color of telegraph during charge-up phase ability.hover.activeColor=Color of telegraph when ability is active ability.hover.homing=Projectile tracks toward target ability.hover.homingStr=How aggressively the projectile tracks (higher = tighter turns) +ability.hover.hitType=Single: stops on first hit. Pierce: can hit each entity once. Multi: can re-hit entities using the delay below. Pierce/Multi both respect Max Hits. +ability.hover.multiHitDelay=Ticks between repeat hits on the same entity when Hit Type is Multi (20 ticks = 1 second) +ability.hover.maxHits=Maximum total hits before projectile ends in Pierce/Multi modes. Lower values reduce repeated hit spam and improve performance. ability.hover.explosive=Creates explosion on impact ability.hover.explosionRad=Size of explosion radius +ability.hover.maxHitAmount=Maximum hits absorbed before defend ability ends (0 = unlimited) +ability.hover.counterType=Flat: fixed damage counter-attack. Percent: counter-attack deals a percentage of the absorbed damage. 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 @@ -1916,7 +2106,7 @@ ability.hover.speed=Movement speed of projectile ability.hover.lifetime=Maximum ticks before despawning ability.hover.knockback=Push force applied to targets ability.hover.boomerang=Projectile returns to caster after reaching max distance -ability.hover.dashMode=Aggressive dashes toward target, Defensive dashes away +ability.hover.dashMode=Aggressive dashes toward target, Defensive dashes away, Directional dashes in looking direction ability.hover.aoe=Affects all valid targets in range instead of just one ability.hover.dmgOnPull=Deal damage continuously while pulling targets ability.hover.lineOfSight=Requires clear line of sight to the target @@ -1929,20 +2119,142 @@ 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 +ability.hover.innerRadius=Minimum distance from caster. Entities closer than this are not hit. Creates a donut-shaped dead zone. Also shown on the telegraph. +ability.hover.telegraphShape=Shape of the telegraph warning indicator. Different shapes use different size parameters. +ability.hover.telegraphHeight=Vertical offset from the ground for telegraph rendering +ability.hover.telegraphRadius=Radius of the telegraph shape (used by Circle, Ring, Square) +ability.hover.telegraphInnerRadius=Inner radius creating a hollow center. Used by Ring (donut) and Cone (truncated wedge). +ability.hover.telegraphLength=Forward distance of the telegraph shape (used by Line, Cone) +ability.hover.telegraphWidth=Side-to-side width of the telegraph (used by Line) +ability.hover.telegraphAngle=Spread angle in degrees (used by Cone) +ability.hover.telegraphActiveTicks=How long the telegraph stays visible during the active phase (20 ticks = 1 second). Set to 0 for windup-only telegraph. +ability.hover.syncTelegraph=When enabled, telegraph active duration automatically matches the ability duration +ability.hover.launching=When enabled, wall launches forward dealing damage and knockback + +# Energy Barrier Abilities +ability.cnpc.dome=Dome +ability.cnpc.wall=Wall +ability.cnpc.shield=Shield +ability.cnpc.slicer=Slicer + +ability.section.barrier=Barrier +ability.section.properties=Properties +ability.section.panel=Panel +ability.section.launch=Launch +ability.section.slicer=Slicer +ability.section.icon=Icon +ability.hasIcon=Custom Icon +ability.icon.tint=Tint Color + +ability.domeRadius=Dome Radius +ability.useHealth=Use Health +ability.maxHealth=Max Health +ability.useDuration=Use Duration +ability.duration=Duration +ability.defaultMultiplier=Default Multiplier +ability.innerAlpha=Inner Alpha +ability.heightOffset=Height Offset +ability.section.offset=Offset +ability.offsetX=X Offset +ability.offsetY=Y Offset +ability.offsetZ=Z Offset + +ability.solid=Solid +ability.knockbackEnabled=Knockback +ability.knockbackStrength=Knockback Strength +ability.absorbing=Absorbing +ability.absorbRadius=Absorb Radius +ability.reflect=Reflect +ability.reflectStrength=Strength (%) +ability.meleeEnabled=Allows Melee +ability.meleeDamageMultiplier=Melee Multiplier + +ability.followCaster=Follow Caster +ability.hover.followCaster=Dome stays centered on the caster as they move +ability.hover.solid=Entities cannot pass through the barrier boundary +ability.hover.knockbackEnabled=Repulsion field pushing entities away from barrier surface +ability.hover.absorbing=Damage dealt to the caster is redirected to the barrier's health +ability.hover.absorbRadius=Max distance from the barrier for absorption to work. -1 = unlimited, 0 = barrier extent (dome radius or panel size x3), positive = block radius +ability.hover.reflect=Rebounds non-breaking projectiles and reduces their damage by Strength +ability.targetOwner=Target Owner +ability.hover.targetOwner=Sets the reflected projectile's target to the original caster. With homing enabled, the projectile will home toward its former caster. +ability.hover.meleeEnabled=Barrier can be hit and damaged by melee attacks + + +ability.variant.small=Small +ability.variant.large=Large +ability.variant.static=Static +ability.variant.launched=Launched + +ability.addChain=Chain +ability.entrySource=Add Entry Source +ability.fromNpc=From NPC +ability.byReference=By Reference +ability.createNew=Create New +ability.selectSlot=Select NPC Ability +ability.loadType=Load Type +ability.loadAbility=Load Ability +ability.loadChain=Load Chain +ability.validFor=Valid For +ability.userType.NPC_ONLY=NPCs +ability.userType.PLAYER_ONLY=Players +ability.userType.BOTH=Both +ability.userType.NONE=NO ONE! +ability.icon.section.uv=UV Coordinates +ability.icon.x=Icon X +ability.icon.y=Icon Y +ability.icon.layers=Layers +ability.icon.layer=Layer + +gui.both=Both +gui.players=Players +gui.tags=Tags # Conditions condition.edit=Edit Condition -condition.hp_above=NPC HP Above -condition.hp_below=NPC HP Below -condition.target_hp_above=Target HP Above -condition.target_hp_below=Target HP Below +condition.filter=Filter Type +condition.filter.target=Target +condition.filter.caster=Caster +condition.filter.both=Both + +# Condition HP Threshold +condition.hp_threshold=HP Threshold +condition.hp_above=HP Above +condition.hp_below=HP Below +condition.hp_equal=HP Equal +condition.threshold=Threshold +condition.percent=Use Percent +condition.threshold_type=Threshold Type + +# Condition Hit Count condition.hit_count=Hit Count -condition.percent=Threshold -condition.hits=Required Hits -condition.within=Within (ticks) +condition.required_hits=Required Hits +condition.within_ticks=Within (ticks) + +# Condition Item +condition.item=Has Item +condition.usage_type=Usage Type +condition.armor_slot=Armor Slot +condition.full_armor=Full Armor +condition.item_count=Item Count +condition.item_name=Item Name + +# Condition Threshold +condition.above=Above +condition.below=Below +condition.equal=Equal +condition.threshold_flat=Threshold +condition.threshold_percent=Threshold % + +# Condition Quest Completed +condition.quest_completed=Quest Completed +condition.select_quest=Select Quest + +# Condition Has Effect +condition.has_effect=Has Effect +condition.select_effect=Select Effect # Condition Hover Tooltips condition.hover.type=Condition type that must be met for ability to activate @@ -1954,11 +2266,16 @@ condition.hover.hitCount=Activates after receiving X hits within the time window condition.hover.hits=Number of hits required to trigger condition condition.hover.within=Time window in ticks (20 ticks = 1 second) condition.hover.threshold=Health percentage threshold (1-99%) +condition.hover.armor_slots=Equipment in specific armor slots +condition.hover.item_name=Filter by item name or identifier +condition.hover.required_count=Number of matching items required # Effect Hover Tooltips 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 @@ -2014,7 +2331,6 @@ auction.filter.search=Search auction.bid.minimum=Minimum Bid: %s auction.bid.yourBid=Your Bid: auction.bid.place=Place Bid -auction.bid.placeBid=Place Bid auction.bid.buyout=Buyout Now # Errors @@ -2022,6 +2338,7 @@ auction.error.notEnoughCurrency=Not enough currency! auction.error.bidTooLow=Bid must be at least %s. auction.error.blacklisted=This item cannot be listed on the Auction House. auction.error.boundItem=Bound items cannot be listed on the Auction House. +auction.error.bidExceedsBuyout=Bid meets or exceeds buyout price. Use Buy Now instead. # Navigation auction.nav.listings=Browse Auctions @@ -2086,7 +2403,6 @@ auction.trades.leftClickRebid=Left-click to rebid auction.trades.rightClickRefund=Right-click to claim refund auction.claim.soldItem=Item: %s auction.claim.buyer=Buyer: %s -auction.claim.outbidItem=Item: %s auction.claim.outbidBy=Outbid by: %s # Sell Page - Buyout Toggle @@ -2114,8 +2430,45 @@ auction.bid.yourBalance=Your Balance: %s auction.buyout.title=Buy Now auction.buyout.confirm=Purchase this item for: -# Auction Status -auction.ended=Ended +# Global Auction Management GUI +global.auction.manage.title=Global Auction Management +global.auction.manage.listings=Listings +global.auction.manage.create=Create +global.auction.manage.claims=Claims +global.auction.manage.sort=Sort +global.auction.manage.search=Search +global.auction.manage.page=Page +global.auction.manage.hint.listings=Left-click: open listing details +global.auction.manage.hint.listings2=Right-click: stop player | Shift-right: cancel to global +global.auction.manage.hint.stop=Right-click: stop player +global.auction.manage.hint.cancel=Shift-right-click: cancel to global +global.auction.manage.hint.claims=Left-click twice to claim global entries +global.auction.manage.details=Listing Details +global.auction.manage.selectListing=Left-click a listing to view details +global.auction.manage.seller=Seller Name +global.auction.manage.startPrice=Start Price +global.auction.manage.buyoutPrice=Buyout Price +global.auction.manage.durationHours=Duration Hours +global.auction.manage.stagedItem=Staged Item +global.auction.manage.create.submit=Create Fake Auction +global.auction.manage.hint.create=Use right-panel inventory to stage items +global.auction.manage.confirm=Click again to confirm +global.auction.manage.confirm.stop=Right-click again to confirm stop player +global.auction.manage.confirm.cancel=Shift-right-click again to confirm cancel to global +global.auction.manage.confirm.claim=Left-click again to confirm claim +global.auction.manage.error.noItem=Stage an item first +global.auction.manage.error.invalidStart=Enter a valid starting price +global.auction.manage.error.invalidBuyout=Buyout must be zero or >= start -# Role -role.auctioneer=Auctioneer +# Directory Fullscreen +gui.move=Move +gui.moving=Moving +gui.confirm=Confirm +gui.move.selectItems=Select Items to Move (max %d) Press Confirm when Ready +gui.move.selectCategory=Select Destination Category +animation.mirror=Mirror +gui.builtin.tag=(Built-in) +ability.damage=Damage +ability.allowed=Allowed +gui.move.confirmLine=Move %d item(s) to: +gui.category=Category diff --git a/src/main/resources/assets/customnpcs/lang/ko_KR.lang b/src/main/resources/assets/customnpcs/lang/ko_KR.lang index e3a672289..e0c124dee 100644 --- a/src/main/resources/assets/customnpcs/lang/ko_KR.lang +++ b/src/main/resources/assets/customnpcs/lang/ko_KR.lang @@ -423,6 +423,7 @@ script.interact=상호작용 script.update=업데이트 script.console=콘솔 script.language=언어 +script.default=기본 script.damaged=데미지 script.killed=사망 script.attack=공격 diff --git a/src/main/resources/assets/customnpcs/lang/ru_RU.lang b/src/main/resources/assets/customnpcs/lang/ru_RU.lang index 2c6f76422..22dd39276 100644 --- a/src/main/resources/assets/customnpcs/lang/ru_RU.lang +++ b/src/main/resources/assets/customnpcs/lang/ru_RU.lang @@ -461,6 +461,7 @@ script.interact=Взаимодействие script.update=Обновление script.console=Консоль script.language=Язык +script.default=По умолч. script.damaged=Получ. урон script.killed=Убит script.attack=Атакует diff --git a/src/main/resources/assets/customnpcs/lang/zh_CN.lang b/src/main/resources/assets/customnpcs/lang/zh_CN.lang index 32105c7db..53793cecb 100644 --- a/src/main/resources/assets/customnpcs/lang/zh_CN.lang +++ b/src/main/resources/assets/customnpcs/lang/zh_CN.lang @@ -641,6 +641,7 @@ script.interact=对话 script.update=更新 script.console=控制台 script.language=语言 +script.default=默认 script.damaged=伤害 script.killed=杀死 script.attack=攻击 diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/beam.png b/src/main/resources/assets/customnpcs/textures/gui/ability/beam.png new file mode 100644 index 000000000..066b1b0b9 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/beam.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/charge.png b/src/main/resources/assets/customnpcs/textures/gui/ability/charge.png new file mode 100644 index 000000000..078114fd9 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/charge.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/cutter.png b/src/main/resources/assets/customnpcs/textures/gui/ability/cutter.png new file mode 100644 index 000000000..1d3cee95d Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/cutter.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/dash.png b/src/main/resources/assets/customnpcs/textures/gui/ability/dash.png new file mode 100644 index 000000000..79604af4a Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/dash.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/disc.png b/src/main/resources/assets/customnpcs/textures/gui/ability/disc.png new file mode 100644 index 000000000..0b5b984b8 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/disc.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/disc_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/disc_overlay.png new file mode 100644 index 000000000..34e291089 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/disc_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/dome.png b/src/main/resources/assets/customnpcs/textures/gui/ability/dome.png new file mode 100644 index 000000000..e13fad24e Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/dome.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/effect.png b/src/main/resources/assets/customnpcs/textures/gui/ability/effect.png new file mode 100644 index 000000000..9e1a6022f Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/effect.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/effect_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/effect_overlay.png new file mode 100644 index 000000000..84c0306ff Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/effect_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/guard.png b/src/main/resources/assets/customnpcs/textures/gui/ability/guard.png new file mode 100644 index 000000000..6b5630d4a Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/guard.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/hazard.png b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard.png new file mode 100644 index 000000000..b14e3d0b3 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/hazard_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard_overlay.png new file mode 100644 index 000000000..a0181aeac Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit.png b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit.png new file mode 100644 index 000000000..250deaee6 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit_overlay.png new file mode 100644 index 000000000..15881f843 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot.png b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot.png new file mode 100644 index 000000000..b9e4e930f Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot_overlay.png new file mode 100644 index 000000000..33a83327e Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/orb.png b/src/main/resources/assets/customnpcs/textures/gui/ability/orb.png new file mode 100644 index 000000000..3b60cff14 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/orb.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/shield.png b/src/main/resources/assets/customnpcs/textures/gui/ability/shield.png new file mode 100644 index 000000000..b2e229db5 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/shield.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave.png b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave.png new file mode 100644 index 000000000..e7df66d5c Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave_overlay.png new file mode 100644 index 000000000..dae4f2441 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/slam.png b/src/main/resources/assets/customnpcs/textures/gui/ability/slam.png new file mode 100644 index 000000000..bfa581fb4 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/slam.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper.png b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper.png new file mode 100644 index 000000000..f91317535 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper_overlay.png new file mode 100644 index 000000000..23048a1b8 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/teleport.png b/src/main/resources/assets/customnpcs/textures/gui/ability/teleport.png new file mode 100644 index 000000000..8ffa07c71 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/teleport.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/trap.png b/src/main/resources/assets/customnpcs/textures/gui/ability/trap.png new file mode 100644 index 000000000..f6ef614c0 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/trap.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/vortex.png b/src/main/resources/assets/customnpcs/textures/gui/ability/vortex.png new file mode 100644 index 000000000..968fcaee5 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/vortex.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/wall.png b/src/main/resources/assets/customnpcs/textures/gui/ability/wall.png new file mode 100644 index 000000000..83de77ef0 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/wall.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/wall_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/wall_overlay.png new file mode 100644 index 000000000..1a661b7cf Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/wall_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png b/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png new file mode 100644 index 000000000..ad84e3327 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/x_icon_blue.png b/src/main/resources/assets/customnpcs/textures/gui/auction/x_icon_blue.png new file mode 100644 index 000000000..9f4c340c1 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/x_icon_blue.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/directory.png b/src/main/resources/assets/customnpcs/textures/gui/directory.png new file mode 100644 index 000000000..fc8842597 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/directory.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/icons.png b/src/main/resources/assets/customnpcs/textures/gui/icons.png index 6f2993cd1..261b5a954 100644 Binary files a/src/main/resources/assets/customnpcs/textures/gui/icons.png and b/src/main/resources/assets/customnpcs/textures/gui/icons.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/script/icons.png b/src/main/resources/assets/customnpcs/textures/gui/script/icons.png new file mode 100644 index 000000000..4e19870f3 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/script/icons.png differ diff --git a/tools/standalone-JaninoLoader-1.0.1-ALPHA.jar b/tools/standalone-JaninoLoader-1.0.1-ALPHA.jar deleted file mode 100644 index cc5b1c843..000000000 Binary files a/tools/standalone-JaninoLoader-1.0.1-ALPHA.jar and /dev/null differ diff --git a/tools/standalone-JaninoLoader-1.0.2.jar b/tools/standalone-JaninoLoader-1.0.2.jar new file mode 100644 index 000000000..a03157587 Binary files /dev/null and b/tools/standalone-JaninoLoader-1.0.2.jar differ diff --git a/update/abilities.md b/update/abilities.md new file mode 100644 index 000000000..cb4eee563 --- /dev/null +++ b/update/abilities.md @@ -0,0 +1,207 @@ +# Abilities + +--- + +The **Ability System** adds full combat abilities to CustomNPC+. Give NPCs powerful attacks with visual telegraphs, launch energy projectiles, set traps, chain abilities into combos, and let players unlock abilities of their own. + +--- + +## How Abilities Work + +Every ability follows a **phase-based flow**: **Wind-up** (charge with telegraphs/animations) → **Active** (fire, deal damage, apply effects) → **Dazed** (optional recovery if interrupted). + +**Core Settings:** Cooldown (universal + per-ability), Targeting (Aggro/Self/AOE Self/AOE Target), Range (min/max), Lock Movement/Rotation per phase, Interruptible wind-up, Weight (NPC priority), Invulnerability per phase, Ignore I-Frames, Free on Cast, and Magic Damage (separate type with split ratios). + +> Abilities can be configured on individual NPCs or saved as **global presets**. + +--- + +## Melee Abilities + +- **Slam** - Leap toward target, AOE on impact. Configurable radius, knockback, leap height. Air slams deal reduced damage +- **Heavy Hit** - Powerful single strike with bonus knockback and configurable hit delay +- **Cutter** - Slashing arc in a cone with configurable angle and reach + +> All melee abilities support configurable damage, knockback, and potion effects on hit. + +--- + +## Energy Projectiles + +A full projectile system with a **Variant System** for patterns like dual-fire or barrages. + +**Types:** Orb (homing spheres, dual-fire/barrage variants), Disc (spinning, optional boomerang, vertical/horizontal), Beam (sustained, Free Aim mode), Laser Shot (instant hitscan, no homing). + +**Shared Settings:** Anchor Point (7 presets + custom offset), Display (colors, glow, transparency, size), Homing (toggle, turn rate, range), Combat (damage, knockback, AOE splash), Hit Type (Single/Pierce/Multi with max hit count), Lifespan (speed, max age, max distance), Size Interpolation, Proximity Alpha, and Explosions (configurable radius, toggleable block damage). + +--- + +## Energy Barriers + +Defensive constructs that block incoming attacks. + +- **Dome** - Spherical barrier around the caster +- **Wall** - Flat panel with optional launch mode (fires forward dealing damage/knockback) +- **Shield** - Held panel following the caster's facing direction + +**Properties:** HP/durability, melee vulnerability toggle, damage absorption (redirects caster damage to barrier), projectile reflection, ally/target filtering, custom position offsets. + +--- + +## Defensive Abilities + +- **Guard** - Reduces incoming damage by configurable %. Ends on duration or max hit count +- **Counter** - Absorbs attacks and counter-attacks. Flat or percentage-based counter damage with counter animation +- **Dodge** - Fully evades incoming attacks. Randomized dodge animations from up to 3 slots + +--- + +## Movement Abilities + +- **Charge** - Rush forward dealing damage in path. Configurable speed, hit width, knockback. Direction locks during wind-up +- **Dash** - Quick directional movement without damage. Supports directional key input +- **Teleport** - Instant relocate to target's position + +--- + +## AOE Abilities + +- **Shockwave** - AOE burst from caster with configurable radius and knockback +- **Sweeper** - Rotational sweep around caster. Can run alongside other abilities in chains +- **Vortex** - Pulling force dragging entities toward center while dealing damage + +--- + +## Hazards & Traps + +### Hazards + +Persistent damaging zones with configurable damage interval, zone count (up to 20), shape (circle/square), height, and duration. Can affect caster. + +**Visual Presets:** Default, Toxic, Inferno, Arcane, Electric, Frost. + +### Traps + +Proximity-triggered, sit dormant until an entity enters trigger radius. Configurable arm time, trigger count, cooldown, damage radius, knockback. Can be hidden until triggered. + +**Presets:** Hidden, Venom (Poison), Explosive (Fire), Cursed (Weakness), Shock (Mining Fatigue), Snare (Slowness). + +### Zone Visuals + +Both have configurable ground fill, concentric rings, rotating borders, accents (static/swaying/flickering), lightning arcs, and particles with multiple motion types. + +--- + +## Ability Effect + +Support ability for buffs, debuffs, healing, and custom effects. + +**Targeting:** Self or AOE Self (with Allies/Enemies/All filter based on Party/Faction). + +**Applies:** Flat and percentage healing (instant or over time), vanilla potion effects, custom effects, and mod-registered effect actions. + +**Built-in Variants:** Self Heal, Healing Aura, Poison Debuff. + +--- + +## Custom Ability + +Blank-slate ability for scripters with hooks: **Start**, **Execute**, **Tick** (with phase/count), **Complete**, **Toggle / Toggle Tick** (multi-state). Full telegraph control with all shapes. Supports instant and multi-state toggle modes. + +--- + +## Burst System + +Abilities fire **multiple times in rapid succession** as a single use. + +- **Burst Amount** - Additional repetitions after initial cast +- **Burst Delay** - Ticks between each burst +- **Replay Animations** and **Overlap Mode** (previous entities persist during next burst) + +> Available on most ability types including energy projectiles, melee, and movement abilities. + +--- + +## Chained Abilities + +Chain abilities into **sequential combos** with configurable delays between entries. Options: Wind-up All (simultaneous wind-up), Chain Cooldown, Chain Conditions (checked once for the whole chain). + +**Concurrency:** Effect, Hazard, Trap, and Sweeper types can execute alongside the primary ability instead of waiting. + +> Works with the ability hotbar and supports live previewing in the editor. + +--- + +## Telegraph System + +Visual ground indicators during wind-up that shift color before firing. + +**Shapes:** Circle, Ring (donut), Line (rectangle), Cone (fan/wedge), Point, Square. + +**Features:** ARGB color customization for telegraph and warning phases, entity-following or fixed position, proper ground/air height handling, saved as reusable presets. + +--- + +## Animations & Sound + +Per-phase animations (Wind-up, Active, Dazed) with optional animation-synced duration. Custom sound events for wind-up and active phases. Phase colors on the caster. Multiple animations can be registered under one common name. + +--- + +## Effects & Conditions + +### Potion Effects + +Abilities can apply potion effects on hit with configurable type, duration, and amplifier (up to 255). Supports modded effects via manual potion IDs. + +**Presets:** Fire, Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue. + +### Conditions + +Control when abilities can be used. Each checks **Caster**, **Target**, or **Both**: + +- **HP Threshold** - Above/below/equal (flat or percentage) +- **Hit Count** - Times hit within a time window +- **Has Item** - Holding, wearing, or carrying a specific item +- **Quest Completed** - Player completed a specific quest +- **Has Effect** - Has a specific custom effect + +--- + +## Player Abilities + +### Ability Hotbar + +12-slot bar accessed by holding **HUD Key** + **scroll wheel**. Shows icons with cooldown progress. Horizontal or vertical layout with 3, 5, or 7 visible slots. Configured via drag-and-drop in the CNPC+ Inventory Ability Tab, customized in the HUD Editor. + +### Player Features + +Unlock via scripting/commands, per-ability cooldowns, cancel on double-tap during wind-up, ability visibility toggle, proper state management (logout/dimension/death/respawn cleanup, movement suppression during locks), and flight safety. + +--- + +## Scripting API + +**Ability Events:** StartEvent, ExecuteEvent (both cancelable), InterruptEvent, CompleteEvent, HitEvent (cancelable, modifiable damage/knockback), TickEvent (phase + count), PlayerAbilityEvent. + +**Energy Projectile Events:** Fired, Update, EntityImpact, BlockImpact, Expired. + +**Ability Extender System:** Register custom lifecycle hooks (onAbilityStart, onAbilityTick, onAbilityComplete, onAbilityDamage) per ability. Scripts are instanced per use. + +--- + +## Ability Preview + +Live preview in the editor — test telegraphs, animations, projectiles, burst patterns, and chains on a dummy NPC with no world effects. + +--- + +## Commands + +- `/kam ability list|types|prebuilts` - List abilities, types, or built-ins +- `/kam ability info|delete|reload ` - View, delete, or reload abilities +- `/kam ability give|remove ` - Player ability management +- `/kam ability giveChain|removeChain ` - Chain management +- `/kam ability player` - Manage player abilities + +--- diff --git a/update/auction.md b/update/auction.md new file mode 100644 index 000000000..6603c7626 --- /dev/null +++ b/update/auction.md @@ -0,0 +1,85 @@ +# Auction House + +--- + +The **Auction House** is a global player marketplace where players can list items, bid against each other, and purchase instantly. Combined with a built-in currency system, it creates a full economy for your server. + +--- + +## Currency System + +CNPC+ has a **built-in currency** — fully configurable name, starting balance, and max cap. Profile-persistent across character slots. Integrates with Vault-compatible economy plugins. Tracks lifetime earned/spent per player. Full scripting API support. + +--- + +## Selling + +List items with a **Starting Price** for bidding and an optional **Buyout Price** for instant purchase. Auctions last **24 hours** by default. Configurable listing fee, sales tax, and minimum listing price. + +--- + +## Bidding + +Bids must meet a **minimum increment** above the current bid (default 5%, configurable). **Snipe Protection** extends auctions on last-second bids. Outbid currency is automatically refunded. + +--- + +## Buyout + +Instant purchase at the seller's Buyout Price. If you're the highest bidder, you only pay the **difference** between your bid and the buyout. + +--- + +## My Trades + +Manage all auction activity in one screen: Active Listings, Active Bids, and Ready to Claim. Cancel your own listings (items returned as claims, configurable cancellation penalty if bids exist, default 10%). + +> Claims expire after **20 days**. + +--- + +## Search & Sorting + +Search by **item name** and **seller name** simultaneously. Listings show item attributes and stats. Sort by: Newest, Ending Soon, Price (Low/High), Most Bids. + +--- + +## Notifications + +Instant notifications for: item sold, outbid, auction won, auction expired, claim ready. Offline players receive a **claim summary** on login. + +--- + +## Trade Slots + +Players get limited **Trade Slots** (default 8) shared across listings, bids, and pending claims. Expandable via permissions (`customnpcs.auction.trades.X`, up to 45, or `.*` for unlimited). + +--- + +## Item Blacklist + +Block items by: specific registry name, wildcard patterns, entire mods, or NBT tags. **Soulbound** and **Profile-Slotbound** items are always blocked. + +**Commands:** `/kam auction blacklist add|remove|list|reload|check` + +--- + +## Auctioneer Role + +Set the Auctioneer role on any NPC — players interact to open the full Auction House. + +--- + +## Admin Tools + +**Admin GUI** with three tabs: Listings (view/search/stop/cancel), Create (server listings with custom seller/prices/durations), Claims (global admin pool). + +**Commands:** `/kam auction open` (player), `/kam auction list [page]` and `/kam auction view ` (admin). Configurable per-type auction logging. + +--- + +## Scripting API + +All auction events are **cancelable**: CreateEvent, BidEvent, BuyoutEvent, CancelEvent, ClaimEvent. + +--- diff --git a/update/npc-and-tools.md b/update/npc-and-tools.md new file mode 100644 index 000000000..0b69dd1b5 --- /dev/null +++ b/update/npc-and-tools.md @@ -0,0 +1,71 @@ +# NPC, Animation & Tool Improvements + +A collection of improvements to NPCs, animations, items, and tools alongside the major feature updates. + +## Cloner Tab Overhaul +The Cloner now supports **folders and subfolders** for organizing all cloner categories (animations, abilities, forms, auras, outlines, effects, linked items). Full-width directory browser, improved tab navigation, and tag-based quick filtering. + +## Animation Improvements +- **Data Store** for passing data across animation events and frames +- **Task System** - Consumer-based animation lifecycle events +- **Expanded scripting API** + +## Animated Textures +**Frame-based animated textures** for linked/scripted items, custom effect icons, ability hotbar icons, and scripted GUI textured rectangles. Configurable frames per row, ticks per frame, and interpolation. + +## NPC API Additions +- **Hitbox Data** (`IHitboxData`) - Independent width/height scaling +- **Tint Data** (`ITintData`) - Hurt tint and persistent color tints with alpha +- **Behavior Properties** - Sprint, swim, doors, fire reactions, tactical chance, walking range now scriptable +- **Sound Control** (`ISound`) - Volume, pitch, repeat, position +- **Skin Overlay Colors** - `getColor()`/`setColor()` for tinting overlay layers +- **Knockback API** - With support for respecting/ignoring knockback resistance +- **Six Overlays in Singleplayer** now work properly +- **Error Reporting** - Script exceptions report to Script Console with stack traces + +## Natural Spawn Improvements +Improved GUI, runtime control, despawn handling, and fixed biome spawn persistence. + +## NPC Combat & Behavior +- NPCs now properly respect **attack speed** before allowing hits +- **Passive Faction Protection** prevents damage to passive faction NPCs +- Improved **track speed** handling for smoother target following +- **Invalid Texture Fallback** to default skin instead of errors + +## Additional Changes +- Player Dialog Events now work like NPC Dialog Events +- Linked Item attack speed configuration and new scripting API methods +- Right-click cycling on multi-option NPC buttons (Hair, Eyes, Fur, etc.) +- Legacy Quest Import (CustomNPCs 1.6.4 format) +- Fullscreen & pannable GUIs, unified menu background +- Textfield CTRL shortcuts (A, C, V, etc.) +- `java.lang.reflect` banned in scripts for security +- Server-side fix for entity packet loss (invisible NPCs) + +# Bug Fixes + +## Scripting Engine +- Fixed script config sync between server and client +- Fixed Bukkit integration compatibility + +## Quests & Dialogs +- Fixed quest cooldown for MC Custom and RL Custom timer types +- Fixed quest/dialog modification names, saving, and category assignment +- Fixed bard music restarting/duplicating on dialog open + +## NPCs +- Fixed spawner yaw using camera yaw instead of proper facing +- Fixed biome spawn settings not persisting +- Fixed NPC invisibility from request client packet issues +- Fixed track speed handling and set speed edge cases +- Fixed missing spawn data, block waypoint pathing, and job spawner behavior +- Fixed hitbox scaling and collision issues + +## Animations +- Fixed animation offsets conflicting with vanilla offsets +- Fixed lookup failures, syncing, resync on teleport +- Fixed wrong names on registration and controller loading twice on startup + +## Mounts +- Fixed movement jitter (now follows vanilla horse/boat sync pattern) +- Fixed dismount edge cases diff --git a/update/scripting.md b/update/scripting.md new file mode 100644 index 000000000..a56e808f0 --- /dev/null +++ b/update/scripting.md @@ -0,0 +1,44 @@ +# Script Editor & Scripting Enhancements + +--- + +The script editor has been rebuilt into a **full-featured code editor** inside Minecraft with syntax highlighting, autocomplete, error detection, and Java scripting support. + +--- + +## Script Editor + +### Writing Code + +- **Syntax Highlighting** - Color-coded keywords, types, variables, methods, strings, comments. Context-aware coloring for locals, globals, and chained calls +- **Autocomplete** - Smart suggestions with static/instance context awareness, frequency-based ordering, and smart cursor placement for method parameters. Auto-imports for class names +- **Error Detection** - Catches wrong argument types, missing methods, type mismatches, unused imports with detailed hover messages +- **Built-in Globals** - ECMAScript 5.1 objects (`Math`, `JSON`, `Date`, `Number`) and script globals (`npc`, `world`, `event`) recognized automatically +- **JS Language Support** - Arrow functions, shorthand methods, object literals, and array expressions understood by highlighter and type resolver + +> Hover any symbol for **full type info and documentation** with JSDoc markdown formatting, scrollable tooltips, and code blocks. + +### Navigation + +`CTRL+G` Go to Line, `CTRL+F` Search, `CTRL+H` Replace, `CTRL+Click` Go to Definition, Fullscreen Mode. + +### Editing + +Undo/Redo (word-level), Duplicate Line (`CTRL+D`), Comment Toggle (`CTRL+/`), Rename (all occurrences), Move Lines, Copy Whole Line (empty selection), Triple Click (select line). + +### Visual Polish + +Line numbers with current line highlight, smooth scrolling, indent guides (green current scope), brace matching (red unclosed), smart bracket auto-close, resizable/pannable panels, keyboard shortcut overlay. + +--- + +## Java Scripting (Janino) + +Write scripts in **real Java** compiled natively via the **Janino** compiler. Full Java language support (classes, interfaces, enums, generics, lambdas, method references). Automatic hook resolution by method name. Per-tab language selector to mix Java and JavaScript. Works in NPC, Player, Forge, Recipe, Effect, and Linked Item scripts. External `.java` files load automatically. + +--- + +## Client-Side Scripting + +Scripts can run **on the client** — server-controlled, auto-synced on login and reload, off by default. Enables custom UI effects, visual feedback, and client-only hooks while the server stays in control. + diff --git a/update/traders.md b/update/traders.md new file mode 100644 index 000000000..108722ebc --- /dev/null +++ b/update/traders.md @@ -0,0 +1,11 @@ +# Trader Enhancements + +Traders upgraded with a **stock system** and **currency integration** for proper shops with limited supply and real economy support. + +## Stock System +**Stock Modes:** Global (shared pool) or Per-Player (individual purchase limits). +**Restock Timers:** MC Daily/Weekly, RL Daily/Weekly, or Custom (MC ticks / real-time). +> Stock counts, out-of-stock indicators, and restock timers are visible in the trade interface. Admins can manually reset stock/cooldowns via the Trader GUI. + +## Currency Trades +Trades can require **currency on top of items** — e.g., a diamond sword costing 3 diamonds **plus** 500 coins.