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/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 23d9047f1..5d29506b6 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,8 @@ .project /bin/ /config/ +/copilot/ +/buildSrc/build/ /crash-reports/ /logs/ options.txt @@ -39,3 +41,10 @@ addon.late.local.gradle.kts layout.json out run +src/main/resources/assets/customnpcs/api +df/ +tmp/ +src/test +node_modules +.github/pages-dist + diff --git a/.gitmodules b/.gitmodules index d8252cb6a..d3428cb3d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,6 @@ path = src/api url = https://github.com/KAMKEEL/CustomNPC-Plus-API.git branch = dev +[submodule "gradle-plugins"] + path = gradle-plugins + url = https://github.com/bigguy345/dts-gradle-plugin diff --git a/1.11_Beta_Update.md b/1.11_Beta_Update.md new file mode 100644 index 000000000..815c62e5d --- /dev/null +++ b/1.11_Beta_Update.md @@ -0,0 +1,92 @@ +# CNPC+ 1.11 Beta - The Scripting Update + +🟡 **In Testing** + + + +## Features: ⚒️ + +- **Syntax Highlighting:** + +> Full color-coded script editor. Keywords, types, variables, methods, strings, and comments are all distinct. Scope-aware coloring distinguishes local fields from globals and chained method calls. + + + +- **Autocomplete:** + +> Smart suggestions as you type. Context-aware for static vs instance access, shows method parameters, resolves chained calls, and suggests auto imports for classes. Frequently used members prioritized. + + + +- **Error Detection:** + +> Catch mistakes before running. Type mismatches, wrong arguments, missing methods, unused imports, duplicate definitions, and more -- all underlined with hover messages explaining the issue. + + + +- **Hover Information:** + +> Hover any symbol to see its type, documentation, and declaration. Works on methods, fields, classes, and even generics. Click to pin tooltips in place. + + + +- **Script Editor Overhaul:** + +> - **Line Numbers** - Gutter with current line highlighting. +> - **Go To Line** - CTRL+G to jump to any line. +> - **Search & Replace** - CTRL+F / CTRL+H with real-time highlighting. +> - **Go To Definition** - CTRL+Click to jump to any symbol. +> - **Smart Undo/Redo** - Word-level instead of character-level. +> - **Line Operations** - Duplicate, delete, move up/down. +> - **Comment Toggle** - CTRL+/ for selected lines. +> - **Rename** - Rename a symbol across all occurrences. +> - **Smooth Scrolling** - Eased scroll animation. +> - **Indent Guides** - Scope-highlighted vertical indent lines. +> - **Brace Matching** - Highlighted pairs, red for unclosed. +> - **Smart Brackets** - Auto-pairing for `{}`, `()`, `[]`, `""`, `''`. +> - **Fullscreen Mode** - Expand editor to fill the game window. +> - **Shortcut Overlay** - View all keyboard shortcuts at a glance. + + + +- **Java Scripting (Janino):** + +> Write scripts in real Java compiled at runtime. Name methods after hooks for automatic wiring. Language selector per tab to switch between Java and JavaScript. External `.java` file support. + + + +- **Client-Side Scripting:** + +> Run scripts on the client for responsive experiences. Server-controlled -- off by default, must be explicitly enabled. Script files sync automatically on login and reload. + + + +- **Cloner Tab Overhaul:** + +> Folder-based organization for saved NPCs, items, and entries. Full-width directory browser for large collections. Improved tab navigation. + + + +- **Addon API Support:** + +> Addons can ship type definitions that load into the script editor automatically. Full autocomplete, hover info, and documentation for addon APIs. Addons can extend existing CNPC+ types with new methods. + + + +- **Animation Improvements:** + +> Data store for passing data across animation events and frames. New consumer-based task system for animation lifecycle. Expanded scripting API for animation control. + + + +**Extras** + +- Player Dialog Events now work like NPC Dialog Events. +- Attack speed configuration for linked items. +- Client-side balance prediction during Trader interactions. +- Right-click cycling on multi-option NPC buttons (Hair, Eyes, Fur, etc.). +- Fixed quest cooldown for MC Custom and RL Custom timer types. +- Fixed Bard music restarting when opening dialogs. +- Fixed NPC biome spawn settings not saving after editing. +- Fixed block waypoint issues. +- Fixed script config syncing between server and client. diff --git a/1.11_Update.md b/1.11_Update.md new file mode 100644 index 000000000..c6101a559 --- /dev/null +++ b/1.11_Update.md @@ -0,0 +1,118 @@ +# ✏️ CustomNPC+ 1.11 - The Scripting Update ✏️ + +--- + +The **Scripting Update** completely transforms how you write scripts in CNPC+! A brand new **Script Editor** with **syntax highlighting**, **autocomplete**, and **error detection** makes scripting feel like a real IDE. Write scripts in **Java** with the new Janino engine, enable **client-side scripting** for responsive experiences, and organize your Cloner with **folders**! + +--- + +## Script Editor 📝 + +The script editor has been rebuilt from the ground up into a **full-featured code editor** right inside Minecraft. + +### Writing Code + +- **Syntax Highlighting** - Keywords, types, variables, methods, strings, and comments are all color-coded automatically. The editor understands your code -- local variables, global fields, and chained method calls each get their own color +- **Autocomplete** - Start typing and get smart suggestions for methods, fields, and classes. Suggestions know whether you're in a static or instance context, and frequently used members appear first +- **Auto Imports** - Type a class name and the editor suggests the correct import for you +- **Error Detection** - Catch mistakes before you even run your script! Wrong argument types, missing methods, type mismatches, unused imports, and more are all underlined with detailed error messages on hover + +> Hover over any symbol to see its **full type information**, documentation, and declaration -- just like a desktop IDE. + +--- + +### Navigation + +- **Go To Line** - `CTRL+G` jumps to any line instantly +- **Search & Replace** - `CTRL+F` to search, `CTRL+H` to replace. All matches highlight in real-time +- **Go To Definition** - `CTRL+Click` any method, field, or type to jump straight to its definition +- **Fullscreen Mode** - Expand the editor to fill your entire game window for maximum workspace + +### Editing + +- **Undo/Redo** - Smart undo that works on whole words at a time, not individual characters +- **Line Operations** - Duplicate lines with `CTRL+D`, delete lines, and move lines up or down with shortcuts +- **Comment Toggle** - `CTRL+/` to comment or uncomment selected lines +- **Rename** - Rename a variable or method and every occurrence updates at once +- **Copy Whole Line** - Copy with nothing selected grabs the entire line +- **Triple Click** - Select an entire line instantly + +### Visual Polish + +- **Line Numbers** - A clean gutter with line numbers and current line highlighting +- **Smooth Scrolling** - Eased scroll animations for a polished feel +- **Indent Guides** - Vertical lines show your code's nesting depth, with the current scope highlighted in green +- **Brace Matching** - Matching `{}` braces light up, and unclosed braces turn red +- **Smart Brackets** - Typing `{` automatically creates the closing `}` with correct indentation. Same for `()`, `[]`, `""`, and `''` +- **Keyboard Shortcut Overlay** - Press a button to see all available shortcuts at a glance + +--- + +## Java Scripting ☕ + +Write scripts in **real Java** instead of JavaScript! Powered by the **Janino** compiler, your Java code is compiled and runs natively. + +- **Full Java Language** - Use classes, interfaces, enums, generics, lambdas, and everything you know from Java +- **Automatic Hook Resolution** - Just name your methods after the hook you want (e.g., `init`, `tick`, `interact`) and they're wired up automatically +- **Language Selector** - Each script tab has a dropdown to choose between JavaScript and Java. Mix and match across tabs +- **External Files** - Write `.java` scripts in an external editor and they're loaded automatically + +> Java and JavaScript scripts coexist side by side. Pick whichever language fits your workflow! + +--- + +## Client-Side Scripting 🖥️ + +Scripts can now run **on the client** for responsive, visual experiences! + +- **Server Controlled** - Server owners decide whether client scripting is allowed. Players can't enable it on their own +- **Automatic Sync** - Script files are sent from the server to all connected clients on login, and re-synced whenever scripts are reloaded +- **Safe by Default** - Client scripting is off by default and must be explicitly enabled in the server config + +> Client-side scripts open the door to custom UI effects, visual feedback, and client-only hooks -- all while the server stays in full control. + +--- + +## Cloner Tab Overhaul 📂 + +The Cloner now supports **folders** for organizing your saved NPCs, items, and entries! + +- **Folder System** - Create folders and subfolders to keep your cloner organized however you like +- **Full Screen Browser** - A new full-width directory view makes browsing large collections much easier +- **Improved Tabs** - Better tab navigation for switching between cloner categories + +--- + +## Addon API Support 📘 + +Addon developers can now ship **type definitions** alongside their mods, giving scripters full autocomplete and documentation for addon APIs! + +- **Automatic Loading** - Any mod can include API definitions and they'll appear in the script editor automatically +- **Patch Support** - Addons can extend existing CNPC+ types with new methods (e.g., a DBC addon adding `getDBCPlayer()` to the Player type) +- **Full Documentation** - Parameter names, return types, and descriptions all show up in autocomplete and hover info + +> If you're a scripter using addons, you get autocomplete for their APIs with zero setup. If you're an addon developer, just include your definitions and everything works. + +--- + +## Animation Improvements 🎬 + +- **Data Store** - Animations can now store and pass data across events and frames for more complex animation logic +- **Task System** - A new consumer-based system for reacting to animation lifecycle events, replacing the old approach +- **Expanded API** - More animation control exposed to the scripting API + +--- + +## Additional Changes 🔧 + +- **Player Dialog Events** - Now work the same way as NPC Dialog Events for consistency +- **Linked Item Attack Speed** - Added attack speed configuration to linked items +- **Trader Balance Preview** - Client-side balance prediction shows your expected balance during trades +- **Right-Click Cycling** - Multi-option NPC buttons (Hair, Eyes, Fur, etc.) can now be right-clicked to cycle backwards +- **Quest Cooldown Fix** - Fixed cooldown not working for MC Custom and RL Custom timer types +- **Bard Music Fix** - Fixed music restarting or duplicating when opening dialogs +- **Biome Spawn Fix** - Fixed NPC biome spawn settings not saving after editing +- **Block Waypoint Fix** - Fixed issues with block waypoints +- **Script Config Fix** - Fixed script configuration not syncing properly between server and client + +--- diff --git a/Ability_Update.md b/Ability_Update.md new file mode 100644 index 000000000..c81302f1c --- /dev/null +++ b/Ability_Update.md @@ -0,0 +1,368 @@ +# ⚔️ 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, set **traps** and **hazards**, chain abilities into devastating combos, 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. Supports both a **universal cooldown** and **per-ability cooldowns** +- **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 +- **Invulnerability** - Make the caster invulnerable during Wind-up, Active, or both phases +- **Ignore I-Frames** - Bypass Minecraft's damage immunity timer, allowing rapid consecutive hits +- **Free on Cast** - The ability enters cooldown the moment it launches, freeing the caster while spawned entities (projectiles, zones, barriers) persist independently +- **Magic Damage** - Abilities can deal magic damage as a separate damage type, with configurable damage values and split ratios + +> 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. Air slams deal reduced damage based on required leap height +- **Heavy Hit** - A single powerful melee strike with bonus knockback and a configurable hit delay +- **Cutter** - A slashing arc attack in a cone. Configurable angle and reach + +> 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. Energy projectiles use a **Variant System** — each base type (Orb, Beam, Disc) can be configured with variants like dual-fire or barrage patterns, all from within the same ability type. + +### Orbs + +Homing energy spheres that track their target through the air. Configurable with variants for dual or barrage firing patterns. + +### Discs + +Flat spinning projectiles with optional **boomerang** behavior. Supports both vertical and horizontal orientation. + +### Beams + +Sustained energy beams that connect the caster to their target. Supports a **Free Aim** mode for manual aiming without homing. + +### Laser Shot + +An **instant-fire** hitscan projectile with configurable width and speed. No homing — pure aim. + +### 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. Supports custom offset anchors and a **Launch From Anchor** setting +- **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 +- **Hit Type** - Choose how the projectile interacts with targets: **Single** (hits one), **Pierce** (passes through), or **Multi** (hits multiple) +- **Lifespan** - Projectile speed, max age, and max travel distance (up to 150 blocks) +- **Explosions** - Energy projectiles can detonate on impact with configurable explosion radius. Block damage can be toggled in the Energy Config + +--- + +## Energy Barriers 🛡️ + +Defensive energy constructs that block incoming projectiles and attacks. + +- **Dome** - A spherical barrier centered on the caster. Blocks incoming energy projectiles with configurable per-type damage multipliers, HP/durability, and duration +- **Wall** - A placeable flat energy panel with configurable dimensions and height offset. Has an optional **launch mode** that fires the wall forward, dealing damage and knockback +- **Shield** - A held energy panel that follows the caster's facing direction for directional blocking + +**Barrier Properties:** +- **HP & Durability** - Barriers have health and break when depleted +- **Melee Vulnerability** - Barriers can be configured to take damage from melee attacks +- **Damage Absorption** - Attacks aimed at the caster can be redirected to damage the barrier instead +- **Ally/Target Filtering** - Configure which projectiles are blocked based on ownership +- **Offset Support** - Position barriers with custom offsets from the caster + +--- + +## Defensive Abilities 🏰 + +Reactive defensive stances that protect the caster when hit. + +- **Guard** - Enter a defensive stance that **reduces incoming damage** by a configurable percentage. Lasts until duration expires or a max hit count is reached +- **Counter** - Absorb incoming attacks and **counter-attack the attacker**. Counter damage can be a flat value or a percentage of the absorbed damage. Plays a counter-attack animation on each successful counter +- **Dodge** - Fully **evade incoming attacks**, negating all damage. Plays randomized dodge animations from up to three configurable animation slots + +> All defensive abilities support configurable duration and maximum hit counts before they break. + +--- + +## 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. + +- **Shockwave** - An AOE burst radiating outward from the caster, dealing damage and knockback in a configurable radius +- **Sweeper** - A wide rotational sweep attack around the caster with configurable radius and rotation speed. Can run concurrently with other abilities in chains +- **Vortex** - Creates a pulling force that drags nearby entities toward the center while dealing damage + +--- + +## Hazards & Traps 🪤 + +Ground-based zone abilities for area denial and ambush tactics. + +### Hazards + +Persistent damaging areas that continuously hurt entities standing inside them. Configurable damage interval, zone count (up to 20), shape (circle or square), zone height, and duration. Can optionally affect the caster. + +**Zone Visual Presets:** Default, Toxic, Inferno, Arcane, Electric, Frost — each with themed colors, particles, and visual effects. + +### Traps + +Proximity-triggered burst abilities that sit dormant until an entity enters the trigger radius. Support configurable arm time, multiple triggers before expiring, trigger cooldown, damage radius, and knockback. Traps can be **hidden** (invisible) until triggered, revealing with a brief burst effect. + +**Trap Presets:** +- **Hidden** - Minimal visibility, no effects — a pure stealth trap +- **Venom** - Applies Poison with toxic green visuals +- **Explosive** - Applies Fire with fiery orange particles +- **Cursed** - Applies Weakness with purple arcane effects +- **Shock** - Applies Mining Fatigue with blue electrical sparks +- **Snare** - Applies Slowness with icy blue visuals + +### Zone Visuals + +Both hazards and traps share a rich visual system with configurable layers: ground fill, concentric rings, rotating borders, accents (static, swaying, or flickering), lightning arcs, and particle effects with multiple motion types (rising, drifting, sparks). + +--- + +## Ability Effect 💫 + +A support ability for applying buffs, debuffs, healing, and custom effects to allies or enemies. + +**Targeting:** +- **Self** - Affect only the caster (self-buffs, self-healing) +- **AOE Self** - Area-of-effect centered on the caster with a configurable radius + +**Target Filter (AOE):** +- **Allies** - Only affect friendly entities +- **Enemies** - Only affect hostile entities +- **All** - Affect everyone in range + +Allies are determined by **Party** for players and **Faction** for NPCs. A toggle controls whether the caster is included in AOE effects. + +**Effect Types:** +- Flat and percentage-based healing (instant or over time) +- Vanilla potion effects +- Custom effects from the Custom Effect system +- Mod-registered effect actions + +**Built-in Variants:** Self Heal, Healing Aura, Poison Debuff. + +--- + +## Custom Ability 🔧 + +A blank-slate ability type designed for **scripters** to build fully custom abilities through script hooks. + +**Script Hooks:** +- **Start** - Fired when the ability begins +- **Execute** - Fired when entering the active phase +- **Tick** - Fired every game tick with phase and tick count +- **Complete** - Fired when the ability finishes +- **Toggle / Toggle Tick** - For toggle-mode abilities with multiple states + +**Features:** +- Full telegraph control with all shape types (Circle, Ring, Line, Cone, Point, Square) +- Configurable telegraph dimensions, colors, and duration +- Supports both instant execution and multi-state toggle modes + +--- + +## Burst System 🔁 + +Abilities can be configured to **fire multiple times in rapid succession** as a single use. + +- **Burst Amount** - Number of additional repetitions after the initial cast +- **Burst Delay** - Ticks between each burst iteration +- **Replay Animations** - Optionally replay the wind-up animation on each burst +- **Overlap Mode** - Previous entities can persist while the next burst fires, allowing stacking effects + +> Burst is available on most ability types including energy projectiles, melee abilities, and movement abilities. + +--- + +## Chained Abilities ⛓️ + +Chain multiple abilities together into **sequential combos** that execute one after another. + +- **Ordered Entries** - Each entry in the chain references an ability with a configurable delay before it fires +- **Wind-up All** - Optionally wind up all abilities simultaneously before the chain begins +- **Chain Cooldown** - A single cooldown applied after the entire chain completes +- **Chain Conditions** - Conditions checked once for the whole chain, not per-ability + +### Concurrency + +Specific ability types can be marked to run **concurrently** within a chain — executing alongside the primary ability instead of waiting in sequence. Concurrent-capable types include Effect, Hazard, Trap, and Sweeper. + +> Chained abilities work with the ability hotbar and support live previewing in the editor. + +--- + +## Telegraph System 📍 + +**Telegraphs** are visual ground indicators that warn players before an ability lands. They appear during the wind-up phase and transition into a warning state before 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 +- **Square** - Square area 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 +- **Height Handling** - Telegraphs properly handle ground and air positioning +- **Custom Controls** - Full telegraph configuration available on Custom Abilities + +> 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 +- **Dazed Animation** - Plays during the dazed recovery state +- **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 +- **Multiple Animations** - Multiple animations can be registered under one common name + +> 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. Supports both preset effect types and **manual potion IDs** for custom or modded effects with amplification up to 255. + +**Available Preset Effects:** +Fire, Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue + +### Conditions + +Abilities support a **condition system** that controls when they can be used. Each condition can be checked on the **Caster**, the **Target**, or **Both**. + +**Condition Types:** +- **HP Threshold** - Check if an entity's health is above, below, or equal to a value (supports flat or percentage) +- **Hit Count** - Require the caster to have been hit a certain number of times within a time window +- **Has Item** - Check if an entity is holding, wearing, or carrying a specific item +- **Quest Completed** - Check if a player has completed a specific quest +- **Has Effect** - Check if an entity has a specific custom effect applied + +--- + +## Player Abilities 🧑 + +Players can unlock and use abilities with a full hotbar and management system! + +### Ability Hotbar + +The **Ability Hotbar** is a 12-slot bar for equipping and switching between unlocked abilities. Hold the **HUD Key** and use the **scroll wheel** to cycle through your equipped abilities. The hotbar displays ability icons with cooldown progress and supports horizontal or vertical layouts with 3, 5, or 7 visible slots. + +Configure your hotbar through drag-and-drop in the **CNPC+ Inventory Ability Tab**, and customize its appearance in the **HUD Editor** under CNPC+ Inventory Settings. + +### Player Features +- **Unlock System** - Players receive abilities via scripting or commands +- **Per-Ability Cooldowns** - Each ability can have its own cooldown in addition to the universal cooldown +- **Cancel on Double-Tap** - Double-tap the ability key during wind-up to cancel and immediately enter cooldown +- **Ability Visibility** - Hide or show specific abilities in the HUD and usage +- **State Management** - Abilities are properly cancelled on logout, dimension change, death, and respawn. Movement input is suppressed during ability locks +- **Flight Safety** - Abilities do not affect players who are flying + +--- + +## 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 +- **PlayerAbilityEvent** - Events for player ability actions + +### Energy Projectile Scripting + +Full scripting interfaces for all energy projectile types with 5 event hooks: +- **Fired** - When the projectile launches +- **Update** - Every tick during flight +- **EntityImpact** - On hitting an entity +- **BlockImpact** - On hitting a block +- **Expired** - When the projectile's lifespan ends + +### Ability Extender System + +Register custom **lifecycle hooks** on abilities with the Ability Extender system: +- **onAbilityStart** - When the ability begins +- **onAbilityTick** - Every tick during execution +- **onAbilityComplete** - When the ability finishes +- **onAbilityDamage** - When the ability deals damage + +Multiple extenders can be registered per ability. Ability scripts are **instanced** — every use gets its own fresh set of variables for optimal performance. + +> 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, projectile visuals, burst patterns, and chained ability sequences 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 prebuilts` - List all built-in abilities +- `/kam ability info ` - View ability details +- `/kam ability delete ` - Delete a custom ability +- `/kam ability reload` - Reload abilities from disk +- `/kam ability give` - Give an ability to a player +- `/kam ability remove` - Remove an ability from a player +- `/kam ability giveChain` - Give a chained ability to a player +- `/kam ability removeChain` - Remove a chained ability from a player +- `/kam ability player` - Manage player abilities + +--- diff --git a/Auction_Update.md b/Auction_Update.md new file mode 100644 index 000000000..a4612402e --- /dev/null +++ b/Auction_Update.md @@ -0,0 +1,167 @@ +# 🏪 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! + +### 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 with a configurable **minimum listing price**. + +> 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 configurable **cancellation penalty** is charged (default 10%). + +> Claims expire after **20 days**. Make sure to collect your items and currency before they're gone! + +### Search & Sorting + +Find what you're looking for with search and sort tools. Search filters by both **item name** and **seller name** simultaneously. + +**Sort Options:** +- Newest +- Ending Soon +- Price (Low to High) +- Price (High to Low) +- Most Bids + +### Notifications + +Get notified immediately when: +- Your item **sells** +- You get **outbid** +- You **win** an auction +- Your auction **expires** with no bids +- A **claim is ready** for pickup + +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, or grant **unlimited slots** with the `customnpcs.auction.trades.unlimited` permission. + +--- + +## 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! + +**Blacklist Commands:** +- `/kam auction blacklist add ` - Add to the blacklist +- `/kam auction blacklist remove ` - Remove from the blacklist +- `/kam auction blacklist list [item|mod|nbt]` - View blacklisted entries +- `/kam auction blacklist reload` - Reload blacklist from config +- `/kam auction blacklist check` - Check if your held item is blacklisted + +--- + +## 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. + +--- + +## Admin Tools 🔨 + +### Admin Auction GUI + +A dedicated management interface for server admins with three tabs: + +- **Listings** - View and search all active auctions. Stop or cancel any listing +- **Create** - Create server-managed listings with custom seller names, prices, and durations +- **Claims** - Manage the global admin claims pool + +### Auction Commands + +**Player Commands:** +- `/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. Each log type can be toggled individually. + +--- + +## Scripting API 📜 + +Full event support for auction interactions. All events are **cancelable**, allowing scripts to intercept and control auction behavior: + +- **CreateEvent** - Before an auction is created +- **BidEvent** - Before a bid is placed +- **BuyoutEvent** - Before an instant purchase +- **CancelEvent** - Before a listing is cancelled +- **ClaimEvent** - Before a claim is collected + +--- diff --git a/Extra_Update.md b/Extra_Update.md new file mode 100644 index 000000000..279d9a6d4 --- /dev/null +++ b/Extra_Update.md @@ -0,0 +1,143 @@ +# ✏️ CustomNPC+ 1.11 - The Scripting Update ✏️ + +--- + +The **Scripting Update** completely transforms how you write scripts in CNPC+! A brand new **Script Editor** with **syntax highlighting**, **autocomplete**, and **error detection** makes scripting feel like a real IDE. Write scripts in **Java** with the new Janino engine, enable **client-side scripting** for responsive experiences, and organize your Cloner with **folders**! + +--- + +## Script Editor 📝 + +The script editor has been rebuilt from the ground up into a **full-featured code editor** right inside Minecraft. + +### Writing Code + +- **Syntax Highlighting** - Keywords, types, variables, methods, strings, and comments are all color-coded automatically. The editor understands your code -- local variables, global fields, and chained method calls each get their own color +- **Autocomplete** - Start typing and get smart suggestions for methods, fields, and classes. Suggestions know whether you're in a static or instance context, and frequently used members appear first. Smart cursor placement inserts methods with the cursor between parentheses when parameters exist +- **Auto Imports** - Type a class name and the editor suggests the correct import for you +- **Error Detection** - Catch mistakes before you even run your script! Wrong argument types, missing methods, type mismatches, unused imports, and more are all underlined with detailed error messages on hover +- **ECMAScript 5.1 Globals** - Built-in objects like `Math`, `JSON`, `Date`, and `Number` are recognized automatically in JavaScript mode +- **Global Script Variables** - Variables like `npc`, `world`, and `event` are recognized in the syntax highlighter and autocomplete as global definitions + +> Hover over any symbol to see its **full type information**, documentation, and declaration -- just like a desktop IDE. Hover tooltips render **JSDoc with markdown formatting**, headings, and code blocks, and support **scrolling and panning** for long documentation. + +--- + +### Navigation + +- **Go To Line** - `CTRL+G` jumps to any line instantly +- **Search & Replace** - `CTRL+F` to search, `CTRL+H` to replace. All matches highlight in real-time +- **Go To Definition** - `CTRL+Click` any method, field, or type to jump straight to its definition +- **Fullscreen Mode** - Expand the editor to fill your entire game window for maximum workspace + +### Editing + +- **Undo/Redo** - Smart undo that works on whole words at a time, not individual characters +- **Line Operations** - Duplicate lines with `CTRL+D`, delete lines, and move lines up or down with shortcuts +- **Comment Toggle** - `CTRL+/` to comment or uncomment selected lines +- **Rename** - Rename a variable or method and every occurrence updates at once +- **Copy Whole Line** - Copy with nothing selected grabs the entire line +- **Triple Click** - Select an entire line instantly + +### Visual Polish + +- **Line Numbers** - A clean gutter with line numbers and current line highlighting +- **Smooth Scrolling** - Eased scroll animations for a polished feel +- **Indent Guides** - Vertical lines show your code's nesting depth, with the current scope highlighted in green +- **Brace Matching** - Matching `{}` braces light up, and unclosed braces turn red +- **Smart Brackets** - Typing `{` automatically creates the closing `}` with correct indentation. Same for `()`, `[]`, `""`, and `''` +- **Resizable Panels** - Autocomplete and hover info panels can be resized and panned to fit your workspace +- **Keyboard Shortcut Overlay** - Press a button to see all available shortcuts at a glance + +--- + +## Java Scripting ☕ + +Write scripts in **real Java** instead of JavaScript! Powered by the **Janino** compiler, your Java code is compiled and runs natively. + +- **Full Java Language** - Use classes, interfaces, enums, generics, lambdas, and everything you know from Java +- **Automatic Hook Resolution** - Just name your methods after the hook you want (e.g., `init`, `tick`, `interact`) and they're wired up automatically +- **Language Selector** - Each script tab has a dropdown to choose between JavaScript and Java. Mix and match across tabs +- **External Files** - Write `.java` scripts in an external editor and they're loaded automatically + +> Java and JavaScript scripts coexist side by side. Pick whichever language fits your workflow! + +--- + +## Client-Side Scripting 🖥️ + +Scripts can now run **on the client** for responsive, visual experiences! + +- **Server Controlled** - Server owners decide whether client scripting is allowed. Players can't enable it on their own +- **Automatic Sync** - Script files are sent from the server to all connected clients on login, and re-synced whenever scripts are reloaded +- **Safe by Default** - Client scripting is off by default and must be explicitly enabled in the server config + +> Client-side scripts open the door to custom UI effects, visual feedback, and client-only hooks -- all while the server stays in full control. + +--- + +## Cloner Tab Overhaul 📂 + +The Cloner now supports **folders** for organizing your saved NPCs, items, and entries! + +- **Folder System** - Create folders and subfolders to keep your cloner organized however you like +- **Full Screen Browser** - A new full-width directory view makes browsing large collections much easier +- **Improved Tabs** - Better tab navigation for switching between cloner categories + +--- + +## Addon API Support 📘 + +Addon developers can now ship **type definitions** alongside their mods, giving scripters full autocomplete and documentation for addon APIs! + +- **Automatic Loading** - Any mod can include API definitions and they'll appear in the script editor automatically +- **Patch Support** - Addons can extend existing CNPC+ types with new methods (e.g., a DBC addon adding `getDBCPlayer()` to the Player type) +- **Full Documentation** - Parameter names, return types, and descriptions all show up in autocomplete and hover info + +> If you're a scripter using addons, you get autocomplete for their APIs with zero setup. If you're an addon developer, just include your definitions and everything works. + +--- + +## Animation Improvements 🎬 + +- **Data Store** - Animations can now store and pass data across events and frames for more complex animation logic +- **Task System** - A new consumer-based system for reacting to animation lifecycle events, replacing the old approach +- **Expanded API** - More animation control exposed to the scripting API + +--- + +## Animated Textures 🖼️ + +Items and effects now support **frame-based animated textures**! + +- **Linked & Scripted Items** - Configure animated textures with custom frame count and frame time +- **Custom Effects** - Custom effect icons support animation with the same frame system +- **Configurable** - Set frames per row, ticks per frame, and interpolation between frames + +--- + +## NPC API Additions 🧩 + +New scripting API properties for finer control over NPC behavior and appearance: + +- **Hitbox Data** - Scale NPC hitbox width and height independently via `IHitboxData` +- **Tint Data** - Control hurt tint (damage flash) and apply persistent color tints with alpha via `ITintData` +- **Behavior Properties** - Sprint, swim, door interaction, and walking range are now scriptable +- **Sound Control** - Full sound management via `ISound` with volume, pitch, repeat, and position +- **Error Reporting** - Script action exceptions now report to the Script Console with full stack traces instead of failing silently + +--- + +## Additional Changes 🔧 + +- **Player Dialog Events** - Now work the same way as NPC Dialog Events for consistency +- **Linked Item Attack Speed** - Added attack speed configuration to linked items +- **Trader Balance Preview** - Client-side balance prediction shows your expected balance during trades +- **Right-Click Cycling** - Multi-option NPC buttons (Hair, Eyes, Fur, etc.) can now be right-clicked to cycle backwards +- **Quest Cooldown Fix** - Fixed cooldown not working for MC Custom and RL Custom timer types +- **Bard Music Fix** - Fixed music restarting or duplicating when opening dialogs +- **Biome Spawn Fix** - Fixed NPC biome spawn settings not saving after editing +- **Block Waypoint Fix** - Fixed issues with block waypoints +- **Script Config Fix** - Fixed script configuration not syncing properly between server and client + +--- diff --git a/build.gradle b/build.gradle index b76ad9d0c..a76186d6d 100644 --- a/build.gradle +++ b/build.gradle @@ -3,9 +3,10 @@ plugins { id 'com.gtnewhorizons.gtnhconvention' id 'idea' + id "dts.typescript-generator" } -version = "1.10.3" +version = "1.11" group= "kamkeel.customnpc-plus" archivesBaseName = "CustomNPC-Plus" @@ -31,6 +32,21 @@ tasks.create('buildNoMixin', Exec) { commandLine gradleWrapper, 'build', '-Pnomixin' } +// No Nashorn Run Tasks +tasks.create('runClientNoNashorn', Exec) { + description 'Runs the client without Nashorn' + group 'CustomNPC+' + workingDir project.rootDir + commandLine gradleWrapper, 'runClient', '-PnoNashorn' +} + +tasks.create('runServerNoNashorn', Exec) { + description 'Runs the server without Nashorn' + group 'CustomNPC+' + workingDir project.rootDir + commandLine gradleWrapper, 'runServer', '-PnoNashorn' +} + sourceSets.main.java { def apiDir = file('src/api/java') @@ -41,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 a7c959872..33eb048c1 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -35,8 +35,18 @@ */ def embedMixin = !project.hasProperty("nomixin"); dependencies { - runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev") - runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946") + runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.44-GTNH:dev") + if (!project.hasProperty("noNashorn")) { + runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946") + } + +// 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")) + + testImplementation("junit:junit:4.13.2") if(embedMixin){ // Normal Jar will include built in Mixins diff --git a/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md b/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md deleted file mode 100644 index fb1c33158..000000000 --- a/docs/CNPC_1.11_MARKET_UPDATE_PLAN.md +++ /dev/null @@ -1,1871 +0,0 @@ -# CustomNPC+ 1.11 Market Update - Implementation Plan - -## Overview - -This document outlines the implementation plan for the CustomNPC+ 1.11 update, focusing on three major features: - -1. **Auction House** - A new NPC role allowing players to access a global auction system -2. **Currency System** - Built-in currency integration with VaultAPI for Bukkit hybrid servers -3. **Trader Enhancements** - Stock/Inventory system with per-player/per-server options and reset timers - ---- - -## Table of Contents - -1. [Architecture Overview](#architecture-overview) -2. [Feature 1: Currency System](#feature-1-currency-system) -3. [Feature 2: Trader Enhancements](#feature-2-trader-enhancements) -4. [Feature 3: Auction House](#feature-3-auction-house) -5. [Implementation Order](#implementation-order) -6. [File Summary](#file-summary) -7. [Testing Strategy](#testing-strategy) - ---- - -## Architecture Overview - -### Current Codebase Patterns - -The implementation will follow existing patterns found in the codebase: - -| Pattern | Used By | Will Be Applied To | -|---------|---------|-------------------| -| Singleton Controller | `BankController`, `QuestController` | `AuctionController`, `CurrencyController` | -| Role Interface | `RoleTrader`, `RoleBank` | `RoleAuctioneer` | -| Player Data Extension | `PlayerBankData`, `PlayerQuestData` | `PlayerAuctionData`, `PlayerCurrencyData` | -| Cooldown System | `Quest.repeat`, `JobItemGiver` | Trader Stock Reset | -| Optional Addon | `PixelmonHelper`, `DBCAddon` | `VaultHelper` | -| NBT Serialization | All data classes | All new data classes | -| Cache System | `Market.java`, `CacheHashMap` | Auction listings cache | - -### Package Structure for New Features - -``` -noppes/npcs/ -├── controllers/ -│ ├── AuctionController.java # Manages global auction house -│ ├── CurrencyController.java # Manages currency settings -│ └── data/ -│ ├── AuctionListing.java # Single auction listing -│ ├── AuctionData.java # World auction data -│ ├── PlayerAuctionData.java # Per-player auction history -│ ├── PlayerCurrencyData.java # Per-player currency balance -│ └── TraderStock.java # Trader stock configuration -├── roles/ -│ └── RoleAuctioneer.java # Auctioneer NPC role -├── containers/ -│ ├── ContainerAuction*.java # Auction GUI containers -│ └── ContainerNPCTraderStock.java # Stock management container -├── client/gui/ -│ ├── player/ -│ │ └── GuiAuction*.java # Player-facing auction GUIs -│ └── roles/ -│ └── GuiNpcAuctioneerSetup.java # Auctioneer configuration GUI - -kamkeel/npcs/ -├── controllers/ -│ └── CurrencyController.java # Currency management -├── network/packets/ -│ ├── data/ -│ │ ├── AuctionSyncPacket.java # Sync auction data -│ │ └── CurrencySyncPacket.java # Sync currency data -│ └── player/ -│ ├── AuctionActionPacket.java # Auction actions (bid, buy, sell) -│ └── CurrencyActionPacket.java # Currency transactions -└── compat/ - └── VaultHelper.java # VaultAPI integration -``` - ---- - -## Feature 1: Currency System - -### 1.1 Overview - -The currency system provides a unified economy layer that can: -- Use VaultAPI when available on Bukkit hybrid servers (Cauldron, Thermos, Mohist) -- Fall back to an internal item-based currency when VaultAPI is unavailable -- Be configured per-world or globally - -### 1.2 VaultAPI Integration - -#### 1.2.1 Dependency Setup - -**File: `dependencies.gradle`** -```gradle -// VaultAPI - compile-only for optional integration -compileOnly("net.milkbowl.vault:VaultAPI:1.4") { - transitive = false -} -``` - -**File: `repositories.gradle`** -```gradle -maven { - name = "vault-repo" - url = "https://nexus.hc.to/content/repositories/pub_releases/" -} -``` - -> **Note:** VaultAPI 1.4.1 works with 1.7.10 Bukkit hybrid servers. The dependency is compile-only so the mod works without Vault present. - -#### 1.2.2 VaultHelper Class - -**File: `src/main/java/kamkeel/npcs/compat/VaultHelper.java`** - -```java -package kamkeel.npcs.compat; - -import cpw.mods.fml.common.Loader; -import net.minecraft.entity.player.EntityPlayer; -import noppes.npcs.LogWriter; -import org.bukkit.Bukkit; -import org.bukkit.plugin.RegisteredServiceProvider; - -public class VaultHelper { - public static boolean Enabled = false; - public static boolean Available = false; - - // Cached via reflection - private static Object economy = null; - private static Class economyClass = null; - private static java.lang.reflect.Method getBalance; - private static java.lang.reflect.Method withdrawPlayer; - private static java.lang.reflect.Method depositPlayer; - private static java.lang.reflect.Method hasMethod; - private static java.lang.reflect.Method format; - - public static void load() { - // Check if we're on a Bukkit hybrid server - try { - Class.forName("org.bukkit.Bukkit"); - Available = true; - } catch (ClassNotFoundException e) { - Available = false; - return; - } - - // Try to hook into Vault - try { - Class vaultClass = Class.forName("net.milkbowl.vault.economy.Economy"); - economyClass = vaultClass; - - RegisteredServiceProvider rsp = Bukkit.getServicesManager() - .getRegistration(vaultClass); - - if (rsp != null) { - economy = rsp.getProvider(); - - // Cache reflection methods - getBalance = economyClass.getMethod("getBalance", String.class); - withdrawPlayer = economyClass.getMethod("withdrawPlayer", - String.class, double.class); - depositPlayer = economyClass.getMethod("depositPlayer", - String.class, double.class); - hasMethod = economyClass.getMethod("has", String.class, double.class); - format = economyClass.getMethod("format", double.class); - - Enabled = true; - LogWriter.info("VaultAPI Economy hooked successfully!"); - } - } catch (Exception e) { - LogWriter.info("VaultAPI not available: " + e.getMessage()); - Enabled = false; - } - } - - // Economy Methods - public static double getBalance(EntityPlayer player) { - if (!Enabled) return 0.0; - try { - return (Double) getBalance.invoke(economy, player.getCommandSenderName()); - } catch (Exception e) { - LogWriter.except(e); - return 0.0; - } - } - - public static boolean withdraw(EntityPlayer player, double amount) { - if (!Enabled) return false; - try { - Object response = withdrawPlayer.invoke(economy, - player.getCommandSenderName(), amount); - return (Boolean) response.getClass() - .getMethod("transactionSuccess").invoke(response); - } catch (Exception e) { - LogWriter.except(e); - return false; - } - } - - public static boolean deposit(EntityPlayer player, double amount) { - if (!Enabled) return false; - try { - Object response = depositPlayer.invoke(economy, - player.getCommandSenderName(), amount); - return (Boolean) response.getClass() - .getMethod("transactionSuccess").invoke(response); - } catch (Exception e) { - LogWriter.except(e); - return false; - } - } - - public static boolean has(EntityPlayer player, double amount) { - if (!Enabled) return false; - try { - return (Boolean) hasMethod.invoke(economy, - player.getCommandSenderName(), amount); - } catch (Exception e) { - LogWriter.except(e); - return false; - } - } - - public static String formatCurrency(double amount) { - if (!Enabled) return String.format("%.2f", amount); - try { - return (String) format.invoke(economy, amount); - } catch (Exception e) { - return String.format("%.2f", amount); - } - } -} -``` - -#### 1.2.3 Initialization Hook - -**File: `src/main/java/noppes/npcs/CustomNpcs.java`** - -Add to `load()` method after AddonManager: -```java -// Initialize VaultAPI integration (for Bukkit hybrid servers) -VaultHelper.load(); -``` - -### 1.3 Currency Controller - -**File: `src/main/java/kamkeel/npcs/controllers/CurrencyController.java`** - -```java -package kamkeel.npcs.controllers; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import kamkeel.npcs.compat.VaultHelper; -import noppes.npcs.NoppesUtilPlayer; - -public class CurrencyController { - private static CurrencyController instance; - - // Configuration - public boolean useVaultIfAvailable = true; - public ItemStack fallbackCurrency = null; // Item to use when Vault unavailable - public double itemToVaultRatio = 1.0; // 1 item = X vault currency - - public static CurrencyController getInstance() { - if (instance == null) { - instance = new CurrencyController(); - } - return instance; - } - - /** - * Check if Vault economy is being used - */ - public boolean isUsingVault() { - return useVaultIfAvailable && VaultHelper.Enabled; - } - - /** - * Get player's balance (Vault or item count) - */ - public double getBalance(EntityPlayer player) { - if (isUsingVault()) { - return VaultHelper.getBalance(player); - } - // Fall back to counting items - if (fallbackCurrency != null) { - return NoppesUtilPlayer.countItems(player, fallbackCurrency, false, false); - } - return 0.0; - } - - /** - * Check if player can afford amount - */ - public boolean canAfford(EntityPlayer player, double amount) { - if (isUsingVault()) { - return VaultHelper.has(player, amount); - } - return getBalance(player) >= amount; - } - - /** - * Withdraw currency from player - */ - public boolean withdraw(EntityPlayer player, double amount) { - if (isUsingVault()) { - return VaultHelper.withdraw(player, amount); - } - // Remove items - if (fallbackCurrency != null) { - ItemStack toRemove = fallbackCurrency.copy(); - toRemove.stackSize = (int) Math.ceil(amount / itemToVaultRatio); - return NoppesUtilPlayer.consumeItem(player, toRemove, false, false); - } - return false; - } - - /** - * Deposit currency to player - */ - public boolean deposit(EntityPlayer player, double amount) { - if (isUsingVault()) { - return VaultHelper.deposit(player, amount); - } - // Give items - if (fallbackCurrency != null) { - ItemStack toGive = fallbackCurrency.copy(); - toGive.stackSize = (int) Math.floor(amount / itemToVaultRatio); - return player.inventory.addItemStackToInventory(toGive); - } - return false; - } - - /** - * Format currency for display - */ - public String format(double amount) { - if (isUsingVault()) { - return VaultHelper.formatCurrency(amount); - } - return String.format("%.0f", amount); - } - - // NBT Persistence - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setBoolean("UseVault", useVaultIfAvailable); - compound.setDouble("ItemRatio", itemToVaultRatio); - if (fallbackCurrency != null) { - compound.setTag("FallbackItem", fallbackCurrency.writeToNBT(new NBTTagCompound())); - } - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - useVaultIfAvailable = compound.getBoolean("UseVault"); - itemToVaultRatio = compound.getDouble("ItemRatio"); - if (compound.hasKey("FallbackItem")) { - fallbackCurrency = ItemStack.loadItemStackFromNBT( - compound.getCompoundTag("FallbackItem")); - } - } -} -``` - -### 1.4 Player Currency Data - -**File: `src/main/java/noppes/npcs/controllers/data/PlayerCurrencyData.java`** - -```java -package noppes.npcs.controllers.data; - -import net.minecraft.nbt.NBTTagCompound; -import java.util.HashMap; - -public class PlayerCurrencyData { - private final PlayerData parent; - - // Transaction history (for auditing/display) - public HashMap transactionHistory = new HashMap<>(); - public double totalEarned = 0.0; - public double totalSpent = 0.0; - - public PlayerCurrencyData(PlayerData parent) { - this.parent = parent; - } - - public void recordTransaction(double amount, boolean isEarning) { - long timestamp = System.currentTimeMillis(); - transactionHistory.put(timestamp, isEarning ? amount : -amount); - if (isEarning) { - totalEarned += amount; - } else { - totalSpent += amount; - } - // Limit history size - if (transactionHistory.size() > 100) { - // Remove oldest entries - Long oldest = transactionHistory.keySet().stream() - .min(Long::compare).orElse(null); - if (oldest != null) { - transactionHistory.remove(oldest); - } - } - } - - public void loadNBTData(NBTTagCompound compound) { - if (compound.hasKey("CurrencyData")) { - NBTTagCompound data = compound.getCompoundTag("CurrencyData"); - totalEarned = data.getDouble("TotalEarned"); - totalSpent = data.getDouble("TotalSpent"); - } - } - - public void saveNBTData(NBTTagCompound compound) { - NBTTagCompound data = new NBTTagCompound(); - data.setDouble("TotalEarned", totalEarned); - data.setDouble("TotalSpent", totalSpent); - compound.setTag("CurrencyData", data); - } -} -``` - -### 1.5 Configuration UI - -Add currency configuration to the global settings GUI: - -**File: `src/main/java/noppes/npcs/client/gui/global/GuiNPCManageCurrency.java`** - -This GUI will allow server operators to: -- Enable/disable Vault integration -- Set fallback currency item -- Configure item-to-Vault ratio -- View server economy statistics - ---- - -## Feature 2: Trader Enhancements - -### 2.1 Overview - -Enhance the existing `RoleTrader` with: -- **Stock System**: Limited inventory that depletes when players buy -- **Per-Player vs Per-Server Stock**: Configure whether stock is shared or individual -- **Stock Reset Timer**: Automatic restocking based on configurable cooldown (like quest cooldowns) -- **Currency Integration**: Use Vault currency alongside or instead of item-based trading - -### 2.2 Trader Stock Configuration - -#### 2.2.1 Stock Data Class - -**File: `src/main/java/noppes/npcs/controllers/data/TraderStock.java`** - -```java -package noppes.npcs.controllers.data; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import java.util.HashMap; - -public class TraderStock { - // Stock configuration - public boolean enableStock = false; - public boolean perPlayer = false; // false = per-server, true = per-player - - // Reset configuration (mirrors Quest cooldown system) - public EnumStockReset resetType = EnumStockReset.NONE; - public long customResetTime = 0; // For MCCUSTOM/RLCUSTOM types - - // Stock quantities per slot (max stock) - public int[] maxStock = new int[18]; - - // Current stock (per-server mode) - public int[] currentStock = new int[18]; - public long lastResetTime = 0; - - // Per-player stock tracking - public HashMap playerStock = new HashMap<>(); - - public TraderStock() { - for (int i = 0; i < 18; i++) { - maxStock[i] = -1; // -1 = unlimited - currentStock[i] = -1; - } - } - - /** - * Get available stock for a slot - */ - public int getAvailableStock(int slot, String playerName) { - if (!enableStock || maxStock[slot] < 0) { - return Integer.MAX_VALUE; // Unlimited - } - - if (perPlayer) { - PlayerTraderStock pStock = playerStock.get(playerName); - if (pStock == null) { - return maxStock[slot]; // Not purchased yet - } - return pStock.getStock(slot, maxStock[slot]); - } - - return currentStock[slot]; - } - - /** - * Consume stock when purchase is made - */ - public boolean consumeStock(int slot, String playerName, int amount) { - if (!enableStock || maxStock[slot] < 0) { - return true; // Unlimited - } - - if (perPlayer) { - PlayerTraderStock pStock = playerStock.computeIfAbsent( - playerName, k -> new PlayerTraderStock()); - return pStock.consumeStock(slot, maxStock[slot], amount); - } - - if (currentStock[slot] >= amount) { - currentStock[slot] -= amount; - return true; - } - return false; - } - - /** - * Check if stock should reset - */ - public boolean shouldReset(long currentTime) { - if (resetType == EnumStockReset.NONE) { - return false; - } - - long elapsed = currentTime - lastResetTime; - long resetInterval = getResetInterval(); - - return elapsed >= resetInterval; - } - - /** - * Reset all stock to max values - */ - public void resetStock(long currentTime) { - lastResetTime = currentTime; - - for (int i = 0; i < 18; i++) { - currentStock[i] = maxStock[i]; - } - - // Clear per-player stock - playerStock.clear(); - } - - /** - * Get reset interval in milliseconds - */ - public long getResetInterval() { - switch (resetType) { - case MCDAILY: - return 24000 * 50; // 24000 ticks * 50ms - case MCWEEKLY: - return 168000 * 50; - case MCCUSTOM: - return customResetTime * 50; - case RLDAILY: - return 86400000L; // 24 hours in ms - case RLWEEKLY: - return 604800000L; // 7 days in ms - case RLCUSTOM: - return customResetTime; - default: - return Long.MAX_VALUE; - } - } - - /** - * Get time until next reset (for display) - */ - public long getTimeUntilReset(long currentTime) { - if (resetType == EnumStockReset.NONE) { - return -1; - } - long elapsed = currentTime - lastResetTime; - long interval = getResetInterval(); - return Math.max(0, interval - elapsed); - } - - // NBT Serialization - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setBoolean("EnableStock", enableStock); - compound.setBoolean("PerPlayer", perPlayer); - compound.setInteger("ResetType", resetType.ordinal()); - compound.setLong("CustomResetTime", customResetTime); - compound.setIntArray("MaxStock", maxStock); - compound.setIntArray("CurrentStock", currentStock); - compound.setLong("LastResetTime", lastResetTime); - - // Save per-player stock - NBTTagList playerList = new NBTTagList(); - for (Map.Entry entry : playerStock.entrySet()) { - NBTTagCompound playerTag = new NBTTagCompound(); - playerTag.setString("Player", entry.getKey()); - entry.getValue().writeToNBT(playerTag); - playerList.appendTag(playerTag); - } - compound.setTag("PlayerStock", playerList); - - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - enableStock = compound.getBoolean("EnableStock"); - perPlayer = compound.getBoolean("PerPlayer"); - resetType = EnumStockReset.values()[compound.getInteger("ResetType")]; - customResetTime = compound.getLong("CustomResetTime"); - maxStock = compound.getIntArray("MaxStock"); - currentStock = compound.getIntArray("CurrentStock"); - lastResetTime = compound.getLong("LastResetTime"); - - // Load per-player stock - NBTTagList playerList = compound.getTagList("PlayerStock", 10); - for (int i = 0; i < playerList.tagCount(); i++) { - NBTTagCompound playerTag = playerList.getCompoundTagAt(i); - String playerName = playerTag.getString("Player"); - PlayerTraderStock pStock = new PlayerTraderStock(); - pStock.readFromNBT(playerTag); - playerStock.put(playerName, pStock); - } - } -} - -// Inner class for per-player stock tracking -class PlayerTraderStock { - public int[] purchasedAmounts = new int[18]; - public long lastPurchaseTime = 0; - - public int getStock(int slot, int maxStock) { - return Math.max(0, maxStock - purchasedAmounts[slot]); - } - - public boolean consumeStock(int slot, int maxStock, int amount) { - if (getStock(slot, maxStock) >= amount) { - purchasedAmounts[slot] += amount; - lastPurchaseTime = System.currentTimeMillis(); - return true; - } - return false; - } - - public void writeToNBT(NBTTagCompound compound) { - compound.setIntArray("Purchased", purchasedAmounts); - compound.setLong("LastPurchase", lastPurchaseTime); - } - - public void readFromNBT(NBTTagCompound compound) { - purchasedAmounts = compound.getIntArray("Purchased"); - lastPurchaseTime = compound.getLong("LastPurchase"); - } -} -``` - -#### 2.2.2 Stock Reset Enum - -**File: `src/main/java/noppes/npcs/constants/EnumStockReset.java`** - -```java -package noppes.npcs.constants; - -public enum EnumStockReset { - NONE, // Never resets - MCDAILY, // Every 24000 MC ticks (1 MC day) - MCWEEKLY, // Every 168000 MC ticks (7 MC days) - MCCUSTOM, // Custom MC tick interval - RLDAILY, // Every 24 real hours - RLWEEKLY, // Every 7 real days - RLCUSTOM // Custom real-time interval -} -``` - -### 2.3 RoleTrader Modifications - -**File: `src/main/java/noppes/npcs/roles/RoleTrader.java`** - -Add the following to `RoleTrader`: - -```java -// Add new fields -public TraderStock stock = new TraderStock(); -public boolean useCurrency = false; // Use Vault/Currency system -public double[] slotPrices = new double[18]; // Currency prices per slot - -// Modify interact() to check stock reset -@Override -public void interact(EntityPlayer player) { - // Check for stock reset before opening GUI - if (stock.enableStock) { - long currentTime = stock.resetType.name().startsWith("RL") - ? System.currentTimeMillis() - : player.worldObj.getTotalWorldTime(); - - if (stock.shouldReset(currentTime)) { - stock.resetStock(currentTime); - // Save to market if using shared market - if (!marketName.isEmpty()) { - Market.save(this, marketName); - } - } - } - - npc.say(player, npc.advanced.getInteractLine()); - NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerTrader, npc); -} - -// Modify writeToNBT -@Override -public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { - // ... existing code ... - - // Add stock data - nbttagcompound.setTag("Stock", stock.writeToNBT(new NBTTagCompound())); - nbttagcompound.setBoolean("UseCurrency", useCurrency); - - // Save currency prices - NBTTagList priceList = new NBTTagList(); - for (double price : slotPrices) { - NBTTagCompound priceTag = new NBTTagCompound(); - priceTag.setDouble("Price", price); - priceList.appendTag(priceTag); - } - nbttagcompound.setTag("SlotPrices", priceList); - - return nbttagcompound; -} - -// Modify readFromNBT -@Override -public void readFromNBT(NBTTagCompound nbttagcompound) { - // ... existing code ... - - // Load stock data - if (nbttagcompound.hasKey("Stock")) { - stock.readFromNBT(nbttagcompound.getCompoundTag("Stock")); - } - useCurrency = nbttagcompound.getBoolean("UseCurrency"); - - // Load currency prices - if (nbttagcompound.hasKey("SlotPrices")) { - NBTTagList priceList = nbttagcompound.getTagList("SlotPrices", 10); - for (int i = 0; i < priceList.tagCount() && i < 18; i++) { - slotPrices[i] = priceList.getCompoundTagAt(i).getDouble("Price"); - } - } -} -``` - -### 2.4 ContainerNPCTrader Modifications - -**File: `src/main/java/noppes/npcs/containers/ContainerNPCTrader.java`** - -Modify `slotClick()` to handle stock and currency: - -```java -public ItemStack slotClick(int slotIndex, EntityPlayer player) { - RoleTrader role = (RoleTrader) npc.roleInterface; - String playerName = player.getCommandSenderName(); - - // ... existing validation ... - - // Check stock availability - if (role.stock.enableStock) { - int available = role.stock.getAvailableStock(slotIndex, playerName); - if (available <= 0) { - // Out of stock - send message to player - return null; - } - } - - // Handle currency-based purchase - if (role.useCurrency && role.slotPrices[slotIndex] > 0) { - double price = role.slotPrices[slotIndex]; - CurrencyController currency = CurrencyController.getInstance(); - - if (!currency.canAfford(player, price)) { - // Can't afford - send message - return null; - } - - // Withdraw currency - if (!currency.withdraw(player, price)) { - return null; - } - } else { - // ... existing item-based currency logic ... - } - - // Consume stock - if (role.stock.enableStock) { - role.stock.consumeStock(slotIndex, playerName, 1); - } - - // ... existing item delivery logic ... - - // Save if using market - if (!role.marketName.isEmpty()) { - Market.save(role, role.marketName); - } - - return soldItem; -} -``` - -### 2.5 Trader Setup GUI Additions - -**File: `src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java`** - -Add new configuration options: - -```java -// Add buttons/fields for: -// - "Enable Stock" toggle -// - "Per Player" / "Per Server" radio buttons -// - "Reset Type" dropdown (None, MC Daily, MC Weekly, etc.) -// - "Custom Reset Time" field -// - "Use Currency" toggle -// - Per-slot stock quantity inputs -// - Per-slot currency price inputs - -private void initStockGui() { - addButton(new GuiNpcButton(20, x, y, 80, 20, - "Enable Stock: " + (role.stock.enableStock ? "Yes" : "No"))); - - addButton(new GuiNpcButton(21, x, y + 22, 80, 20, - role.stock.perPlayer ? "Per Player" : "Per Server")); - - String[] resetTypes = {"None", "MC Daily", "MC Weekly", "MC Custom", - "RL Daily", "RL Weekly", "RL Custom"}; - addButton(new GuiNpcButton(22, x, y + 44, 80, 20, resetTypes, - role.stock.resetType.ordinal())); - - addButton(new GuiNpcButton(23, x, y + 66, 80, 20, - "Use Currency: " + (role.useCurrency ? "Yes" : "No"))); -} -``` - ---- - -## Feature 3: Auction House - -### 3.1 Overview - -The Auction House is a global trading system where players can: -- **List items for sale** at fixed prices or as auctions with bidding -- **Browse listings** by category, search, and filter -- **Bid on auctions** with automatic outbid notifications -- **Buy instantly** for buy-it-now prices -- **Manage their listings** (cancel, modify) -- **Collect proceeds and expired items** via mailbox or direct claim - -### 3.2 Auction Data Structures - -#### 3.2.1 AuctionListing - -**File: `src/main/java/noppes/npcs/controllers/data/AuctionListing.java`** - -```java -package noppes.npcs.controllers.data; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import java.util.UUID; - -public class AuctionListing { - public int id; - public UUID sellerUUID; - public String sellerName; - public ItemStack item; - - // Pricing - public double startingPrice; - public double buyoutPrice; // 0 = no buyout - public double currentBid; - public UUID highBidderUUID; - public String highBidderName; - - // Timing - public long listingTime; - public long expirationTime; - public EnumAuctionDuration duration; - - // Status - public EnumAuctionStatus status = EnumAuctionStatus.ACTIVE; - - // Category - public EnumAuctionCategory category = EnumAuctionCategory.MISC; - - public AuctionListing() {} - - public AuctionListing(UUID seller, String sellerName, ItemStack item, - double startPrice, double buyout, EnumAuctionDuration duration) { - this.sellerUUID = seller; - this.sellerName = sellerName; - this.item = item.copy(); - this.startingPrice = startPrice; - this.buyoutPrice = buyout; - this.currentBid = startPrice; - this.duration = duration; - this.listingTime = System.currentTimeMillis(); - this.expirationTime = listingTime + duration.getMillis(); - this.category = categorizeItem(item); - } - - /** - * Check if auction has expired - */ - public boolean isExpired() { - return System.currentTimeMillis() >= expirationTime; - } - - /** - * Get time remaining in milliseconds - */ - public long getTimeRemaining() { - return Math.max(0, expirationTime - System.currentTimeMillis()); - } - - /** - * Place a bid - */ - public boolean placeBid(UUID bidder, String bidderName, double amount) { - if (status != EnumAuctionStatus.ACTIVE) return false; - if (amount <= currentBid) return false; - if (bidder.equals(sellerUUID)) return false; // Can't bid on own item - - // Minimum bid increment (5% or 1, whichever is greater) - double minIncrement = Math.max(1, currentBid * 0.05); - if (amount < currentBid + minIncrement) return false; - - highBidderUUID = bidder; - highBidderName = bidderName; - currentBid = amount; - - return true; - } - - /** - * Execute buyout - */ - public boolean buyout(UUID buyer, String buyerName) { - if (status != EnumAuctionStatus.ACTIVE) return false; - if (buyoutPrice <= 0) return false; // No buyout available - if (buyer.equals(sellerUUID)) return false; - - highBidderUUID = buyer; - highBidderName = buyerName; - currentBid = buyoutPrice; - status = EnumAuctionStatus.SOLD; - - return true; - } - - /** - * Cancel listing (seller only, before any bids) - */ - public boolean cancel(UUID requester) { - if (!requester.equals(sellerUUID)) return false; - if (highBidderUUID != null) return false; // Has bids, can't cancel - - status = EnumAuctionStatus.CANCELLED; - return true; - } - - /** - * Auto-categorize item based on type - */ - private EnumAuctionCategory categorizeItem(ItemStack item) { - // Implement item categorization logic - // Check for weapons, armor, tools, food, blocks, etc. - return EnumAuctionCategory.MISC; - } - - // NBT Serialization - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setInteger("Id", id); - compound.setString("SellerUUID", sellerUUID.toString()); - compound.setString("SellerName", sellerName); - compound.setTag("Item", item.writeToNBT(new NBTTagCompound())); - compound.setDouble("StartPrice", startingPrice); - compound.setDouble("BuyoutPrice", buyoutPrice); - compound.setDouble("CurrentBid", currentBid); - if (highBidderUUID != null) { - compound.setString("BidderUUID", highBidderUUID.toString()); - compound.setString("BidderName", highBidderName); - } - compound.setLong("ListingTime", listingTime); - compound.setLong("ExpirationTime", expirationTime); - compound.setInteger("Duration", duration.ordinal()); - compound.setInteger("Status", status.ordinal()); - compound.setInteger("Category", category.ordinal()); - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - id = compound.getInteger("Id"); - sellerUUID = UUID.fromString(compound.getString("SellerUUID")); - sellerName = compound.getString("SellerName"); - item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); - startingPrice = compound.getDouble("StartPrice"); - buyoutPrice = compound.getDouble("BuyoutPrice"); - currentBid = compound.getDouble("CurrentBid"); - if (compound.hasKey("BidderUUID")) { - highBidderUUID = UUID.fromString(compound.getString("BidderUUID")); - highBidderName = compound.getString("BidderName"); - } - listingTime = compound.getLong("ListingTime"); - expirationTime = compound.getLong("ExpirationTime"); - duration = EnumAuctionDuration.values()[compound.getInteger("Duration")]; - status = EnumAuctionStatus.values()[compound.getInteger("Status")]; - category = EnumAuctionCategory.values()[compound.getInteger("Category")]; - } -} -``` - -#### 3.2.2 Supporting Enums - -**File: `src/main/java/noppes/npcs/constants/EnumAuctionDuration.java`** - -```java -package noppes.npcs.constants; - -public enum EnumAuctionDuration { - SHORT(2 * 60 * 60 * 1000L), // 2 hours - MEDIUM(12 * 60 * 60 * 1000L), // 12 hours - LONG(24 * 60 * 60 * 1000L), // 24 hours - VERY_LONG(48 * 60 * 60 * 1000L); // 48 hours - - private final long millis; - - EnumAuctionDuration(long millis) { - this.millis = millis; - } - - public long getMillis() { - return millis; - } - - public String getDisplayName() { - switch (this) { - case SHORT: return "2 Hours"; - case MEDIUM: return "12 Hours"; - case LONG: return "24 Hours"; - case VERY_LONG: return "48 Hours"; - default: return "Unknown"; - } - } -} -``` - -**File: `src/main/java/noppes/npcs/constants/EnumAuctionStatus.java`** - -```java -package noppes.npcs.constants; - -public enum EnumAuctionStatus { - ACTIVE, // Currently listed - SOLD, // Successfully sold (buyout or auction end with bids) - EXPIRED, // Ended without bids - CANCELLED, // Cancelled by seller - CLAIMED // Item/money has been claimed -} -``` - -**File: `src/main/java/noppes/npcs/constants/EnumAuctionCategory.java`** - -```java -package noppes.npcs.constants; - -public enum EnumAuctionCategory { - WEAPONS, - ARMOR, - TOOLS, - FOOD, - POTIONS, - BLOCKS, - MATERIALS, - ENCHANTED, - MISC -} -``` - -### 3.3 Auction Controller - -**File: `src/main/java/noppes/npcs/controllers/AuctionController.java`** - -```java -package noppes.npcs.controllers; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import noppes.npcs.CustomNpcs; -import noppes.npcs.LogWriter; -import noppes.npcs.controllers.data.AuctionListing; -import noppes.npcs.constants.*; - -import java.io.File; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -public class AuctionController { - private static AuctionController instance; - - // All listings (thread-safe for async operations) - public ConcurrentHashMap listings = new ConcurrentHashMap<>(); - - // Index by seller for quick lookup - private Map> sellerIndex = new ConcurrentHashMap<>(); - - // Pending claims (seller -> items/money to claim) - public Map> pendingClaims = new ConcurrentHashMap<>(); - - private int nextId = 1; - private long lastSaveTime = 0; - private static final long SAVE_INTERVAL = 60000; // Save every minute - - // Configuration - public double listingFee = 0.0; // Fee to list item - public double saleTax = 0.05; // 5% tax on sales - public int maxListingsPerPlayer = 20; - public boolean requireAuctioneer = true; // Require Auctioneer NPC to access - - public static AuctionController getInstance() { - if (instance == null) { - instance = new AuctionController(); - instance.load(); - } - return instance; - } - - /** - * Create a new auction listing - */ - public AuctionListing createListing(EntityPlayer seller, ItemStack item, - double startPrice, double buyout, - EnumAuctionDuration duration) { - UUID sellerUUID = seller.getUniqueID(); - - // Check max listings - Set sellerListings = sellerIndex.get(sellerUUID); - if (sellerListings != null && sellerListings.size() >= maxListingsPerPlayer) { - return null; - } - - // Charge listing fee - if (listingFee > 0) { - CurrencyController currency = CurrencyController.getInstance(); - if (!currency.withdraw(seller, listingFee)) { - return null; - } - } - - // Create listing - AuctionListing listing = new AuctionListing( - sellerUUID, seller.getCommandSenderName(), - item, startPrice, buyout, duration - ); - listing.id = nextId++; - - // Add to indexes - listings.put(listing.id, listing); - sellerIndex.computeIfAbsent(sellerUUID, k -> new HashSet<>()).add(listing.id); - - // Remove item from seller inventory - item.stackSize = 0; - - scheduleSave(); - return listing; - } - - /** - * Place a bid on an auction - */ - public boolean placeBid(EntityPlayer bidder, int listingId, double amount) { - AuctionListing listing = listings.get(listingId); - if (listing == null || listing.isExpired()) return false; - - CurrencyController currency = CurrencyController.getInstance(); - - // Check if bidder can afford - if (!currency.canAfford(bidder, amount)) return false; - - // Refund previous bidder - if (listing.highBidderUUID != null) { - addClaim(listing.highBidderUUID, listing.highBidderName, - null, listing.currentBid, "Outbid refund for: " + - listing.item.getDisplayName()); - } - - // Place bid - if (!listing.placeBid(bidder.getUniqueID(), - bidder.getCommandSenderName(), amount)) { - return false; - } - - // Hold currency from bidder - currency.withdraw(bidder, amount); - - scheduleSave(); - return true; - } - - /** - * Buyout an auction - */ - public boolean buyout(EntityPlayer buyer, int listingId) { - AuctionListing listing = listings.get(listingId); - if (listing == null || listing.buyoutPrice <= 0) return false; - - CurrencyController currency = CurrencyController.getInstance(); - - // Check if buyer can afford - if (!currency.canAfford(buyer, listing.buyoutPrice)) return false; - - // Refund previous bidder if any - if (listing.highBidderUUID != null) { - addClaim(listing.highBidderUUID, listing.highBidderName, - null, listing.currentBid, "Buyout refund for: " + - listing.item.getDisplayName()); - } - - // Execute buyout - if (!listing.buyout(buyer.getUniqueID(), buyer.getCommandSenderName())) { - return false; - } - - // Withdraw from buyer - currency.withdraw(buyer, listing.buyoutPrice); - - // Calculate seller proceeds (minus tax) - double proceeds = listing.buyoutPrice * (1 - saleTax); - - // Add claims for both parties - addClaim(listing.sellerUUID, listing.sellerName, null, proceeds, - "Sale of: " + listing.item.getDisplayName()); - addClaim(buyer.getUniqueID(), buyer.getCommandSenderName(), - listing.item, 0, "Purchased: " + listing.item.getDisplayName()); - - scheduleSave(); - return true; - } - - /** - * Cancel a listing (seller only) - */ - public boolean cancelListing(EntityPlayer player, int listingId) { - AuctionListing listing = listings.get(listingId); - if (listing == null) return false; - - if (!listing.cancel(player.getUniqueID())) return false; - - // Return item to seller - addClaim(listing.sellerUUID, listing.sellerName, listing.item, 0, - "Cancelled listing: " + listing.item.getDisplayName()); - - scheduleSave(); - return true; - } - - /** - * Process expired auctions (called periodically) - */ - public void processExpiredAuctions() { - long now = System.currentTimeMillis(); - - for (AuctionListing listing : listings.values()) { - if (listing.status != EnumAuctionStatus.ACTIVE) continue; - if (!listing.isExpired()) continue; - - if (listing.highBidderUUID != null) { - // Auction successful - has bids - listing.status = EnumAuctionStatus.SOLD; - - double proceeds = listing.currentBid * (1 - saleTax); - addClaim(listing.sellerUUID, listing.sellerName, null, proceeds, - "Auction sold: " + listing.item.getDisplayName()); - addClaim(listing.highBidderUUID, listing.highBidderName, - listing.item, 0, "Won auction: " + listing.item.getDisplayName()); - } else { - // No bids - return to seller - listing.status = EnumAuctionStatus.EXPIRED; - addClaim(listing.sellerUUID, listing.sellerName, listing.item, 0, - "Expired listing: " + listing.item.getDisplayName()); - } - } - - scheduleSave(); - } - - /** - * Get active listings with optional filters - */ - public List getActiveListings(EnumAuctionCategory category, - String search, - int page, int pageSize) { - return listings.values().stream() - .filter(l -> l.status == EnumAuctionStatus.ACTIVE) - .filter(l -> !l.isExpired()) - .filter(l -> category == null || l.category == category) - .filter(l -> search == null || search.isEmpty() || - l.item.getDisplayName().toLowerCase() - .contains(search.toLowerCase())) - .sorted(Comparator.comparingLong(l -> l.expirationTime)) - .skip((long) page * pageSize) - .limit(pageSize) - .collect(Collectors.toList()); - } - - /** - * Get player's own listings - */ - public List getPlayerListings(UUID playerUUID) { - Set ids = sellerIndex.get(playerUUID); - if (ids == null) return Collections.emptyList(); - - return ids.stream() - .map(listings::get) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - /** - * Get pending claims for a player - */ - public List getPendingClaims(UUID playerUUID) { - return pendingClaims.getOrDefault(playerUUID, Collections.emptyList()); - } - - /** - * Claim pending items/money - */ - public boolean claim(EntityPlayer player, int claimIndex) { - List claims = pendingClaims.get(player.getUniqueID()); - if (claims == null || claimIndex >= claims.size()) return false; - - AuctionClaim claim = claims.get(claimIndex); - - // Give item or money - if (claim.item != null) { - if (!player.inventory.addItemStackToInventory(claim.item.copy())) { - return false; // Inventory full - } - } - if (claim.money > 0) { - CurrencyController.getInstance().deposit(player, claim.money); - } - - claims.remove(claimIndex); - scheduleSave(); - return true; - } - - private void addClaim(UUID playerUUID, String playerName, - ItemStack item, double money, String description) { - AuctionClaim claim = new AuctionClaim(item, money, description); - pendingClaims.computeIfAbsent(playerUUID, k -> new ArrayList<>()).add(claim); - } - - // Persistence - private void scheduleSave() { - long now = System.currentTimeMillis(); - if (now - lastSaveTime > SAVE_INTERVAL) { - save(); - lastSaveTime = now; - } - } - - public void save() { - try { - NBTTagCompound compound = new NBTTagCompound(); - compound.setInteger("NextId", nextId); - compound.setDouble("ListingFee", listingFee); - compound.setDouble("SaleTax", saleTax); - compound.setInteger("MaxListings", maxListingsPerPlayer); - - // Save listings - NBTTagList listingList = new NBTTagList(); - for (AuctionListing listing : listings.values()) { - listingList.appendTag(listing.writeToNBT(new NBTTagCompound())); - } - compound.setTag("Listings", listingList); - - // Save claims - NBTTagList claimList = new NBTTagList(); - for (Map.Entry> entry : pendingClaims.entrySet()) { - NBTTagCompound playerClaims = new NBTTagCompound(); - playerClaims.setString("UUID", entry.getKey().toString()); - NBTTagList claims = new NBTTagList(); - for (AuctionClaim claim : entry.getValue()) { - claims.appendTag(claim.writeToNBT(new NBTTagCompound())); - } - playerClaims.setTag("Claims", claims); - claimList.appendTag(playerClaims); - } - compound.setTag("PendingClaims", claimList); - - File file = new File(CustomNpcs.getWorldSaveDirectory(), "auction.dat"); - CompressedStreamTools.writeCompressed(compound, - new java.io.FileOutputStream(file)); - - } catch (Exception e) { - LogWriter.except(e); - } - } - - public void load() { - try { - File file = new File(CustomNpcs.getWorldSaveDirectory(), "auction.dat"); - if (!file.exists()) return; - - NBTTagCompound compound = CompressedStreamTools.readCompressed( - new java.io.FileInputStream(file)); - - nextId = compound.getInteger("NextId"); - listingFee = compound.getDouble("ListingFee"); - saleTax = compound.getDouble("SaleTax"); - maxListingsPerPlayer = compound.getInteger("MaxListings"); - - // Load listings - NBTTagList listingList = compound.getTagList("Listings", 10); - for (int i = 0; i < listingList.tagCount(); i++) { - AuctionListing listing = new AuctionListing(); - listing.readFromNBT(listingList.getCompoundTagAt(i)); - listings.put(listing.id, listing); - sellerIndex.computeIfAbsent(listing.sellerUUID, k -> new HashSet<>()) - .add(listing.id); - } - - // Load claims - NBTTagList claimList = compound.getTagList("PendingClaims", 10); - for (int i = 0; i < claimList.tagCount(); i++) { - NBTTagCompound playerClaims = claimList.getCompoundTagAt(i); - UUID playerUUID = UUID.fromString(playerClaims.getString("UUID")); - NBTTagList claims = playerClaims.getTagList("Claims", 10); - List claimsList = new ArrayList<>(); - for (int j = 0; j < claims.tagCount(); j++) { - AuctionClaim claim = new AuctionClaim(); - claim.readFromNBT(claims.getCompoundTagAt(j)); - claimsList.add(claim); - } - pendingClaims.put(playerUUID, claimsList); - } - - } catch (Exception e) { - LogWriter.except(e); - } - } -} - -// Claim data structure -class AuctionClaim { - public ItemStack item; - public double money; - public String description; - public long timestamp; - - public AuctionClaim() {} - - public AuctionClaim(ItemStack item, double money, String description) { - this.item = item != null ? item.copy() : null; - this.money = money; - this.description = description; - this.timestamp = System.currentTimeMillis(); - } - - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - if (item != null) { - compound.setTag("Item", item.writeToNBT(new NBTTagCompound())); - } - compound.setDouble("Money", money); - compound.setString("Description", description); - compound.setLong("Timestamp", timestamp); - return compound; - } - - public void readFromNBT(NBTTagCompound compound) { - if (compound.hasKey("Item")) { - item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); - } - money = compound.getDouble("Money"); - description = compound.getString("Description"); - timestamp = compound.getLong("Timestamp"); - } -} -``` - -### 3.4 Auctioneer Role - -**File: `src/main/java/noppes/npcs/roles/RoleAuctioneer.java`** - -```java -package noppes.npcs.roles; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.NoppesUtilServer; -import noppes.npcs.constants.EnumGuiType; -import noppes.npcs.entity.EntityNPCInterface; - -public class RoleAuctioneer extends RoleInterface { - - // Configuration - public String auctionHouseName = "Global"; // For future multi-auction support - public boolean allowSelling = true; - public boolean allowBuying = true; - public boolean showExpiredListings = true; - - // Custom messages - public String welcomeMessage = ""; - public String sellDisabledMessage = "This auctioneer does not accept listings."; - public String buyDisabledMessage = "This auctioneer does not sell items."; - - public RoleAuctioneer(EntityNPCInterface npc) { - super(npc); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setString("AuctionHouse", auctionHouseName); - compound.setBoolean("AllowSelling", allowSelling); - compound.setBoolean("AllowBuying", allowBuying); - compound.setBoolean("ShowExpired", showExpiredListings); - compound.setString("WelcomeMsg", welcomeMessage); - compound.setString("SellDisabledMsg", sellDisabledMessage); - compound.setString("BuyDisabledMsg", buyDisabledMessage); - return compound; - } - - @Override - public void readFromNBT(NBTTagCompound compound) { - auctionHouseName = compound.getString("AuctionHouse"); - allowSelling = compound.getBoolean("AllowSelling"); - allowBuying = compound.getBoolean("AllowBuying"); - showExpiredListings = compound.getBoolean("ShowExpired"); - welcomeMessage = compound.getString("WelcomeMsg"); - sellDisabledMessage = compound.getString("SellDisabledMsg"); - buyDisabledMessage = compound.getString("BuyDisabledMsg"); - } - - @Override - public void interact(EntityPlayer player) { - // Show welcome message if set - if (!welcomeMessage.isEmpty()) { - npc.say(player, npc.advanced.getInteractLine()); - } - - // Open auction house GUI - NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, npc); - } -} -``` - -### 3.5 Update EnumRoleType - -**File: `src/main/java/noppes/npcs/constants/EnumRoleType.java`** - -```java -public enum EnumRoleType { - None, - Trader, - Follower, - Bank, - Transporter, - Postman, - Companion, - Mount, - Auctioneer // Add this -} -``` - -### 3.6 Update DataAdvanced - -**File: `src/main/java/noppes/npcs/DataAdvanced.java`** - -Add to `setRole()` method: - -```java -else if (role == EnumRoleType.Auctioneer && !(npc.roleInterface instanceof RoleAuctioneer)) - npc.roleInterface = new RoleAuctioneer(npc); -``` - -### 3.7 Update EnumGuiType - -**File: `src/main/java/noppes/npcs/constants/EnumGuiType.java`** - -Add new GUI types: - -```java -// Auction House GUIs -PlayerAuction, // Main auction browse/buy interface -PlayerAuctionSell, // Create new listing -PlayerAuctionMyListings, // View own listings -PlayerAuctionClaims, // Claim items/money -AuctioneerSetup, // NPC configuration -ManageAuctions // Admin management -``` - -### 3.8 Auction GUI System - -The auction GUI system will consist of multiple interconnected screens: - -#### 3.8.1 Main Auction Browser - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionBrowse.java`** - -Features: -- Category filter tabs (Weapons, Armor, Tools, etc.) -- Search bar for item names -- Sort options (Time remaining, Price, Recently listed) -- Paginated listing display -- Quick buy/bid buttons - -#### 3.8.2 Create Listing GUI - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java`** - -Features: -- Item slot for the item to sell -- Starting price input -- Buyout price input (optional) -- Duration selector -- Listing fee display -- Confirm button - -#### 3.8.3 My Listings GUI - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionMyListings.java`** - -Features: -- List of player's active listings -- Current bid status -- Time remaining -- Cancel button (if no bids) - -#### 3.8.4 Claims GUI - -**File: `src/main/java/noppes/npcs/client/gui/player/GuiAuctionClaims.java`** - -Features: -- List of pending claims (items won, money from sales, refunds) -- Claim button for each item -- Claim all button - -### 3.9 Network Packets - -#### 3.9.1 Auction Action Packet - -**File: `src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java`** - -```java -package kamkeel.npcs.network.packets.player; - -public class AuctionActionPacket extends AbstractPacket { - - public enum Action { - CREATE_LISTING, - PLACE_BID, - BUYOUT, - CANCEL, - CLAIM, - CLAIM_ALL, - BROWSE, - MY_LISTINGS - } - - private Action action; - private int listingId; - private double amount; - private NBTTagCompound itemData; - private int duration; - private double buyoutPrice; - private int category; - private String search; - private int page; - - // Implement sendData/receiveData... -} -``` - -#### 3.9.2 Auction Sync Packet - -**File: `src/main/java/kamkeel/npcs/network/packets/data/AuctionSyncPacket.java`** - -Used to send auction listing data to clients for GUI display. - -### 3.10 Periodic Tasks - -Add to server tick handler to process expired auctions: - -**File: `src/main/java/noppes/npcs/ServerTickHandler.java`** - -```java -private int auctionCheckCounter = 0; - -@SubscribeEvent -public void onServerTick(TickEvent.ServerTickEvent event) { - // ... existing code ... - - // Check expired auctions every 5 minutes (6000 ticks) - if (++auctionCheckCounter >= 6000) { - auctionCheckCounter = 0; - AuctionController.getInstance().processExpiredAuctions(); - } -} -``` - ---- - -## Implementation Order - -The features should be implemented in this order due to dependencies: - -### Phase 1: Currency System (Foundation) -1. Add VaultAPI dependency to build files -2. Create `VaultHelper.java` with reflection-based integration -3. Create `CurrencyController.java` -4. Add initialization hook in `CustomNpcs.java` -5. Create `PlayerCurrencyData.java` and integrate with `PlayerData` -6. Create currency configuration GUI -7. Test with and without Vault present - -### Phase 2: Trader Enhancements -1. Create `EnumStockReset.java` -2. Create `TraderStock.java` -3. Modify `RoleTrader.java` to add stock and currency fields -4. Modify `ContainerNPCTrader.java` to handle stock/currency -5. Update `GuiNpcTraderSetup.java` with new options -6. Update network packets for stock synchronization -7. Test stock depletion and reset timers - -### Phase 3: Auction House -1. Create auction enums (`EnumAuctionDuration`, `EnumAuctionStatus`, `EnumAuctionCategory`) -2. Create `AuctionListing.java` and `AuctionClaim` classes -3. Create `AuctionController.java` -4. Update `EnumRoleType.java` to add Auctioneer -5. Create `RoleAuctioneer.java` -6. Update `DataAdvanced.java` for role instantiation -7. Update `EnumGuiType.java` with auction GUIs -8. Create auction containers -9. Create auction GUI classes -10. Create network packets -11. Add periodic task for expired auctions -12. Create auctioneer setup GUI -13. Comprehensive testing - ---- - -## File Summary - -### New Files to Create - -| File | Description | -|------|-------------| -| `kamkeel/npcs/compat/VaultHelper.java` | VaultAPI integration | -| `kamkeel/npcs/controllers/CurrencyController.java` | Currency management | -| `noppes/npcs/controllers/data/PlayerCurrencyData.java` | Per-player currency data | -| `noppes/npcs/controllers/data/TraderStock.java` | Trader stock configuration | -| `noppes/npcs/constants/EnumStockReset.java` | Stock reset types | -| `noppes/npcs/controllers/AuctionController.java` | Auction house management | -| `noppes/npcs/controllers/data/AuctionListing.java` | Auction listing data | -| `noppes/npcs/constants/EnumAuctionDuration.java` | Auction duration options | -| `noppes/npcs/constants/EnumAuctionStatus.java` | Auction status states | -| `noppes/npcs/constants/EnumAuctionCategory.java` | Item categories | -| `noppes/npcs/roles/RoleAuctioneer.java` | Auctioneer NPC role | -| `noppes/npcs/containers/ContainerAuction*.java` | Auction containers | -| `noppes/npcs/client/gui/player/GuiAuction*.java` | Auction GUIs | -| `noppes/npcs/client/gui/roles/GuiNpcAuctioneerSetup.java` | Auctioneer config | -| `kamkeel/npcs/network/packets/player/AuctionActionPacket.java` | Auction actions | -| `kamkeel/npcs/network/packets/data/AuctionSyncPacket.java` | Auction data sync | - -### Files to Modify - -| File | Changes | -|------|---------| -| `dependencies.gradle` | Add VaultAPI dependency | -| `repositories.gradle` | Add Vault repository | -| `CustomNpcs.java` | Initialize VaultHelper, AuctionController | -| `EnumRoleType.java` | Add Auctioneer | -| `EnumGuiType.java` | Add auction GUI types | -| `DataAdvanced.java` | Handle Auctioneer role | -| `RoleTrader.java` | Add stock and currency support | -| `ContainerNPCTrader.java` | Handle stock/currency transactions | -| `GuiNpcTraderSetup.java` | Add stock/currency UI | -| `PlayerData.java` | Add PlayerCurrencyData | -| `CommonProxy.java` | Register auction containers | -| `ServerTickHandler.java` | Add auction expiration check | -| `PacketHandler.java` | Register auction packets | - ---- - -## Testing Strategy - -### Unit Testing -- Currency operations (deposit, withdraw, balance) -- Stock depletion and reset calculations -- Auction bid validation -- Auction expiration handling - -### Integration Testing -- VaultAPI integration on hybrid servers -- Fallback to item currency when Vault unavailable -- Stock persistence across server restarts -- Auction persistence and recovery - -### User Acceptance Testing -- Complete trading flow with stock limits -- Complete auction flow (list → bid → win → claim) -- Currency display formatting -- GUI usability - -### Edge Cases -- Negative currency amounts -- Concurrent bids on same auction -- Server crash during transaction -- Player offline when auction ends -- Maximum listings per player -- Inventory full when claiming - ---- - -## API/Scripting Extensions - -Consider adding these scripting hooks: - -```java -// ICurrency interface for scripts -double getBalance(IPlayer player); -boolean withdraw(IPlayer player, double amount); -boolean deposit(IPlayer player, double amount); -String format(double amount); - -// IAuction interface for scripts -IAuctionListing createListing(IPlayer seller, IItemStack item, - double startPrice, double buyout, int durationHours); -boolean cancelListing(int listingId); -List getPlayerListings(IPlayer player); - -// Events -onAuctionCreated(IAuctionListing listing); -onAuctionBid(IAuctionListing listing, IPlayer bidder, double amount); -onAuctionSold(IAuctionListing listing, IPlayer buyer, double price); -onAuctionExpired(IAuctionListing listing); -onTraderPurchase(ITrader trader, IPlayer buyer, int slot, int stockRemaining); -onTraderStockReset(ITrader trader); -``` - ---- - -## Conclusion - -This implementation plan provides a comprehensive roadmap for the CustomNPC+ 1.11 Market Update. The three features are designed to work together seamlessly: - -1. **Currency System** provides the foundation for monetary transactions -2. **Trader Enhancements** modernize the existing trader with stock and currency support -3. **Auction House** creates a global marketplace leveraging the currency system - -The implementation follows existing codebase patterns and can be developed incrementally, with each phase building on the previous one. 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 new file mode 160000 index 000000000..19dc9a836 --- /dev/null +++ b/gradle-plugins @@ -0,0 +1 @@ +Subproject commit 19dc9a836148062fa744b9a9ca87391f84274b44 diff --git a/gradle.properties b/gradle.properties index 48416e9a4..f2e101204 100644 --- a/gradle.properties +++ b/gradle.properties @@ -199,7 +199,7 @@ disableCheckstyle = true # ideaCheckSpotlessOnBuild = true # Non-GTNH properties -modVersion = 1.10.3 +modVersion = 1.11.0 # Increase Gradle's JVM memory usage to avoid daemon expiration due to # insufficient heap space on CI builds. diff --git a/repositories.gradle b/repositories.gradle index 12ce0d893..f4da1c8c5 100644 --- a/repositories.gradle +++ b/repositories.gradle @@ -5,4 +5,7 @@ repositories { name = "sponge" url = "https://repo.spongepowered.org/maven/" } + flatDir { + dirs 'lib' + } } 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 305a3778c..efce1a99b 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 305a3778c86fed2680b8cad173b7e5fb0f3c98e6 +Subproject commit efce1a99b75dc6931e406b77bf188115befb54e2 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/CommandNoppes.java b/src/main/java/foxz/command/CommandNoppes.java index 8c051aa85..f5b5ccd73 100644 --- a/src/main/java/foxz/command/CommandNoppes.java +++ b/src/main/java/foxz/command/CommandNoppes.java @@ -2,9 +2,16 @@ package foxz.command; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; import java.util.List; +/** + * @deprecated The /noppes command is deprecated and no longer supported. + * Please use the /kam command instead for all CNPC+ operations. + */ +@Deprecated public class CommandNoppes extends CommandBase { public CmdNoppes noppes = new CmdNoppes(this); @@ -21,6 +28,15 @@ public class CommandNoppes extends CommandBase { @Override public void processCommand(ICommandSender var1, String[] var2) { + // Send deprecation warning + var1.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[DEPRECATED] " + + EnumChatFormatting.YELLOW + "The /noppes command is deprecated and no longer supported.")); + var1.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW + + "Please use " + EnumChatFormatting.GREEN + "/kam" + EnumChatFormatting.YELLOW + " commands instead.")); + var1.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + + "Type " + EnumChatFormatting.WHITE + "/kam help" + EnumChatFormatting.GRAY + " for available commands.")); + + // Still execute the command for backwards compatibility noppes.processCommand(var1, var2); } diff --git a/src/main/java/foxz/utils/Market.java b/src/main/java/foxz/utils/Market.java index ca260b90b..54905423c 100644 --- a/src/main/java/foxz/utils/Market.java +++ b/src/main/java/foxz/utils/Market.java @@ -31,9 +31,6 @@ public class Market { NBTTagCompound roleCompound = r.writeNBT(new NBTTagCompound()); roleCompound.setString("SaveName", name); putMarketCache(name, roleCompound); - if (r.recordHistory) - return; - saveFile(roleCompound); } 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/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/RenderEnergyBeam.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java new file mode 100644 index 000000000..c870f6a07 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java @@ -0,0 +1,597 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityAbilityBeam; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import net.minecraft.util.Vec3; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +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 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, proximityAlpha); + restoreRenderState(); + return; + } + + // Get trail points (these are RELATIVE to origin) + List trail = beam.getTrailPoints(); + if (trail.isEmpty()) { + restoreRenderState(); + return; + } + + // Get interpolated head offset + 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; + + // Get beam properties + float beamWidth = beam.getBeamWidth(); + float headSize = beam.getHeadSize(); + int innerColor = beam.getInnerColor(); + int outerColor = beam.getOuterColor(); + float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha; + + // Render everything relative to origin position + GL11.glPushMatrix(); + GL11.glTranslated(renderOriginX, renderOriginY, renderOriginZ); + + // 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, beam.getInnerAlpha() * proximityAlpha); + } + + float innerAlpha = beam.getInnerAlpha() * proximityAlpha; + + // Render trail segments with smooth connections (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 head at interpolated offset position + renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks); + + GL11.glPopMatrix(); + + restoreRenderState(); + } + + /** + * 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 proximityAlpha) { + float headSize = beam.getHeadSize(); + float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks); + float size = headSize * chargeProgress; + + if (size <= 0.01f) return; + + int innerColor = beam.getInnerColor(); + int outerColor = beam.getOuterColor(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Pulsing effect + float pulseTime = beam.ticksExisted + partialTicks; + float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f; + float scale = size * (1.0f + scaleModifier); + + // Render lightning during charging if enabled + if (beam.hasLightningEffect()) { + renderAttachedLightning(beam, 0.6f * 0.5f, scale); + } + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + // Inner scale defines the core size + float innerScale = 0.6f; + + // Render outer glow only if enabled + if (beam.isOuterColorEnabled()) { + float outerScale = innerScale + beam.getOuterColorWidth(); + float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha; + GL11.glDepthMask(false); + GL11.glPushMatrix(); + GL11.glScalef(outerScale, outerScale, outerScale); + renderCube(outerColor, outerAlpha, 0.5f); + GL11.glPopMatrix(); + GL11.glDepthMask(true); + } + + // Render inner core + GL11.glScalef(innerScale, innerScale, innerScale); + renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + } + + /** + * 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, float innerAlpha) { + GL11.glPushMatrix(); + // Already at origin (0,0,0) + + // Inner scale defines the core size + float innerScale = 0.6f; + + // Render outer glow only if enabled + // outerColorWidth is an additive offset from inner size + if (outerColorEnabled) { + float outerScale = innerScale + outerColorWidth; + GL11.glDepthMask(false); + GL11.glPushMatrix(); + GL11.glScalef(size * outerScale, size * outerScale, size * outerScale); + renderCube(outerColor, outerAlpha, 0.5f); + GL11.glPopMatrix(); + GL11.glDepthMask(true); + } + + // Render inner core (solid) + GL11.glPushMatrix(); + GL11.glScalef(size * innerScale, size * innerScale, size * innerScale); + renderCube(innerColor, innerAlpha, 0.5f); + GL11.glPopMatrix(); + + GL11.glPopMatrix(); + } + + /** + * Render the beam trail with smooth connections between segments. + * 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, float innerAlpha) { + if (trail.size() < 2) return; + + int trailSize = trail.size(); + + // Pre-compute perpendicular frames at each point + // At connection points, average the perpendiculars for smooth transitions + List perpFrames = computePerpendiculars(trail); + + // Inner scale defines the core width + float innerScale = 0.6f; + float innerWidth = width * innerScale; + + // Render outer glow trail (wider, translucent) - only if enabled + // outerColorWidth is an additive offset from inner width + if (outerColorEnabled) { + float outerWidth = innerWidth + outerColorWidth * width; + GL11.glDepthMask(false); + renderTrailTube(trail, perpFrames, outerWidth, outerColor, 0.3f, true); + GL11.glDepthMask(true); + } + + // Render inner core trail + renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false); + } + + /** + * Render trail with fading effect (comet style) for non-anchored beams. + * 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, float innerAlpha) { + if (trail.size() < 2) return; + + List ages = beam.getTrailPointAges(); + int fadeTime = beam.getTrailFadeTime(); + + // Pre-compute perpendicular frames + List perpFrames = computePerpendiculars(trail); + + // Inner scale defines the core width + float innerScale = 0.6f; + float innerWidth = width * innerScale; + + // Render outer glow trail with fading + if (outerColorEnabled) { + float outerWidth = innerWidth + outerColorWidth * width; + GL11.glDepthMask(false); + renderFadingTrailTube(trail, perpFrames, ages, fadeTime, outerWidth, outerColor, 0.3f); + GL11.glDepthMask(true); + } + + // Render inner core trail with fading + 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) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + float halfWidth = width * 0.5f; + int size = trail.size(); + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + + for (int i = 0; i < size - 1; i++) { + Vec3 p1 = trail.get(i); + Vec3 p2 = trail.get(i + 1); + double[] frame1 = perpFrames.get(i); + double[] frame2 = perpFrames.get(i + 1); + + // 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 = 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; + + // Skip fully faded segments + if (alpha1 <= 0.01f && alpha2 <= 0.01f) continue; + + // Calculate 4 corners at start + double s1x = p1.xCoord - frame1[0] * halfWidth - frame1[3] * halfWidth; + double s1y = p1.yCoord - frame1[1] * halfWidth - frame1[4] * halfWidth; + double s1z = p1.zCoord - frame1[2] * halfWidth - frame1[5] * halfWidth; + + double s2x = p1.xCoord + frame1[0] * halfWidth - frame1[3] * halfWidth; + double s2y = p1.yCoord + frame1[1] * halfWidth - frame1[4] * halfWidth; + double s2z = p1.zCoord + frame1[2] * halfWidth - frame1[5] * halfWidth; + + double s3x = p1.xCoord + frame1[0] * halfWidth + frame1[3] * halfWidth; + double s3y = p1.yCoord + frame1[1] * halfWidth + frame1[4] * halfWidth; + double s3z = p1.zCoord + frame1[2] * halfWidth + frame1[5] * halfWidth; + + double s4x = p1.xCoord - frame1[0] * halfWidth + frame1[3] * halfWidth; + double s4y = p1.yCoord - frame1[1] * halfWidth + frame1[4] * halfWidth; + double s4z = p1.zCoord - frame1[2] * halfWidth + frame1[5] * halfWidth; + + // Calculate 4 corners at end + double e1x = p2.xCoord - frame2[0] * halfWidth - frame2[3] * halfWidth; + double e1y = p2.yCoord - frame2[1] * halfWidth - frame2[4] * halfWidth; + double e1z = p2.zCoord - frame2[2] * halfWidth - frame2[5] * halfWidth; + + double e2x = p2.xCoord + frame2[0] * halfWidth - frame2[3] * halfWidth; + double e2y = p2.yCoord + frame2[1] * halfWidth - frame2[4] * halfWidth; + double e2z = p2.zCoord + frame2[2] * halfWidth - frame2[5] * halfWidth; + + double e3x = p2.xCoord + frame2[0] * halfWidth + frame2[3] * halfWidth; + double e3y = p2.yCoord + frame2[1] * halfWidth + frame2[4] * halfWidth; + double e3z = p2.zCoord + frame2[2] * halfWidth + frame2[5] * halfWidth; + + double e4x = p2.xCoord - frame2[0] * halfWidth + frame2[3] * halfWidth; + double e4y = p2.yCoord - frame2[1] * halfWidth + frame2[4] * halfWidth; + double e4z = p2.zCoord - frame2[2] * halfWidth + frame2[5] * halfWidth; + + // Bottom face + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(s2x, s2y, s2z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e2x, e2y, e2z); + tess.addVertex(e1x, e1y, e1z); + + // Top face + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s4x, s4y, s4z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e4x, e4y, e4z); + tess.addVertex(e3x, e3y, e3z); + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s3x, s3y, s3z); + + // Left face + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s1x, s1y, s1z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e1x, e1y, e1z); + tess.addVertex(e4x, e4y, e4z); + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s4x, s4y, s4z); + + // Right face + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s2x, s2y, s2z); + tess.addVertex(s3x, s3y, s3z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(e2x, e2y, e2z); + } + + tess.draw(); + } + + /** + * Compute perpendicular frames for each point in the trail. + * At interior points, average the perpendiculars from both directions for smooth curves. + * Returns list of [horzX, horzY, horzZ, vertX, vertY, vertZ] for each point. + */ + private List computePerpendiculars(List trail) { + List frames = new ArrayList<>(); + int size = trail.size(); + + for (int i = 0; i < size; i++) { + double[] frame = new double[6]; + + // Calculate direction at this point + double dx, dy, dz; + if (i == 0) { + // First point - use direction to next + Vec3 p1 = trail.get(0); + Vec3 p2 = trail.get(1); + dx = p2.xCoord - p1.xCoord; + dy = p2.yCoord - p1.yCoord; + dz = p2.zCoord - p1.zCoord; + } else if (i == size - 1) { + // Last point - use direction from previous + Vec3 p1 = trail.get(size - 2); + Vec3 p2 = trail.get(size - 1); + dx = p2.xCoord - p1.xCoord; + dy = p2.yCoord - p1.yCoord; + dz = p2.zCoord - p1.zCoord; + } else { + // Interior point - average directions + Vec3 p0 = trail.get(i - 1); + Vec3 p1 = trail.get(i); + Vec3 p2 = trail.get(i + 1); + double dx1 = p1.xCoord - p0.xCoord; + double dy1 = p1.yCoord - p0.yCoord; + double dz1 = p1.zCoord - p0.zCoord; + double dx2 = p2.xCoord - p1.xCoord; + double dy2 = p2.yCoord - p1.yCoord; + double dz2 = p2.zCoord - p1.zCoord; + // Average the directions + dx = (dx1 + dx2) * 0.5; + dy = (dy1 + dy2) * 0.5; + dz = (dz1 + dz2) * 0.5; + } + + // Normalize direction + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0.001) { + dx /= len; + dy /= len; + dz /= len; + } else { + 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; + } + + // Cross product for horizontal perpendicular + double horzX = dy * upZ - dz * upY; + double horzY = dz * upX - dx * upZ; + double horzZ = dx * upY - dy * upX; + double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ); + if (horzLen > 0) { + horzX /= horzLen; + horzY /= horzLen; + horzZ /= horzLen; + } + + // Cross product for vertical perpendicular + double vertX = dy * horzZ - dz * horzY; + 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; + frames.add(frame); + } + + return frames; + } + + /** + * 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[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + float halfWidth = width * 0.5f; + int size = trail.size(); + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + + for (int i = 0; i < size - 1; i++) { + Vec3 p1 = trail.get(i); + Vec3 p2 = trail.get(i + 1); + double[] frame1 = perpFrames.get(i); + double[] frame2 = perpFrames.get(i + 1); + + // Calculate alpha based on position (fade from start or constant) + float alpha1, alpha2; + if (fadeFromStart) { + float progress1 = (float) i / size; + float progress2 = (float) (i + 1) / size; + alpha1 = baseAlpha * progress1; + alpha2 = baseAlpha * progress2; + } else { + alpha1 = baseAlpha; + alpha2 = baseAlpha; + } + + // Calculate 4 corners at start + double s1x = p1.xCoord - frame1[0] * halfWidth - frame1[3] * halfWidth; + double s1y = p1.yCoord - frame1[1] * halfWidth - frame1[4] * halfWidth; + double s1z = p1.zCoord - frame1[2] * halfWidth - frame1[5] * halfWidth; + + double s2x = p1.xCoord + frame1[0] * halfWidth - frame1[3] * halfWidth; + double s2y = p1.yCoord + frame1[1] * halfWidth - frame1[4] * halfWidth; + double s2z = p1.zCoord + frame1[2] * halfWidth - frame1[5] * halfWidth; + + double s3x = p1.xCoord + frame1[0] * halfWidth + frame1[3] * halfWidth; + double s3y = p1.yCoord + frame1[1] * halfWidth + frame1[4] * halfWidth; + double s3z = p1.zCoord + frame1[2] * halfWidth + frame1[5] * halfWidth; + + double s4x = p1.xCoord - frame1[0] * halfWidth + frame1[3] * halfWidth; + double s4y = p1.yCoord - frame1[1] * halfWidth + frame1[4] * halfWidth; + double s4z = p1.zCoord - frame1[2] * halfWidth + frame1[5] * halfWidth; + + // Calculate 4 corners at end + double e1x = p2.xCoord - frame2[0] * halfWidth - frame2[3] * halfWidth; + double e1y = p2.yCoord - frame2[1] * halfWidth - frame2[4] * halfWidth; + double e1z = p2.zCoord - frame2[2] * halfWidth - frame2[5] * halfWidth; + + double e2x = p2.xCoord + frame2[0] * halfWidth - frame2[3] * halfWidth; + double e2y = p2.yCoord + frame2[1] * halfWidth - frame2[4] * halfWidth; + double e2z = p2.zCoord + frame2[2] * halfWidth - frame2[5] * halfWidth; + + double e3x = p2.xCoord + frame2[0] * halfWidth + frame2[3] * halfWidth; + double e3y = p2.yCoord + frame2[1] * halfWidth + frame2[4] * halfWidth; + double e3z = p2.zCoord + frame2[2] * halfWidth + frame2[5] * halfWidth; + + double e4x = p2.xCoord - frame2[0] * halfWidth + frame2[3] * halfWidth; + double e4y = p2.yCoord - frame2[1] * halfWidth + frame2[4] * halfWidth; + double e4z = p2.zCoord - frame2[2] * halfWidth + frame2[5] * halfWidth; + + // Bottom face (s1-s2-e2-e1) + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(s2x, s2y, s2z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e2x, e2y, e2z); + tess.addVertex(e1x, e1y, e1z); + + // Top face (s4-e4-e3-s3) + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s4x, s4y, s4z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e4x, e4y, e4z); + tess.addVertex(e3x, e3y, e3z); + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s3x, s3y, s3z); + + // Left face (s1-e1-e4-s4) + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s1x, s1y, s1z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e1x, e1y, e1z); + tess.addVertex(e4x, e4y, e4z); + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s4x, s4y, s4z); + + // Right face (s2-s3-e3-e2) + tess.setColorRGBA_F(r, g, b, alpha1); + tess.addVertex(s2x, s2y, s2z); + tess.addVertex(s3x, s3y, s3z); + tess.setColorRGBA_F(r, g, b, alpha2); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(e2x, e2y, e2z); + } + + tess.draw(); + } + + /** + * Render the beam head as a glowing cube. + * 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 innerAlpha, float partialTicks) { + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Pulsing effect + float pulseTime = beam.ticksExisted + partialTicks; + float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.1f; + float scale = size * (1.0f + scaleModifier); + + // Render lightning BEFORE rotation so it crackles in all directions (only on head) + if (beam.hasLightningEffect()) { + renderAttachedLightning(beam, 0.6f * 0.5f, scale); + } + + // Rotation + GL11.glRotatef(beam.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f); + GL11.glRotatef(beam.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f); + GL11.glRotatef(beam.getInterpolatedRotationZ(partialTicks), 0.0f, 0.0f, 1.0f); + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + // Inner scale defines the core size + float innerScale = 0.6f; + + // Render outer glow only if enabled + // outerColorWidth is an additive offset from inner size + if (beam.isOuterColorEnabled()) { + float outerScale = innerScale + beam.getOuterColorWidth(); + GL11.glDepthMask(false); + GL11.glPushMatrix(); + GL11.glScalef(outerScale, outerScale, outerScale); + renderCube(outerColor, outerAlpha, 0.5f); + GL11.glPopMatrix(); + GL11.glDepthMask(true); + } + + // Render inner core + GL11.glScalef(innerScale, innerScale, innerScale); + renderCube(innerColor, innerAlpha, 0.5f); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + } + +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java new file mode 100644 index 000000000..eb4d9f21c --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java @@ -0,0 +1,181 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +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 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(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Get interpolated values + float size = disc.getInterpolatedSize(partialTicks); + float radius = disc.getDiscRadius() * size; + float thickness = disc.getDiscThickness() * size; + + // Subtle pulsing effect + float pulseTime = entity.ticksExisted + partialTicks; + float scaleModifier = (float) Math.sin(pulseTime * 0.1f) * 0.03f; + float scale = 1.0f + scaleModifier; + + // Render lightning BEFORE rotation so it crackles in all directions + if (disc.hasLightningEffect()) { + renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale); + } + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + if (disc.isVertical()) { + // Vertical mode: thin edge faces direction of travel (like a saw blade) + // 1. Spin in local space (Y-axis) + // 2. Tilt 90° to stand up (X-axis) + // 3. Orient to face travel direction (Y-axis world yaw) + GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + } + + 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() * proximityAlpha, radius * outerScale, thickness); + GL11.glDepthMask(true); + } + + // Render inner square (solid) + renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + + restoreRenderState(); + } + + /** + * Render a flat square (thin cube) centered at origin. + * The square lies flat on the XZ plane with thin Y height. + */ + private void renderFlatSquare(int color, float alpha, float halfSize, float thickness) { + float halfThick = thickness * 0.5f; + + // Render as a thin cube + renderCubeCustom(color, alpha, halfSize, halfThick, halfSize); + } + + /** + * Render a cube with custom dimensions. + */ + private void renderCubeCustom(int color, float alpha, float halfX, float halfY, float halfZ) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + + net.minecraft.client.renderer.Tessellator tess = net.minecraft.client.renderer.Tessellator.instance; + + // Top face (y+) + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, 1, 0); + tess.addVertex(-halfX, halfY, halfZ); + tess.addVertex(halfX, halfY, halfZ); + tess.addVertex(halfX, halfY, -halfZ); + tess.addVertex(-halfX, halfY, -halfZ); + tess.draw(); + + // Bottom face (y-) + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, -1, 0); + tess.addVertex(-halfX, -halfY, -halfZ); + tess.addVertex(halfX, -halfY, -halfZ); + tess.addVertex(halfX, -halfY, halfZ); + tess.addVertex(-halfX, -halfY, halfZ); + tess.draw(); + + // Front face (z+) + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, 0, 1); + tess.addVertex(-halfX, -halfY, halfZ); + tess.addVertex(halfX, -halfY, halfZ); + tess.addVertex(halfX, halfY, halfZ); + tess.addVertex(-halfX, halfY, halfZ); + tess.draw(); + + // Back face (z-) + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(0, 0, -1); + tess.addVertex(halfX, -halfY, -halfZ); + tess.addVertex(-halfX, -halfY, -halfZ); + tess.addVertex(-halfX, halfY, -halfZ); + tess.addVertex(halfX, halfY, -halfZ); + tess.draw(); + + // Right face (x+) + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(1, 0, 0); + tess.addVertex(halfX, -halfY, halfZ); + tess.addVertex(halfX, -halfY, -halfZ); + tess.addVertex(halfX, halfY, -halfZ); + tess.addVertex(halfX, halfY, halfZ); + tess.draw(); + + // Left face (x-) + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + tess.setNormal(-1, 0, 0); + tess.addVertex(-halfX, -halfY, -halfZ); + tess.addVertex(-halfX, -halfY, halfZ); + tess.addVertex(-halfX, halfY, halfZ); + tess.addVertex(-halfX, halfY, -halfZ); + tess.draw(); + } +} 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/RenderEnergyLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java new file mode 100644 index 000000000..c2cfe716a --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java @@ -0,0 +1,350 @@ +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.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 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) { + EntityAbilityLaser laser = (EntityAbilityLaser) entity; + + 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, proximityAlpha); + restoreRenderState(); + return; + } + + // 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.getLaserWidth(); + float alpha = 1.0f; + + // Calculate render offset (entity position is used as reference) + double offsetX = x - laser.posX; + double offsetY = y - laser.posY; + double offsetZ = z - laser.posZ; + + // Render start relative to camera + double renderStartX = startX + offsetX; + double renderStartY = startY + offsetY; + double renderStartZ = startZ + offsetZ; + double renderEndX = endX + offsetX; + double renderEndY = endY + offsetY; + double renderEndZ = endZ + offsetZ; + + // Calculate perpendicular vectors for the beam rectangle + double dx = renderEndX - renderStartX; + double dy = renderEndY - renderStartY; + double dz = renderEndZ - renderStartZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len < 0.001) { + restoreRenderState(); + return; + } + + // Normalize direction + dx /= len; + dy /= len; + dz /= len; + + // 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; + } + + // Cross product for horizontal perpendicular + double horzX = dy * upZ - dz * upY; + double horzY = dz * upX - dx * upZ; + double horzZ = dx * upY - dy * upX; + double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ); + if (horzLen > 0) { + horzX /= horzLen; + horzY /= horzLen; + horzZ /= horzLen; + } + + // Cross product for vertical perpendicular + double vertX = dy * horzZ - dz * horzY; + 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; + + // Render outer rectangle (larger, outer color, translucent) - only if enabled + // outerColorWidth is an additive offset from inner width + if (laser.isOuterColorEnabled()) { + 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 * 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 * 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 * 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); + } + + restoreRenderState(); + } + + private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) { + float headSize = laser.getLaserWidth() * 0.5f; + float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks); + float size = headSize * chargeProgress; + + if (size <= 0.01f) return; + + int innerColor = laser.getInnerColor(); + int outerColor = laser.getOuterColor(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Pulsing effect + float pulseTime = laser.ticksExisted + partialTicks; + float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f; + float scale = size * (1.0f + scaleModifier); + + // Render lightning during charging if enabled + if (laser.hasLightningEffect()) { + renderAttachedLightning(laser, 0.6f * 0.5f, scale); + } + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + // Inner scale defines the core size + float innerScale = 0.6f; + + // Render outer glow only if enabled + if (laser.isOuterColorEnabled()) { + float outerScale = innerScale + laser.getOuterColorWidth(); + float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha; + GL11.glDepthMask(false); + GL11.glPushMatrix(); + GL11.glScalef(outerScale, outerScale, outerScale); + renderCube(outerColor, outerAlpha, 0.5f); + GL11.glPopMatrix(); + GL11.glDepthMask(true); + } + + // Render inner core + GL11.glScalef(innerScale, innerScale, innerScale); + renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + } + + /** + * 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) { + AttachedLightningRenderer.LightningState state = getLightningState(laser); + + float density = laser.getLightningDensity(); + // Lightning radius extends outward from inner width + float innerRadius = width * 0.6f * 0.5f; + float radius = innerRadius + laser.getLightningRadius() * width; + int outerColor = laser.getOuterColor(); + int innerColor = laser.getInnerColor(); + int fadeTime = laser.getLightningFadeTime(); + + // Render lightning at multiple points along the laser + // Start, middle, and end points + double midX = (startX + endX) * 0.5; + double midY = (startY + endY) * 0.5; + double midZ = (startZ + endZ) * 0.5; + + GL11.glPushMatrix(); + GL11.glTranslated(midX, midY, midZ); + state.update(density, radius, outerColor, innerColor, fadeTime); + state.render(); + GL11.glPopMatrix(); + + // Also render at the tip + GL11.glPushMatrix(); + GL11.glTranslated(endX, endY, endZ); + // Use a secondary state for the tip + AttachedLightningRenderer.LightningState tipState = getTipLightningState(laser); + tipState.update(density * 0.7f, radius * 0.8f, outerColor, innerColor, fadeTime); + tipState.render(); + GL11.glPopMatrix(); + } + + + /** + * Get or create the tip lightning state for the laser. + * Persisted per entity ID so arcs accumulate and fade properly across frames. + */ + private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) { + 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) { + float[] rgb = extractRGB(color); + float r = rgb[0], g = rgb[1], b = rgb[2]; + + float halfWidth = width * 0.5f; + + // Calculate 8 corners of the box + // Start corners + double s1x = x1 - horzX * halfWidth - vertX * halfWidth; + double s1y = y1 - horzY * halfWidth - vertY * halfWidth; + double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth; + + double s2x = x1 + horzX * halfWidth - vertX * halfWidth; + double s2y = y1 + horzY * halfWidth - vertY * halfWidth; + double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth; + + double s3x = x1 + horzX * halfWidth + vertX * halfWidth; + double s3y = y1 + horzY * halfWidth + vertY * halfWidth; + double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth; + + double s4x = x1 - horzX * halfWidth + vertX * halfWidth; + double s4y = y1 - horzY * halfWidth + vertY * halfWidth; + double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth; + + // End corners + double e1x = x2 - horzX * halfWidth - vertX * halfWidth; + double e1y = y2 - horzY * halfWidth - vertY * halfWidth; + double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth; + + double e2x = x2 + horzX * halfWidth - vertX * halfWidth; + double e2y = y2 + horzY * halfWidth - vertY * halfWidth; + double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth; + + double e3x = x2 + horzX * halfWidth + vertX * halfWidth; + double e3y = y2 + horzY * halfWidth + vertY * halfWidth; + double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth; + + double e4x = x2 - horzX * halfWidth + vertX * halfWidth; + double e4y = y2 - horzY * halfWidth + vertY * halfWidth; + double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth; + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, alpha); + + // Bottom face + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(s2x, s2y, s2z); + tess.addVertex(e2x, e2y, e2z); + tess.addVertex(e1x, e1y, e1z); + + // Top face + tess.addVertex(s4x, s4y, s4z); + tess.addVertex(e4x, e4y, e4z); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(s3x, s3y, s3z); + + // Left face + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(e1x, e1y, e1z); + tess.addVertex(e4x, e4y, e4z); + tess.addVertex(s4x, s4y, s4z); + + // Right face + tess.addVertex(s2x, s2y, s2z); + tess.addVertex(s3x, s3y, s3z); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(e2x, e2y, e2z); + + // Start cap + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(s4x, s4y, s4z); + tess.addVertex(s3x, s3y, s3z); + tess.addVertex(s2x, s2y, s2z); + + // End cap + tess.addVertex(e1x, e1y, e1z); + tess.addVertex(e2x, e2y, e2z); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(e4x, e4y, e4z); + + tess.draw(); + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java new file mode 100644 index 000000000..5efe83222 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java @@ -0,0 +1,97 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +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; + +/** + * Renders the AbilityOrb entity as a cube with inner and outer layers. + * Minecraft-style blocky appearance using Tessellator. + */ +@SideOnly(Side.CLIENT) +public class RenderEnergyOrb extends RenderEnergy { + + private static final int LIGHTNING_FADE_TICKS = 6; + + @Override + 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(); + GL11.glTranslated(x, y, z); + + // Get interpolated size for smooth rendering + float size = orb.getInterpolatedSize(partialTicks); + + // Pulsing scale effect + float pulseTime = entity.ticksExisted + partialTicks; + float scaleModifier = (float) Math.sin(pulseTime * 0.15f) * 0.05f; + float scale = size * (1.0f + scaleModifier); + + // Render lightning BEFORE rotation so it crackles in all directions + if (orb.hasLightningEffect()) { + 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 + GL11.glRotatef(orb.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f); + GL11.glRotatef(orb.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f); + GL11.glRotatef(orb.getInterpolatedRotationZ(partialTicks), 0.0f, 0.0f, 1.0f); + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + // 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()) { + float outerScale = innerScale + orb.getOuterColorWidth(); + GL11.glDepthMask(false); + GL11.glPushMatrix(); + GL11.glScalef(outerScale, outerScale, outerScale); + 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(), orb.getInnerAlpha() * proximityAlpha, 0.5f); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + + restoreRenderState(); + } + +} 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/RenderSweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java new file mode 100644 index 000000000..01ec9b429 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java @@ -0,0 +1,235 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.entity.EntityEnergySweeper; +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; + +/** + * Renders the Sweeper beam as a thin rotating laser attached to the NPC. + * Uses similar rendering style to the Beam trail for visual consistency. + */ +@SideOnly(Side.CLIENT) +public class RenderSweeper extends Render { + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + 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(); + float outerColorWidth = sweeper.getOuterColorWidth(); + float angle = sweeper.getInterpolatedAngle(partialTicks); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Rotate the beam around Y axis (angle already includes baseYaw) + 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, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth); + + GL11.glPopMatrix(); + + restoreRenderState(); + } + + 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); + + // Force full brightness - prevents world lighting from darkening sweeper + 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(); + } + + /** + * 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, float height, int innerColor, int outerColor, + boolean outerColorEnabled, float outerColorWidth) { + // Extract colors + 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; + + // 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) - 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, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f); + GL11.glDepthMask(true); + + // 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) + renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f); + } + + /** + * 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 height, float r, float g, float b, float a) { + // 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; + + // Normalize direction + dx /= len; + dy /= len; + dz /= len; + + // Calculate perpendicular vectors + double upX = 0, upY = 1, upZ = 0; + if (Math.abs(dy) > 0.9) { + upX = 1; + upY = 0; + upZ = 0; + } + + // Cross product for horizontal perpendicular + double horzX = dy * upZ - dz * upY; + double horzY = dz * upX - dx * upZ; + double horzZ = dx * upY - dy * upX; + double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ); + if (horzLen > 0) { + horzX /= horzLen; + horzY /= horzLen; + horzZ /= horzLen; + } + + // Cross product for vertical perpendicular + double vertX = dy * horzZ - dz * horzY; + double vertY = dz * horzX - dx * horzZ; + double vertZ = dx * horzY - dy * horzX; + + float halfWidth = width * 0.5f; + float halfHeight = height * 0.5f; + + // 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 * halfHeight; + double s2y = y1 + horzY * halfWidth - vertY * halfHeight; + double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight; + + 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 * halfHeight; + double s4y = y1 - horzY * halfWidth + vertY * halfHeight; + double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight; + + 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 * halfHeight; + double e2y = y2 + horzY * halfWidth - vertY * halfHeight; + double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight; + + 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 * halfHeight; + double e4y = y2 - horzY * halfWidth + vertY * halfHeight; + double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight; + + Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); + tess.setColorRGBA_F(r, g, b, a); + + // Bottom face + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(s2x, s2y, s2z); + tess.addVertex(e2x, e2y, e2z); + tess.addVertex(e1x, e1y, e1z); + + // Top face + tess.addVertex(s4x, s4y, s4z); + tess.addVertex(e4x, e4y, e4z); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(s3x, s3y, s3z); + + // Left face + tess.addVertex(s1x, s1y, s1z); + tess.addVertex(e1x, e1y, e1z); + tess.addVertex(e4x, e4y, e4z); + tess.addVertex(s4x, s4y, s4z); + + // Right face + tess.addVertex(s2x, s2y, s2z); + tess.addVertex(s3x, s3y, s3z); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(e2x, e2y, e2z); + + // End cap (tip of beam) + tess.addVertex(e1x, e1y, e1z); + tess.addVertex(e2x, e2y, e2z); + tess.addVertex(e3x, e3y, e3z); + tess.addVertex(e4x, e4y, e4z); + + tess.draw(); + } + + @Override + protected ResourceLocation getEntityTexture(Entity entity) { + return null; + } +} 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 new file mode 100644 index 000000000..dc653e73f --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java @@ -0,0 +1,425 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.client.event.RenderWorldLastEvent; +import org.lwjgl.opengl.GL11; + +/** + * Renders telegraph warning shapes in the world. + * Register this as an event handler on the Forge event bus. + */ +public class TelegraphRenderer { + + public static TelegraphRenderer Instance; + + private static final int CIRCLE_SEGMENTS = 32; + private static final int CONE_SEGMENTS = 16; + + public TelegraphRenderer() { + Instance = this; + } + + @SubscribeEvent + public void onRenderWorldLast(RenderWorldLastEvent event) { + if (TelegraphManager.ClientInstance == null || !TelegraphManager.ClientInstance.hasTelegraphs()) { + return; + } + + Minecraft mc = Minecraft.getMinecraft(); + EntityPlayer player = mc.thePlayer; + if (player == null) return; + + float partialTicks = event.partialTicks; + + // Get player interpolated position for camera offset + double playerX = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; + double playerY = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; + double playerZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; + + // Setup GL state for transparent rendering + GL11.glPushMatrix(); + 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.glDepthMask(false); + + // Render each telegraph + for (TelegraphInstance instance : TelegraphManager.ClientInstance.getTelegraphs()) { + renderTelegraph(instance, playerX, playerY, playerZ, partialTicks); + } + + // Restore GL state + GL11.glDepthMask(true); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_TEXTURE_2D); + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + + private void renderTelegraph(TelegraphInstance instance, double playerX, double playerY, double playerZ, float partialTicks) { + Telegraph telegraph = instance.getTelegraph(); + if (telegraph == null || telegraph.getType() == TelegraphType.NONE) { + return; + } + + // Calculate render position relative to camera using interpolated positions for smooth movement + double renderX = instance.getInterpolatedX(partialTicks) - playerX; + double renderY = instance.getInterpolatedY(partialTicks) - playerY + telegraph.getHeightOffset(); + double renderZ = instance.getInterpolatedZ(partialTicks) - playerZ; + + // Get animated color + int color = instance.getAnimatedColor(partialTicks); + float alpha = ((color >> 24) & 0xFF) / 255.0f; + float red = ((color >> 16) & 0xFF) / 255.0f; + float green = ((color >> 8) & 0xFF) / 255.0f; + float blue = (color & 0xFF) / 255.0f; + + GL11.glPushMatrix(); + GL11.glTranslated(renderX, renderY, renderZ); + + // Rotate for directional shapes using interpolated yaw for smooth rotation + GL11.glRotatef(-instance.getInterpolatedYaw(partialTicks), 0, 1, 0); + + switch (telegraph.getType()) { + case CIRCLE: + renderCircle(telegraph.getRadius(), red, green, blue, alpha); + break; + case RING: + renderRing(telegraph.getRadius(), telegraph.getInnerRadius(), red, green, blue, alpha); + break; + case LINE: + renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha); + break; + case CONE: + 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; + } + + GL11.glPopMatrix(); + } + + private void renderCircle(float radius, float r, float g, float b, float a) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawing(GL11.GL_TRIANGLE_FAN); + tessellator.setColorRGBA_F(r, g, b, a); + + // Center point + tessellator.addVertex(0, 0, 0); + + // Circle points + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + double x = Math.cos(angle) * radius; + double z = Math.sin(angle) * radius; + tessellator.addVertex(x, 0, z); + } + + tessellator.draw(); + + // Draw border + renderCircleBorder(radius, r, g, b, Math.min(1.0f, a * 2)); + } + + private void renderCircleBorder(float radius, float r, float g, float b, float a) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawing(GL11.GL_LINE_LOOP); + tessellator.setColorRGBA_F(r, g, b, a); + + for (int i = 0; i < CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + double x = Math.cos(angle) * radius; + double z = Math.sin(angle) * radius; + tessellator.addVertex(x, 0.01, z); + } + + tessellator.draw(); + } + + private void renderRing(float outerRadius, float innerRadius, float r, float g, float b, float a) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP); + tessellator.setColorRGBA_F(r, g, b, a); + + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + double cosA = Math.cos(angle); + double sinA = Math.sin(angle); + + // Outer point + tessellator.addVertex(cosA * outerRadius, 0, sinA * outerRadius); + // Inner point + tessellator.addVertex(cosA * innerRadius, 0, sinA * innerRadius); + } + + tessellator.draw(); + + // Draw borders + renderCircleBorder(outerRadius, r, g, b, Math.min(1.0f, a * 2)); + renderCircleBorder(innerRadius, r, g, b, Math.min(1.0f, a * 2)); + } + + private void renderLine(float length, float width, float r, float g, float b, float a) { + float halfWidth = width / 2; + + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(r, g, b, a); + + // Rectangle from origin forward + tessellator.addVertex(-halfWidth, 0, 0); + tessellator.addVertex(halfWidth, 0, 0); + tessellator.addVertex(halfWidth, 0, length); + tessellator.addVertex(-halfWidth, 0, length); + + tessellator.draw(); + + // Draw border + tessellator.startDrawing(GL11.GL_LINE_LOOP); + tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2)); + + tessellator.addVertex(-halfWidth, 0.01, 0); + tessellator.addVertex(halfWidth, 0.01, 0); + tessellator.addVertex(halfWidth, 0.01, length); + tessellator.addVertex(-halfWidth, 0.01, length); + + tessellator.draw(); + } + + 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; + + if (innerRadius <= 0) { + // Standard cone: triangle fan from origin + tessellator.startDrawing(GL11.GL_TRIANGLE_FAN); + tessellator.setColorRGBA_F(r, g, b, a); + + 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(); + } + } + + private void renderPoint(float r, float g, float b, float a) { + float size = 0.5f; + + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(r, g, b, a); + + // Diamond shape + tessellator.addVertex(0, 0, -size); + tessellator.addVertex(size, 0, 0); + tessellator.addVertex(0, 0, size); + tessellator.addVertex(-size, 0, 0); + + 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 ==================== + + /** + * Render a telegraph in GUI space for ability preview. + * This is used by the Manage Abilities GUI to show telegraph shapes. + * + * @param instance The telegraph instance to render + * @param centerX X center position in GUI space + * @param centerY Y center position in GUI space + * @param centerZ Z center position in GUI space + * @param scale Scale factor for the telegraph + * @param partialTicks Partial ticks for interpolation + */ + public void renderTelegraphInGUI(TelegraphInstance instance, + double centerX, double centerY, double centerZ, + float scale, float partialTicks) { + if (instance == null) return; + + Telegraph telegraph = instance.getTelegraph(); + if (telegraph == null || telegraph.getType() == TelegraphType.NONE) { + return; + } + + // Get animated color + int color = instance.getAnimatedColor(partialTicks); + float alpha = ((color >> 24) & 0xFF) / 255.0f; + float red = ((color >> 16) & 0xFF) / 255.0f; + float green = ((color >> 8) & 0xFF) / 255.0f; + float blue = (color & 0xFF) / 255.0f; + + // Setup GL state + GL11.glPushMatrix(); + 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.glDepthMask(false); + + GL11.glTranslated(centerX, centerY, centerZ); + GL11.glScalef(scale, scale, scale); + + // Rotate for directional shapes + GL11.glRotatef(-instance.getInterpolatedYaw(partialTicks), 0, 1, 0); + + // Render based on type + switch (telegraph.getType()) { + case CIRCLE: + renderCircle(telegraph.getRadius(), red, green, blue, alpha); + break; + case RING: + renderRing(telegraph.getRadius(), telegraph.getInnerRadius(), red, green, blue, alpha); + break; + case LINE: + renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha); + break; + case CONE: + 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; + } + + // Restore GL state + GL11.glDepthMask(true); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_TEXTURE_2D); + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java new file mode 100644 index 000000000..4debb90d6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -0,0 +1,304 @@ +package kamkeel.npcs.client.renderer.lightning; + +import net.minecraft.client.renderer.Tessellator; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +/** + * Renders lightning arcs attached to an entity (in local space). + * Supports both instant arcs and fading persistent bolts that move with the entity. + */ +public class AttachedLightningRenderer { + + private static final Random rand = new Random(); + + /** + * Data for a single lightning bolt with fading support. + */ + public static class LightningArc { + public List points; + public int age; + public int maxAge; + public int outerColor; + public int innerColor; + + public LightningArc(List points, int maxAge, int outerColor, int innerColor) { + this.points = points; + this.age = 0; + this.maxAge = maxAge; + this.outerColor = outerColor; + this.innerColor = innerColor; + } + + public float getAlphaMultiplier() { + // Fade out over lifetime + if (maxAge <= 0) return 0.0f; + return 1.0f - ((float) age / (float) maxAge); + } + + public boolean isDead() { + return age >= maxAge; + } + + public void tick() { + age++; + } + } + + /** + * Storage for persistent lightning arcs per entity. + * Call updateAndRender() each frame from the entity's renderer. + */ + public static class LightningState { + private final List arcs = new ArrayList<>(); + private float spawnAccumulator = 0; + + /** + * Update arc ages, remove dead arcs, spawn new ones based on density. + * + * @param density Arcs per tick (can be fractional) + * @param radius Max arc distance from center + * @param outerColor Outer glow color + * @param innerColor Inner core color + * @param maxAge How many ticks arcs live (for fading) + */ + public void update(float density, float radius, int outerColor, int innerColor, int maxAge) { + // Age existing arcs and remove dead ones + Iterator iter = arcs.iterator(); + while (iter.hasNext()) { + LightningArc arc = iter.next(); + arc.tick(); + if (arc.isDead()) { + iter.remove(); + } + } + + // Spawn new arcs based on density + spawnAccumulator += density; + while (spawnAccumulator >= 1.0f) { + spawnAccumulator -= 1.0f; + arcs.add(createArc(radius, outerColor, innerColor, maxAge)); + } + } + + /** + * Age existing arcs and remove dead ones without spawning new arcs. + * Use with addArc() for custom arc generation. + */ + public void tick() { + Iterator iter = arcs.iterator(); + while (iter.hasNext()) { + LightningArc arc = iter.next(); + arc.tick(); + if (arc.isDead()) { + iter.remove(); + } + } + } + + /** + * Add a custom arc to the state. + */ + public void addArc(LightningArc arc) { + arcs.add(arc); + } + + /** + * Render all active arcs in local space. + * Call this after glTranslated to entity position. + * Note: Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). This avoids nesting + * glPushAttrib calls which can overflow the GL attrib stack (depth 16) when + * other mods also push attribs during entity rendering. + */ + public void render() { + if (arcs.isEmpty()) return; + + GL11.glDepthMask(false); + + Tessellator tess = Tessellator.instance; + + for (LightningArc arc : arcs) { + float alphaMult = arc.getAlphaMultiplier(); + + // Render outer glow + renderBoltPath(tess, arc.points, arc.outerColor, 0.025f, 0.35f * alphaMult); + + // Render inner core + renderBoltPath(tess, arc.points, arc.innerColor, 0.012f, 0.7f * alphaMult); + } + + GL11.glDepthMask(true); + } + + public int getArcCount() { + return arcs.size(); + } + } + + /** + * Create a new lightning arc from center to a random point. + */ + private static LightningArc createArc(float radius, int outerColor, int innerColor, int maxAge) { + // Random end point on sphere + double theta = rand.nextDouble() * Math.PI * 2; + double phi = Math.acos(2 * rand.nextDouble() - 1); + double r = radius * (0.5 + rand.nextDouble() * 0.5); + + double endX = r * Math.sin(phi) * Math.cos(theta); + double endY = r * Math.sin(phi) * Math.sin(theta); + double endZ = r * Math.cos(phi); + + int segments = 4 + rand.nextInt(3); + float displacement = radius * 0.25f; + + List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement); + + return new LightningArc(points, maxAge, outerColor, innerColor); + } + + /** + * 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) { + List points = new ArrayList<>(); + points.add(new double[]{x1, y1, z1}); + + double dx = x2 - x1; + double dy = y2 - y1; + double dz = z2 - z1; + + // Create perpendicular vectors for displacement + Vec3d dir = new Vec3d(dx, dy, dz); + Vec3d perp1 = dir.copy().perpendicular().normalize(); + Vec3d perp2 = dir.copy().crossProduct(perp1).normalize(); + + for (int i = 1; i < segments; i++) { + double t = (double) i / segments; + + double px = x1 + dx * t; + double py = y1 + dy * t; + double pz = z1 + dz * t; + + // Displacement strongest in middle + float strength = (float) (1.0 - Math.abs(t - 0.5) * 2.0) * displacement; + double offset1 = (rand.nextDouble() - 0.5) * 2 * strength; + double offset2 = (rand.nextDouble() - 0.5) * 2 * strength; + + px += perp1.x * offset1 + perp2.x * offset2; + py += perp1.y * offset1 + perp2.y * offset2; + pz += perp1.z * offset1 + perp2.z * offset2; + + points.add(new double[]{px, py, pz}); + } + + points.add(new double[]{x2, y2, z2}); + return points; + } + + /** + * Render the lightning path as quads. + */ + private static void renderBoltPath(Tessellator tess, List points, int color, float width, float alpha) { + if (alpha <= 0.01f) return; + + 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++) { + double[] p1 = points.get(i); + double[] p2 = points.get(i + 1); + + double segDx = p2[0] - p1[0]; + double segDy = p2[1] - p1[1]; + double segDz = p2[2] - p1[2]; + + Vec3d segDir = new Vec3d(segDx, segDy, segDz); + Vec3d perp = segDir.copy().perpendicular().normalize().multiply(width); + + // First quad + tess.startDrawingQuads(); + tess.setBrightness(0xF000F0); + tess.setColorRGBA(r, g, b, a); + + tess.addVertex(p1[0] - perp.x, p1[1] - perp.y, p1[2] - perp.z); + tess.addVertex(p1[0] + perp.x, p1[1] + perp.y, p1[2] + perp.z); + tess.addVertex(p2[0] + perp.x, p2[1] + perp.y, p2[2] + perp.z); + tess.addVertex(p2[0] - perp.x, p2[1] - perp.y, p2[2] - perp.z); + + tess.draw(); + + // Second quad (perpendicular for 3D look) + Vec3d perp2 = segDir.copy().crossProduct(perp).normalize().multiply(width); + + tess.startDrawingQuads(); + tess.setBrightness(0xF000F0); + tess.setColorRGBA(r, g, b, a); + + tess.addVertex(p1[0] - perp2.x, p1[1] - perp2.y, p1[2] - perp2.z); + tess.addVertex(p1[0] + perp2.x, p1[1] + perp2.y, p1[2] + perp2.z); + tess.addVertex(p2[0] + perp2.x, p2[1] + perp2.y, p2[2] + perp2.z); + tess.addVertex(p2[0] - perp2.x, p2[1] - perp2.y, p2[2] - perp2.z); + + tess.draw(); + } + } + + /** + * Create a lightning arc between two arbitrary points. + */ + public static LightningArc createArcBetween(double x1, double y1, double z1, + double x2, double y2, double z2, + float displacement, int outerColor, int innerColor, int maxAge) { + int segments = 4 + rand.nextInt(3); + List points = generateLightningPath(x1, y1, z1, x2, y2, z2, segments, displacement); + return new LightningArc(points, maxAge, outerColor, innerColor); + } + + // ==================== INSTANT RENDERING (no persistence) ==================== + + /** + * Render a single instant lightning arc (no fading, drawn this frame only). + * Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). + */ + public static void renderInstantArc(float radius, int outerColor, int innerColor) { + double theta = rand.nextDouble() * Math.PI * 2; + double phi = Math.acos(2 * rand.nextDouble() - 1); + double r = radius * (0.5 + rand.nextDouble() * 0.5); + + double endX = r * Math.sin(phi) * Math.cos(theta); + double endY = r * Math.sin(phi) * Math.sin(theta); + double endZ = r * Math.cos(phi); + + int segments = 4 + rand.nextInt(3); + float displacement = radius * 0.25f; + + List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement); + + GL11.glDepthMask(false); + + Tessellator tess = Tessellator.instance; + renderBoltPath(tess, points, outerColor, 0.025f, 0.35f); + renderBoltPath(tess, points, innerColor, 0.012f, 0.7f); + + GL11.glDepthMask(true); + } + + /** + * Render multiple instant arcs. + */ + public static void renderCracklingLightning(int count, float radius, int outerColor, int innerColor) { + for (int i = 0; i < count; i++) { + renderInstantArc(radius, outerColor, innerColor); + } + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java new file mode 100644 index 000000000..beea63fd3 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java @@ -0,0 +1,295 @@ +package kamkeel.npcs.client.renderer.lightning; + +import net.minecraft.world.World; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Random; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * Lightning bolt data model with fractal segment generation. + * Adapted from Botania's LightningBolt by Vazkii/ChickenBones. + */ +public class LightningBolt { + + public static ConcurrentLinkedQueue boltList = new ConcurrentLinkedQueue<>(); + + public ArrayList segments = new ArrayList<>(); + public Vec3d start; + public Vec3d end; + + public double length; + public int numSegments0; + private int numSplits; + private boolean finalized; + private Random rand; + public long seed; + + public int particleAge; + public int particleMaxAge; + public boolean isDead; + + private World world; + private HashMap splitParents = new HashMap<>(); + + public float speed = 1.5F; + public static final int FADE_TIME = 4; // Short lifespan for projectile-attached lightning + + public int colorOuter; + public int colorInner; + + public LightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) { + this.world = world; + this.seed = seed; + this.rand = new Random(seed); + + this.start = start; + this.end = end; + this.speed = ticksPerMeter; + + this.colorOuter = colorOuter; + this.colorInner = colorInner; + + this.numSegments0 = 1; + this.length = end.copy().subtract(start).mag(); + 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)); + } + + /** + * Apply default fractal splitting for natural-looking lightning. + */ + public void defaultFractal() { + fractal(2, length / 1.5, 0.7F, 0.7F, 45); + fractal(2, length / 4, 0.5F, 0.8F, 50); + fractal(2, length / 15, 0.5F, 0.9F, 55); + fractal(2, length / 30, 0.5F, 1.0F, 60); + fractal(2, length / 60, 0, 0, 0); + fractal(2, length / 100, 0, 0, 0); + fractal(2, length / 400, 0, 0, 0); + } + + /** + * Simplified fractal for short-lived projectile lightning. + * Less detail but faster and more appropriate for fast-moving objects. + */ + public void simpleFractal() { + fractal(2, length / 2.0, 0.4F, 0.6F, 35); + fractal(2, length / 6, 0.3F, 0.7F, 40); + fractal(2, length / 20, 0, 0, 0); + } + + /** + * Apply fractal splitting to create branching lightning. + * + * @param splits Number of splits per segment + * @param amount Displacement amount + * @param splitChance Probability of branching (0-1) + * @param splitLength Length multiplier for branches + * @param splitAngle Angle for branch splits in degrees + */ + public void fractal(int splits, double amount, double splitChance, double splitLength, double splitAngle) { + if (finalized) return; + + ArrayList oldSegments = segments; + segments = new ArrayList<>(); + + Segment prev = null; + + for (Segment segment : oldSegments) { + prev = segment.prev; + + Vec3d subSegment = segment.diff.copy().multiply(1.0 / splits); + + BoltPoint[] newPoints = new BoltPoint[splits + 1]; + + Vec3d startPoint = segment.startPoint.point; + newPoints[0] = segment.startPoint; + newPoints[splits] = segment.endPoint; + + for (int i = 1; i < splits; i++) { + Vec3d randOff = segment.diff.copy().perpendicular().normalize() + .rotate(rand.nextFloat() * 360, segment.diff); + randOff.multiply((rand.nextFloat() - 0.5F) * amount * 2); + + Vec3d basePoint = startPoint.copy().add(subSegment.copy().multiply(i)); + + newPoints[i] = new BoltPoint(basePoint, randOff); + } + + for (int i = 0; i < splits; i++) { + Segment next = new Segment(newPoints[i], newPoints[i + 1], segment.light, + segment.segmentNo * splits + i, segment.splitNo); + next.prev = prev; + if (prev != null) { + prev.next = next; + } + + if (i != 0 && rand.nextFloat() < splitChance) { + Vec3d splitRot = next.diff.copy().xCrossProduct() + .rotate(rand.nextFloat() * 360, next.diff); + Vec3d diff = next.diff.copy() + .rotate((rand.nextFloat() * 0.66F + 0.33F) * splitAngle, splitRot) + .multiply(splitLength); + + numSplits++; + splitParents.put(numSplits, next.splitNo); + + Segment split = new Segment(newPoints[i], + new BoltPoint(newPoints[i + 1].basePoint, newPoints[i + 1].offsetVec.copy().add(diff)), + segment.light / 2F, next.segmentNo, numSplits); + split.prev = prev; + + segments.add(split); + } + + prev = next; + segments.add(next); + } + + if (segment.next != null) { + segment.next.prev = prev; + } + } + + numSegments0 *= splits; + } + + /** + * Finalize the bolt after all fractal passes. + */ + public void finalizeBolt() { + if (finalized) return; + finalized = true; + + calculateEndDiffs(); + Collections.sort(segments, new SegmentLightSorter()); + } + + private void calculateEndDiffs() { + Collections.sort(segments, new SegmentSorter()); + + for (Segment segment : segments) { + segment.calcEndDiffs(); + } + } + + public void onUpdate() { + particleAge++; + if (particleAge >= particleMaxAge) { + isDead = true; + } + } + + /** + * Update all active lightning bolts. Called from client tick handler. + */ + public static void updateAll() { + for (Iterator iterator = boltList.iterator(); iterator.hasNext(); ) { + LightningBolt bolt = iterator.next(); + bolt.onUpdate(); + if (bolt.isDead) { + iterator.remove(); + } + } + } + + // ==================== INNER CLASSES ==================== + + public class BoltPoint { + public Vec3d point; + public Vec3d basePoint; + public Vec3d offsetVec; + + public BoltPoint(Vec3d basePoint, Vec3d offsetVec) { + this.point = basePoint.copy().add(offsetVec); + this.basePoint = basePoint; + this.offsetVec = offsetVec; + } + } + + public class Segment { + public BoltPoint startPoint; + public BoltPoint endPoint; + + public Vec3d diff; + public Segment prev; + public Segment next; + + public Vec3d nextDiff; + public Vec3d prevDiff; + + public float sinPrev; + public float sinNext; + public float light; + + public int segmentNo; + public int splitNo; + + public Segment(BoltPoint start, BoltPoint end, float light, int segmentNo, int splitNo) { + this.startPoint = start; + this.endPoint = end; + this.light = light; + this.segmentNo = segmentNo; + this.splitNo = splitNo; + calcDiff(); + } + + 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); + } + + public void calcDiff() { + diff = endPoint.point.copy().subtract(startPoint.point); + } + + public void calcEndDiffs() { + if (prev != null) { + Vec3d prevDiffNorm = prev.diff.copy().normalize(); + Vec3d thisDiffNorm = diff.copy().normalize(); + + prevDiff = thisDiffNorm.copy().add(prevDiffNorm).normalize(); + sinPrev = (float) Math.sin(thisDiffNorm.angle(prevDiffNorm.multiply(-1)) / 2); + } else { + prevDiff = diff.copy().normalize(); + sinPrev = 1; + } + + if (next != null) { + Vec3d nextDiffNorm = next.diff.copy().normalize(); + Vec3d thisDiffNorm = diff.copy().normalize(); + + nextDiff = thisDiffNorm.add(nextDiffNorm).normalize(); + sinNext = (float) Math.sin(thisDiffNorm.angle(nextDiffNorm.multiply(-1)) / 2); + } else { + nextDiff = diff.copy().normalize(); + sinNext = 1; + } + } + } + + public class SegmentSorter implements Comparator { + @Override + public int compare(Segment o1, Segment o2) { + int comp = Integer.compare(o1.splitNo, o2.splitNo); + if (comp == 0) { + return Integer.compare(o1.segmentNo, o2.segmentNo); + } + return comp; + } + } + + public class SegmentLightSorter implements Comparator { + @Override + public int compare(Segment o1, Segment o2) { + return Float.compare(o2.light, o1.light); + } + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java new file mode 100644 index 000000000..d3f9aeedd --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java @@ -0,0 +1,201 @@ +package kamkeel.npcs.client.renderer.lightning; + +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +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.Tessellator; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.entity.Entity; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraftforge.client.event.RenderWorldLastEvent; +import org.lwjgl.opengl.GL11; + +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) +public class LightningHandler { + + private static final ResourceLocation TEXTURE_OUTER = new ResourceLocation("customnpcs", "textures/effects/lightning_outer.png"); + private static final ResourceLocation TEXTURE_INNER = new ResourceLocation("customnpcs", "textures/effects/lightning_inner.png"); + + public static int lightningCount = 0; + + private static Vec3d getRelativeViewVector(Vec3d pos) { + Entity renderEntity = Minecraft.getMinecraft().renderViewEntity; + return new Vec3d( + (float) renderEntity.posX - pos.x, + (float) renderEntity.posY + renderEntity.getEyeHeight() - pos.y, + (float) renderEntity.posZ - pos.z + ); + } + + @SubscribeEvent + public void onRenderWorldLast(RenderWorldLastEvent event) { + float partialTicks = event.partialTicks; + Entity entity = Minecraft.getMinecraft().thePlayer; + TextureManager textureManager = Minecraft.getMinecraft().renderEngine; + + double interpPosX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks; + double interpPosY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks; + double interpPosZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks; + + if (LightningBolt.boltList.isEmpty()) { + return; + } + + GL11.glPushMatrix(); + GL11.glTranslated(-interpPosX, -interpPosY, -interpPosZ); + + Tessellator tessellator = Tessellator.instance; + + GL11.glDepthMask(false); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_CULL_FACE); + + lightningCount = 0; + + // Render outer layer (translucent glow) + for (LightningBolt bolt : LightningBolt.boltList) { + renderBolt(bolt, tessellator, partialTicks, false); + } + + // Render inner layer (bright core) + for (LightningBolt bolt : LightningBolt.boltList) { + renderBolt(bolt, tessellator, partialTicks, true); + } + + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + GL11.glDepthMask(true); + + GL11.glPopMatrix(); + } + + private void renderBolt(LightningBolt bolt, Tessellator tessellator, float partialTicks, boolean inner) { + lightningCount++; + + float boltAge = bolt.particleAge < 0 ? 0 : (float) bolt.particleAge / (float) bolt.particleMaxAge; + float mainAlpha; + if (!inner) { + mainAlpha = (1 - boltAge) * 0.4F; + } else { + mainAlpha = 1 - boltAge * 0.5F; + } + + int expandTime = (int) (bolt.length * bolt.speed); + + int renderStart = (int) ((expandTime / 2 - bolt.particleMaxAge + bolt.particleAge) / (float) (expandTime / 2) * bolt.numSegments0); + int renderEnd = (int) ((bolt.particleAge + expandTime) / (float) expandTime * bolt.numSegments0); + + for (Segment segment : bolt.segments) { + if (segment.segmentNo < renderStart || segment.segmentNo > renderEnd) { + continue; + } + + Vec3d playerVec = getRelativeViewVector(segment.startPoint.point).multiply(-1); + + double width = 0.008F * (playerVec.mag() / 8 + 1) * (1 + segment.light) * 0.4F; + + Vec3d diff1 = playerVec.copy().crossProduct(segment.prevDiff).normalize().multiply(width / segment.sinPrev); + Vec3d diff2 = playerVec.copy().crossProduct(segment.nextDiff).normalize().multiply(width / segment.sinNext); + + Vec3d startVec = segment.startPoint.point; + Vec3d endVec = segment.endPoint.point; + + int color = inner ? bolt.colorInner : bolt.colorOuter; + Color c = new Color(color); + int alpha = (int) (mainAlpha * segment.light * c.getAlpha()); + + tessellator.startDrawingQuads(); + tessellator.setBrightness(0xF000F0); + tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha); + + tessellator.addVertex(endVec.x - diff2.x, endVec.y - diff2.y, endVec.z - diff2.z); + tessellator.addVertex(startVec.x - diff1.x, startVec.y - diff1.y, startVec.z - diff1.z); + tessellator.addVertex(startVec.x + diff1.x, startVec.y + diff1.y, startVec.z + diff1.z); + tessellator.addVertex(endVec.x + diff2.x, endVec.y + diff2.y, endVec.z + diff2.z); + + tessellator.draw(); + + // Rounded end caps + if (segment.next == null) { + Vec3d roundEnd = segment.endPoint.point.copy().add(segment.diff.copy().normalize().multiply(width)); + + tessellator.startDrawingQuads(); + tessellator.setBrightness(0xF000F0); + tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha); + + tessellator.addVertex(roundEnd.x - diff2.x, roundEnd.y - diff2.y, roundEnd.z - diff2.z); + tessellator.addVertex(endVec.x - diff2.x, endVec.y - diff2.y, endVec.z - diff2.z); + tessellator.addVertex(endVec.x + diff2.x, endVec.y + diff2.y, endVec.z + diff2.z); + tessellator.addVertex(roundEnd.x + diff2.x, roundEnd.y + diff2.y, roundEnd.z + diff2.z); + + tessellator.draw(); + } + + if (segment.prev == null) { + Vec3d roundEnd = segment.startPoint.point.copy().subtract(segment.diff.copy().normalize().multiply(width)); + + tessellator.startDrawingQuads(); + tessellator.setBrightness(0xF000F0); + tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha); + + tessellator.addVertex(startVec.x - diff1.x, startVec.y - diff1.y, startVec.z - diff1.z); + tessellator.addVertex(roundEnd.x - diff1.x, roundEnd.y - diff1.y, roundEnd.z - diff1.z); + tessellator.addVertex(roundEnd.x + diff1.x, roundEnd.y + diff1.y, roundEnd.z + diff1.z); + tessellator.addVertex(startVec.x + diff1.x, startVec.y + diff1.y, startVec.z + diff1.z); + + tessellator.draw(); + } + } + } + + /** + * Spawn a lightning bolt between two points. + * + * @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) + */ + 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); + bolt.defaultFractal(); + bolt.finalizeBolt(); + LightningBolt.boltList.add(bolt); + } + + /** + * Spawn a lightning bolt with automatic seed. + */ + public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, int colorOuter, int colorInner) { + spawnLightningBolt(world, start, end, ticksPerMeter, System.nanoTime(), colorOuter, colorInner); + } + + /** + * Spawn a simple lightning bolt for projectiles - less detail, faster. + */ + public static void spawnSimpleLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, int colorOuter, int colorInner) { + LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, System.nanoTime(), colorOuter, colorInner); + bolt.simpleFractal(); + bolt.finalizeBolt(); + LightningBolt.boltList.add(bolt); + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/Quaternion.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/Quaternion.java new file mode 100644 index 000000000..cda0307b7 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/Quaternion.java @@ -0,0 +1,85 @@ +package kamkeel.npcs.client.renderer.lightning; + +/** + * Quaternion class for axis-angle rotations in lightning calculations. + * Adapted from Botania's Quat by ChickenBones. + */ +public class Quaternion { + public double x; + public double y; + public double z; + public double s; + + public Quaternion() { + s = 1.0; + x = 0.0; + y = 0.0; + z = 0.0; + } + + public Quaternion(Quaternion quat) { + x = quat.x; + y = quat.y; + z = quat.z; + s = quat.s; + } + + public Quaternion(double s, double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + this.s = s; + } + + public static Quaternion aroundAxis(double ax, double ay, double az, double angle) { + angle *= 0.5; + double sinAngle = Math.sin(angle); + return new Quaternion(Math.cos(angle), ax * sinAngle, ay * sinAngle, az * sinAngle); + } + + public static Quaternion aroundAxis(Vec3d axis, double angle) { + return aroundAxis(axis.x, axis.y, axis.z, angle); + } + + public void multiply(Quaternion quat) { + double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z; + double d1 = s * quat.x + x * quat.s - y * quat.z + z * quat.y; + double d2 = s * quat.y + x * quat.z + y * quat.s - z * quat.x; + double d3 = s * quat.z - x * quat.y + y * quat.x + z * quat.s; + s = d; + x = d1; + y = d2; + z = d3; + } + + public double mag() { + return Math.sqrt(x * x + y * y + z * z + s * s); + } + + public void normalize() { + double d = mag(); + if (d == 0.0) { + return; + } + d = 1.0 / d; + x *= d; + y *= d; + z *= d; + s *= d; + } + + public void rotate(Vec3d vec) { + double d = -x * vec.x - y * vec.y - z * vec.z; + double d1 = s * vec.x + y * vec.z - z * vec.y; + double d2 = s * vec.y - x * vec.z + z * vec.x; + double d3 = s * vec.z + x * vec.y - y * vec.x; + vec.x = d1 * s - d * x - d2 * z + d3 * y; + vec.y = d2 * s - d * y + d1 * z - d3 * x; + vec.z = d3 * s - d * z - d1 * y + d2 * x; + } + + @Override + public String toString() { + return "Quaternion(" + s + ", " + x + ", " + y + ", " + z + ")"; + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/Vec3d.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/Vec3d.java new file mode 100644 index 000000000..018e55bdb --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/Vec3d.java @@ -0,0 +1,184 @@ +package kamkeel.npcs.client.renderer.lightning; + +import net.minecraft.entity.Entity; +import net.minecraft.util.Vec3; +import org.lwjgl.opengl.GL11; + +/** + * 3D Vector helper class for lightning calculations. + * Adapted from Botania's Vector3 by ChickenBones. + */ +public class Vec3d { + public double x; + public double y; + public double z; + + public Vec3d() { + } + + public Vec3d(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public Vec3d(Vec3d vec) { + this.x = vec.x; + this.y = vec.y; + this.z = vec.z; + } + + public Vec3d(Vec3 vec) { + this.x = vec.xCoord; + this.y = vec.yCoord; + this.z = vec.zCoord; + } + + public Vec3d copy() { + return new Vec3d(this); + } + + public static Vec3d fromEntity(Entity e) { + return new Vec3d(e.posX, e.posY, e.posZ); + } + + public static Vec3d fromEntityCenter(Entity e) { + return new Vec3d(e.posX, e.posY - e.yOffset + e.height / 2, e.posZ); + } + + public Vec3d set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + + public Vec3d set(Vec3d vec) { + this.x = vec.x; + this.y = vec.y; + this.z = vec.z; + return this; + } + + public double dotProduct(Vec3d vec) { + double d = vec.x * x + vec.y * y + vec.z * z; + if (d > 1 && d < 1.00001) d = 1; + else if (d < -1 && d > -1.00001) d = -1; + return d; + } + + public Vec3d crossProduct(Vec3d vec) { + double d = y * vec.z - z * vec.y; + double d1 = z * vec.x - x * vec.z; + double d2 = x * vec.y - y * vec.x; + x = d; + y = d1; + z = d2; + return this; + } + + public Vec3d add(double x, double y, double z) { + this.x += x; + this.y += y; + this.z += z; + return this; + } + + public Vec3d add(Vec3d vec) { + this.x += vec.x; + this.y += vec.y; + this.z += vec.z; + return this; + } + + public Vec3d subtract(Vec3d vec) { + this.x -= vec.x; + this.y -= vec.y; + this.z -= vec.z; + return this; + } + + public Vec3d multiply(double d) { + this.x *= d; + this.y *= d; + this.z *= d; + return this; + } + + public double mag() { + return Math.sqrt(x * x + y * y + z * z); + } + + public double magSquared() { + return x * x + y * y + z * z; + } + + public Vec3d normalize() { + double d = mag(); + if (d != 0) { + multiply(1 / d); + } + return this; + } + + public Vec3d perpendicular() { + if (z == 0) { + return zCrossProduct(); + } + return xCrossProduct(); + } + + public Vec3d xCrossProduct() { + double d = z; + double d1 = -y; + x = 0; + y = d; + z = d1; + return this; + } + + public Vec3d zCrossProduct() { + double d = y; + double d1 = -x; + x = d; + y = d1; + z = 0; + return this; + } + + public Vec3 toVec3() { + return Vec3.createVectorHelper(x, y, z); + } + + public double angle(Vec3d vec) { + return Math.acos(copy().normalize().dotProduct(vec.copy().normalize())); + } + + public Vec3d negate() { + x = -x; + y = -y; + z = -z; + return this; + } + + public Vec3d rotate(double angle, Vec3d axis) { + Quaternion.aroundAxis(axis.copy().normalize(), angle).rotate(this); + return this; + } + + public void glVertex() { + GL11.glVertex3d(x, y, z); + } + + @Override + public String toString() { + return "Vec3d(" + x + ", " + y + ", " + z + ")"; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Vec3d)) return false; + Vec3d v = (Vec3d) o; + return x == v.x && y == v.y && z == v.z; + } +} diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java new file mode 100644 index 000000000..982a975b3 --- /dev/null +++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java @@ -0,0 +1,434 @@ +package kamkeel.npcs.command; + +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.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; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import static kamkeel.npcs.util.ColorUtil.sendError; +import static kamkeel.npcs.util.ColorUtil.sendResult; + +public class AbilityCommand extends CommandKamkeelBase { + + @Override + public String getCommandName() { + return "ability"; + } + + @Override + public String getDescription() { + return "Ability operations"; + } + + @SubCommand( + desc = "List all custom abilities" + ) + public void list(ICommandSender sender, String[] args) { + Set names = AbilityController.Instance.getCustomAbilityNames(); + if (names.isEmpty()) { + sendResult(sender, "No custom abilities found."); + return; + } + + sendResult(sender, "Custom Abilities (" + names.size() + "):"); + for (String name : names) { + Ability ability = AbilityController.Instance.getCustomAbility(name); + if (ability != null) { + sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")"); + } else { + sendResult(sender, " - \u00A7b" + name); + } + } + } + + @SubCommand( + desc = "List all registered ability types" + ) + public void types(ICommandSender sender, String[] args) { + String[] typeIds = AbilityController.Instance.getTypes(); + if (typeIds.length == 0) { + sendResult(sender, "No ability types registered."); + return; + } + + List sortedTypes = new ArrayList<>(); + for (String typeId : typeIds) { + sortedTypes.add(typeId); + } + Collections.sort(sortedTypes); + + sendResult(sender, "Registered Ability Types (" + sortedTypes.size() + "):"); + for (String typeId : sortedTypes) { + sendResult(sender, " - \u00A7d" + typeId); + } + } + + @SubCommand( + desc = "Reload abilities from disk" + ) + public void reload(ICommandSender sender, String[] args) { + AbilityController.Instance.load(); + sendResult(sender, "Abilities and chained abilities reloaded from disk."); + } + + @SubCommand( + 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 "); + return; + } + + String name = joinArgs(args, 0); + if (!AbilityController.Instance.hasCustomAbilityName(name)) { + sendError(sender, "No custom ability with name: " + name); + return; + } + + AbilityController.Instance.deleteCustomAbility(name); + sendResult(sender, "Deleted ability: \u00A7b" + name); + } + + @SubCommand( + desc = "Get info about an ability", + usage = "" + ) + public void info(ICommandSender sender, String[] args) { + if (args.length < 1) { + sendError(sender, "Usage: /kam ability info "); + return; + } + + 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.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"); + if (ability.isInterruptible()) { + sendResult(sender, " Dazed: \u00A7e" + ability.getDazedTicks() + " ticks"); + } + sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange()); + sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No")); + sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name()); + } + + @SubCommand( + desc = "List all built-in abilities available for players" + ) + public void prebuilts(ICommandSender sender, String[] args) { + Set names = AbilityController.Instance.getAbilityNames(); + if (names.isEmpty()) { + sendResult(sender, "No built-in abilities found."); + return; + } + + List playerAbilities = new ArrayList<>(); + for (String name : names) { + Ability ability = AbilityController.Instance.getAbility(name); + if (ability != null && ability.getAllowedBy().allowsPlayer()) { + playerAbilities.add(name); + } + } + + if (playerAbilities.isEmpty()) { + sendResult(sender, "No player-usable built-in abilities found."); + return; + } + + Collections.sort(playerAbilities); + sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):"); + for (String name : playerAbilities) { + Ability ability = AbilityController.Instance.getAbility(name); + String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]"; + sendResult(sender, " - \u00A7b" + name + " " + userType); + } + } + + @SubCommand( + desc = "Give an ability to a player", + usage = " " + ) + public void give(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability give "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + if (ability == null) { + sendError(sender, "Ability not found: " + abilityKey); + return; + } + + // Use the ability's canonical ID for storage (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId(); + if (canonicalKey == null || canonicalKey.isEmpty()) { + canonicalKey = abilityKey; + } + String displayName = ability.getDisplayName(); + + if (!ability.getAllowedBy().allowsPlayer()) { + sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players."); + return; + } + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player already has ability: " + displayName); + return; + } + + data.abilityData.unlockAbility(canonicalKey); + sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName); + } + + @SubCommand( + desc = "Remove an ability from a player", + usage = " " + ) + public void remove(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability remove "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + if (ability == null) { + sendError(sender, "Ability not found: " + abilityKey); + return; + } + String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey; + String displayName = ability.getDisplayName(); + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (!data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player doesn't have ability: " + displayName); + return; + } + + data.abilityData.lockAbility(canonicalKey); + 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( + desc = "List abilities unlocked for a player", + usage = "" + ) + public void player(ICommandSender sender, String[] args) { + if (args.length < 1) { + sendError(sender, "Usage: /kam ability player "); + return; + } + + String playerName = args[0]; + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + String[] abilityKeys = data.abilityData.getUnlockedAbilities(); + + if (abilityKeys.length == 0) { + sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities."); + return; + } + + sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):"); + int selected = data.abilityData.getSelectedIndex(); + for (int i = 0; i < abilityKeys.length; i++) { + String key = abilityKeys[i]; + String prefix = (i == selected) ? "\u00A7e> " : " "; + + 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 { + // 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); + } + } + } + } + + private String joinArgs(String[] args, int startIndex) { + StringBuilder sb = new StringBuilder(); + for (int i = startIndex; i < args.length; i++) { + if (i > startIndex) sb.append(" "); + sb.append(args[i]); + } + return sb.toString(); + } + + /** + * Get list of player-usable ability names (for tab completion). + * Resolves UUIDs to names so tab completion shows human-readable names. + * Used by CommandKamkeel for {@code } usage token. + */ + public static List getPlayerAbilityNames() { + 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 new file mode 100644 index 000000000..a56dce671 --- /dev/null +++ b/src/main/java/kamkeel/npcs/command/AuctionCommand.java @@ -0,0 +1,185 @@ +package kamkeel.npcs.command; + +import kamkeel.npcs.command.auction.BlacklistSubCommand; +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumGuiType; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.controllers.data.PlayerData; + +import java.util.List; +import java.util.UUID; + +import static kamkeel.npcs.util.ColorUtil.sendError; +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(); + registerNestedCommand(new BlacklistSubCommand()); + } + + @Override + public String getCommandName() { + return "auction"; + } + + @Override + public String getDescription() { + return "Auction operations"; + } + + @SubCommand( + desc = "List active auctions", + usage = "[page]" + ) + public void list(ICommandSender sender, String[] args) throws CommandException { + if (!ConfigMarket.AuctionEnabled) { + sendError(sender, "Auction system is disabled"); + return; + } + + AuctionController controller = AuctionController.getInstance(); + if (controller == null) { + sendError(sender, "Auction system is not available"); + return; + } + + int page = 1; + if (args.length > 0) { + try { + page = Integer.parseInt(args[0]); + } catch (NumberFormatException ex) { + sendError(sender, "Invalid page number: " + args[0]); + return; + } + } + + 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 / COMMAND_PAGE_SIZE)); + + if (listings.isEmpty()) { + sendMessage(sender, "\u00A77No active auctions found"); + return; + } + + sendMessage(sender, String.format("\u00A76=== Active Auctions (Page %d/%d) ===", page, totalPages)); + for (AuctionListing listing : listings) { + String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown"; + String price = listing.hasBids() ? + String.format("%,d (bid)", listing.currentBid) : + String.format("%,d (start)", listing.startingPrice); + sendMessage(sender, String.format("\u00A7e%s \u00A77by \u00A7b%s\u00A77 - \u00A76%s %s", + itemName, listing.sellerName, price, ConfigMarket.CurrencyName)); + } + } + + @SubCommand( + desc = "View player's auction activity", + usage = "" + ) + public void view(ICommandSender sender, String[] args) throws CommandException { + if (!ConfigMarket.AuctionEnabled) { + sendError(sender, "Auction system is disabled"); + return; + } + + AuctionController controller = AuctionController.getInstance(); + if (controller == null) { + sendError(sender, "Auction system is not available"); + return; + } + + if (args.length < 1) { + throw new CommandException("Usage: /auction view "); + } + + String playername = args[0]; + List dataList = PlayerDataController.Instance.getPlayersData(sender, playername); + + if (dataList.isEmpty()) { + sendError(sender, "Unknown player: " + playername); + return; + } + + for (PlayerData playerdata : dataList) { + UUID playerUUID = UUID.fromString(playerdata.uuid); + List activeListings = controller.getPlayerActiveListings(playerUUID); + List activeBids = controller.getPlayerActiveBids(playerUUID); + int claimCount = controller.getPlayerClaims(playerUUID).size(); + + sendMessage(sender, String.format("\u00A76=== Auction Activity for %s ===", playerdata.playername)); + sendMessage(sender, String.format("\u00A77Active Listings: \u00A7e%d", activeListings.size())); + sendMessage(sender, String.format("\u00A77Active Bids: \u00A7e%d", activeBids.size())); + sendMessage(sender, String.format("\u00A77Pending Claims: \u00A7e%d", claimCount)); + + if (!activeListings.isEmpty()) { + sendMessage(sender, "\u00A7a--- Selling ---"); + for (AuctionListing listing : activeListings) { + String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown"; + String price = listing.hasBids() ? + String.format("%,d (bid)", listing.currentBid) : + String.format("%,d (start)", listing.startingPrice); + sendMessage(sender, String.format(" \u00A7e%s \u00A77- \u00A76%s", itemName, price)); + } + } + + if (!activeBids.isEmpty()) { + sendMessage(sender, "\u00A7e--- Bidding ---"); + for (AuctionListing bid : activeBids) { + String itemName = bid.item != null ? bid.item.getDisplayName() : "Unknown"; + sendMessage(sender, String.format(" \u00A7e%s \u00A77- \u00A76%,d %s", + itemName, bid.currentBid, ConfigMarket.CurrencyName)); + } + } + } + } + + @SubCommand( + desc = "Open the Auction GUI", + usage = "", + permission = 0 + ) + public void open(ICommandSender sender, String[] args) throws CommandException { + if (!ConfigMarket.AuctionEnabled) { + sendError(sender, "Auction system is disabled"); + return; + } + + if (!(sender instanceof EntityPlayer)) { + sendError(sender, "This command can only be used by players"); + return; + } + + EntityPlayer player = (EntityPlayer) sender; + + // Open the auction GUI without requiring an NPC + NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, null); + sendResult(sender, "Opening Auction..."); + } + + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] args) { + if (args.length == 1) { + return getListOfStringsMatchingLastWord(args, getAllSubCommandNames()); + } + + // Delegate to nested commands for deeper tab completion + List nestedCompletions = getNestedTabCompletions(sender, args); + if (nestedCompletions != null) { + return nestedCompletions; + } + + return null; + } +} diff --git a/src/main/java/kamkeel/npcs/command/CloneCommand.java b/src/main/java/kamkeel/npcs/command/CloneCommand.java index 027ff228e..312293ca5 100644 --- a/src/main/java/kamkeel/npcs/command/CloneCommand.java +++ b/src/main/java/kamkeel/npcs/command/CloneCommand.java @@ -13,6 +13,7 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import noppes.npcs.controllers.ServerCloneController; +import noppes.npcs.controllers.data.CloneFolder; import noppes.npcs.entity.EntityNPCInterface; import java.util.List; @@ -35,20 +36,24 @@ public class CloneCommand extends CommandKamkeelBase { @SubCommand( desc = "Add NPC(s) to clone storage", - usage = " [clonedname]", + usage = " [clonedname]", permission = 4 ) public void add(ICommandSender sender, String[] args) { - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { + if (tab < 1 || tab > 15) { sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } int x = sender.getPlayerCoordinates().posX; @@ -64,32 +69,47 @@ public class CloneCommand extends CommandKamkeelBase { NBTTagCompound compound = new NBTTagCompound(); if (!npc.writeToNBTOptional(compound)) return; - ServerCloneController.Instance.addClone(compound, name, tab); - sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab)); + if (folder != null) { + ServerCloneController.Instance.addClone(compound, name, folder); + sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Folder \u00A7b%s\u00A77", name, folder)); + } else { + ServerCloneController.Instance.addClone(compound, name, tab); + sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab)); + } } } } @SubCommand( desc = "List NPC from clone storage", - usage = "", + usage = "", permission = 2 ) public void list(ICommandSender sender, String[] args) { sendMessage(sender, "--- Stored NPCs --- (server side)"); - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { + if (tab < 1 || tab > 15) { sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } - for (String name : ServerCloneController.Instance.getClones(tab)) { + List clones; + if (folder != null) { + clones = ServerCloneController.Instance.getClones(folder); + } else { + clones = ServerCloneController.Instance.getClones(tab); + } + for (String name : clones) { sendMessage(sender, name); } sendMessage(sender, "------------------------------------"); @@ -97,59 +117,75 @@ public class CloneCommand extends CommandKamkeelBase { @SubCommand( desc = "Remove NPC from clone storage", - usage = " ", + usage = " ", permission = 4 ) public void del(ICommandSender sender, String[] args) throws CommandException { String nametodel = args[0]; - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { - sendError(sender, String.format("Tab must be within 1-15")); + if (tab < 1 || tab > 15) { + sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; - } - - boolean deleted = false; - for (String name : ServerCloneController.Instance.getClones(tab)) { - if (nametodel.equalsIgnoreCase(name)) { - ServerCloneController.Instance.removeClone(name, tab); - deleted = true; - break; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; } } - if (!ServerCloneController.Instance.removeClone(nametodel, tab)) { + + boolean success; + if (folder != null) { + success = ServerCloneController.Instance.removeClone(nametodel, folder); + } else { + success = ServerCloneController.Instance.removeClone(nametodel, tab); + } + + if (!success) { sendError(sender, String.format("NPC '%s' was not found", nametodel)); } else { - sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab)); + if (folder != null) { + sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Folder \u00A7b%s\u00A77", nametodel, folder)); + } else { + sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab)); + } } } @SubCommand( desc = "Spawn cloned NPC", - usage = " [[world:]x,y,z]] [newname]", + usage = " [[world:]x,y,z]] [newname]", permission = 2 ) public void spawn(ICommandSender sender, String[] args) throws CommandException { String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { - sendError(sender, String.format("Tab must be within 1-15")); + if (tab < 1 || tab > 15) { + sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } String newname = null; - NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + NBTTagCompound compound; + if (folder != null) { + compound = ServerCloneController.Instance.getCloneData(sender, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + } if (compound == null) { sendError(sender, "Unknown npc"); return; @@ -211,22 +247,26 @@ public class CloneCommand extends CommandKamkeelBase { } @SubCommand( - desc = "Spawn cloned NPC", - usage = " [[world:]x,y,z]] [newname]", + desc = "Spawn cloned NPC in a grid", + usage = " [[world:]x,y,z]] [newname]", permission = 2 ) public void grid(ICommandSender sender, String[] args) throws CommandException { String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { - sendError(sender, String.format("Tab must be within 1-15")); + if (tab < 1 || tab > 15) { + sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } int width, height; @@ -238,9 +278,13 @@ public class CloneCommand extends CommandKamkeelBase { return; } - String newname = null; - NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + NBTTagCompound compound; + if (folder != null) { + compound = ServerCloneController.Instance.getCloneData(sender, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + } if (compound == null) { sendError(sender, "Unknown npc"); return; @@ -317,6 +361,163 @@ public class CloneCommand extends CommandKamkeelBase { return; } + @SubCommand( + desc = "List all custom clone folders", + usage = "", + permission = 2 + ) + public void listfolders(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + sendMessage(sender, "--- Clone Folders ---"); + for (CloneFolder f : ServerCloneController.Instance.getFolderList()) { + sendMessage(sender, f.name); + } + sendMessage(sender, "------------------------------------"); + } + + @SubCommand( + desc = "Create a custom clone folder", + usage = "", + permission = 4 + ) + public void createfolder(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String name = args[0]; + if (!CloneFolder.isValidName(name)) { + sendError(sender, String.format("Invalid folder name: %s", name)); + return; + } + if (ServerCloneController.Instance.hasFolder(name)) { + sendError(sender, String.format("Folder '%s' already exists", name)); + return; + } + CloneFolder created = ServerCloneController.Instance.createFolder(name); + if (created != null) { + sendResult(sender, String.format("Created folder \u00A7b%s", name)); + } else { + sendError(sender, String.format("Failed to create folder '%s'", name)); + } + } + + @SubCommand( + desc = "Rename a custom clone folder", + usage = " ", + permission = 4 + ) + public void renamefolder(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String oldName = args[0]; + String newName = args[1]; + if (!ServerCloneController.Instance.hasFolder(oldName)) { + sendError(sender, String.format("Unknown folder: %s", oldName)); + return; + } + if (!CloneFolder.isValidName(newName)) { + sendError(sender, String.format("Invalid folder name: %s", newName)); + return; + } + if (ServerCloneController.Instance.renameFolder(oldName, newName)) { + sendResult(sender, String.format("Renamed folder \u00A7b%s\u00A77 to \u00A7b%s", oldName, newName)); + } else { + sendError(sender, String.format("Failed to rename folder '%s'", oldName)); + } + } + + @SubCommand( + desc = "Delete an empty custom clone folder", + usage = "", + permission = 4 + ) + public void deletefolder(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String name = args[0]; + if (!ServerCloneController.Instance.hasFolder(name)) { + sendError(sender, String.format("Unknown folder: %s", name)); + return; + } + if (ServerCloneController.Instance.deleteFolder(name)) { + sendResult(sender, String.format("Deleted folder \u00A7b%s", name)); + } else { + sendError(sender, String.format("Failed to delete folder '%s' (folder must be empty)", name)); + } + } + + @SubCommand( + desc = "Move a clone between tabs/folders", + usage = " ", + permission = 4 + ) + public void move(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String cloneName = args[0]; + + int fromTab = -1; + String fromFolder = null; + try { + fromTab = Integer.parseInt(args[1]); + if (fromTab < 1 || fromTab > 15) { + sendError(sender, "Source tab must be within 1-15"); + return; + } + } catch (NumberFormatException ex) { + fromFolder = args[1]; + if (!ServerCloneController.Instance.hasFolder(fromFolder)) { + sendError(sender, String.format("Unknown source folder: %s", fromFolder)); + return; + } + } + + int toTab = -1; + String toFolder = null; + try { + toTab = Integer.parseInt(args[2]); + if (toTab < 1 || toTab > 15) { + sendError(sender, "Destination tab must be within 1-15"); + return; + } + } catch (NumberFormatException ex) { + toFolder = args[2]; + if (!ServerCloneController.Instance.hasFolder(toFolder)) { + sendError(sender, String.format("Unknown destination folder: %s", toFolder)); + return; + } + } + + boolean success; + if (fromFolder != null && toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder); + } else if (fromFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab); + } else if (toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder); + } else { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab); + } + + if (success) { + String from = fromFolder != null ? fromFolder : String.valueOf(fromTab); + String to = toFolder != null ? toFolder : String.valueOf(toTab); + sendResult(sender, String.format("Moved \u00A7e%s\u00A77 from \u00A7b%s\u00A77 to \u00A7b%s", cloneName, from, to)); + } else { + sendError(sender, String.format("Failed to move '%s'", cloneName)); + } + } + public World getWorld(String t) { WorldServer[] ws = MinecraftServer.getServer().worldServers; for (WorldServer w : ws) { diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java index 76bc80b94..f87068968 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java @@ -10,6 +10,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import noppes.npcs.CustomNpcsPermissions; import noppes.npcs.config.ConfigMain; +import noppes.npcs.config.ConfigMarket; import noppes.npcs.scripted.CustomNPCsException; import java.lang.reflect.Method; @@ -19,6 +20,8 @@ import java.util.HashMap; 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 { @@ -43,8 +46,13 @@ public class CommandKamkeel extends CommandBase { registerCommand(new OverlayCommand()); registerCommand(new CommandCommand()); registerCommand(new EffectCommand()); + registerCommand(new AbilityCommand()); + registerCommand(new MoneyCommand()); + if (ConfigMarket.AuctionEnabled) + registerCommand(new AuctionCommand()); if (ConfigMain.AttributesEnabled) registerCommand(new AttributeCommand()); + registerCommand(new DebugCommand()); } public void registerCommand(CommandKamkeelBase command) { @@ -128,7 +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 = 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()])); } } @@ -136,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 af2366f89..c6ffe7ec1 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java @@ -12,12 +12,16 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; 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(); + public Map nestedCommands = new HashMap(); public CommandKamkeelBase() { for (Method m : this.getClass().getDeclaredMethods()) { @@ -31,6 +35,14 @@ public abstract class CommandKamkeelBase extends CommandBase { } } + /** + * Register a nested command class as a subcommand. + * The nested command's getCommandName() becomes the subcommand name. + */ + public void registerNestedCommand(CommandKamkeelBase command) { + nestedCommands.put(command.getCommandName().toLowerCase(), command); + } + @Override public void processCommand(ICommandSender sender, String[] args) throws CommandException { @@ -51,7 +63,7 @@ public abstract class CommandKamkeelBase extends CommandBase { } public boolean runSubCommands() { - return !subcommands.isEmpty(); + return !subcommands.isEmpty() || !nestedCommands.isEmpty(); } @Retention(value = RetentionPolicy.RUNTIME) @@ -71,6 +83,22 @@ public abstract class CommandKamkeelBase extends CommandBase { } public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException { + // Check nested commands first + CommandKamkeelBase nested = nestedCommands.get(command.toLowerCase()); + if (nested != null) { + if (!canSendNestedCommand(sender, nested)) { + throw new CommandException("You are not allowed to use this command: " + command); + } + + if (args.length == 0 || !nested.runSubCommands()) { + nested.processCommand(sender, args); + } else { + nested.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length)); + } + return; + } + + // Fall back to method subcommands Method m = subcommands.get(command.toLowerCase()); if (m == null) throw new CommandException("Unknown subcommand " + command); @@ -132,4 +160,55 @@ public abstract class CommandKamkeelBase extends CommandBase { return false; } + + public boolean canSendNestedCommand(ICommandSender sender, CommandKamkeelBase nested) { + int permission = nested.getRequiredPermissionLevel(); + String subCommand = nested.getCommandName(); + + if (sender.canCommandSenderUseCommand(permission, getSubUniversalPermission())) { + return true; + } + + if (sender.canCommandSenderUseCommand(permission, getSubCommandPermission(subCommand))) { + return true; + } + + if (sender instanceof EntityPlayer) { + return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand)); + } + + return false; + } + + // ========================================= + // Tab Completion Helpers + // ========================================= + + /** + * Get all subcommand names (both method-based and nested) + */ + public String[] getAllSubCommandNames() { + Set names = new HashSet<>(); + names.addAll(subcommands.keySet()); + names.addAll(nestedCommands.keySet()); + return names.toArray(new String[0]); + } + + /** + * Get tab completions for nested command at given depth + */ + public List getNestedTabCompletions(ICommandSender sender, String[] args) { + if (args.length == 0) return null; + + String subCmd = args[0].toLowerCase(); + CommandKamkeelBase nested = nestedCommands.get(subCmd); + + if (nested != null && args.length > 1) { + // Delegate to nested command + String[] nestedArgs = Arrays.copyOfRange(args, 1, args.length); + return nested.addTabCompletionOptions(sender, nestedArgs); + } + + return null; + } } 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/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/MoneyCommand.java b/src/main/java/kamkeel/npcs/command/MoneyCommand.java new file mode 100644 index 000000000..ee034243d --- /dev/null +++ b/src/main/java/kamkeel/npcs/command/MoneyCommand.java @@ -0,0 +1,168 @@ +package kamkeel.npcs.command; + +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.PlayerTradeData; + +import java.util.List; + +import static kamkeel.npcs.util.ColorUtil.sendError; +import static kamkeel.npcs.util.ColorUtil.sendResult; + +public class MoneyCommand extends CommandKamkeelBase { + + @Override + public String getCommandName() { + return "money"; + } + + @Override + public String getDescription() { + return "Currency operations"; + } + + @SubCommand( + desc = "Show player's balance", + usage = "" + ) + public void balance(ICommandSender sender, String[] args) throws CommandException { + String playername = args[0]; + List dataList = PlayerDataController.Instance.getPlayersData(sender, playername); + + if (dataList.isEmpty()) { + sendError(sender, "Unknown player: " + playername); + return; + } + + for (PlayerData playerdata : dataList) { + PlayerTradeData currency = playerdata.tradeData; + long balance = currency.getBalance(); + sendResult(sender, String.format("Player \u00A7b%s\u00A77 has \u00A76%,d %s", + playerdata.playername, balance, ConfigMarket.CurrencyName)); + } + } + + @SubCommand( + desc = "Give currency to player", + usage = " " + ) + public void give(ICommandSender sender, String[] args) throws CommandException { + String playername = args[0]; + long amount; + try { + amount = Long.parseLong(args[1]); + } catch (NumberFormatException ex) { + sendError(sender, "Invalid amount: " + args[1]); + return; + } + + if (amount <= 0) { + sendError(sender, "Amount must be positive"); + return; + } + + List dataList = PlayerDataController.Instance.getPlayersData(sender, playername); + + if (dataList.isEmpty()) { + sendError(sender, "Unknown player: " + playername); + return; + } + + for (PlayerData playerdata : dataList) { + PlayerTradeData currency = playerdata.tradeData; + if (currency.deposit(amount)) { + playerdata.save(); + sendResult(sender, String.format("Gave \u00A76%,d %s\u00A77 to player \u00A7b%s\u00A77. New balance: \u00A76%,d", + amount, ConfigMarket.CurrencyName, playerdata.playername, currency.getBalance())); + } else { + sendError(sender, String.format("Failed to give currency to %s (would exceed max balance)", + playerdata.playername)); + } + } + } + + @SubCommand( + desc = "Withdraw currency from player", + usage = " " + ) + public void withdraw(ICommandSender sender, String[] args) throws CommandException { + String playername = args[0]; + long amount; + try { + amount = Long.parseLong(args[1]); + } catch (NumberFormatException ex) { + sendError(sender, "Invalid amount: " + args[1]); + return; + } + + if (amount <= 0) { + sendError(sender, "Amount must be positive"); + return; + } + + List dataList = PlayerDataController.Instance.getPlayersData(sender, playername); + + if (dataList.isEmpty()) { + sendError(sender, "Unknown player: " + playername); + return; + } + + for (PlayerData playerdata : dataList) { + PlayerTradeData currency = playerdata.tradeData; + if (currency.withdraw(amount)) { + playerdata.save(); + sendResult(sender, String.format("Withdrew \u00A76%,d %s\u00A77 from player \u00A7b%s\u00A77. New balance: \u00A76%,d", + amount, ConfigMarket.CurrencyName, playerdata.playername, currency.getBalance())); + } else { + sendError(sender, String.format("Failed to withdraw from %s (insufficient funds)", + playerdata.playername)); + } + } + } + + @SubCommand( + desc = "Set player's balance", + usage = " " + ) + public void set(ICommandSender sender, String[] args) throws CommandException { + String playername = args[0]; + long amount; + try { + amount = Long.parseLong(args[1]); + } catch (NumberFormatException ex) { + sendError(sender, "Invalid amount: " + args[1]); + return; + } + + if (amount < 0) { + sendError(sender, "Amount cannot be negative"); + return; + } + + List dataList = PlayerDataController.Instance.getPlayersData(sender, playername); + + if (dataList.isEmpty()) { + sendError(sender, "Unknown player: " + playername); + return; + } + + for (PlayerData playerdata : dataList) { + PlayerTradeData currency = playerdata.tradeData; + currency.setBalance(amount); + playerdata.save(); + sendResult(sender, String.format("Set balance of player \u00A7b%s\u00A77 to \u00A76%,d %s", + playerdata.playername, currency.getBalance(), ConfigMarket.CurrencyName)); + } + } + + @Override + public List addTabCompletionOptions(ICommandSender par1, String[] args) { + if (args.length == 1) { + return getListOfStringsMatchingLastWord(args, new String[]{"balance", "give", "withdraw", "set"}); + } + return null; + } +} 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..5ccbe5319 100644 --- a/src/main/java/kamkeel/npcs/command/QuestCommand.java +++ b/src/main/java/kamkeel/npcs/command/QuestCommand.java @@ -115,7 +115,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(); diff --git a/src/main/java/kamkeel/npcs/command/ScriptCommand.java b/src/main/java/kamkeel/npcs/command/ScriptCommand.java index 41415cb81..61b380dbd 100644 --- a/src/main/java/kamkeel/npcs/command/ScriptCommand.java +++ b/src/main/java/kamkeel/npcs/command/ScriptCommand.java @@ -12,6 +12,7 @@ public class ScriptCommand extends CommandKamkeelBase { @SubCommand(desc = "Reload scripts data and folders.") public Boolean reload(ICommandSender sender, String args[]) { ScriptController.Instance.loadCategories(); + ScriptController.Instance.syncClientScripts(null); if (ScriptController.Instance.loadPlayerScripts()) sendResult(sender, "Reload player scripts successfully"); diff --git a/src/main/java/kamkeel/npcs/command/auction/BlacklistSubCommand.java b/src/main/java/kamkeel/npcs/command/auction/BlacklistSubCommand.java new file mode 100644 index 000000000..a9902a890 --- /dev/null +++ b/src/main/java/kamkeel/npcs/command/auction/BlacklistSubCommand.java @@ -0,0 +1,226 @@ +package kamkeel.npcs.command.auction; + +import kamkeel.npcs.command.CommandKamkeelBase; +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import noppes.npcs.controllers.data.AuctionBlacklist; + +import java.util.List; + +import static kamkeel.npcs.util.ColorUtil.sendError; +import static kamkeel.npcs.util.ColorUtil.sendMessage; +import static kamkeel.npcs.util.ColorUtil.sendResult; + +public class BlacklistSubCommand extends CommandKamkeelBase { + + @Override + public String getCommandName() { + return "blacklist"; + } + + @Override + public String getDescription() { + return "Manage auction item blacklist"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) throws CommandException { + // Show help when called with no subcommand + sendHelp(sender); + } + + private void sendHelp(ICommandSender sender) { + sendMessage(sender, "\u00A76=== Auction Blacklist Commands ==="); + sendMessage(sender, "\u00A7e/cnpc auction blacklist add "); + sendMessage(sender, "\u00A7e/cnpc auction blacklist remove "); + sendMessage(sender, "\u00A7e/cnpc auction blacklist list [item|mod|nbt]"); + sendMessage(sender, "\u00A7e/cnpc auction blacklist reload"); + sendMessage(sender, "\u00A7e/cnpc auction blacklist check \u00A77(checks held item)"); + } + + @SubCommand( + desc = "Add item, mod, or NBT tag to blacklist", + usage = " " + ) + public void add(ICommandSender sender, String[] args) throws CommandException { + if (args.length < 2) { + sendError(sender, "Usage: /cnpc auction blacklist add "); + return; + } + + String type = args[0].toLowerCase(); + String value = args[1]; + + switch (type) { + case "item": + if (AuctionBlacklist.addItem(value)) { + sendResult(sender, "Added item to blacklist: " + value); + } else { + sendError(sender, "Failed to add item to blacklist"); + } + break; + case "mod": + if (AuctionBlacklist.addMod(value)) { + sendResult(sender, "Added mod to blacklist: " + value); + } else { + sendError(sender, "Failed to add mod to blacklist"); + } + break; + case "nbt": + if (AuctionBlacklist.addNBTTag(value)) { + sendResult(sender, "Added NBT tag to blacklist: " + value); + } else { + sendError(sender, "Failed to add NBT tag to blacklist"); + } + break; + default: + sendError(sender, "Unknown type: " + type + ". Use: item, mod, or nbt"); + } + } + + @SubCommand( + desc = "Remove item, mod, or NBT tag from blacklist", + usage = " " + ) + public void remove(ICommandSender sender, String[] args) throws CommandException { + if (args.length < 2) { + sendError(sender, "Usage: /cnpc auction blacklist remove "); + return; + } + + String type = args[0].toLowerCase(); + String value = args[1]; + + switch (type) { + case "item": + if (AuctionBlacklist.removeItem(value)) { + sendResult(sender, "Removed item from blacklist: " + value); + } else { + sendError(sender, "Item not found in blacklist: " + value); + } + break; + case "mod": + if (AuctionBlacklist.removeMod(value)) { + sendResult(sender, "Removed mod from blacklist: " + value); + } else { + sendError(sender, "Mod not found in blacklist: " + value); + } + break; + case "nbt": + if (AuctionBlacklist.removeNBTTag(value)) { + sendResult(sender, "Removed NBT tag from blacklist: " + value); + } else { + sendError(sender, "NBT tag not found in blacklist: " + value); + } + break; + default: + sendError(sender, "Unknown type: " + type + ". Use: item, mod, or nbt"); + } + } + + @SubCommand( + desc = "List blacklisted items, mods, or NBT tags", + usage = "[item|mod|nbt]" + ) + public void list(ICommandSender sender, String[] args) throws CommandException { + String filter = args.length > 0 ? args[0].toLowerCase() : "all"; + + if (filter.equals("all") || filter.equals("item")) { + List items = AuctionBlacklist.getBlacklistedItems(); + sendMessage(sender, "\u00A76=== Blacklisted Items (" + items.size() + ") ==="); + if (items.isEmpty()) { + sendMessage(sender, "\u00A77 (none)"); + } else { + for (String item : items) { + sendMessage(sender, "\u00A7e " + item); + } + } + } + + if (filter.equals("all") || filter.equals("mod")) { + List mods = AuctionBlacklist.getBlacklistedMods(); + sendMessage(sender, "\u00A76=== Blacklisted Mods (" + mods.size() + ") ==="); + if (mods.isEmpty()) { + sendMessage(sender, "\u00A77 (none)"); + } else { + for (String mod : mods) { + sendMessage(sender, "\u00A7e " + mod); + } + } + } + + if (filter.equals("all") || filter.equals("nbt")) { + List tags = AuctionBlacklist.getBlacklistedNBTTags(); + sendMessage(sender, "\u00A76=== Blacklisted NBT Tags (" + tags.size() + ") ==="); + if (tags.isEmpty()) { + sendMessage(sender, "\u00A77 (none)"); + } else { + for (String tag : tags) { + sendMessage(sender, "\u00A7e " + tag); + } + } + } + + sendMessage(sender, "\u00A77Note: Soulbound and Profile-Slotbound items are always blocked."); + } + + @SubCommand( + desc = "Reload blacklist from config" + ) + public void reload(ICommandSender sender, String[] args) throws CommandException { + AuctionBlacklist.reload(); + sendResult(sender, "Blacklist reloaded from config"); + } + + @SubCommand( + desc = "Check if held item is blacklisted", + permission = 0 + ) + public void check(ICommandSender sender, String[] args) throws CommandException { + if (!(sender instanceof EntityPlayer)) { + sendError(sender, "This command can only be used by players"); + return; + } + + EntityPlayer player = (EntityPlayer) sender; + ItemStack heldItem = player.getHeldItem(); + + if (heldItem == null) { + sendError(sender, "You are not holding an item"); + return; + } + + String registryName = AuctionBlacklist.getRegistryName(heldItem); + sendMessage(sender, "\u00A76=== Blacklist Check ==="); + sendMessage(sender, "\u00A77Item: \u00A7e" + heldItem.getDisplayName()); + sendMessage(sender, "\u00A77Registry: \u00A7e" + (registryName != null ? registryName : "unknown")); + + boolean isBlacklisted = AuctionBlacklist.isBlacklisted(heldItem); + boolean canBypass = AuctionBlacklist.canBypass(player); + + if (isBlacklisted) { + sendMessage(sender, "\u00A7cStatus: BLACKLISTED"); + if (canBypass) { + sendMessage(sender, "\u00A7aYou have bypass permission"); + } + } else { + sendMessage(sender, "\u00A7aStatus: ALLOWED"); + } + } + + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] args) { + if (args.length == 1) { + return getListOfStringsMatchingLastWord(args, getAllSubCommandNames()); + } + if (args.length == 2) { + String subCmd = args[0].toLowerCase(); + if (subCmd.equals("add") || subCmd.equals("remove") || subCmd.equals("list")) { + return getListOfStringsMatchingLastWord(args, new String[]{"item", "mod", "nbt"}); + } + } + return null; + } +} 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..003f58fca --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -0,0 +1,1487 @@ +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.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 net.minecraft.entity.player.EntityPlayer; +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.syncAllCustomAbilities(); + 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; + + 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); + 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; + } + if (changed) { + pData.save(); + } + } + } + } + + customAbilityRevision++; + LogWriter.script("Deleted custom ability: " + name); + SyncController.syncAllCustomAbilities(); + 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.syncAllChainedAbilities(); + 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; + + 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); + 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.syncAllChainedAbilities(); + 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 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 73f16ebf6..fcb3436af 100644 --- a/src/main/java/kamkeel/npcs/controllers/ProfileController.java +++ b/src/main/java/kamkeel/npcs/controllers/ProfileController.java @@ -1,6 +1,5 @@ package kamkeel.npcs.controllers; -import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.data.profile.CNPCData; import kamkeel.npcs.controllers.data.profile.EnumProfileOperation; import kamkeel.npcs.controllers.data.profile.IProfileData; @@ -524,6 +523,7 @@ 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); EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true); } else { @@ -861,6 +861,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()); @@ -873,21 +876,29 @@ 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); } diff --git a/src/main/java/kamkeel/npcs/controllers/SyncController.java b/src/main/java/kamkeel/npcs/controllers/SyncController.java index 9617f4d12..d0ee7b16c 100644 --- a/src/main/java/kamkeel/npcs/controllers/SyncController.java +++ b/src/main/java/kamkeel/npcs/controllers/SyncController.java @@ -2,14 +2,19 @@ package kamkeel.npcs.controllers; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.addon.DBCAddon; 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.EnumSyncType; import kamkeel.npcs.network.packets.data.LoginPacket; +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; @@ -44,6 +49,7 @@ 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.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -72,7 +78,9 @@ public class SyncController { EnumSyncType.ANVIL_RECIPES, EnumSyncType.CUSTOM_EFFECTS, EnumSyncType.MAGIC, - EnumSyncType.MAGIC_CYCLE + EnumSyncType.MAGIC_CYCLE, + EnumSyncType.CUSTOM_ABILITY, + EnumSyncType.CHAINED_ABILITY }; public static void load() { @@ -88,6 +96,8 @@ public class SyncController { registerCache(EnumSyncType.CUSTOM_EFFECTS, SyncController::customEffectsNBT); registerCache(EnumSyncType.MAGIC, SyncController::magicsNBT); registerCache(EnumSyncType.MAGIC_CYCLE, SyncController::magicCyclesNBT); + registerCache(EnumSyncType.CUSTOM_ABILITY, SyncController::customAbilitiesNBT); + registerCache(EnumSyncType.CHAINED_ABILITY, SyncController::chainedAbilitiesNBT); } public static void syncPlayer(EntityPlayerMP player) { @@ -174,6 +184,14 @@ public class SyncController { DBCAddon.instance.syncPlayer(player); syncPlayerData(player, false); PartyInfoPacket.sendPartyData(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 EnumMap getServerRevisionSnapshot() { @@ -323,6 +341,48 @@ public class SyncController { 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(EnumSyncType.CUSTOM_ABILITY); + if (payload == null) { + return; + } + PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CUSTOM_ABILITY, payload)); + updateAllPlayerRevisions(EnumSyncType.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(EnumSyncType.CHAINED_ABILITY); + if (payload == null) { + return; + } + PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CHAINED_ABILITY, payload)); + updateAllPlayerRevisions(EnumSyncType.CHAINED_ABILITY, payload.getRevision()); + } + public static void syncPlayerData(EntityPlayerMP player, boolean update) { PlayerData data = PlayerData.get(player); if (data != null) { @@ -595,6 +655,35 @@ public class SyncController { 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 name = nbt.getString("CustomAbilityId"); + Ability ability = AbilityController.Instance.fromNBT(nbt); + if (ability != null) { + ability.setName(name); + sync.put(name, ability); + } + } + AbilityController.Instance.setCustomAbilities(sync); + break; + } + case 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); + break; + } } ClientCacheHandler.updateClientRevision(enumSyncType, revision); @@ -787,6 +876,32 @@ public class SyncController { 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); @@ -843,6 +958,10 @@ public class SyncController { return EnumSet.of(EnumSyncType.ANVIL_RECIPES); case CUSTOM_EFFECTS: return EnumSet.of(EnumSyncType.CUSTOM_EFFECTS); + case CUSTOM_ABILITY: + return EnumSet.of(EnumSyncType.CUSTOM_ABILITY); + case CHAINED_ABILITY: + return EnumSet.of(EnumSyncType.CHAINED_ABILITY); default: return EnumSet.noneOf(EnumSyncType.class); } diff --git a/src/main/java/kamkeel/npcs/controllers/TelegraphController.java b/src/main/java/kamkeel/npcs/controllers/TelegraphController.java new file mode 100644 index 000000000..7956f4ff6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/TelegraphController.java @@ -0,0 +1,400 @@ +package kamkeel.npcs.controllers; + +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +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.player.EntityPlayerMP; +import net.minecraft.world.World; +import noppes.npcs.CustomNpcs; +import noppes.npcs.LogWriter; +import noppes.npcs.api.ITelegraph; +import noppes.npcs.api.ITelegraphInstance; +import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.handler.ITelegraphHandler; +import noppes.npcs.scripted.ScriptTelegraph; +import noppes.npcs.scripted.ScriptTelegraphInstance; +import noppes.npcs.util.NBTJsonUtil; + +import java.io.File; +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Server-side controller for managing telegraphs. + * Provides factory methods for creating telegraphs and spawn methods for sending to clients. + * Also manages saved telegraph presets. + */ +public class TelegraphController implements ITelegraphHandler { + + public static TelegraphController Instance; + + // Saved telegraph presets (name -> Telegraph) + private HashMap savedTelegraphs = new HashMap<>(); + + // Active server-side telegraph instances (for removal tracking) + private ConcurrentHashMap activeInstances = new ConcurrentHashMap<>(); + + public TelegraphController() { + } + + public static void init() { + Instance = new TelegraphController(); + Instance.load(); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // INTERNAL SPAWN METHODS + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Spawn a telegraph at a fixed position. + * + * @param telegraph The telegraph configuration + * @param world The world + * @param x X position + * @param y Y position + * @param z Z position + * @param yaw Rotation yaw (for directional telegraphs like LINE/CONE) + * @return The spawned telegraph instance + */ + public TelegraphInstance spawn(Telegraph telegraph, World world, double x, double y, double z, float yaw) { + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + instance.setWorld(world); + activeInstances.put(instance.getInstanceId(), instance); + TelegraphSpawnPacket.sendToDimension(instance, world.provider.dimensionId); + return instance; + } + + /** + * Spawn a telegraph at a position with default yaw. + */ + public TelegraphInstance spawn(Telegraph telegraph, World world, double x, double y, double z) { + return spawn(telegraph, world, x, y, z, 0); + } + + /** + * Spawn a telegraph that follows an entity. + * + * @param telegraph The telegraph configuration + * @param entity The entity to follow + * @return The spawned telegraph instance + */ + public TelegraphInstance spawn(Telegraph telegraph, Entity entity) { + return spawn(telegraph, entity, 0); + } + + /** + * Spawn a telegraph that follows an entity with yaw. + */ + public TelegraphInstance spawn(Telegraph telegraph, Entity entity, float yaw) { + TelegraphInstance instance = new TelegraphInstance(telegraph, entity.posX, entity.posY, entity.posZ, yaw); + instance.setWorld(entity.worldObj); + instance.setEntityIdToFollow(entity.getEntityId()); + activeInstances.put(instance.getInstanceId(), instance); + TelegraphSpawnPacket.sendToTracking(instance, entity); + return instance; + } + + /** + * Spawn a telegraph to a specific player only. + */ + public TelegraphInstance spawnToPlayer(Telegraph telegraph, EntityPlayerMP player, double x, double y, double z, float yaw) { + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + instance.setWorld(player.worldObj); + activeInstances.put(instance.getInstanceId(), instance); + TelegraphSpawnPacket.send(instance, player); + return instance; + } + + /** + * Spawn a telegraph to all players on the server. + */ + public TelegraphInstance spawnToAll(Telegraph telegraph, World world, double x, double y, double z, float yaw) { + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + instance.setWorld(world); + activeInstances.put(instance.getInstanceId(), instance); + TelegraphSpawnPacket.sendToAll(instance); + return instance; + } + + /** + * Spawn a telegraph to all players tracking an entity. + */ + public TelegraphInstance spawnToTracking(Telegraph telegraph, Entity entity, double x, double y, double z, float yaw) { + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + instance.setWorld(entity.worldObj); + activeInstances.put(instance.getInstanceId(), instance); + TelegraphSpawnPacket.sendToTracking(instance, entity); + return instance; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // REMOVAL METHODS + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Remove a telegraph by instance ID. + */ + public void remove(String instanceId) { + TelegraphInstance instance = activeInstances.remove(instanceId); + if (instance != null && instance.getWorld() != null) { + TelegraphRemovePacket.sendToDimension(instanceId, instance.getDimensionId()); + } + } + + /** + * Remove a telegraph instance. + */ + public void remove(TelegraphInstance instance) { + if (instance != null) { + remove(instance.getInstanceId()); + } + } + + /** + * Remove a telegraph for a specific player only. + */ + public void removeFromPlayer(String instanceId, EntityPlayerMP player) { + activeInstances.remove(instanceId); + TelegraphRemovePacket.send(instanceId, player); + } + + /** + * Get an active telegraph instance by ID. + */ + public TelegraphInstance getActiveInstance(String instanceId) { + return activeInstances.get(instanceId); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // PRESET MANAGEMENT + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Save a telegraph preset (internal use). + * + * @param name The name for the preset + * @param telegraph The telegraph configuration to save + */ + public void saveInternal(String name, Telegraph telegraph) { + if (name == null || name.isEmpty() || telegraph == null) return; + + telegraph.setId(name); + savedTelegraphs.put(name, telegraph); + saveTelegraphFile(name, telegraph); + } + + /** + * Get a saved telegraph preset by name (internal use). + * + * @param name The preset name + * @return The telegraph configuration, or null if not found + */ + public Telegraph getInternal(String name) { + return savedTelegraphs.get(name); + } + + /** + * Delete a saved telegraph preset. + * + * @param name The preset name + */ + public void delete(String name) { + Telegraph removed = savedTelegraphs.remove(name); + if (removed != null) { + File file = new File(getDir(), name + ".json"); + if (file.exists()) { + file.delete(); + } + } + } + + /** + * Check if a preset exists. + */ + public boolean has(String name) { + return savedTelegraphs.containsKey(name); + } + + /** + * Get all saved preset names. + */ + public String[] getSavedNames() { + return savedTelegraphs.keySet().toArray(new String[0]); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // PERSISTENCE + // ═══════════════════════════════════════════════════════════════════════════ + + private File getDir() { + return new File(CustomNpcs.getWorldSaveDirectory(), "telegraphs"); + } + + public void load() { + savedTelegraphs.clear(); + LogWriter.info("Loading telegraph presets..."); + + File dir = getDir(); + if (!dir.exists()) { + dir.mkdirs(); + return; + } + + File[] files = dir.listFiles(); + if (files == null) return; + + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) continue; + try { + Telegraph telegraph = new Telegraph(); + telegraph.readNBT(NBTJsonUtil.LoadFile(file)); + String name = file.getName().substring(0, file.getName().length() - 5); + telegraph.setId(name); + savedTelegraphs.put(name, telegraph); + } catch (Exception e) { + LogWriter.error("Error loading telegraph preset: " + file.getName(), e); + } + } + + LogWriter.info("Loaded " + savedTelegraphs.size() + " telegraph presets."); + } + + private void saveTelegraphFile(String name, Telegraph telegraph) { + try { + File dir = getDir(); + if (!dir.exists()) { + dir.mkdirs(); + } + + File file = new File(dir, name + ".json_new"); + File file2 = new File(dir, name + ".json"); + + NBTJsonUtil.SaveFile(file, telegraph.writeNBT()); + if (file2.exists()) { + file2.delete(); + } + file.renameTo(file2); + } catch (Exception e) { + LogWriter.error("Error saving telegraph preset: " + name, e); + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // ITelegraphHandler INTERFACE IMPLEMENTATION + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public ITelegraph createCircle(float radius) { + return new ScriptTelegraph(Telegraph.circle(radius)); + } + + @Override + public ITelegraph createRing(float outerRadius, float innerRadius) { + return new ScriptTelegraph(Telegraph.ring(outerRadius, innerRadius)); + } + + @Override + public ITelegraph createLine(float length, float width) { + return new ScriptTelegraph(Telegraph.line(length, width)); + } + + @Override + public ITelegraph createCone(float length, float angle) { + 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()); + } + + @Override + public ITelegraph create(String type) { + if (type == null) return null; + try { + TelegraphType telegraphType = TelegraphType.valueOf(type.toUpperCase()); + Telegraph telegraph; + switch (telegraphType) { + case CIRCLE: + telegraph = Telegraph.circle(3.0f); + break; + case RING: + telegraph = Telegraph.ring(5.0f, 2.0f); + break; + case LINE: + telegraph = Telegraph.line(5.0f, 2.0f); + break; + case CONE: + telegraph = Telegraph.cone(5.0f, 45.0f); + break; + case SQUARE: + telegraph = Telegraph.square(3.0f); + break; + case POINT: + telegraph = Telegraph.point(); + break; + default: + telegraph = Telegraph.circle(3.0f); + } + return new ScriptTelegraph(telegraph); + } catch (IllegalArgumentException e) { + return null; + } + } + + @Override + public ITelegraphInstance spawn(ITelegraph telegraph, IWorld world, double x, double y, double z) { + return spawn(telegraph, world, x, y, z, 0); + } + + @Override + public ITelegraphInstance spawn(ITelegraph telegraph, IWorld world, double x, double y, double z, float yaw) { + if (telegraph == null || world == null) return null; + Telegraph internal = ((ScriptTelegraph) telegraph).getMCTelegraph(); + TelegraphInstance instance = spawn(internal, (World) world.getMCWorld(), x, y, z, yaw); + return new ScriptTelegraphInstance(instance); + } + + @Override + public ITelegraphInstance spawn(ITelegraph telegraph, IEntity entity) { + return spawn(telegraph, entity, 0); + } + + @Override + public ITelegraphInstance spawn(ITelegraph telegraph, IEntity entity, float yaw) { + if (telegraph == null || entity == null) return null; + Telegraph internal = ((ScriptTelegraph) telegraph).getMCTelegraph(); + TelegraphInstance instance = spawn(internal, (Entity) entity.getMCEntity(), yaw); + return new ScriptTelegraphInstance(instance); + } + + @Override + public ITelegraph get(String name) { + Telegraph telegraph = savedTelegraphs.get(name); + return telegraph != null ? new ScriptTelegraph(new Telegraph(telegraph)) : null; + } + + @Override + public void save(String name, ITelegraph telegraph) { + if (name == null || name.isEmpty() || telegraph == null) return; + Telegraph internal = ((ScriptTelegraph) telegraph).getMCTelegraph(); + saveInternal(name, internal); + } + + @Override + public void remove(ITelegraphInstance instance) { + if (instance != null) { + remove(instance.getInstanceId()); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java new file mode 100644 index 000000000..05049d8bb --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -0,0 +1,2918 @@ +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.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 noppes.npcs.controllers.data.Frame; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.entity.EntityNPCInterface; +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 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; + +public abstract class Ability implements IAbility, IAbilityAction { + + // ═══════════════════════════════════════════════════════════════════ + // CONFIGURATION (saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + 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<>(); + + // Targeting + protected TargetingMode targetingMode = TargetingMode.AGGRO_TARGET; + protected float minRange = 0; + protected float maxRange = 20; + + // Timing (ticks) + protected int cooldownTicks = 0; // Added to global cooldown after ability completes + protected int windUpTicks = 20; + protected boolean syncWindupWithAnimation = true; + protected int dazedTicks = 80; // Only used when interrupted during WINDUP (if interruptible) + + // Interruption + protected boolean interruptible = true; + protected InvulnerableMode invulnerableMode = InvulnerableMode.NONE; + protected boolean ignoreIFrames = false; + + // Feedback + protected LockMode lockMovement = LockMode.WINDUP; + protected RotationMode rotationMode = RotationMode.FREE; + 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 + + // Sounds + protected String windUpSound = ""; // Sound to play when wind up starts + protected String activeSound = ""; // Sound to play when active phase starts + + // 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; + protected TelegraphType telegraphType = TelegraphType.CIRCLE; + protected float telegraphHeightOffset = 0.1f; + + // 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<>(); + + // Burst + protected boolean burstEnabled = false; + protected int burstAmount = 0; // number of EXTRA repetitions + protected int burstDelay = 0; // ticks between bursts + protected boolean burstReplayAnimations = true; + protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts + + // ═══════════════════════════════════════════════════════════════════ + // EXECUTION STATE (not saved, reset each combat) + // ═══════════════════════════════════════════════════════════════════ + + protected transient AbilityPhase phase = AbilityPhase.IDLE; + protected transient int currentTick = 0; + protected transient EntityLivingBase currentTarget; + protected transient long executionStartTime; + 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) + // ═══════════════════════════════════════════════════════════════════ + + 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. + * 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); + + /** + * Called every tick of ACTIVE phase + */ + public abstract void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick); + + /** + * Write type-specific config to NBT + */ + public abstract void writeTypeNBT(NBTTagCompound nbt); + + /** + * Read type-specific config from NBT + */ + public abstract void readTypeNBT(NBTTagCompound nbt); + + // ═══════════════════════════════════════════════════════════════════ + // OPTIONAL OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + /** + * Returns true if this ability type deals damage. + * Override in non-damaging subclasses to return false. + * Used by external mods to determine whether to show + * damage-related configuration (e.g., DBC stats tab). + */ + public boolean hasDamage() { + 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 + * with the returned variants. If empty or single-entry, the dialog is skipped. + */ + public List getVariants() { + return Collections.emptyList(); + } + + /** + * Whether this ability type supports the burst system. + * Override to return false for abilities that shouldn't repeat (Guard, Heal, Sweeper, etc.). + */ + public boolean allowBurst() { + return true; + } + + /** + * Whether this ability supports overlap mode for burst (entities from previous bursts keep flying). + * Override to return true for entity-spawning projectile abilities (Orb, Beam, Disc, LaserShot). + */ + public boolean allowOverlap() { + return false; + } + + /** + * Whether this ability 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 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 resetForBurst() {} + + /** + * Apply damage to an entity with ability hit event support. + * 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 + * @return true if damage was applied (not cancelled), false if cancelled + */ + protected boolean applyAbilityDamage(EntityLivingBase caster, EntityLivingBase hitEntity, + float damage, float knockback) { + double dx = hitEntity.posX - caster.posX; + double dz = hitEntity.posZ - caster.posZ; + return applyAbilityDamageInternal(caster, hitEntity, damage, knockback, 0.0f, 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. + * + * @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 knockbackDirX The X component of knockback direction + * @param knockbackDirZ The Z component of knockback direction + * @return true if damage was applied (not cancelled), false if cancelled + */ + protected boolean applyAbilityDamageWithDirection(EntityLivingBase caster, EntityLivingBase hitEntity, + float damage, float knockback, + double knockbackDirX, double knockbackDirZ) { + 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. + * Supports both NPC and Player casters. + */ + private boolean applyAbilityDamageInternal(EntityLivingBase caster, EntityLivingBase hitEntity, + float damage, float knockback, float knockbackUp, + double knockbackDirX, double knockbackDirZ) { + // 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 + } + damage = hitEvent.getDamage(); + knockback = hitEvent.getKnockback(); + knockbackUp = hitEvent.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) { + 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, 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; + } + + private void applyKnockback(EntityLivingBase hitEntity, double dirX, double dirZ, float knockback, float knockbackUp) { + double len = Math.sqrt(dirX * dirX + dirZ * dirZ); + double x = 0; + double z = 0; + if (len > 0) { + x = (dirX / len) * knockback * 0.5; + z = (dirZ / len) * knockback * 0.5; + } + double y = knockbackUp > 0 ? knockbackUp : 0.1D; + hitEntity.addVelocity(x, y, z); + hitEntity.velocityChanged = true; + } + + /** + * Applies all configured effects to the given entity. + * Call this after damage is applied to the target. + * + * @param entity The entity to apply effects to + */ + protected void applyEffects(EntityLivingBase entity) { + if (entity == null || effects.isEmpty()) { + return; + } + for (AbilityPotionEffect effect : effects) { + effect.apply(entity); + } + } + + public float getTelegraphRadius() { + return 5.0f; + } + + public float getTelegraphLength() { + return 5.0f; + } + + public float getTelegraphWidth() { + return 2.0f; + } + + public float getTelegraphAngle() { + 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 + * code paths explicit and readable. + *

+ * NPCs always have an aggro target passed to ability methods. + * Players never do — they use look direction for aiming instead. + */ + protected final boolean isPlayerCaster(EntityLivingBase caster) { + return caster instanceof EntityPlayer; + } + + /** + * Whether the telegraph should remain visible during the ACTIVE phase. + * Default: false (telegraph removed at WINDUP→ACTIVE transition). + * Override for abilities where the active phase IS the attack (e.g., sweeping/spinning attacks) + * so the telegraph stays visible while damage is being dealt. + */ + public boolean keepTelegraphDuringActive() { + return false; + } + + /** + * Returns true if this ability controls NPC movement during ACTIVE phase. + * When true, AI pathfinding will be blocked during ability execution. + * Override in abilities that move the NPC (Charge, Dash, Slam, etc.) + */ + public boolean hasAbilityMovement() { + return false; + } + + /** + * Returns true if the targeting mode for this ability type is locked and cannot be changed. + * Most abilities have fixed targeting (e.g., Heal is always SELF, Charge is always AGGRO_TARGET). + * Override and return false for abilities with flexible targeting. + */ + public boolean isTargetingModeLocked() { + return true; + } + + /** + * Returns the allowed targeting modes for this ability, or null if all modes are allowed. + * Override in abilities that only support specific targeting modes. + */ + public TargetingMode[] getAllowedTargetingModes() { + return null; + } + + /** + * Add field definitions for this ability's GUI. + * Override in subclasses to add type-specific fields. The list already contains + * the base fields (General, Target, Effects tabs), so subclasses can also + * modify, insert into, or remove base fields using {@link FieldDef#insertBefore}, + * {@link FieldDef#insertAfter}, or direct list manipulation. + *

+ * Fields added here without an explicit {@code .tab()} will default to the "Type" tab. + * + * @param defs The mutable list of field definitions to add to or modify + */ + @SideOnly(Side.CLIENT) + public void getAbilityDefinitions(List defs) { + } + + /** + * Builds and returns all field definitions for this ability's GUI. + * Base fields (General, Target, Effects) are added first, then + * {@link #getAbilityDefinitions(List)} is called so subclasses can add + * type-specific fields and modify any existing fields. + */ + @SideOnly(Side.CLIENT) + public final List getAllDefinitions() { + List defs = new ArrayList<>(); + + // ── 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) + ).tab("General")); + defs.add(FieldDef.section("ability.section.timing").tab("General")); + defs.add(FieldDef.intField("ability.windUpTicks", this::getRawWindUpTicks, this::setWindUpTicks) + .tab("General").range(0, 1000) + .visibleWhen(() -> !hasWindUpAnimation())); + defs.add(FieldDef.row( + FieldDef.intField("ability.windUpTicks", this::getRawWindUpTicks, this::setWindUpTicks).range(0, 1000), + FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) + .hover("ability.hover.sync") + ).tab("General").visibleWhen(() -> hasWindUpAnimation() && !isSyncWindupWithAnimation())); + defs.add(FieldDef.row( + FieldDef.labelField("ability.windUpTicks", () -> getWindUpTicks() + "t"), + FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) + .hover("ability.hover.sync") + ).tab("General").visibleWhen(() -> hasWindUpAnimation() && isSyncWindupWithAnimation())); + 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", LockMode.getDisplayKeys(), + () -> this.getLockMovement().getDisplayKey(), + v -> { + for (LockMode t : LockMode.values()) { + if (t.getDisplayKey().equals(v)) { + this.setLockMovement(t); + break; + } + } + }) + .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; + } + } + }) + .hover("ability.hover.rotationMode"), + FieldDef.stringEnumField("ability.rotationPhase", getRotationPhaseKeys(), + () -> 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") + .enabledWhen(() -> !invulnerableMode.invulnerableDuringWindup()), + FieldDef.intField("ability.dazedTicks", this::getDazedTicks, this::setDazedTicks) + .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()) { + defs.add(FieldDef.section("ability.section.burst").tab("General")); + defs.add(FieldDef.boolField("ability.burstEnabled", this::isBurstEnabled, this::setBurstEnabled) + .tab("General")); + defs.add(FieldDef.row( + FieldDef.intField("ability.burstAmount", this::getBurstAmount, this::setBurstAmount).range(1, 100), + FieldDef.intField("ability.burstDelay", this::getBurstDelay, this::setBurstDelay).range(0, 1000) + ).tab("General").visibleWhen(this::isBurstEnabled)); + defs.add(FieldDef.boolField("ability.burstReplayAnimations", this::isBurstReplayAnimations, this::setBurstReplayAnimations) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstReplay")); + if (allowOverlap()) { + defs.add(FieldDef.boolField("ability.burstOverlap", this::isBurstOverlap, this::setBurstOverlap) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstOverlap")); + } + } + + // ── 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(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")); + } + + // ── Target tab ─────────────────────────────────────────────── + defs.add(FieldDef.row( + FieldDef.intField("ability.minRange", () -> (int) getMinRange(), v -> setMinRange(v)).range(0, 100), + FieldDef.intField("ability.maxRange", () -> (int) getMaxRange(), v -> setMaxRange(v)).range(1, 100) + ).tab("Target")); + if (!isTargetingModeLocked()) { + TargetingMode[] allowed = getAllowedTargetingModes(); + if (allowed != null && allowed.length > 0) { + String[] allowedKeys = new String[allowed.length]; + for (int i = 0; i < allowed.length; i++) { + 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) { + } + }) + .tab("Target").hover("ability.hover.targeting")); + } else { + defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, + this::getTargetingMode, this::setTargetingMode) + .tab("Target").hover("ability.hover.targeting")); + } + } + + // ── Effects tab ────────────────────────────────────────────── + defs.add(FieldDef.section("ability.section.sounds").tab("Effects")); + defs.add(FieldDef.soundSubGui("ability.windUpSound", this::getWindUpSound, this::setWindUpSound) + .tab("Effects")); + defs.add(FieldDef.soundSubGui("ability.activeSound", this::getActiveSound, this::setActiveSound) + .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) + .tab("Effects")); + defs.add(FieldDef.animSubGui("ability.activeAnimation", + 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 && !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) + .tab("Effects").hover("ability.hover.showTelegraph")); + defs.add(FieldDef.colorSubGui("ability.windUpColor", this::getWindUpColor, this::setWindUpColor) + .tab("Effects").visibleWhen(this::isShowTelegraph)); + defs.add(FieldDef.colorSubGui("ability.activeColor", this::getActiveColor, this::setActiveColor) + .tab("Effects").visibleWhen(this::isShowTelegraph)); + } + + // ── Type-specific fields ───────────────────────────────────── + int baseSize = defs.size(); + getAbilityDefinitions(defs); + // Default tab for ability-added fields that don't specify one + for (int i = baseSize; i < defs.size(); i++) { + if (defs.get(i).getTab() == null) { + defs.get(i).tab("Type"); + } + } + + // ── 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); + } + + 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. + *

+ * Third-party mods can extend SubGuiAbilityConfig and override initTypeTab(), + * handleTypeButton(), and handleTypeTextField() to provide custom type settings. + * + * @param callback The callback to notify when the ability is saved + * @return A SubGuiAbilityConfig instance (or subclass) for configuring this ability + */ + @SideOnly(Side.CLIENT) + public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { + return new SubGuiAbilityConfig(this, callback); + } + + /** + * Create a telegraph instance for this ability. + * Override for custom telegraph shapes. + * + * @param caster The caster + * @param target The target (for position calculation) + * @return The telegraph instance, or null if no telegraph + */ + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || telegraphType == TelegraphType.NONE) { + return null; + } + + Telegraph telegraph; + double x, y, z; + float yaw = caster.rotationYaw; + + // Determine position based on targeting mode + boolean positionAtCaster = targetingMode == TargetingMode.AOE_SELF || + targetingMode == TargetingMode.SELF || + telegraphType == TelegraphType.LINE || + telegraphType == 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; + } + + // Create telegraph based on type + switch (telegraphType) { + case CIRCLE: + telegraph = Telegraph.circle(getTelegraphRadius()); + break; + case RING: + telegraph = Telegraph.ring(getTelegraphRadius(), getTelegraphInnerRadius()); + break; + case LINE: + telegraph = Telegraph.line(getTelegraphLength(), getTelegraphWidth()); + break; + case CONE: + 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); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + instance.setCasterEntityId(caster.getEntityId()); + + // Set entity to follow based on targeting mode + if (positionAtCaster) { + // AOE_SELF abilities: telegraph follows caster during windup + instance.setEntityIdToFollow(caster.getEntityId()); + + // 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) { + if (!isRotationLockedDuringWindup()) { + 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 + } + } else if (target != null) { + // AOE_TARGET abilities: telegraph follows target during windup + instance.setEntityIdToFollow(target.getEntityId()); + } + + 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, or startY - 0.5 if airborne + */ + public static double findGroundLevel(World world, double x, double startY, double z) { + 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); + + for (int checkY = startBlockY; checkY >= startBlockY - maxSearchDown && checkY >= 0; checkY--) { + Block block = world.getBlock(blockX, checkY, blockZ); + if (block != null && block.getMaterial().isSolid()) { + return checkY + 1; + } + } + + // No ground found within range — place slightly under entity + return startY - 0.5; + } + + /** + * Get the current telegraph instances. + */ + public List getTelegraphInstances() { + return telegraphInstances; + } + + /** + * Set the telegraph instances (called by DataAbilities). + */ + public void setTelegraphInstances(List instances) { + this.telegraphInstances = instances != null ? instances : new ArrayList<>(); + } + + // ═══════════════════════════════════════════════════════════════════ + // EXECUTION LOGIC (called by CombatHandler) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Start executing this ability. + * If windUpTicks is 0, skips WINDUP and goes directly to ACTIVE. + */ + public void start(EntityLivingBase target) { + this.currentTick = 0; + this.currentTarget = target; + this.executionStartTime = System.currentTimeMillis(); + this.burstIndex = 0; + this.burstEntities.clear(); + + if (windUpTicks <= 0) { + this.phase = AbilityPhase.ACTIVE; + } else { + this.phase = AbilityPhase.WINDUP; + } + } + + /** + * Tick the ability forward. Called every game tick while executing. + *

+ * Normal flow: WINDUP -> ACTIVE -> IDLE + * Interrupted flow: WINDUP -> DAZED -> IDLE (dazed only on interrupt during WINDUP) + * + * @return true if phase changed this tick + */ + public boolean tick() { + if (phase == AbilityPhase.IDLE) return false; + + currentTick++; + + switch (phase) { + case WINDUP: + if (currentTick >= windUpTicks) { + phase = AbilityPhase.ACTIVE; + currentTick = 0; + return true; + } + break; + case ACTIVE: + // Abilities control their own completion by calling signalCompletion() + // No auto-complete - each ability determines when it's done + break; + case DAZED: + // Dazed phase is only entered on interrupt during WINDUP + // NPC cannot attack during this time + if (currentTick >= dazedTicks) { + phase = AbilityPhase.IDLE; + currentTick = 0; + return true; + } + break; + + case BURST_DELAY: + // Waiting between burst repetitions - free movement/rotation + if (currentTick >= burstDelay) { + if (burstReplayAnimations && getWindUpTicks() > 0) { + phase = AbilityPhase.WINDUP; + } else { + phase = AbilityPhase.ACTIVE; + } + currentTick = 0; + return true; + } + break; + } + return false; + } + + /** + * Signal that the ability has completed its active phase. + * Called by abilities when they are done. + * For example, AbilitySlam calls this when the NPC lands. + * + * @return true if phase changed to IDLE + */ + public boolean signalCompletion() { + if (phase == AbilityPhase.ACTIVE) { + // Check if more burst iterations remain + if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) { + // 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; + return true; + } + + // Final completion - let burst entities die naturally (don't force-kill) + burstEntities.clear(); + if (freeOnCast) { + // Free on Cast: detach entities (let them live independently) instead of killing + detach(); + } else { + cleanup(); + } + phase = AbilityPhase.IDLE; + currentTick = 0; + return true; + } + return false; + } + + /** + * Interrupt this ability. Transitions to DAZED phase if interruptible during WINDUP. + * Called when NPC takes direct damage during WINDUP. + */ + public void interrupt() { + cleanupBurstEntities(); + cleanup(); + if (interruptible && phase == AbilityPhase.WINDUP) { + // Interrupted during windup - go to dazed state + phase = AbilityPhase.DAZED; + currentTick = 0; + } else { + // Force stop - go directly to IDLE + phase = AbilityPhase.IDLE; + currentTick = 0; + } + burstIndex = 0; + currentTarget = 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(); + } + + /** + * Check if executing + */ + public boolean isExecuting() { + return phase != AbilityPhase.IDLE; + } + + /** + * 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 (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) { + return false; + } + if (isInvulnerableForCurrentPhase()) { + return false; + } + + // Only direct physical hits can interrupt, not magic, fire, or other indirect damage + if (source == null) { + return false; + } + + // Reject indirect damage types + if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) { + return false; + } + + // Reject damage without a direct attacker entity + if (source.getEntity() == null) { + return false; + } + + // Direct hit from an entity - can interrupt + return true; + } + + /** + * Reset all execution state (called on combat end, NPC death, target lost, etc.) + */ + public void reset() { + cleanupBurstEntities(); + cleanup(); + phase = AbilityPhase.IDLE; + currentTick = 0; + burstIndex = 0; + currentTarget = null; + telegraphInstances.clear(); + previewMode = false; + previewEntityHandler = null; + instanceScript = null; + } + + /** + * Cleanup any resources created by this ability. + * Override this to kill spawned entities, cancel telegraphs, etc. + * Called when ability ends for any reason (completion, interrupt, reset, NPC death). + */ + public void cleanup() { + // Override in subclasses to clean up spawned entities, etc. + } + + /** + * Kill all entities tracked during burst overlap and clear the list. + */ + protected void cleanupBurstEntities() { + for (Entity e : burstEntities) { + if (e != null && !e.isDead) { + killAbilityEntity(e); + } + } + burstEntities.clear(); + } + + // ═══════════════════════════════════════════════════════════════════ + // PREVIEW MODE SUPPORT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Whether this ability is running in preview mode (GUI preview). + * When true, abilities should skip damage, effects, sounds, and particles + * but still run their core logic (entity spawning, movement, timing). + */ + public boolean isPreview() { + return previewMode; + } + + public void setPreviewMode(boolean preview) { + this.previewMode = preview; + } + + public void setPreviewEntityHandler(PreviewEntityHandler handler) { + this.previewEntityHandler = handler; + } + + /** + * Spawn an entity during ability execution. + * In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld(). + */ + protected void spawnAbilityEntity(Entity entity) { + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntitySpawned(entity); + } else { + entity.worldObj.spawnEntityInWorld(entity); + if (!entity.worldObj.isRemote && entity instanceof EntityEnergyProjectile) { + EventHooks.onEnergyProjectileFired((EntityEnergyProjectile) entity); + } + } + if (burstEnabled && burstOverlap) { + burstEntities.add(entity); + } + } + + /** + * Kill an entity spawned by this ability. + * In preview mode, notifies PreviewEntityHandler of removal. + */ + protected void killAbilityEntity(Entity entity) { + if (entity == null) return; + entity.setDead(); + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntityRemoved(entity); + } + } + + /** + * Maximum duration (in ticks) for preview before auto-stopping. + * Override in movement abilities that have variable duration. + * Default: 200 ticks (10 seconds). + */ + public int getMaxPreviewDuration() { + return 200; + } + + // ═══════════════════════════════════════════════════════════════════ + // CONDITION CHECKING + // ═══════════════════════════════════════════════════════════════════ + + 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 a player caster, skipping 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; + } + + + // ═══════════════════════════════════════════════════════════════════ + // NBT (config only, execution state is transient) + // ═══════════════════════════════════════════════════════════════════ + + 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); + nbt.setString("targetingMode", targetingMode.name()); + nbt.setFloat("minRange", minRange); + nbt.setFloat("maxRange", maxRange); + nbt.setInteger("cooldown", cooldownTicks); + nbt.setInteger("windUp", windUpTicks); + 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.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", (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); + nbt.setInteger("burstAmount", burstAmount); + nbt.setInteger("burstDelay", burstDelay); + nbt.setBoolean("burstReplayAnimations", burstReplayAnimations); + nbt.setBoolean("burstOverlap", burstOverlap); + + // Conditions + NBTTagList condList = new NBTTagList(); + for (AbilityCondition c : conditions) condList.appendTag(c.writeNBT()); + nbt.setTag("conditions", condList); + + // Effects + NBTTagList effectList = new NBTTagList(); + for (AbilityPotionEffect effect : effects) { + effectList.appendTag(effect.writeNBT()); + } + nbt.setTag("effects", effectList); + + // Type-specific + NBTTagCompound typeNBT = new NBTTagCompound(); + 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.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") : 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.getInteger("windUpAnimationId"); + activeAnimationId = nbt.getInteger("activeAnimationId"); + dazedAnimationId = nbt.hasKey("dazedAnimationId") ? nbt.getInteger("dazedAnimationId") : -1; + windUpAnimationName = nbt.getString("windUpAnimationName"); + activeAnimationName = nbt.getString("activeAnimationName"); + 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; + } + + // Burst + 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++) { + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); + if (c != null) conditions.add(c); + } + + // Effects + effects.clear(); + if (nbt.hasKey("effects")) { + NBTTagList effectList = nbt.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); + } + } + } + + // 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); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String 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; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public TargetingMode getTargetingMode() { + return targetingMode; + } + + public void setTargetingMode(TargetingMode targetingMode) { + this.targetingMode = targetingMode; + } + + public float getMinRange() { + return minRange; + } + + public void setMinRange(float minRange) { + this.minRange = minRange; + } + + public float getMaxRange() { + return maxRange; + } + + public void setMaxRange(float maxRange) { + this.maxRange = maxRange; + } + + public int getCooldownTicks() { + return cooldownTicks; + } + + public void setCooldownTicks(int cooldownTicks) { + this.cooldownTicks = Math.max(0, cooldownTicks); + } + + public int getWindUpTicks() { + return calculateWindupFromAnimation(); + } + + public int getRawWindUpTicks() { + return windUpTicks; + } + + public void setWindUpTicks(int windUpTicks) { + this.windUpTicks = Math.max(0, windUpTicks); + } + + public boolean isSyncWindupWithAnimation() { + return syncWindupWithAnimation; + } + + public boolean hasWindUpAnimation() { + return (windUpAnimationName != null && !windUpAnimationName.isEmpty()) || windUpAnimationId >= 0; + } + + public void setSyncWindupWithAnimation(boolean syncWindupWithAnimation) { + this.syncWindupWithAnimation = syncWindupWithAnimation; + } + + public int getDazedTicks() { + return dazedTicks; + } + + public void setDazedTicks(int dazedTicks) { + this.dazedTicks = Math.max(0, dazedTicks); + } + + public boolean isInterruptible() { + return interruptible; + } + + public void setInterruptible(boolean interruptible) { + this.interruptible = interruptible; + } + + 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(LockMode lockMovement) { + this.lockMovement = lockMovement; + } + + public RotationMode getRotationMode() { + return rotationMode; + } + + public void setRotationMode(RotationMode rotationMode) { + this.rotationMode = rotationMode; + } + + public LockMode getRotationPhase() { + return 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 + public int getLockMovementType() { + return lockMovement.ordinal(); + } + + /** + * 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 = LockMode.fromOrdinal(type); + } + + /** + * API method: Get rotation mode as integer. + * + * @return 0=FREE, 1=LOCKED, 2=TRACK + */ + @Override + public int getRotationModeType() { + return rotationMode.ordinal(); + } + + /** + * API method: Set rotation mode from integer. + * + * @param type 0=FREE, 1=LOCKED, 2=TRACK + */ + @Override + public void setRotationModeType(int type) { + this.rotationMode = RotationMode.fromOrdinal(type); + } + + /** + * API method: Get rotation phase as integer. + * + * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public int getRotationPhaseType() { + return rotationPhase.ordinal(); + } + + /** + * API method: Set rotation phase from integer. + * + * @param type 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public void setRotationPhaseType(int type) { + this.rotationPhase = 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); + } + + /** + * Check if movement (pathfinding/motion) should be locked during WINDUP phase. + */ + @Override + public boolean isMovementLockedDuringWindup() { + return lockMovement.locksWindup(); + } + + /** + * Check if movement (pathfinding/motion) should be locked during ACTIVE phase. + */ + @Override + public boolean isMovementLockedDuringActive() { + return lockMovement.locksActive(); + } + + /** + * Check if rotation (yaw/pitch) should be locked during WINDUP phase. + */ + @Override + public boolean isRotationLockedDuringWindup() { + return rotationMode == RotationMode.LOCKED && rotationPhase.locksWindup(); + } + + /** + * Check if rotation (yaw/pitch) should be locked during ACTIVE phase. + */ + @Override + public boolean isRotationLockedDuringActive() { + return rotationMode == RotationMode.LOCKED && rotationPhase.locksActive(); + } + + /** + * Check if movement should be locked during the current phase. + */ + public boolean isMovementLockedForCurrentPhase() { + switch (phase) { + case WINDUP: + return isMovementLockedDuringWindup(); + case ACTIVE: + return isMovementLockedDuringActive(); + case BURST_DELAY: + return false; // Free movement during burst delay + default: + return false; + } + } + + /** + * 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. + */ + public boolean isRotationLockedForCurrentPhase() { + switch (phase) { + case WINDUP: + return isRotationLockedDuringWindup(); + case ACTIVE: + return isRotationLockedDuringActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay + default: + return false; + } + } + + /** + * Check if hit scan (force face target) is active during the current phase. + */ + public boolean isHitScanForCurrentPhase() { + if (rotationMode != RotationMode.TRACK) return false; + switch (phase) { + case WINDUP: + return rotationPhase.locksWindup(); + case ACTIVE: + return rotationPhase.locksActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay + default: + return false; + } + } + + public int getWindUpColor() { + return windUpColor; + } + + public void setWindUpColor(int windUpColor) { + this.windUpColor = windUpColor; + } + + public int getActiveColor() { + return activeColor; + } + + public void setActiveColor(int activeColor) { + this.activeColor = activeColor; + } + + public String getWindUpSound() { + return windUpSound; + } + + public void setWindUpSound(String windUpSound) { + this.windUpSound = windUpSound; + } + + public String getActiveSound() { + return activeSound; + } + + public void setActiveSound(String activeSound) { + 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; + + // 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; + } + + public int getWindUpAnimationId() { + return windUpAnimationId; + } + + public void setWindUpAnimationId(int windUpAnimationId) { + this.windUpAnimationId = windUpAnimationId; + } + + public String getWindUpAnimationName() { + return windUpAnimationName; + } + + public void setWindUpAnimationName(String windUpAnimationName) { + this.windUpAnimationName = windUpAnimationName != null ? windUpAnimationName : ""; + } + + public Animation getActiveAnimation() { + if (AnimationController.Instance == null) return null; + + // 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; + } + + public int getActiveAnimationId() { + return activeAnimationId; + } + + public void setActiveAnimationId(int activeAnimationId) { + this.activeAnimationId = activeAnimationId; + } + + public String getActiveAnimationName() { + return activeAnimationName; + } + + public void setActiveAnimationName(String activeAnimationName) { + 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; + } + + public void setShowTelegraph(boolean showTelegraph) { + this.showTelegraph = showTelegraph; + } + + public TelegraphType getTelegraphType() { + return telegraphType; + } + + public void setTelegraphType(TelegraphType telegraphType) { + this.telegraphType = telegraphType; + } + + public float getTelegraphHeightOffset() { + return telegraphHeightOffset; + } + + public void setTelegraphHeightOffset(float telegraphHeightOffset) { + this.telegraphHeightOffset = telegraphHeightOffset; + } + + public AbilityPhase getPhase() { + 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. + */ + @Override + public int getPhaseInt() { + return phase.ordinal(); + } + + public int getCurrentTick() { + return currentTick; + } + + public EntityLivingBase getCurrentTarget() { + return currentTarget; + } + + public NBTTagCompound getCustomData() { + return customData; + } + + 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(AbilityCondition c) { + conditions.add(c); + } + + public UserType getAllowedBy() { + return allowedBy; + } + + public void setAllowedBy(UserType allowedBy) { + 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; + } + + public void setIgnoreCooldown(boolean ignoreCooldown) { + this.ignoreCooldown = ignoreCooldown; + } + + 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) { + this.effects = effects != null ? effects : new ArrayList<>(); + } + + public void addEffect(AbilityPotionEffect effect) { + if (effect != null && effect.isValid()) { + effects.add(effect); + } + } + + public void clearEffects() { + effects.clear(); + } + + // Burst getters/setters + + public boolean isBurstEnabled() { + return burstEnabled; + } + + public void setBurstEnabled(boolean burstEnabled) { + this.burstEnabled = burstEnabled; + } + + public int getBurstAmount() { + return burstAmount; + } + + public void setBurstAmount(int burstAmount) { + this.burstAmount = Math.max(0, burstAmount); + } + + public int getBurstDelay() { + return burstDelay; + } + + public void setBurstDelay(int burstDelay) { + this.burstDelay = Math.max(0, burstDelay); + } + + public boolean isBurstReplayAnimations() { + return burstReplayAnimations; + } + + public void setBurstReplayAnimations(boolean burstReplayAnimations) { + this.burstReplayAnimations = burstReplayAnimations; + } + + public boolean isBurstOverlap() { + return burstOverlap; + } + + public void setBurstOverlap(boolean burstOverlap) { + this.burstOverlap = burstOverlap; + } + + public int getBurstIndex() { + return burstIndex; + } + + /** + * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). + */ + private static String[] getRotationPhaseKeys() { + return new String[]{ + "ability.lockMove.windup", + "ability.lockMove.active", + "ability.lockMove.both" + }; + } + + // ═══════════════════════════════════════════════════════════════════ + // WINDUP DURATION CALCULATION + // ═══════════════════════════════════════════════════════════════════ + + private int calculateWindupFromAnimation() { + if (!syncWindupWithAnimation) { + return windUpTicks; + } + + if (AnimationController.Instance == null) { + return this.windUpTicks; + } + + Animation animation = null; + // 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; + } + + // Calculate total duration by summing all frame durations + int totalDuration = 0; + for (Frame frame : animation.frames) { + totalDuration += frame.getDuration(); + } + + // Return total duration + 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 + // ═══════════════════════════════════════════════════════════════════ + + @Override + public int getAllowedByType() { + return allowedBy.ordinal(); + } + + @Override + public void setAllowedByType(int type) { + this.allowedBy = UserType.fromOrdinal(type); + } + + @Override + public INbt getNbt() { + 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/AbilityVariant.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java new file mode 100644 index 000000000..0ef3b9692 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java @@ -0,0 +1,54 @@ +package kamkeel.npcs.controllers.data.ability; + +import java.util.function.Consumer; + +/** + * Represents a variant/template for an ability type. + * When a user creates an ability that has registered variants, + * they are presented with a selection dialog before the ability is created. + *

+ * Each variant has a display name (lang key) and a configurator that + * applies preset values to the newly created ability. + */ +public class AbilityVariant { + + private final String displayKey; + private final String group; + private final Consumer configurator; + + /** + * @param displayKey Lang key for the variant display name (e.g., "ability.variant.dual") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, Consumer configurator) { + this(displayKey, null, configurator); + } + + /** + * @param displayKey Lang key for the variant display name + * @param group Optional group header shown in the variant selection GUI (e.g., "DBC Addon") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, String group, Consumer configurator) { + this.displayKey = displayKey; + this.group = group; + this.configurator = configurator; + } + + public String getDisplayKey() { + return displayKey; + } + + public String getGroup() { + return group; + } + + /** + * Apply this variant's preset configuration to the given ability. + */ + public void apply(Ability ability) { + if (configurator != null) { + configurator.accept(ability); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/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/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/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..eca7aded0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java @@ -0,0 +1,109 @@ +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); + } + + @SideOnly(Side.CLIENT) + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.subGuiField("condition.select_effect", + () -> new SubGuiCustomEffectSelect(effectId, effectIndex), + gui -> { + SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui; + if (sel.getSelectedEffectId() >= 0) { + effectId = sel.getSelectedEffectId(); + effectIndex = sel.getSelectedIndex(); + } + }) + .buttonLabel(() -> { + if (effectId < 0) return "None"; + CustomEffect effect = getEffect(); + return effect != null ? effect.getName() : "ID:" + effectId; + }) + .clearable(() -> { + effectId = -1; + effectIndex = 0; + })); + } + + @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; + } + + private 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..2955b7610 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java @@ -0,0 +1,91 @@ +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(FieldDef.subGuiField("condition.select_quest", + () -> new GuiQuestSelection(questId), + gui -> { + GuiQuestSelection sel = (GuiQuestSelection) gui; + if (sel.selectedQuest != null) { + questId = sel.selectedQuest.id; + } + }) + .buttonLabel(() -> { + if (questId < 0) return "None"; + Quest q = QuestController.Instance.quests.get(questId); + return q != null ? q.title : "ID:" + questId; + }) + .clearable(() -> questId = -1)); + } + + @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..bdf95508f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java @@ -0,0 +1,531 @@ +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; + + /** + * 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 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.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; + 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/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 new file mode 100644 index 000000000..a54f526ee --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -0,0 +1,64 @@ +package 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.EnergyDisplayData; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Per-projectile data: anchor point + optional color override. + * All projectiles share the primary EnergyDisplayData; this class + * allows individual projectiles to override just the inner/outer colors. + */ +public class ProjectileData { + public EnergyAnchorData anchor; + public boolean colorOverride = false; + public int innerColor = 0xFFFFFF; + public int outerColor = 0x8888FF; + + public ProjectileData(AnchorPoint defaultAnchor) { + this.anchor = new EnergyAnchorData(defaultAnchor); + } + + /** + * Returns the display data to use for this projectile. + * If colorOverride is false, returns the primary display data directly. + * If colorOverride is true, returns a copy with overridden inner/outer colors. + */ + public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) { + // Always return a copy so entity mutations never bleed back into the ability template. + EnergyDisplayData resolved = primary.copy(); + if (colorOverride) { + resolved.innerColor = this.innerColor; + resolved.outerColor = this.outerColor; + } + return resolved; + } + + public void writeNBT(NBTTagCompound nbt) { + anchor.writeNBT(nbt); + nbt.setBoolean("colorOverride", colorOverride); + if (colorOverride) { + nbt.setInteger("overrideInnerColor", innerColor); + nbt.setInteger("overrideOuterColor", outerColor); + } + } + + public void readNBT(NBTTagCompound nbt) { + anchor.readNBT(nbt); + colorOverride = nbt.getBoolean("colorOverride"); + if (colorOverride) { + innerColor = nbt.getInteger("overrideInnerColor"); + outerColor = nbt.getInteger("overrideOuterColor"); + } + } + + public ProjectileData copy() { + ProjectileData copy = new ProjectileData(anchor.anchorPoint); + copy.anchor = anchor.copy(); + copy.colorOverride = colorOverride; + copy.innerColor = innerColor; + copy.outerColor = outerColor; + return copy; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/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/energy/EnergyAnchorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyAnchorData.java new file mode 100644 index 000000000..f618ae3f7 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyAnchorData.java @@ -0,0 +1,118 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyAnchorData; + +public class EnergyAnchorData implements IEnergyAnchorData { + public AnchorPoint anchorPoint = AnchorPoint.FRONT; + public float anchorOffsetX = 0; + public float anchorOffsetY = 0; + public float anchorOffsetZ = 0; + public boolean launchFromAnchor = false; + + public EnergyAnchorData() { + } + + public EnergyAnchorData(AnchorPoint anchorPoint) { + this.anchorPoint = anchorPoint; + } + + public EnergyAnchorData(AnchorPoint anchorPoint, float anchorOffsetX, float anchorOffsetY, float anchorOffsetZ) { + this.anchorPoint = anchorPoint; + this.anchorOffsetX = anchorOffsetX; + this.anchorOffsetY = anchorOffsetY; + this.anchorOffsetZ = anchorOffsetZ; + } + + public EnergyAnchorData(int anchorPoint) { + this.anchorPoint = AnchorPoint.fromOrdinal(anchorPoint); + } + + public EnergyAnchorData(int anchorPoint, float anchorOffsetX, float anchorOffsetY, float anchorOffsetZ) { + this.anchorPoint = AnchorPoint.fromOrdinal(anchorPoint); + this.anchorOffsetX = anchorOffsetX; + this.anchorOffsetY = anchorOffsetY; + this.anchorOffsetZ = anchorOffsetZ; + } + + public AnchorPoint getAnchorPoint() { + return anchorPoint; + } + + public void setAnchorPoint(AnchorPoint anchorPoint) { + this.anchorPoint = anchorPoint; + } + + @Override + public int getAnchor() { + return anchorPoint.ordinal(); + } + + @Override + public void setAnchor(int anchor) { + this.anchorPoint = AnchorPoint.fromOrdinal(anchor); + } + + @Override + public float getAnchorOffsetX() { + return anchorOffsetX; + } + + @Override + public void setAnchorOffsetX(float anchorOffsetX) { + this.anchorOffsetX = anchorOffsetX; + } + + @Override + public float getAnchorOffsetY() { + return anchorOffsetY; + } + + @Override + public void setAnchorOffsetY(float anchorOffsetY) { + this.anchorOffsetY = anchorOffsetY; + } + + @Override + public float getAnchorOffsetZ() { + return anchorOffsetZ; + } + + @Override + public void setAnchorOffsetZ(float anchorOffsetZ) { + 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 = 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() { + 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/energy/EnergyDisplayData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java new file mode 100644 index 000000000..72bcffbb8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java @@ -0,0 +1,137 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyDisplayData; + +/** + * Groups visual color properties shared by all energy abilities. + * Used as a parameter object for entity constructors and ability configuration. + */ +public class EnergyDisplayData implements IEnergyDisplayData { + public int innerColor = 0xFFFFFF; + public int outerColor = 0x8888FF; + 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(int innerColor, int outerColor) { + this.innerColor = innerColor; + this.outerColor = outerColor; + } + + public EnergyDisplayData(int innerColor, int outerColor, boolean outerColorEnabled, + float outerColorWidth, float outerColorAlpha, float rotationSpeed) { + this.innerColor = innerColor; + this.outerColor = outerColor; + this.outerColorEnabled = outerColorEnabled; + this.outerColorWidth = outerColorWidth; + this.outerColorAlpha = outerColorAlpha; + 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; + } + + @Override + public void setInnerColor(int innerColor) { + this.innerColor = innerColor; + } + + @Override + public int getOuterColor() { + return outerColor; + } + + @Override + public void setOuterColor(int outerColor) { + this.outerColor = outerColor; + } + + @Override + public boolean isOuterColorEnabled() { + return outerColorEnabled; + } + + @Override + public void setOuterColorEnabled(boolean outerColorEnabled) { + this.outerColorEnabled = outerColorEnabled; + } + + @Override + public float getOuterColorWidth() { + return outerColorWidth; + } + + @Override + public void setOuterColorWidth(float outerColorWidth) { + this.outerColorWidth = outerColorWidth; + } + + @Override + public float getOuterColorAlpha() { + return outerColorAlpha; + } + + @Override + public void setOuterColorAlpha(float outerColorAlpha) { + this.outerColorAlpha = outerColorAlpha; + } + + @Override + public float getInnerAlpha() { + return innerAlpha; + } + + @Override + public void setInnerAlpha(float innerAlpha) { + this.innerAlpha = innerAlpha; + } + + @Override + public float getRotationSpeed() { + return rotationSpeed; + } + + @Override + public void setRotationSpeed(float rotationSpeed) { + this.rotationSpeed = rotationSpeed; + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("innerColor", innerColor); + nbt.setInteger("outerColor", outerColor); + nbt.setBoolean("outerColorEnabled", outerColorEnabled); + nbt.setFloat("outerColorWidth", outerColorWidth); + nbt.setFloat("outerColorAlpha", outerColorAlpha); + nbt.setFloat("innerAlpha", innerAlpha); + nbt.setFloat("rotationSpeed", rotationSpeed); + } + + public void readNBT(NBTTagCompound nbt) { + innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF; + outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF; + outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled"); + outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f; + outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; + innerAlpha = nbt.hasKey("innerAlpha") ? nbt.getFloat("innerAlpha") : 1.0f; + rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; + } + + public EnergyDisplayData copy() { + 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/energy/EnergyHomingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyHomingData.java new file mode 100644 index 000000000..a0825fac1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyHomingData.java @@ -0,0 +1,87 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyHomingData; + + +/** + * Groups homing/movement properties for energy projectile abilities. + * Used by Orb, Disc, and Beam (not Laser or Sweeper). + */ +public class EnergyHomingData implements IEnergyHomingData { + public float speed = 0.5f; + public boolean homing = true; + public float homingStrength = 0.15f; + public float homingRange = 20.0f; + + public EnergyHomingData() { + } + + public EnergyHomingData(float speed, boolean homing, float homingStrength, float homingRange) { + this.speed = speed; + this.homing = homing; + this.homingStrength = homingStrength; + this.homingRange = homingRange; + } + + @Override + public float getSpeed() { + return speed; + } + + @Override + public void setSpeed(float speed) { + this.speed = Math.max(0.01f, speed); + } + + @Override + public boolean isHoming() { + return homing; + } + + @Override + public void setHoming(boolean homing) { + this.homing = homing; + } + + @Override + public float getHomingStrength() { + return homingStrength; + } + + @Override + public void setHomingStrength(float homingStrength) { + this.homingStrength = homingStrength; + } + + @Override + public float getHomingRange() { + return homingRange; + } + + @Override + public void setHomingRange(float homingRange) { + this.homingRange = homingRange; + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setFloat("speed", speed); + nbt.setBoolean("homing", homing); + nbt.setFloat("homingStrength", homingStrength); + nbt.setFloat("homingRange", homingRange); + } + + public void readNBT(NBTTagCompound nbt) { + speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 0.5f; + homing = !nbt.hasKey("homing") || nbt.getBoolean("homing"); + homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.15f; + homingRange = nbt.hasKey("homingRange") ? nbt.getFloat("homingRange") : 20.0f; + + // Sanitize speed to prevent stuck projectiles + if (Float.isNaN(speed) || Float.isInfinite(speed) || speed <= 0) speed = 0.5f; + } + + public EnergyHomingData copy() { + return new EnergyHomingData(speed, homing, homingStrength, homingRange); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLifespanData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLifespanData.java new file mode 100644 index 000000000..fcb516242 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLifespanData.java @@ -0,0 +1,59 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyLifespanData; + +/** + * Groups lifespan/range properties for energy projectile abilities. + * Used as a parameter object for entity constructors and ability configuration. + */ +public class EnergyLifespanData implements IEnergyLifespanData { + public float maxDistance = 150.0f; + public int maxLifetime = 200; + + public EnergyLifespanData() { + } + + public EnergyLifespanData(float maxDistance, int maxLifetime) { + this.maxDistance = maxDistance; + this.maxLifetime = maxLifetime; + } + + @Override + public float getMaxDistance() { + return maxDistance; + } + + @Override + public void setMaxDistance(float maxDistance) { + this.maxDistance = Float.isNaN(maxDistance) || maxDistance <= 0 ? 150.0f : maxDistance; + } + + @Override + public int getMaxLifetime() { + return maxLifetime; + } + + @Override + public void setMaxLifetime(int maxLifetime) { + this.maxLifetime = maxLifetime <= 0 ? 200 : maxLifetime; + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setFloat("maxDistance", maxDistance); + nbt.setInteger("maxLifetime", maxLifetime); + } + + public void readNBT(NBTTagCompound nbt) { + 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() { + return new EnergyLifespanData(maxDistance, maxLifetime); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLightningData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLightningData.java new file mode 100644 index 000000000..72a412cfd --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyLightningData.java @@ -0,0 +1,85 @@ +package kamkeel.npcs.controllers.data.ability.data.energy; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyLightningData; + +/** + * Groups lightning visual effect properties for energy abilities. + * Used as a parameter object for entity constructors and ability configuration. + */ +public class EnergyLightningData implements IEnergyLightningData { + public boolean lightningEffect = false; + public float lightningDensity = 0.15f; + public float lightningRadius = 0.5f; + public int lightningFadeTime = 6; + + public EnergyLightningData() { + } + + public EnergyLightningData(boolean lightningEffect, float lightningDensity, + float lightningRadius, int lightningFadeTime) { + this.lightningEffect = lightningEffect; + this.lightningDensity = lightningDensity; + this.lightningRadius = lightningRadius; + this.lightningFadeTime = lightningFadeTime; + } + + @Override + public boolean isLightningEffect() { + return lightningEffect; + } + + @Override + public void setLightningEffect(boolean lightningEffect) { + this.lightningEffect = lightningEffect; + } + + @Override + public float getLightningDensity() { + return lightningDensity; + } + + @Override + public void setLightningDensity(float lightningDensity) { + this.lightningDensity = lightningDensity; + } + + @Override + public float getLightningRadius() { + return lightningRadius; + } + + @Override + public void setLightningRadius(float lightningRadius) { + this.lightningRadius = lightningRadius; + } + + @Override + public int getLightningFadeTime() { + return lightningFadeTime; + } + + @Override + public void setLightningFadeTime(int lightningFadeTime) { + this.lightningFadeTime = Math.max(1, lightningFadeTime); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setBoolean("lightningEffect", lightningEffect); + nbt.setFloat("lightningDensity", lightningDensity); + nbt.setFloat("lightningRadius", lightningRadius); + nbt.setInteger("lightningFadeTime", lightningFadeTime); + } + + public void readNBT(NBTTagCompound nbt) { + lightningEffect = nbt.hasKey("lightningEffect") && nbt.getBoolean("lightningEffect"); + lightningDensity = nbt.hasKey("lightningDensity") ? nbt.getFloat("lightningDensity") : 0.15f; + lightningRadius = nbt.hasKey("lightningRadius") ? nbt.getFloat("lightningRadius") : 0.5f; + lightningFadeTime = nbt.hasKey("lightningFadeTime") ? nbt.getInteger("lightningFadeTime") : 6; + if (lightningFadeTime <= 0) lightningFadeTime = 1; + } + + public EnergyLightningData copy() { + return new EnergyLightningData(lightningEffect, lightningDensity, lightningRadius, lightningFadeTime); + } +} 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/enums/AbilityPhase.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AbilityPhase.java new file mode 100644 index 000000000..a0549b09a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AbilityPhase.java @@ -0,0 +1,9 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +public enum AbilityPhase { + IDLE, // Not executing + WINDUP, // Charging up (telegraph visible) + ACTIVE, // Executing (damage happens) + DAZED, // Stunned after interrupt during WINDUP (cannot attack) + BURST_DELAY // Waiting between burst repetitions (free movement/rotation) +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AnchorPoint.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AnchorPoint.java new file mode 100644 index 000000000..567713d34 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/AnchorPoint.java @@ -0,0 +1,71 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Defines anchor points for ability charging effects. + * Determines where the charging visual (orb, disc, etc.) appears relative to the entity. + */ +public enum AnchorPoint { + FRONT("Front"), // In front of entity face (default) + CENTER("Center"), // Entity center + 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 + EYE("Eye"); // Eye level, centered + + private final String displayName; + + AnchorPoint(String displayName) { + this.displayName = displayName; + } + + public String getDisplayName() { + return displayName; + } + + /** + * Get AnchorPoint from ordinal value. + * Returns FRONT if ordinal is out of bounds. + */ + public static AnchorPoint fromOrdinal(int ordinal) { + AnchorPoint[] vals = values(); + if (ordinal < 0 || ordinal >= vals.length) { + return FRONT; + } + return vals[ordinal]; + } + + /** + * Get all display names for GUI dropdowns. + */ + public static String[] getDisplayNames() { + AnchorPoint[] values = values(); + String[] names = new String[values.length]; + for (int i = 0; i < values.length; i++) { + names[i] = values[i].displayName; + } + return names; + } + + @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"; + 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/enums/LockMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/LockMode.java new file mode 100644 index 000000000..47d7b1d1d --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/LockMode.java @@ -0,0 +1,83 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Defines when an ability locks NPC movement and rotation. + */ +public enum LockMode { + /** + * No movement lock - NPC can move freely during both phases. + */ + NO, + + /** + * Lock movement during WINDUP phase only. + * NPC can move during ACTIVE phase. + */ + WINDUP, + + /** + * Lock movement during ACTIVE phase only. + * NPC can move during WINDUP phase. + */ + ACTIVE, + + /** + * Lock movement during both WINDUP and ACTIVE phases. + */ + WINDUP_AND_ACTIVE; + + /** + * Check if movement should be locked during WINDUP phase. + */ + public boolean locksWindup() { + return this == WINDUP || this == WINDUP_AND_ACTIVE; + } + + /** + * Check if movement should be locked during ACTIVE phase. + */ + public boolean locksActive() { + return this == ACTIVE || this == WINDUP_AND_ACTIVE; + } + + /** + * Get display name for GUI. + */ + public String getDisplayKey() { + switch (this) { + case NO: + return "gui.no"; + case WINDUP: + return "ability.lockMove.windup"; + case ACTIVE: + return "ability.lockMove.active"; + case WINDUP_AND_ACTIVE: + return "ability.lockMove.both"; + default: + return "gui.no"; + } + } + + /** + * Get all display keys for GUI dropdown. + */ + public static String[] getDisplayKeys() { + return new String[]{ + "gui.no", + "ability.lockMove.windup", + "ability.lockMove.active", + "ability.lockMove.both" + }; + } + + /** + * Get LockMode from ordinal, with fallback to WINDUP. + */ + public static LockMode fromOrdinal(int ordinal) { + LockMode[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return WINDUP; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/enums/RotationMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/RotationMode.java new file mode 100644 index 000000000..f8f1ec860 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/RotationMode.java @@ -0,0 +1,53 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Defines what happens to NPC rotation during ability phases. + * Used with a LockMode to control WHEN it applies. + */ +public enum RotationMode { + /** + * NPC rotates normally via AI look helper. + */ + FREE, + + /** + * Freeze rotation at the moment the phase starts. + * NPC stays facing the direction it was looking when the phase began. + */ + LOCKED, + + /** + * Force NPC to continuously face its target (hit scan). + * Overrides AI look helper every tick for precise aiming. + */ + TRACK; + + public String getDisplayKey() { + switch (this) { + case FREE: + return "ability.rotation.free"; + case LOCKED: + return "ability.rotation.locked"; + case TRACK: + return "ability.rotation.track"; + default: + return "ability.rotation.free"; + } + } + + public static String[] getDisplayKeys() { + return new String[]{ + "ability.rotation.free", + "ability.rotation.locked", + "ability.rotation.track" + }; + } + + public static RotationMode fromOrdinal(int ordinal) { + RotationMode[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return FREE; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/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/enums/TargetingMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetingMode.java new file mode 100644 index 000000000..b32b04c9a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/TargetingMode.java @@ -0,0 +1,42 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Defines how an ability selects its target(s). + */ +public enum TargetingMode { + /** + * Target the current aggro target + */ + AGGRO_TARGET, + + /** + * Target self (for buffs, heals, guards) + */ + SELF, + + /** + * AOE centered on self + */ + AOE_SELF, + + /** + * AOE centered on target + */ + AOE_TARGET; + + @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(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/enums/UserType.java b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/UserType.java new file mode 100644 index 000000000..cc5960ff6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/enums/UserType.java @@ -0,0 +1,27 @@ +package kamkeel.npcs.controllers.data.ability.enums; + +/** + * Defines which entity types can use an ability. + */ +public enum UserType { + NPC_ONLY, + PLAYER_ONLY, + BOTH, + NONE; + + public boolean allowsNpc() { + return this == NPC_ONLY || this == BOTH; + } + + public boolean allowsPlayer() { + return this == PLAYER_ONLY || this == BOTH; + } + + public static UserType fromOrdinal(int ordinal) { + UserType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return 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..d691a6d18 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/extender/IAbilityExtender.java @@ -0,0 +1,133 @@ +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 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 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 new file mode 100644 index 000000000..6438f6ba1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java @@ -0,0 +1,513 @@ +package kamkeel.npcs.controllers.data.ability.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +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; +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, CUSTOM_EFFECTS_LIST, and EFFECT_ACTIONS_LIST field types. + */ +@SideOnly(Side.CLIENT) +public class AbilityFieldBuilder extends GuiFieldBuilder { + + // 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); + } + + @Override + protected int build(List fields) { + effectWidgetMeta.clear(); + sortedCustomEffectIds = null; + sortedCustomEffectNames = null; + effectActionIds = null; + effectActionDisplayNames = null; + return super.build(fields); + } + + @Override + protected int buildField(FieldDef def, int y, List fields, int index) { + 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) { + y += 3; + sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); + y += 15; + + List effects = (List) def.getValue(); + if (effects == null) effects = new ArrayList<>(); + + 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++) { + AbilityPotionEffect effect = effects.get(e); + + 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())); + durField.setIntegersOnly(); + durField.setMinMaxDefault(1, 12000, 60); + sw.addTextField(durField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 1}); + widgetId++; + + // 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++; + + // 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 (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; + } + + // ═══════════════════════════════════════════════════════════════════ + // 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 + // ═══════════════════════════════════════════════════════════════════ + + @Override + @SuppressWarnings("unchecked") + public boolean handleButtonEvent(int buttonId, GuiButton button) { + int[] meta = effectWidgetMeta.get(buttonId); + if (meta != null) { + FieldDef def = buttonFieldMap.get(buttonId); + if (def == null) def = clearFieldMap.get(buttonId); + 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: + 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: + 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 (idx < effects.size()) effects.remove(idx); + return true; + case 4: // Add + if (effects.size() < 5) { + 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; + } + } + } + + return super.handleButtonEvent(buttonId, button); + } + + @Override + @SuppressWarnings("unchecked") + public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { + int[] meta = effectWidgetMeta.get(textFieldId); + if (meta != null) { + FieldDef def = textFieldMap.get(textFieldId); + 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; + } + } + + return super.handleTextFieldEvent(textFieldId, field); + } + + 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 new file mode 100644 index 000000000..3bbd80f9b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java @@ -0,0 +1,42 @@ +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.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; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Ability-specific FieldDef factories. These create FieldDef instances + * with types that require ability-specific rendering (e.g. EFFECTS_LIST). + */ +@SideOnly(Side.CLIENT) +public class AbilityFieldDefs { + + @SuppressWarnings("unchecked") + public static FieldDef effectsListField(String label, Supplier> getter, Consumer> setter) { + return FieldDef.custom(label, FieldType.EFFECTS_LIST, + () -> getter.get(), + 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/kamkeel/npcs/controllers/data/ability/gui/GuiAbilityInterface.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/GuiAbilityInterface.java new file mode 100644 index 000000000..0ff9b31f1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/GuiAbilityInterface.java @@ -0,0 +1,411 @@ +package kamkeel.npcs.controllers.data.ability.gui; + +import kamkeel.npcs.client.renderer.TelegraphRenderer; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +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 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; +import org.lwjgl.opengl.GL12; + +import java.util.ArrayList; +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) + * - Viewing direction can be rotated (rotates entire 3D space) + * - Fixed zoom level + * - Preview entities rendered in same coordinate space as NPC + * - NPC position changes (e.g. slam jump) tracked and rendered + */ +public class GuiAbilityInterface extends GuiNPCInterface2 { + + // ==================== FIXED CAMERA SETTINGS ==================== + /** + * Fixed camera zoom level (higher = more zoomed in) + */ + protected static float CAMERA_ZOOM = 45.0f; + /** + * 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) + */ + protected static float viewRotation = 0.0f; + + private GuiNpcButton btnLeft, btnRight; + + // ==================== NPC STATE ==================== + public EntityNPCInterface npc; + + /** + * NPC starting position (saved when preview starts, used to track movement) + */ + protected double npcStartX, npcStartY, npcStartZ; + /** + * Whether we're tracking NPC movement + */ + protected boolean trackingNpcMovement = false; + + /** + * Entities to render in preview space + */ + protected List previewEntities = new ArrayList<>(); + + /** + * Current telegraph to render in preview + */ + protected TelegraphInstance previewTelegraph; + + // ==================== LAYOUT ==================== + /** + * Preview area bounds + */ + protected int previewX, previewY, previewWidth, previewHeight; + /** + * NPC render position on screen + */ + protected int npcScreenX, npcScreenY; + + public int xOffset = 0; + public int yOffset = 0; + + public GuiAbilityInterface(EntityNPCInterface npc) { + this(npc, true); + } + + /** + * @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. + */ + public GuiAbilityInterface(EntityNPCInterface npc, boolean hasMenuNpc) { + super(hasMenuNpc ? npc : null); + this.npc = npc; + this.drawDefaultBackground = false; + + CAMERA_ZOOM = 30f; + NPC_FACING_YAW = 310f; + CAMERA_PITCH = 5f; + } + + @Override + public void initGui() { + super.initGui(); + + // Calculate preview area (left side of GUI) + previewX = guiLeft + 10; + previewY = guiTop + 10; + previewWidth = 200; + 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; + + // Viewing rotation buttons (below preview area) + int btnY = guiTop + 192; + addButton(btnLeft = new GuiNpcButton(680, guiLeft + 10, btnY, 20, 20, "<")); + addButton(btnRight = new GuiNpcButton(681, guiLeft + 32, btnY, 20, 20, ">")); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + // Handle held rotation buttons + if (Mouse.isButtonDown(0)) { + if (btnLeft != null && btnLeft.mousePressed(mc, mouseX, mouseY)) { + viewRotation += partialTicks * 2; + } else if (btnRight != null && btnRight.mousePressed(mc, mouseX, mouseY)) { + viewRotation -= partialTicks * 2; + } + } + + // Draw background and UI elements + super.drawScreen(mouseX, mouseY, partialTicks); + + // Draw the 3D preview + drawPreview(mouseX, mouseY, partialTicks); + } + + /** + * Draw the 3D preview with NPC and entities. + */ + protected void drawPreview(int mouseX, int mouseY, float partialTicks) { + if (hasSubGui()) + return; + + GL11.glColor4f(1, 1, 1, 1); + + // Enable scissor to clip rendering to preview area + GL11.glEnable(GL11.GL_SCISSOR_TEST); + setScissorClip(previewX, previewY, previewWidth, previewHeight); + + // Always use the standard NPC animation renderer for ability preview + EntityLivingBase renderEntity = this.npc; + + // Set NPC facing direction (affects anchor points and visual facing) + npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; + npc.prevRotationYaw = npc.rotationYaw = NPC_FACING_YAW; + npc.prevRotationYawHead = npc.rotationYawHead = NPC_FACING_YAW; + + // Also set on render entity + renderEntity.prevRenderYawOffset = renderEntity.renderYawOffset = NPC_FACING_YAW; + renderEntity.prevRotationYaw = renderEntity.rotationYaw = NPC_FACING_YAW; + renderEntity.prevRotationYawHead = renderEntity.rotationYawHead = NPC_FACING_YAW; + renderEntity.rotationPitch = 0; + + // Calculate NPC position delta for movement rendering (e.g. slam jump) + // Interpolate with partial ticks for smooth movement between frames + double npcDeltaX = 0, npcDeltaY = 0, npcDeltaZ = 0; + if (trackingNpcMovement) { + 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; + } + + // ==================== BEGIN 3D RENDERING ==================== + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glPushMatrix(); + + // Move to NPC render position on screen + GL11.glTranslatef(npcScreenX, npcScreenY, 300F); + + // Apply zoom (scale) + GL11.glScalef(-CAMERA_ZOOM, CAMERA_ZOOM, CAMERA_ZOOM); + + // Flip for screen coordinates (Y is inverted) + GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F); + + // Apply slight camera pitch (looking down at scene) + GL11.glRotatef(CAMERA_PITCH, 1.0F, 0.0F, 0.0F); + + // Apply VIEWING rotation (rotates entire space, not just NPC) + GL11.glRotatef(viewRotation, 0.0F, 1.0F, 0.0F); + + // Setup lighting (standard item lighting for consistent colors) + GL11.glRotatef(135F, 0.0F, 1.0F, 0.0F); + RenderHelper.enableStandardItemLighting(); + GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F); + + // Adjust for entity offset + GL11.glTranslatef(0.0F, renderEntity.yOffset, 0.0F); + + RenderManager.instance.playerViewY = 180F; + ClientEventHandler.renderingEntityInGUI = true; + + // Render the NPC at its position delta (for movement like slam jumps) + RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); + + // Render preview entities at their positions relative to NPC start position + renderPreviewEntities(partialTicks); + + // Render telegraph in preview space + renderPreviewTelegraph(partialTicks); + + ClientEventHandler.renderingEntityInGUI = false; + + GL11.glPopMatrix(); + + // Cleanup GL state + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + + // Disable scissor + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Clear depth buffer so UI renders on top + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + } + + /** + * Render preview entities in the same coordinate space as the NPC. + * Called WITHIN the 3D matrix transformation. + */ + protected void renderPreviewEntities(float partialTicks) { + // Save current GL state that NPC render may have changed + boolean lightingWasEnabled = GL11.glIsEnabled(GL11.GL_LIGHTING); + + // Use the start position as the reference point for entity offsets + double refX = trackingNpcMovement ? npcStartX : npc.posX; + double refY = trackingNpcMovement ? npcStartY : npc.posY; + double refZ = trackingNpcMovement ? npcStartZ : npc.posZ; + + for (Entity entity : previewEntities) { + if (entity == null || entity.isDead) continue; + + // Calculate entity position relative to reference (NPC start position) + double offsetX = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - refX; + double offsetY = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - refY; + double offsetZ = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - refZ; + + // The NPC model was translated by npc.yOffset, so we need to subtract it + offsetY -= npc.yOffset; + + // Reset GL state before each entity to ensure colors render correctly + 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 e) { + // Ignore rendering errors + } + } + + // Restore lighting state for any subsequent rendering + if (lightingWasEnabled) { + GL11.glEnable(GL11.GL_LIGHTING); + } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + /** + * Render the telegraph in the 3D preview space. + * Called within the GL matrix transformation. + */ + protected void renderPreviewTelegraph(float partialTicks) { + if (previewTelegraph == null) return; + if (TelegraphRenderer.Instance == null) return; + + // Telegraph position is in world coords - convert to preview space + double refX = trackingNpcMovement ? npcStartX : npc.posX; + double refY = trackingNpcMovement ? npcStartY : npc.posY; + double refZ = trackingNpcMovement ? npcStartZ : npc.posZ; + + double offsetX = previewTelegraph.getInterpolatedX(partialTicks) - refX; + double offsetY = previewTelegraph.getInterpolatedY(partialTicks) - refY; + double offsetZ = previewTelegraph.getInterpolatedZ(partialTicks) - refZ; + + // Adjust for NPC yOffset (same as entities) + offsetY -= npc.yOffset; + + TelegraphRenderer.Instance.renderTelegraphInGUI(previewTelegraph, offsetX, offsetY, offsetZ, 1.0f, partialTicks); + } + + public void setPreviewTelegraph(TelegraphInstance telegraph) { + this.previewTelegraph = telegraph; + } + + /** + * Set scissor clip for preview area. + */ + protected void setScissorClip(int x, int y, int width, int height) { + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scale = sr.getScaleFactor(); + int scaledY = mc.displayHeight - (y + height) * scale; + GL11.glScissor(x * scale, scaledY, width * scale, height * scale); + } + + // ==================== MOVEMENT TRACKING ==================== + + /** + * Start tracking NPC movement from current position. + */ + public void startTrackingMovement() { + npcStartX = npc.posX; + npcStartY = npc.posY; + npcStartZ = npc.posZ; + trackingNpcMovement = true; + } + + /** + * Stop tracking NPC movement. + */ + public void stopTrackingMovement() { + trackingNpcMovement = false; + } + + // ==================== PREVIEW ENTITY MANAGEMENT ==================== + + public void addPreviewEntity(Entity entity) { + if (entity != null && !previewEntities.contains(entity)) { + previewEntities.add(entity); + } + } + + public void removePreviewEntity(Entity entity) { + previewEntities.remove(entity); + } + + public void clearPreviewEntities() { + previewEntities.clear(); + } + + public List getPreviewEntities() { + return previewEntities; + } + + public float getNpcFacingYaw() { + return NPC_FACING_YAW; + } + + // ==================== BACKGROUND ==================== + + @Override + protected void drawBackground() { + super.drawBackground(); + + drawGradientRect(previewX, previewY, previewX + previewWidth, previewY + previewHeight, + 0xc0101010, 0xd0101010); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + + // ==================== STANDARD OVERRIDES ==================== + + @Override + public boolean doesGuiPauseGame() { + return false; + } + + @Override + public void keyTyped(char par1, int par2) { + boolean hadSubGui = hasSubGui(); + super.keyTyped(par1, par2); + if (par2 == 1 && !hadSubGui) { + close(); + } + } + + public void close() { + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + } + + @Override + public void save() { + } + + @Override + protected void actionPerformed(GuiButton btn) { + if (btn.id == 670) { + close(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IAbilityFieldProvider.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IAbilityFieldProvider.java new file mode 100644 index 000000000..615234a7c --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/IAbilityFieldProvider.java @@ -0,0 +1,26 @@ +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; + +/** + * External field definition provider for abilities. + * Called during getAllDefinitions() to allow mods to inject custom tabs/fields + * into the 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 IAbilityFieldProvider { + /** + * Add field definitions to the ability's GUI. + * Fields added here should use .tab() to assign them to a custom tab. + * + * @param ability The ability being configured + * @param defs The mutable list of field definitions to add to + */ + void addFieldDefinitions(Ability ability, List defs); +} 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/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java new file mode 100644 index 000000000..aa2f5492f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java @@ -0,0 +1,639 @@ +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.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; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.ArrayList; +import java.util.Iterator; +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 + * 3. EXTENDED phase - 100 extra ticks to observe results (entities continue updating) + * 4. IDLE - preview complete + */ +@SideOnly(Side.CLIENT) +public class AbilityPreviewExecutor implements PreviewEntityHandler { + + // ==================== PREVIEW STATE ==================== + private Ability previewAbility; + private EntityNPCInterface previewNpc; + + /** + * 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; + private boolean playing = false; + private boolean paused = false; + + // ==================== TIMING ==================== + private static final int EXTENDED_DURATION = 100; + private int maxPreviewDuration = 200; + + // ==================== FAKE TARGET ==================== + private EntityNPCInterface fakeTarget; + private static final double TARGET_DISTANCE = 5.0; + + // ==================== 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; + + public AbilityPreviewExecutor() { + } + + public void setParentGui(GuiAbilityInterface gui) { + this.parentGui = gui; + } + + /** + * 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.previewNpc = npc; + this.playing = true; + this.paused = false; + + // Save NPC start position for restoring later + this.npcStartX = npc.posX; + this.npcStartY = npc.posY; + this.npcStartZ = npc.posZ; + this.hasStartPosition = true; + + // Create invisible fake target NPC for targeting + createFakeTarget(npc); + + // Start tracking NPC movement + if (parentGui != null) { + 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); + + // 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(); + } else { + // Normal windup flow + this.executorPhase = ExecutorPhase.WINDUP; + + // Create telegraph for preview + previewTelegraph = ability.createTelegraph(previewNpc, fakeTarget); + + // Start windup animation + Animation windUpAnim = ability.getWindUpAnimation(); + if (windUpAnim != null) { + AnimationData data = previewNpc.display.animationData; + data.setEnabled(true); + data.setAnimation(windUpAnim); + data.animation.paused = false; + } + } + } + + /** + * Create an invisible fake target NPC placed in front of the preview NPC. + */ + private void createFakeTarget(EntityNPCInterface npc) { + if (npc.worldObj == null) return; + + try { + fakeTarget = new EntityCustomNpc(npc.worldObj); + float facingYaw = GuiAbilityInterface.NPC_FACING_YAW; + double yawRad = Math.toRadians(facingYaw); + double targetX = npc.posX - Math.sin(yawRad) * TARGET_DISTANCE; + double targetY = npc.posY; + double targetZ = npc.posZ + Math.cos(yawRad) * TARGET_DISTANCE; + fakeTarget.setPosition(targetX, targetY, targetZ); + fakeTarget.prevPosX = targetX; + fakeTarget.prevPosY = targetY; + fakeTarget.prevPosZ = targetZ; + } catch (Exception e) { + fakeTarget = null; + } + } + + public EntityLivingBase getFakeTarget() { + return fakeTarget; + } + + public void play() { + if (previewAbility == null || executorPhase == ExecutorPhase.IDLE) { + return; + } + playing = true; + paused = false; + + if (previewNpc != null) { + AnimationData data = previewNpc.display.animationData; + if (data.animation != null) { + data.animation.paused = false; + } + } + } + + public void pause() { + paused = true; + + // Immediately sync prevPos to pos for NPC and all entities to prevent interpolation jitter + syncPrevPositions(); + + if (previewNpc != null) { + AnimationData data = previewNpc.display.animationData; + if (data.animation != null) { + data.animation.paused = true; + } + } + } + + /** + * Sync prevPos to pos for the NPC and all preview entities. + * Prevents rendering interpolation jitter when standing still or paused. + */ + private void syncPrevPositions() { + if (previewNpc != null) { + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + } + for (Entity entity : previewEntities) { + if (entity != null && !entity.isDead) { + entity.prevPosX = entity.posX; + entity.prevPosY = entity.posY; + entity.prevPosZ = entity.posZ; + } + } + } + + public void stop() { + // Clean up the ability + if (previewAbility != null) { + previewAbility.cleanup(); + previewAbility.setPreviewMode(false); + previewAbility.setPreviewEntityHandler(null); + previewAbility.reset(); + } + + playing = false; + paused = false; + executorPhase = ExecutorPhase.IDLE; + currentTick = 0; + + // Clear chain state + previewChain = null; + chainAbilities = null; + chainDelays = null; + chainIndex = -1; + chainDelayRemaining = 0; + + previewTelegraph = null; + + if (parentGui != null) { + for (Entity entity : previewEntities) { + parentGui.removePreviewEntity(entity); + } + parentGui.stopTrackingMovement(); + parentGui.setPreviewTelegraph(null); + } + previewEntities.clear(); + + // Reset NPC position to start position (undo movement from Slam/Charge/Dash) + if (previewNpc != null && hasStartPosition) { + previewNpc.posX = npcStartX; + previewNpc.posY = npcStartY; + previewNpc.posZ = npcStartZ; + previewNpc.prevPosX = npcStartX; + previewNpc.prevPosY = npcStartY; + previewNpc.prevPosZ = npcStartZ; + previewNpc.motionX = 0; + previewNpc.motionY = 0; + previewNpc.motionZ = 0; + } + + fakeTarget = null; + + if (previewNpc != null) { + AnimationData data = previewNpc.display.animationData; + data.setAnimation(new Animation()); + data.animation.paused = false; + } + } + + /** + * Tick the preview forward. Calls real ability methods. + */ + public void tick() { + if (!playing || previewAbility == null || previewNpc == null) { + return; + } + + if (paused) { + // Sync prevPos to pos for NPC and all entities to prevent interpolation jitter while paused + syncPrevPositions(); + return; + } + + // Sync NPC's prevPos to current pos BEFORE any updates to prevent jitter when standing still + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + + currentTick++; + + if (previewTelegraph != null) { + previewTelegraph.tick(null); + } + + tickEntities(); + + switch (executorPhase) { + case WINDUP: + tickWindup(); + break; + case ACTIVE: + tickActive(); + break; + case EXTENDED: + tickExtended(); + break; + case CHAIN_DELAY: + tickChainDelay(); + break; + default: + break; + } + } + + private void tickWindup() { + // Call the REAL windup tick method + previewAbility.onWindUpTick(previewNpc, fakeTarget, currentTick); + + if (currentTick >= previewAbility.getWindUpTicks()) { + transitionToActive(); + } + } + + private void tickActive() { + // Call the REAL active tick method + 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) { + if (hasNextChainEntry()) { + transitionToChainDelay(); + } else { + transitionToExtended(); + } + return; + } + + // Safety timeout + if (currentTick >= maxPreviewDuration) { + if (hasNextChainEntry()) { + transitionToChainDelay(); + } else { + transitionToExtended(); + } + } + } + + private void tickExtended() { + // Continue ticking entities so they can finish their animations + if (currentTick >= EXTENDED_DURATION) { + playing = false; + } + } + + // ==================== 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; + + previewTelegraph = null; + + // Call the REAL onExecute method (fires entities, initiates movement, etc.) + previewAbility.onExecute(previewNpc, fakeTarget); + + // Start active animation + Animation activeAnim = previewAbility.getActiveAnimation(); + if (activeAnim != null && previewNpc != null) { + AnimationData data = previewNpc.display.animationData; + data.setAnimation(activeAnim); + data.animation.paused = false; + } + } + + private void transitionToExtended() { + executorPhase = ExecutorPhase.EXTENDED; + currentTick = 0; + + if (previewNpc != null) { + AnimationData data = previewNpc.display.animationData; + data.setAnimation(new Animation()); + } + } + + /** + * Simulate basic physics for movement abilities (Slam, Charge, Dash). + * Applies gravity, drag, and ground clamping to NPC position. + */ + private void simulatePhysics() { + if (!previewAbility.hasAbilityMovement()) return; + if (previewNpc == null) return; + + // Save previous position for interpolation + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + + // Apply velocity + previewNpc.posX += previewNpc.motionX; + previewNpc.posY += previewNpc.motionY; + previewNpc.posZ += previewNpc.motionZ; + + // Apply gravity + previewNpc.motionY -= 0.08; + previewNpc.motionY *= 0.98; + + // Apply horizontal drag + previewNpc.motionX *= 0.91; + previewNpc.motionZ *= 0.91; + + // Ground clamp: if below start position and falling, stop + if (previewNpc.posY < npcStartY && previewNpc.motionY < 0) { + previewNpc.posY = npcStartY; + previewNpc.motionY = 0; + previewNpc.onGround = true; + } + + previewNpc.fallDistance = 0; + } + + private void tickEntities() { + Iterator iter = previewEntities.iterator(); + while (iter.hasNext()) { + Entity entity = iter.next(); + if (entity == null || entity.isDead) { + if (parentGui != null) { + parentGui.removePreviewEntity(entity); + } + iter.remove(); + continue; + } + entity.onUpdate(); + } + } + + // ==================== PreviewEntityHandler ==================== + + @Override + public void onEntitySpawned(Entity entity) { + if (entity == null) return; + previewEntities.add(entity); + if (parentGui != null) { + parentGui.addPreviewEntity(entity); + } + } + + @Override + public void onEntityRemoved(Entity entity) { + if (entity == null) return; + previewEntities.remove(entity); + if (parentGui != null) { + parentGui.removePreviewEntity(entity); + } + } + + // ==================== GETTERS ==================== + + public boolean isPlaying() { + return playing; + } + + public boolean isPaused() { + return paused; + } + + public boolean isActive() { + return playing || paused; + } + + public boolean isChainPreview() { + return previewChain != null; + } + + public AbilityPhase getPhase() { + switch (executorPhase) { + case WINDUP: + return AbilityPhase.WINDUP; + case ACTIVE: + return AbilityPhase.ACTIVE; + default: + return AbilityPhase.IDLE; + } + } + + public int getCurrentTick() { + return currentTick; + } + + public TelegraphInstance getTelegraph() { + return previewTelegraph; + } + + public List getPreviewEntities() { + return previewEntities; + } + + public Ability getPreviewAbility() { + return previewAbility; + } + + public EntityNPCInterface getPreviewNpc() { + return previewNpc; + } + + public String getStatusString() { + if (!playing && !paused) { + return "Stopped"; + } + + String chainPrefix = ""; + if (previewChain != null && chainAbilities != null) { + chainPrefix = "Chain " + (chainIndex + 1) + "/" + chainAbilities.size() + " - "; + } + + if (paused) { + return chainPrefix + "Paused"; + } else if (executorPhase == ExecutorPhase.WINDUP) { + return chainPrefix + "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0); + } else if (executorPhase == ExecutorPhase.ACTIVE) { + return chainPrefix + "Active: " + currentTick + "/" + maxPreviewDuration; + } else if (executorPhase == ExecutorPhase.EXTENDED) { + 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/preview/PreviewEntityHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/PreviewEntityHandler.java new file mode 100644 index 000000000..d5917260c --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/PreviewEntityHandler.java @@ -0,0 +1,14 @@ +package kamkeel.npcs.controllers.data.ability.preview; + +import net.minecraft.entity.Entity; + +/** + * Interface for routing entity spawn/kill calls during preview mode. + * In preview mode, entities are not added to the world but instead + * tracked by the GUI for rendering in the 3D viewport. + */ +public interface PreviewEntityHandler { + void onEntitySpawned(Entity entity); + + void onEntityRemoved(Entity entity); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java new file mode 100644 index 000000000..c88d63c30 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -0,0 +1,313 @@ +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.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; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.AxisAlignedBB; +import noppes.npcs.api.ability.type.IAbilityCharge; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * 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 AbilityMovement implements IAbilityCharge { + + // Type-specific parameters + private float chargeSpeed = 0.8f; + private float damage = 8.0f; + private float knockback = 3.0f; + private float hitWidth = 1.5f; + + // Type-specific runtime state + private transient Set hitEntities = new HashSet<>(); + + public AbilityCharge() { + this.typeId = "ability.cnpc.charge"; + this.name = "Charge"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 20.0f; + this.minRange = 4.0f; + this.lockMovement = LockMode.WINDUP; + this.cooldownTicks = 0; + this.windUpTicks = 20; + // LINE telegraph showing charge path + this.telegraphType = TelegraphType.LINE; + 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 isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + /** + * 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, int tick) { + if (!isPlayerCaster(caster) && target != null) { + lockDirectionToTarget(caster, target); + enforceLockedRotation(caster); + } + } + + @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(); + + enforceLockedRotation(caster); + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (checkTimeout(tick)) { + stopMomentum(caster); + signalCompletion(); + return; + } + + 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 (!caster.worldObj.isRemote && !isPreview()) { + AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth); + + @SuppressWarnings("unchecked") + 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; + + hitEntities.add(entity.getEntityId()); + + boolean wasHit = applyAbilityDamageWithDirection(caster, livingEntity, damage, knockback, + movementDirection.xCoord, movementDirection.zCoord); + + if (wasHit) { + applyEffects(livingEntity); + caster.worldObj.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f); + } + } + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + stopMomentum(caster); + super.onComplete(caster, target); + } + + @Override + public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { + stopMomentum(caster); + super.onInterrupt(caster, source, damage); + } + + @Override + public void cleanup() { + super.cleanup(); + hitEntities.clear(); + } + + @Override + public void resetForBurst() { + super.resetForBurst(); + hitEntities.clear(); + } + + @Override + public float getTelegraphLength() { + return maxRange; + } + + @Override + public float getTelegraphWidth() { + return hitWidth * 2; + } + + /** + * Creates a LINE telegraph from caster position towards target. + * Telegraph follows caster during windup (so caster can reposition before charging). + * Direction is locked at creation based on target position. + */ + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) { + return null; + } + + // NPC: telegraph points toward aggro target + // Player: telegraph points in look direction + float yaw; + if (!isPlayerCaster(caster) && target != null) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + } else { + yaw = caster.rotationYaw; + } + + // Create LINE telegraph + 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); + + // Position at caster ground level, direction towards target + double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ); + TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, groundY, caster.posZ, yaw); + instance.setCasterEntityId(caster.getEntityId()); + // 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; + } + + @Override + public int getMaxPreviewDuration() { + return (int) Math.ceil(maxRange / chargeSpeed) + 5; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("chargeSpeed", chargeSpeed); + nbt.setFloat("damage", damage); + nbt.setFloat("knockback", knockback); + nbt.setFloat("hitWidth", hitWidth); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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; + this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 1.5f; + } + + // Getters & Setters + public float getChargeSpeed() { + return chargeSpeed; + } + + public void setChargeSpeed(float chargeSpeed) { + this.chargeSpeed = chargeSpeed; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + public float getHitWidth() { + return hitWidth; + } + + public void setHitWidth(float hitWidth) { + this.hitWidth = hitWidth; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("ability.chargeSpeed", this::getChargeSpeed, this::setChargeSpeed) + ), + FieldDef.row( + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } +} 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..f03543028 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java @@ -0,0 +1,208 @@ +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.controllers.AnimationController; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.api.ability.type.IAbilityCounter; +import noppes.npcs.client.gui.builder.FieldDef; + +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"; + + 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 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.isEntityAlive() && damage > 0) { + applyAbilityDamage(caster, attacker, damage, 0); + } + + return 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // 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 new file mode 100644 index 000000000..7454dd3f0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -0,0 +1,475 @@ +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.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.api.ability.type.IAbilityCutter; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Cutter ability: Sweeping fan attack in an arc. + * Deals damage to all entities in a cone/arc in front of the caster. + * Can sweep outward over time or hit instantly. + */ +public class AbilityCutter extends Ability implements IAbilityCutter { + + public enum SweepMode { + SWIPE, + SPIN; + + @Override + public String toString() { + switch (this) { + case SWIPE: + return "ability.sweep.swipe"; + case SPIN: + return "ability.sweep.spin"; + default: + return name(); + } + } + } + + private float arcAngle = 90.0f; + private float range = 6.0f; + private float damage = 7.0f; + private float knockback = 1.5f; + + private SweepMode sweepMode = SweepMode.SWIPE; + private float sweepSpeed = 6.0f; + private int spinDurationTicks = 60; // Duration for SPIN mode + + private boolean piercing = true; + private float innerRadius = 0.0f; + + // 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 = LockMode.NO; + this.cooldownTicks = 0; + this.windUpTicks = 20; + this.telegraphType = TelegraphType.CONE; + this.windUpSound = "random.bow"; + 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 + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + 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; + } + + @Override + public float getTelegraphLength() { + return range; + } + + @Override + public float getTelegraphAngle() { + return arcAngle; + } + + @Override + public float getTelegraphInnerRadius() { + return innerRadius; + } + + @Override + 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, caster.worldObj, innerRadius, range, prevRotation, arcAngle / 2.0f); + } + signalCompletion(); + return; + } + if (!isPreview()) { + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevRotation, currentRotation); + } + break; + + case SPIN: + // Play active sound at spin start + if (!activeSoundPlayed) { + playActiveSound(caster, caster.worldObj); + } + + if (tick >= spinDurationTicks) { + signalCompletion(); + return; + } + float prevSpin = currentRotation; + currentRotation = (currentRotation + sweepSpeed) % 360.0f; + if (!isPreview()) { + hitEntities.clear(); + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevSpin, currentRotation); + } + break; + } + } + + private void playActiveSound(EntityLivingBase caster, World world) { + activeSoundPlayed = true; + if (activeSound != null && !activeSound.isEmpty()) { + world.playSoundAtEntity(caster, activeSound, 1.0f, 1.0f); + } + } + + /** + * Check for entities between two sweep angles, ensuring no gaps between ticks. + * For SWIPE mode, this covers the continuous arc from startAngle to endAngle. + */ + private void performSweepDamageRange(EntityLivingBase caster, World world, float minDist, float maxDist, + float startAngle, float endAngle) { + // Calculate the angular range covered this tick + float minAngle = Math.min(startAngle, endAngle); + float maxAngle = Math.max(startAngle, endAngle); + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + caster.posX - maxDist, caster.posY - 1, caster.posZ - maxDist, + caster.posX + maxDist, caster.posY + 3, caster.posZ + maxDist + ); + + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + + 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; + + double dx = entity.posX - caster.posX; + double dz = entity.posZ - caster.posZ; + double dist = Math.sqrt(dx * dx + dz * dz); + + if (dist < minDist || dist > maxDist) 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()); + + float distFactor = 1.0f - ((float) dist / maxDist) * 0.3f; + float actualDamage = damage * distFactor; + + // Apply damage with scripted event support + boolean wasHit = applyAbilityDamage(caster, entity, actualDamage, knockback); + + // Apply effects if hit wasn't cancelled + if (wasHit) { + applyEffects(entity); + } + } + } + + /** + * Check if an entity falls within the angular range between two sweep positions. + * This ensures entities at long range can't slip between tick-gaps. + */ + private boolean isInSweepRange(double dx, double dz, float casterYaw, float minAngle, float maxAngle) { + double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); + double entityRelative = normalizeAngle(angleToEntity - casterYaw); + return entityRelative >= minAngle && entityRelative <= maxAngle; + } + + private double normalizeAngle(double angle) { + while (angle > 180) angle -= 360; + while (angle < -180) angle += 360; + return angle; + } + + @Override + 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 + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("arcAngle", arcAngle); + nbt.setFloat("range", range); + nbt.setFloat("damage", damage); + nbt.setFloat("knockback", knockback); + nbt.setString("sweepMode", sweepMode.name()); + nbt.setFloat("sweepSpeed", sweepSpeed); + nbt.setInteger("spinDurationTicks", spinDurationTicks); + nbt.setBoolean("piercing", piercing); + nbt.setFloat("innerRadius", innerRadius); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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.getFloat("sweepSpeed"); + this.spinDurationTicks = nbt.getInteger("spinDurationTicks"); + this.piercing = nbt.getBoolean("piercing"); + this.innerRadius = nbt.getFloat("innerRadius"); + } + + // Getters & Setters + public float getArcAngle() { + return arcAngle; + } + + public void setArcAngle(float arcAngle) { + this.arcAngle = arcAngle; + } + + public float getRange() { + return range; + } + + public void setRange(float range) { + this.range = range; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + public SweepMode getSweepModeEnum() { + return sweepMode; + } + + public void setSweepModeEnum(SweepMode sweepMode) { + this.sweepMode = sweepMode; + } + + @Override + public int getSweepMode() { + return sweepMode.ordinal(); + } + + @Override + public void setSweepMode(int mode) { + SweepMode[] values = SweepMode.values(); + this.sweepMode = mode >= 0 && mode < values.length ? values[mode] : SweepMode.SWIPE; + } + + public float getSweepSpeed() { + return sweepSpeed; + } + + public void setSweepSpeed(float sweepSpeed) { + this.sweepSpeed = sweepSpeed; + } + + public int getSpinDurationTicks() { + return spinDurationTicks; + } + + public void setSpinDurationTicks(int spinDurationTicks) { + this.spinDurationTicks = Math.max(1, spinDurationTicks); + } + + public boolean isPiercing() { + return piercing; + } + + public void setPiercing(boolean piercing) { + this.piercing = piercing; + } + + public float getInnerRadius() { + return innerRadius; + } + + public void setInnerRadius(float innerRadius) { + this.innerRadius = innerRadius; + } + + public float getCurrentRotation() { + return currentRotation; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("gui.range", this::getRange, this::setRange) + ), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.section("ability.section.sweep"), + FieldDef.enumField("ability.sweepMode", SweepMode.class, this::getSweepModeEnum, this::setSweepModeEnum) + .hover("ability.hover.sweepMode"), + 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) + .range(1, 1000) + .visibleWhen(() -> this.getSweepModeEnum() == SweepMode.SPIN), + FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing) + .hover("ability.hover.piercing"), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } +} 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 new file mode 100644 index 000000000..88c520c21 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -0,0 +1,404 @@ +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.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.api.ability.type.IAbilityDash; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +/** + * Dash ability: Quick evasive sidestep with NO telegraph. + * Extends AbilityMovement for shared direction locking, stall detection, and velocity application. + */ +public class AbilityDash extends AbilityMovement implements IAbilityDash { + + /** + * Dash behavior mode. + */ + public enum DashMode { + AGGRESSIVE, + DEFENSIVE, + DIRECTIONAL; + + @Override + public String toString() { + switch (this) { + case AGGRESSIVE: + return "ability.dash.aggressive"; + case DEFENSIVE: + return "ability.dash.defensive"; + case DIRECTIONAL: + return "ability.dash.directional"; + default: + return name(); + } + } + } + + /** + * Specific dash direction. + */ + public enum DashDirection { + FORWARD(0), + DIAGONAL_FORWARD_LEFT(45), + DIAGONAL_FORWARD_RIGHT(-45), + LEFT(90), + RIGHT(-90), + DIAGONAL_BACK_LEFT(135), + DIAGONAL_BACK_RIGHT(-135), + BACK(180), + CUSTOM(0); + + private final float angleOffset; + + DashDirection(float angleOffset) { + this.angleOffset = angleOffset; + } + + 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(); + + private static final DashDirection[] AGGRESSIVE_DIRECTIONS = { + DashDirection.FORWARD, + DashDirection.DIAGONAL_FORWARD_LEFT, + DashDirection.DIAGONAL_FORWARD_RIGHT + }; + + private static final DashDirection[] DEFENSIVE_DIRECTIONS = { + DashDirection.LEFT, + DashDirection.RIGHT, + DashDirection.BACK, + DashDirection.DIAGONAL_BACK_LEFT, + DashDirection.DIAGONAL_BACK_RIGHT + }; + + // 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; + + // Type-specific runtime state + private transient DashDirection chosenDirection; + private transient double preDashMotionX; + private transient double preDashMotionZ; + + public AbilityDash() { + this.typeId = "ability.cnpc.dash"; + this.name = "Dash"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 20.0f; + this.minRange = 0.0f; + 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.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/dash.png") + }; + } + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + preDashMotionX = caster.motionX; + preDashMotionZ = caster.motionZ; + initMovement(caster, dashDistance, dashSpeed); + + 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 { + // 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); + } + + // Small upward impulse for a skip/hop arc (gravity handles the descent) + caster.motionY = 0.2; + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (checkTimeout(tick)) { + finishDash(caster); + signalCompletion(); + return; + } + + if (movementDirection == null) { + finishDash(caster); + signalCompletion(); + return; + } + + if (checkStall(caster, tick)) { + finishDash(caster); + signalCompletion(); + return; + } + updatePrevPosition(caster); + + if (getDistanceTraveledSq(caster) >= (double) dashDistance * dashDistance) { + finishDash(caster); + signalCompletion(); + return; + } + + if (checkBlocked(caster, dashSpeed)) { + finishDash(caster); + signalCompletion(); + return; + } + + // 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()) { + // Trail particles + caster.worldObj.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + finishDash(caster); + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + finishDash(caster); + } + + @Override + public void cleanup() { + super.cleanup(); + chosenDirection = null; + preDashMotionX = 0; + preDashMotionZ = 0; + } + + @Override + public void resetForBurst() { + super.resetForBurst(); + chosenDirection = null; + preDashMotionX = 0; + preDashMotionZ = 0; + } + + @Override + public int getMaxPreviewDuration() { + return (int) Math.ceil(dashDistance / dashSpeed) + 5; + } + + @Override + public float getTelegraphRadius() { + return 0; // No telegraph for dash + } + + @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 + public void readTypeNBT(NBTTagCompound nbt) { + try { + this.dashMode = DashMode.valueOf(nbt.getString("dashMode")); + } 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") ? Math.max(0.01f, nbt.getFloat("dashSpeed")) : 0.5f; + this.dashAngle = nbt.hasKey("dashAngle") ? nbt.getFloat("dashAngle") : 0.0f; + } + + // Getters & Setters + public DashMode getDashModeEnum() { + return dashMode; + } + + public void setDashModeEnum(DashMode dashMode) { + this.dashMode = dashMode; + } + + @Override + public int getDashMode() { + return dashMode.ordinal(); + } + + @Override + public void setDashMode(int mode) { + DashMode[] values = DashMode.values(); + this.dashMode = mode >= 0 && mode < values.length ? values[mode] : DashMode.AGGRESSIVE; + } + + public float getDashDistance() { + return dashDistance; + } + + public void setDashDistance(float dashDistance) { + this.dashDistance = dashDistance; + } + + public float getDashSpeed() { + return dashSpeed; + } + + public void setDashSpeed(float dashSpeed) { + 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) { + defs.addAll(Arrays.asList( + FieldDef.enumField("ability.dashMode", DashMode.class, this::getDashModeEnum, this::setDashModeEnum) + .hover("ability.hover.dashMode"), + 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..ac51ca92f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java @@ -0,0 +1,335 @@ +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.api.ability.type.IAbilityDefend; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.controllers.data.Animation; + +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; + } + + @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; + } + } + + // Always calculate the correct reduction for the caller's damage amount + return performDefend(attacker, amount); + } + + /** + * 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/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 new file mode 100644 index 000000000..62d0dc1e1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java @@ -0,0 +1,90 @@ +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.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.List; + +/** + * Guard ability: Defensive stance that reduces incoming damage. + */ +public class AbilityGuard extends AbilityDefend implements IAbilityGuard { + + private float damageReduction = 0.5f; + + public AbilityGuard() { + this.typeId = "ability.cnpc.guard"; + this.name = "Guard"; + this.cooldownTicks = 0; + this.allowedBy = UserType.BOTH; + + this.activeAnimationName = "Ability_Guard_Active"; + 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 + protected boolean isValidDamageSource(DamageSource source) { + return true; + } + + @Override + protected float performDefend(EntityLivingBase attacker, float amount) { + return Math.max(0, amount * (1.0f - damageReduction)); + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void writeSubTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("damageReduction", damageReduction); + } + + @Override + protected void readSubTypeNBT(NBTTagCompound nbt) { + this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f; + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + 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); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + @Override + public float getDamageReduction() { + return damageReduction; + } + + @Override + public void setDamageReduction(float damageReduction) { + this.damageReduction = damageReduction; + } +} 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 new file mode 100644 index 000000000..47f9156a8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -0,0 +1,182 @@ +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.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.List; + +public class AbilityHazard extends AbilityZone implements IAbilityHazard { + + private float radius = 2.0f; + private float damagePerSecond = 1.0f; + private int damageInterval = 20; + private boolean affectsCaster = false; + + public AbilityHazard() { + super(300, new EnergyDisplayData(0x00CC00, 0x006600, true, 1.0f, 0.5f, 1.5f)); + this.typeId = "ability.cnpc.hazard"; + this.name = "Hazard"; + this.windUpTicks = 30; + 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 isConcurrentCapable() { + return true; + } + + @Override + public float getZoneRadius() { + return radius; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + activeEntities.clear(); + + 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); + } + } + + for (int i = 0; i < zoneCount; i++) { + double[] pos = positions.get(i); + + 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); + + applyVisualToEntity(entity); + + if (isPreview()) { + entity.setupPreview(caster); + } + + spawnAbilityEntity(entity); + activeEntities.add(entity); + } + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + writeZoneNBT(nbt); + nbt.setFloat("radius", radius); + nbt.setFloat("damagePerSecond", damagePerSecond); + nbt.setInteger("damageInterval", damageInterval); + nbt.setBoolean("affectsCaster", affectsCaster); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + readZoneNBT(nbt, 300); + this.radius = nbt.getFloat("radius"); + this.damagePerSecond = nbt.getFloat("damagePerSecond"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.affectsCaster = nbt.getBoolean("affectsCaster"); + } + + public float getRadius() { + return radius; + } + + public void setRadius(float radius) { + this.radius = radius; + } + + public float getDamagePerSecond() { + return damagePerSecond; + } + + public void setDamagePerSecond(float damagePerSecond) { + 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 isAffectsCaster() { + return affectsCaster; + } + + public void setAffectsCaster(boolean affectsCaster) { + this.affectsCaster = affectsCaster; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + addPresetFieldDef(defs); + + defs.addAll(Arrays.asList( + FieldDef.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.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("gui.dps", this::getDamagePerSecond, this::setDamagePerSecond), + FieldDef.intField("gui.interval", this::getDamageInterval, this::setDamageInterval) + ), + 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/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java new file mode 100644 index 000000000..56458b1ab --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -0,0 +1,241 @@ +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.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 noppes.npcs.api.ability.type.IAbilityHeavyHit; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Heavy Hit ability: AOE rectangle melee attack in front of the caster. + * Deals high damage to all entities within a rectangular zone and can apply effects. + * Has a LINE telegraph showing the hit area during windup, making it dodgeable. + */ +public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { + + private float damage = 8.0f; + 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"; + this.name = "Heavy Hit"; + this.targetingMode = TargetingMode.AOE_SELF; + this.maxRange = 5.0f; + this.minRange = 0.0f; + this.lockMovement = LockMode.WINDUP; + this.cooldownTicks = 0; + this.windUpTicks = 30; + this.telegraphType = TelegraphType.LINE; + this.showTelegraph = true; + this.windUpSound = "random.anvil_use"; + 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 + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AOE_SELF}; + } + + @Override + public float getTelegraphLength() { + return hitLength; + } + + @Override + public float getTelegraphWidth() { + return hitWidth * 2.0f; // Total width (hitWidth is distance to each side) + } + + @Override + 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 (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); + double forwardZ = Math.cos(yawRad); + double rightX = forwardZ; // perpendicular right + double rightZ = -forwardX; + + // Search area: AABB that encompasses the rectangle + float searchDist = Math.max(hitLength, hitWidth) + 1.0f; + @SuppressWarnings("unchecked") + List entities = 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; + + // Project onto forward direction (must be in front, within hitLength) + double forwardDist = dx * forwardX + dz * forwardZ; + if (forwardDist < 0 || forwardDist > hitLength) continue; + + // Project onto right direction (must be within hitWidth to each side) + double sideDist = dx * rightX + dz * rightZ; + if (Math.abs(sideDist) > hitWidth) continue; + + // 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) { + applyEffects(livingTarget); + anyHit = true; + } + } + + // Play hit sound even if nothing was hit (the attack still happens) + if (!anyHit) { + caster.worldObj.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + } + } + } + + @Override + public void 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.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 + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + public float getHitLength() { + return hitLength; + } + + public void setHitLength(float hitLength) { + this.hitLength = hitLength; + } + + public float getHitWidth() { + return hitWidth; + } + + public void setHitWidth(float hitWidth) { + 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) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + ), + FieldDef.section("ability.section.hitZone"), + FieldDef.row( + 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/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/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java new file mode 100644 index 000000000..104209eeb --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -0,0 +1,374 @@ +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.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.api.ability.type.IAbilityProjectile; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Projectile ability: Ranged attack that deals damage to target. + * Currently instant damage - can be enhanced with custom projectile entities. + */ +public class AbilityProjectile extends Ability implements IAbilityProjectile { + + // Type-specific parameters + private float damage = 6.0f; + private float speed = 1.5f; + private float knockback = 0.5f; + private String projectileType = "fireball"; + private boolean explosive = false; + private float explosionRadius = 0.0f; + private boolean homing = false; + private float homingStrength = 0.1f; + + public AbilityProjectile() { + this.typeId = "ability.cnpc.projectile"; + this.name = "Projectile"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.minRange = 5.0f; + this.maxRange = 20.0f; + this.cooldownTicks = 0; + this.windUpTicks = 15; + this.lockMovement = LockMode.NO; + // No telegraph for projectile - it's a ranged attack + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + } + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (isPlayerCaster(caster)) { + // Player: instant hit-scan in look direction + executePlayerProjectile(caster, caster.worldObj); + } else if (target != null) { + // NPC: instant hit-scan on aggro target + executeNpcProjectile(caster, target, caster.worldObj); + } + + signalCompletion(); + } + + /** + * NPC projectile: instant hit-scan damage on the aggro target. + */ + private void executeNpcProjectile(EntityLivingBase caster, EntityLivingBase target, World world) { + if (isPreview()) return; + + double dx = target.posX - caster.posX; + double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); + double dz = target.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + dx /= len; + dy /= len; + dz /= len; + } + + applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); + + if (explosive && explosionRadius > 0) { + applyExplosionDamage(caster, target, world, target.posX, target.posY, target.posZ); + } + + spawnProjectileParticles(world, caster, target); + } + + /** + * Player projectile: fires instant hit-scan in look direction. + * Raycasts for the first entity in range and applies damage. + */ + private void executePlayerProjectile(EntityLivingBase caster, World world) { + if (isPreview()) return; + + Vec3 look = caster.getLookVec(); + double eyeX = caster.posX; + double eyeY = caster.posY + caster.getEyeHeight(); + double eyeZ = caster.posZ; + + // Raycast: find the closest entity along look direction + EntityLivingBase hitTarget = null; + double closestDist = maxRange; + + @SuppressWarnings("unchecked") + List candidates = world.getEntitiesWithinAABBExcludingEntity(caster, + caster.boundingBox.expand(maxRange, maxRange, maxRange)); + + for (Entity entity : candidates) { + if (!(entity instanceof EntityLivingBase)) continue; + if (entity.isDead) continue; + + // Check if entity is roughly along look direction + double dx = entity.posX - eyeX; + double dy = (entity.posY + entity.height / 2) - eyeY; + double dz = entity.posZ - eyeZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (dist > maxRange || dist < 0.5) continue; + + // Dot product to check alignment with look vector + double dot = (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) / dist; + if (dot < 0.95) continue; // Must be within ~18 degree cone + + if (dist < closestDist) { + closestDist = dist; + hitTarget = (EntityLivingBase) entity; + } + } + + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); + + if (hitTarget != null) { + applyAbilityDamageWithDirection(caster, hitTarget, damage, knockback, look.xCoord, look.zCoord); + + if (explosive && explosionRadius > 0) { + applyExplosionDamage(caster, hitTarget, world, hitTarget.posX, hitTarget.posY, hitTarget.posZ); + } + + spawnProjectileParticles(world, caster, hitTarget); + } else { + // No hit — spawn particles along look direction anyway + spawnProjectileParticlesInDirection(world, caster, look); + } + } + + /** + * Apply explosion splash damage around a point. + */ + private void applyExplosionDamage(EntityLivingBase caster, EntityLivingBase primaryTarget, World world, + double x, double y, double z) { + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity(primaryTarget, + primaryTarget.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + + for (Entity entity : entities) { + if (entity instanceof EntityLivingBase && entity != caster) { + EntityLivingBase living = (EntityLivingBase) entity; + float dist = primaryTarget.getDistanceToEntity(living); + if (dist < explosionRadius) { + float falloff = 1.0f - (dist / explosionRadius); + applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); + } + } + } + + world.playSoundAtEntity(primaryTarget, "random.explode", 0.5f, 1.0f); + for (int i = 0; i < 10; i++) { + world.spawnParticle("explode", + x + (world.rand.nextDouble() - 0.5) * explosionRadius, + y + world.rand.nextDouble() * 2, + z + (world.rand.nextDouble() - 0.5) * explosionRadius, + 0, 0.1, 0); + } + } + + private void spawnProjectileParticles(World world, EntityLivingBase caster, EntityLivingBase target) { + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + double endX = target.posX; + double endY = target.posY + target.height / 2; + double endZ = target.posZ; + + double dx = endX - startX; + double dy = endY - startY; + double dz = endZ - startZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + String particle = "flame"; + if (projectileType.equals("arrow")) { + particle = "crit"; + } else if (projectileType.equals("magic")) { + particle = "witchMagic"; + } + + // Spawn particles along path + int steps = (int) Math.max(5, dist * 2); + for (int i = 0; i < steps; i++) { + double progress = (double) i / steps; + double px = startX + dx * progress; + double py = startY + dy * progress; + double pz = startZ + dz * progress; + world.spawnParticle(particle, px, py, pz, 0, 0, 0); + } + } + + /** + * Spawn projectile particles along a direction (player miss — no entity hit). + */ + private void spawnProjectileParticlesInDirection(World world, EntityLivingBase caster, Vec3 look) { + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + + String particle = "flame"; + if (projectileType.equals("arrow")) { + particle = "crit"; + } else if (projectileType.equals("magic")) { + particle = "witchMagic"; + } + + int steps = (int) Math.max(5, maxRange * 2); + for (int i = 0; i < steps; i++) { + double progress = (double) i / steps * maxRange; + double px = startX + look.xCoord * progress; + double py = startY + look.yCoord * progress; + double pz = startZ + look.zCoord * progress; + world.spawnParticle(particle, px, py, pz, 0, 0, 0); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + // Projectile is instant, nothing to do per-tick + } + + @Override + public float getTelegraphRadius() { + return 0; // No telegraph for projectile + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("damage", damage); + nbt.setFloat("speed", speed); + nbt.setFloat("knockback", knockback); + nbt.setString("projectileType", projectileType); + nbt.setBoolean("explosive", explosive); + nbt.setFloat("explosionRadius", explosionRadius); + nbt.setBoolean("homing", homing); + nbt.setFloat("homingStrength", homingStrength); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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 + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getSpeed() { + return speed; + } + + public void setSpeed(float speed) { + this.speed = speed; + } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + public String getProjectileType() { + return projectileType; + } + + public void setProjectileType(String projectileType) { + this.projectileType = projectileType; + } + + public boolean isExplosive() { + return explosive; + } + + public void setExplosive(boolean explosive) { + this.explosive = explosive; + } + + public float getExplosionRadius() { + return explosionRadius; + } + + public void setExplosionRadius(float explosionRadius) { + this.explosionRadius = explosionRadius; + } + + public boolean isHoming() { + return homing; + } + + public void setHoming(boolean homing) { + this.homing = homing; + } + + public float getHomingStrength() { + return homingStrength; + } + + public void setHomingStrength(float homingStrength) { + this.homingStrength = homingStrength; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + ), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.stringEnumField("ability.projectileType", new String[]{"fireball", "arrow", "magic"}, this::getProjectileType, this::setProjectileType), + FieldDef.section("ability.section.homing"), + FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), + FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), + FieldDef.section("ability.section.explosive"), + FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), + FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } +} 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 new file mode 100644 index 000000000..c5e860c09 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -0,0 +1,236 @@ +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.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 noppes.npcs.api.ability.type.IAbilityShockwave; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Shockwave ability: Pushes targets away from the caster with damage. + * Opposite of Vortex - instant knockback rather than gradual pull. + */ +public class AbilityShockwave extends Ability implements IAbilityShockwave { + + private float pushRadius = 8.0f; + private float pushStrength = 1.5f; + private float damage = 8.0f; + 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 = 8.0f; + this.lockMovement = LockMode.WINDUP_AND_ACTIVE; + this.cooldownTicks = 0; + this.windUpTicks = 25; + this.telegraphType = TelegraphType.CIRCLE; + this.windUpSound = "game.tnt.primed"; + 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 + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AOE_SELF}; + } + + @Override + public float getTelegraphRadius() { + return pushRadius; + } + + @Override + 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 = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); + + 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; + + 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; + } + } + + // 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; + + 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, int tick) { + if (tick >= activeDisplayTicks) + signalCompletion(); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("pushRadius", pushRadius); + nbt.setFloat("pushStrength", pushStrength); + nbt.setFloat("damage", damage); + nbt.setBoolean("aoe", aoe); + nbt.setInteger("activeDisplayTicks", activeDisplayTicks); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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 + public float getPushRadius() { + return pushRadius; + } + + public void setPushRadius(float pushRadius) { + this.pushRadius = pushRadius; + } + + public float getPushStrength() { + return pushStrength; + } + + public void setPushStrength(float pushStrength) { + this.pushStrength = pushStrength; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public boolean isAoe() { + return aoe; + } + + public void setAoe(boolean aoe) { + this.aoe = aoe; + } + + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.section("ability.section.push"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getPushRadius, this::setPushRadius), + FieldDef.floatField("gui.strength", this::getPushStrength, this::setPushStrength) + ), + 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 new file mode 100644 index 000000000..9e917d2d2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -0,0 +1,827 @@ +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.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 java.util.Arrays; +import java.util.List; + +/** + * Slam ability: NPC leaps toward target in an arc and slams down, dealing AOE damage on landing. + *

+ * Phases: + * - WINDUP: NPC prepares to leap, telegraph shows landing zone + * - ACTIVE: NPC is in the air, traveling in arc toward destination + * - Landing: When NPC hits ground, deal AOE damage + * - RECOVERY: Landing recovery animation + */ +public class AbilitySlam extends Ability implements IAbilitySlam { + + // Type-specific config + private float damage = 10.0f; + private float radius = 5.0f; + private float knockbackStrength = 1.5f; + 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"; + this.name = "Slam"; + this.targetingMode = TargetingMode.AOE_SELF; // Can also be AOE_TARGET to leap to target + this.windUpTicks = 30; + this.cooldownTicks = 0; + this.lockMovement = LockMode.WINDUP; + this.minRange = 2.0f; + this.maxRange = 15.0f; + this.telegraphType = TelegraphType.CIRCLE; + this.windUpSound = "mob.irongolem.throw"; + this.activeSound = ""; + // 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") + }; + } + + /** + * Slam can be AOE_SELF (jump in place) or AOE_TARGET (leap to target). + */ + @Override + public boolean isTargetingModeLocked() { + return false; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AOE_SELF, TargetingMode.AOE_TARGET}; + } + + @Override + public boolean hasAbilityMovement() { + return true; // This ability moves the NPC + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (isPlayerCaster(caster)) { + // Player: update target along look direction during windup + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else { + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); + double launchDist = Math.max(4.0, maxRange * 0.5); + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + } + } else { + // NPC: update target position during windup for telegraph tracking + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { + targetX = target.posX; + targetY = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ, 64); + targetZ = target.posZ; + } + } + } + + @Override + 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)) { + executePlayerSlam(caster); + } else { + executeNpcSlam(caster, target); + } + } + + /** + * NPC slam: Lock destination based on targeting mode, then launch in a ballistic arc toward it. + */ + private void executeNpcSlam(EntityLivingBase caster, EntityLivingBase target) { + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { + targetX = target.posX; + targetY = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ, 64); + targetZ = target.posZ; + } else { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } + launchTowardTarget(caster); + } + + /** + * 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) { + // Determine if this qualifies as an air slam (at least 3 blocks above ground) + boolean isAirborne = !caster.onGround; + boolean highEnoughForAirSlam = false; + + 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); + } + } + + /** + * Calculate the initial vertical velocity needed to reach a target height + * in Minecraft's physics (gravity=0.08, vertical drag=0.98). + * Uses iterative simulation since the drag makes a closed-form solution impractical. + */ + private static double calculateLaunchVelocity(double targetHeight) { + // Binary search for the initial velocity that reaches targetHeight + double lo = 0.0, hi = 10.0; + for (int iter = 0; iter < 30; iter++) { + double mid = (lo + hi) / 2.0; + double maxY = simulateMaxHeight(mid); + if (maxY < targetHeight) { + lo = mid; + } else { + hi = mid; + } + } + return (lo + hi) / 2.0; + } + + /** + * Simulate Minecraft vertical physics to find peak height reached + * with a given initial upward velocity. + */ + private static double simulateMaxHeight(double vy) { + double y = 0; + double maxY = 0; + for (int t = 0; t < 200 && vy > 0; t++) { + y += vy; + vy -= 0.08; // gravity + vy *= 0.98; // vertical drag + if (y > maxY) maxY = y; + } + return maxY; + } + + /** + * Calculate ballistic arc and launch caster toward target. + * leapHeight = exact peak height in blocks above launch point. + * leapSpeed = velocity multiplier (faster motion, same height). + */ + private void launchTowardTarget(EntityLivingBase caster) { + double dx = targetX - caster.posX; + double dy = targetY - caster.posY; + double dz = targetZ - caster.posZ; + double horizontalDist = Math.sqrt(dx * dx + dz * dz); + + // Calculate vertical velocity to reach exact leapHeight + double arcHeight = Math.max(1.0, leapHeight); + double vy = calculateLaunchVelocity(arcHeight); + + // For AOE_SELF or very close targets, just hop in place + if (horizontalDist < 0.5) { + caster.motionX = 0; + caster.motionZ = 0; + caster.motionY = vy; + hasLaunched = true; + if (!isPreview() && caster instanceof EntityNPCInterface) { + ((EntityNPCInterface) caster).setNpcJumpingState(true); + } + 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); + } + return; + } + + // Cap the distance if too far + if (horizontalDist > maxRange) { + double scale = maxRange / horizontalDist; + dx *= scale; + dz *= scale; + horizontalDist = maxRange; + targetX = caster.posX + dx; + targetZ = caster.posZ + dz; + } + + // Choose flight time based on distance, scaled by speed (faster = fewer ticks) + double speedFactor = Math.max(0.1, leapSpeed); + int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40)); + + // Minecraft applies drag of 0.91 per tick to horizontal motion in air + // Total distance traveled with initial velocity v0 over n ticks: + // distance = v0 * (1 - drag^n) / (1 - drag) + // Solving for v0: v0 = distance * (1 - drag) / (1 - drag^n) + double drag = 0.91; + double dragPowN = Math.pow(drag, flightTicks); + double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN); + + // Adjust vertical velocity for height difference between start and target + if (dy > 0) { + vy += dy / flightTicks * 1.5; // Going up - need more velocity + } else if (dy < 0) { + vy += dy / flightTicks * 0.3; // Going down - gravity helps + } + + // Normalize horizontal direction and apply velocity + double dirX = dx / horizontalDist; + double dirZ = dz / horizontalDist; + + caster.motionX = dirX * vHorizontal; + caster.motionZ = dirZ * vHorizontal; + caster.motionY = vy; + + hasLaunched = true; + if (!isPreview() && caster instanceof EntityNPCInterface) { + ((EntityNPCInterface) caster).setNpcJumpingState(true); + } + if (!isPreview()) { + // 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 + float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); + caster.rotationYaw = targetYaw; + caster.rotationYawHead = targetYaw; + } + + @Override + 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 + if (!isPreview()) { + caster.fallDistance = 0; + } + + // 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, caster.worldObj); + return; + } + + // 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; + } + } + } + } + } + + /** + * Called when caster lands - deal AOE damage and signal completion. + */ + private void onLanding(EntityLivingBase caster, World world) { + hasLanded = true; + if (!isPreview() && caster instanceof EntityNPCInterface) { + ((EntityNPCInterface) caster).setNpcJumpingState(false); + } + restoreFlightIfNeeded(caster); + + // 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 + caster.fallDistance = 0; + caster.velocityChanged = true; + } + + if (world.isRemote && !isPreview()) return; + if (isPreview()) return; + + // Play slam impact sound on landing + world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f); + + // 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( + caster, caster.boundingBox.expand(radius, radius / 2, radius)); + + 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 + 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(); + } + + /** + * Spawn visual particles for the slam effect. + */ + private void spawnSlamParticles(World world, double x, double y, double z) { + // Spawn explosion particles in a ring + for (int i = 0; i < 20; i++) { + double angle = (i / 20.0) * Math.PI * 2; + double px = x + Math.cos(angle) * radius * 0.8; + double pz = z + Math.sin(angle) * radius * 0.8; + world.spawnParticle("explode", px, y + 0.5, pz, 0, 0.1, 0); + } + + // Spawn smoke at center + for (int i = 0; i < 10; i++) { + world.spawnParticle("smoke", x, y + 0.2, z, + (world.rand.nextDouble() - 0.5) * 0.3, + world.rand.nextDouble() * 0.2, + (world.rand.nextDouble() - 0.5) * 0.3); + } + + // Ground crack particles - check if block is valid + net.minecraft.block.Block groundBlock = world.getBlock((int) x, (int) y - 1, (int) z); + if (groundBlock != null && groundBlock.getMaterial().isSolid()) { + int blockId = net.minecraft.block.Block.getIdFromBlock(groundBlock); + if (blockId > 0) { + for (int i = 0; i < 15; i++) { + double angle = world.rand.nextDouble() * Math.PI * 2; + double dist = world.rand.nextDouble() * radius * 0.6; + double px = x + Math.cos(angle) * dist; + double pz = z + Math.sin(angle) * dist; + world.spawnParticle("blockcrack_" + blockId + "_0", px, y + 0.1, pz, 0, 0.2, 0); + } + } + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + 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 onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + 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 + public void reset() { + 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 + public int getMaxPreviewDuration() { + return 60; + } + + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + // Check if telegraph should be shown + if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) { + return null; + } + + // Telegraph shows at landing zone + if (targetingMode == TargetingMode.AOE_SELF) { + // AOE_SELF: telegraph at caster position, does NOT follow + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else if (targetingMode == TargetingMode.AOE_TARGET && target != null) { + // AOE_TARGET: telegraph at target position, follows target during windup + targetX = target.posX; + targetY = target.posY; + targetZ = target.posZ; + } else { + // Fallback to caster position + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } + + // 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); + telegraph.setColor(windUpColor); + 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()); + + // NPC AOE_TARGET: telegraph follows target during windup + // Player: telegraph stays at caster position (no target to follow) + if (!isPlayerCaster(caster) && targetingMode == TargetingMode.AOE_TARGET && target != null) { + instance.setEntityIdToFollow(target.getEntityId()); + } + + return instance; + } + + @Override + public float getTelegraphRadius() { + return radius; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("damage", damage); + nbt.setFloat("radius", radius); + nbt.setFloat("knockback", knockbackStrength); + nbt.setFloat("leapSpeed", leapSpeed); + nbt.setFloat("leapHeight", leapHeight); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + damage = nbt.getFloat("damage"); + radius = nbt.getFloat("radius"); + knockbackStrength = nbt.getFloat("knockback"); + leapSpeed = nbt.getFloat("leapSpeed"); + leapHeight = nbt.getFloat("leapHeight"); + } + + // Getters & Setters + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getRadius() { + return radius; + } + + public void setRadius(float radius) { + this.radius = radius; + } + + public float getKnockbackStrength() { + return knockbackStrength; + } + + public void setKnockbackStrength(float knockbackStrength) { + this.knockbackStrength = knockbackStrength; + } + + public float getLeapSpeed() { + return leapSpeed; + } + + public void setLeapSpeed(float leapSpeed) { + this.leapSpeed = leapSpeed; + } + + public float getLeapHeight() { + return leapHeight; + } + + public void setLeapHeight(float leapHeight) { + this.leapHeight = leapHeight; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), + FieldDef.floatField("ability.knockback", this::getKnockbackStrength, this::setKnockbackStrength) + ), + FieldDef.section("ability.section.leap"), + FieldDef.row( + FieldDef.floatField("gui.speed", this::getLeapSpeed, this::setLeapSpeed), + FieldDef.floatField("gui.height", this::getLeapHeight, this::setLeapHeight) + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } +} 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 new file mode 100644 index 000000000..d22150c9e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -0,0 +1,588 @@ +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.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; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import noppes.npcs.api.ability.type.IAbilityTeleport; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +/** + * Teleport ability: Instant reposition with wall/line-of-sight checks. + */ +public class AbilityTeleport extends Ability implements IAbilityTeleport { + + /** + * Teleport behavior mode. + */ + public enum TeleportMode { + BLINK, + BEHIND, + SINGLE; + + @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(); + } + } + } + + private static final Random RANDOM = new Random(); + + // Type-specific parameters + private TeleportMode mode = TeleportMode.BLINK; + private int blinkCount = 3; + private int blinkDelayTicks = 10; + private float blinkRadius = 8.0f; + private float behindDistance = 2.0f; + private boolean requireLineOfSight = true; + private boolean damageAtStart = false; + private boolean damageAtEnd = false; + private float damage = 5.0f; + private float damageRadius = 2.0f; + + // Runtime state + private transient int currentBlink = 0; + private transient int ticksSinceLastBlink = 0; + + public AbilityTeleport() { + this.typeId = "ability.cnpc.teleport"; + this.name = "Teleport"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.allowedBy = UserType.NPC_ONLY; + this.maxRange = 30.0f; + this.minRange = 5.0f; + this.cooldownTicks = 0; + this.windUpTicks = 10; + 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"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/teleport.png") + }; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + currentBlink = 0; + ticksSinceLastBlink = blinkDelayTicks; // Trigger first blink immediately + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; + if (currentBlink >= blinkLimit) { + signalCompletion(); + return; + } + + ticksSinceLastBlink++; + + if (ticksSinceLastBlink >= blinkDelayTicks) { + performBlink(caster, target, caster.worldObj); + currentBlink++; + ticksSinceLastBlink = 0; + + // Check if this was the last blink + if (currentBlink >= blinkLimit) { + signalCompletion(); + } + } + } + + private void performBlink(EntityLivingBase caster, EntityLivingBase target, World world) { + if (world.isRemote && !isPreview()) return; + + double oldX = caster.posX; + double oldY = caster.posY; + double oldZ = caster.posZ; + + Vec3 destination = calculateDestination(caster, target, world); + if (destination == null) return; + + if (!isPreview()) { + boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; + if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, + destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { + destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + destination.xCoord, destination.yCoord, destination.zCoord); + if (destination == null) return; + } + + destination = findSafeDestination(world, oldX, oldY, oldZ, + destination.xCoord, destination.yCoord, destination.zCoord); + if (destination == null) return; + + // Damage at origin + if (damageAtStart) { + dealDamageAt(caster, world, oldX, oldY, oldZ); + } + + // Spawn particles at origin + spawnTeleportParticles(world, oldX, oldY, oldZ); + } + + // Teleport + if (isPreview()) { + caster.setPosition(destination.xCoord, destination.yCoord, destination.zCoord); + caster.prevPosX = destination.xCoord; + caster.prevPosY = destination.yCoord; + caster.prevPosZ = destination.zCoord; + } else { + caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + } + caster.fallDistance = 0; + + if (!isPreview()) { + // Spawn particles at destination + spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); + + // Damage at destination + if (damageAtEnd) { + dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + } + } + + // Face target after teleport + if (target != null) { + double dx = target.posX - destination.xCoord; + double dz = target.posZ - destination.zCoord; + float newYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + caster.rotationYaw = newYaw; + caster.rotationYawHead = newYaw; + } + } + + private void spawnTeleportParticles(World world, double x, double y, double z) { + for (int i = 0; i < 20; i++) { + world.spawnParticle("portal", + x + (RANDOM.nextDouble() - 0.5) * 2, + y + RANDOM.nextDouble() * 2, + z + (RANDOM.nextDouble() - 0.5) * 2, + (RANDOM.nextDouble() - 0.5) * 0.5, + RANDOM.nextDouble() * 0.5, + (RANDOM.nextDouble() - 0.5) * 0.5); + } + } + + private Vec3 calculateDestination(EntityLivingBase caster, EntityLivingBase target, World world) { + double newX; + double newY; + double newZ; + + if (target != null) { + switch (mode) { + case BEHIND: + double yaw = Math.toRadians(target.rotationYaw); + newX = target.posX + Math.sin(yaw) * behindDistance; + newZ = target.posZ - Math.cos(yaw) * behindDistance; + newY = target.posY; + return Vec3.createVectorHelper(newX, newY, newZ); + case SINGLE: + case BLINK: + default: + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = Math.min(blinkRadius, maxRange); + double offset = RANDOM.nextDouble() * dist; + newX = target.posX + Math.cos(angle) * offset; + newZ = target.posZ + Math.sin(angle) * offset; + newY = target.posY; + return Vec3.createVectorHelper(newX, newY, newZ); + } + } + + // NPC-only ability — should not reach here + return null; + } + + private Vec3 findSafeDestination(World world, double oldX, double oldY, double oldZ, + double destX, double destY, double destZ) { + int oldBlockX = (int) Math.floor(oldX); + int oldBlockY = (int) Math.floor(oldY); + int oldBlockZ = (int) Math.floor(oldZ); + int destBlockX = (int) Math.floor(destX); + int destBlockY = (int) Math.floor(destY); + int destBlockZ = (int) Math.floor(destZ); + + if (oldBlockX == destBlockX && oldBlockY == destBlockY && oldBlockZ == destBlockZ) { + return null; + } + + double safeY = findSafeYNear(world, destX, destY, destZ); + Vec3 safe = Vec3.createVectorHelper(destX, safeY, destZ); + + if (!isSafeLocation(world, (int) Math.floor(safe.xCoord), + (int) Math.floor(safe.yCoord), (int) Math.floor(safe.zCoord))) { + return null; + } + + return safe; + } + + private double findSafeYNear(World world, double x, double baseY, double z) { + int[] offsets = new int[]{0, 1, -1, 2, -2}; + for (int offset : offsets) { + double y = baseY + offset; + if (isSafeLocation(world, (int) Math.floor(x), (int) Math.floor(y), (int) Math.floor(z))) { + return y; + } + } + return findSafeY(world, x, baseY, z); + } + + private boolean hasLineOfSight(World world, double x1, double y1, double z1, + double x2, double y2, double z2) { + double dx = x2 - x1; + double dy = y2 - y1; + double dz = z2 - z1; + double distance = Math.sqrt(dx * dx + dy * dy + dz * dz); + + if (distance < 0.1) return true; + + dx /= distance; + dy /= distance; + dz /= distance; + + double step = 0.5; + for (double d = step; d < distance; d += step) { + double checkX = x1 + dx * d; + double checkY = y1 + dy * d; + double checkZ = z1 + dz * d; + + int blockX = MathHelper.floor_double(checkX); + int blockY = MathHelper.floor_double(checkY); + int blockZ = MathHelper.floor_double(checkZ); + + // Skip out-of-world coordinates + if (blockY < 0 || blockY >= 256) { + continue; + } + + Block block = world.getBlock(blockX, blockY, blockZ); + if (block != null && block.getMaterial().isSolid() && block.isOpaqueCube()) { + return false; + } + } + + return true; + } + + private Vec3 findValidPositionAlongLine(World world, EntityLivingBase caster, + double x1, double y1, double z1, + double x2, double y2, double z2) { + double dx = x2 - x1; + double dy = y2 - y1; + double dz = z2 - z1; + double distance = Math.sqrt(dx * dx + dy * dy + dz * dz); + + if (distance < 1.0) return null; + + dx /= distance; + dy /= distance; + dz /= distance; + + Vec3 lastValid = null; + double step = 0.5; + + for (double d = 1.0; d < distance; d += step) { + double checkX = x1 + dx * d; + double checkY = y1 + dy * d; + double checkZ = z1 + dz * d; + + if (hasLineOfSight(world, x1, y1 + caster.getEyeHeight(), z1, + checkX, checkY + caster.getEyeHeight(), checkZ)) { + int blockX = MathHelper.floor_double(checkX); + int blockY = MathHelper.floor_double(checkY); + int blockZ = MathHelper.floor_double(checkZ); + + if (isSafeLocation(world, blockX, blockY, blockZ)) { + lastValid = Vec3.createVectorHelper(checkX, checkY, checkZ); + } + } else { + break; + } + } + + return lastValid; + } + + private double findSafeY(World world, double x, double baseY, double z) { + int blockX = MathHelper.floor_double(x); + int blockZ = MathHelper.floor_double(z); + int blockY = MathHelper.floor_double(baseY); + + for (int offset = 0; offset <= 5; offset++) { + if (isSafeLocation(world, blockX, blockY + offset, blockZ)) { + return blockY + offset; + } + if (offset > 0 && isSafeLocation(world, blockX, blockY - offset, blockZ)) { + return blockY - offset; + } + } + + return baseY; + } + + private boolean isSafeLocation(World world, int x, int y, int z) { + // Bounds check - ensure we're within valid world coordinates + if (y < 1 || y >= 255) { + return false; + } + + Block groundBlock = world.getBlock(x, y - 1, z); + Block feetBlock = world.getBlock(x, y, z); + Block headBlock = world.getBlock(x, y + 1, z); + + // Defensive null checks (shouldn't happen in MC 1.7.10, but safe) + if (groundBlock == null || feetBlock == null || headBlock == null) { + return false; + } + + return groundBlock.getMaterial().isSolid() && + !feetBlock.getMaterial().isSolid() && + !headBlock.getMaterial().isSolid(); + } + + private void dealDamageAt(EntityLivingBase caster, World world, double x, double y, double z) { + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox( + x - damageRadius, y - 1, z - damageRadius, + x + damageRadius, y + 2, z + damageRadius + ); + + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, aabb); + + 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)); + if (dist <= damageRadius) { + // Apply damage with scripted event support (no knockback for teleport damage) + boolean wasHit = applyAbilityDamage(caster, living, damage, 0); + if (wasHit) { + applyEffects(living); + } + } + } + } + + @Override + public void reset() { + super.reset(); + currentBlink = 0; + ticksSinceLastBlink = 0; + } + + @Override + public float getTelegraphRadius() { + return 0; // No telegraph for teleport + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setString("mode", mode.name()); + nbt.setInteger("blinkCount", blinkCount); + nbt.setInteger("blinkDelayTicks", blinkDelayTicks); + nbt.setFloat("blinkRadius", blinkRadius); + nbt.setFloat("behindDistance", behindDistance); + nbt.setBoolean("requireLineOfSight", requireLineOfSight); + nbt.setBoolean("damageAtStart", damageAtStart); + nbt.setBoolean("damageAtEnd", damageAtEnd); + nbt.setFloat("damage", damage); + nbt.setFloat("damageRadius", damageRadius); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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.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 + public TeleportMode getModeEnum() { + return mode; + } + + public void setModeEnum(TeleportMode mode) { + this.mode = mode; + } + + @Override + public int getMode() { + return mode.ordinal(); + } + + @Override + public void setMode(int mode) { + TeleportMode[] values = TeleportMode.values(); + this.mode = mode >= 0 && mode < values.length ? values[mode] : TeleportMode.BLINK; + } + + public int getBlinkCount() { + return blinkCount; + } + + public void setBlinkCount(int blinkCount) { + this.blinkCount = blinkCount; + } + + public int getBlinkDelayTicks() { + return blinkDelayTicks; + } + + public void setBlinkDelayTicks(int blinkDelayTicks) { + this.blinkDelayTicks = blinkDelayTicks; + } + + public float getBlinkRadius() { + return blinkRadius; + } + + public void setBlinkRadius(float blinkRadius) { + this.blinkRadius = blinkRadius; + } + + public float getBehindDistance() { + return behindDistance; + } + + public void setBehindDistance(float behindDistance) { + this.behindDistance = behindDistance; + } + + public boolean isRequireLineOfSight() { + return requireLineOfSight; + } + + public void setRequireLineOfSight(boolean requireLineOfSight) { + this.requireLineOfSight = requireLineOfSight; + } + + public boolean isDamageAtStart() { + return damageAtStart; + } + + public void setDamageAtStart(boolean damageAtStart) { + this.damageAtStart = damageAtStart; + } + + public boolean isDamageAtEnd() { + return damageAtEnd; + } + + public void setDamageAtEnd(boolean damageAtEnd) { + this.damageAtEnd = damageAtEnd; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getDamageRadius() { + return damageRadius; + } + + public void setDamageRadius(float damageRadius) { + this.damageRadius = damageRadius; + } + + @Override + public int getMaxPreviewDuration() { + int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; + return blinkLimit * blinkDelayTicks + 10; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.enumField("ability.mode", TeleportMode.class, this::getModeEnum, this::setModeEnum), + FieldDef.floatField("ability.blinkRadius", this::getBlinkRadius, this::setBlinkRadius) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK || this.getModeEnum() == TeleportMode.SINGLE), + FieldDef.row( + FieldDef.intField("ability.blinkCount", this::getBlinkCount, this::setBlinkCount) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK), + FieldDef.intField("ability.blinkDelay", this::getBlinkDelayTicks, this::setBlinkDelayTicks) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK) + ), + FieldDef.floatField("ability.behindDistance", this::getBehindDistance, this::setBehindDistance) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BEHIND), + FieldDef.boolField("ability.lineOfSight", this::isRequireLineOfSight, this::setRequireLineOfSight) + .hover("ability.hover.lineOfSight") + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK || this.getModeEnum() == TeleportMode.SINGLE), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("gui.radius", this::getDamageRadius, this::setDamageRadius) + ), + FieldDef.row( + FieldDef.boolField("ability.damageAtStart", this::isDamageAtStart, this::setDamageAtStart) + .hover("ability.hover.dmgAtStart"), + FieldDef.boolField("ability.damageAtEnd", this::isDamageAtEnd, this::setDamageAtEnd) + .hover("ability.hover.dmgAtEnd") + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } +} 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 new file mode 100644 index 000000000..5e508069a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -0,0 +1,352 @@ +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.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.List; + +public class AbilityTrap extends AbilityZone implements IAbilityTrap { + + private float triggerRadius = 2.0f; + private int armTime = 20; + 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; + + public AbilityTrap() { + super(300, new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.0f, 0.5f, 1.5f)); + this.typeId = "ability.cnpc.trap"; + this.name = "Trap"; + 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 isConcurrentCapable() { + return true; + } + + @Override + public float getZoneRadius() { + return triggerRadius; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + activeEntities.clear(); + + List positions; + if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { + positions = new ArrayList<>(preCalculatedPositions); + preCalculatedPositions.clear(); + } else { + 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); + } + } + + @SideOnly(Side.CLIENT) + public enum TrapPreset { + HIDDEN, VENOM, EXPLOSIVE, CURSED, SHOCK, SNARE; + + @Override + public String toString() { + return "ability.preset." + name().toLowerCase(); + } + } + + 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) { + writeZoneNBT(nbt); + nbt.setFloat("triggerRadius", triggerRadius); + nbt.setInteger("armTime", armTime); + nbt.setInteger("maxTriggers", maxTriggers); + nbt.setInteger("triggerCooldown", triggerCooldown); + nbt.setFloat("damage", damage); + nbt.setFloat("damageRadius", damageRadius); + nbt.setFloat("knockback", knockback); + nbt.setBoolean("visible", visible); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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() { + return triggerRadius; + } + + public void setTriggerRadius(float triggerRadius) { + this.triggerRadius = triggerRadius; + } + + public int getArmTime() { + return armTime; + } + + public void setArmTime(int armTime) { + this.armTime = armTime; + } + + public int getMaxTriggers() { + return maxTriggers; + } + + public void setMaxTriggers(int maxTriggers) { + this.maxTriggers = maxTriggers; + } + + public int getTriggerCooldown() { + return triggerCooldown; + } + + public void setTriggerCooldown(int triggerCooldown) { + this.triggerCooldown = triggerCooldown; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getDamageRadius() { + return damageRadius; + } + + public void setDamageRadius(float damageRadius) { + this.damageRadius = damageRadius; + } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + public boolean isVisible() { + return visible; + } + + public void setVisible(boolean visible) { + this.visible = visible; + } + + @SideOnly(Side.CLIENT) + @Override + protected void addPresetFieldDef(List defs) { + defs.add(FieldDef.subGuiField("gui.applyPreset", + SubGuiTrapPresetSelector::new, + gui -> { + SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui; + if (selector.selectedPreset != null) { + applyTrapPresetDefaults(selector.selectedPreset); + } + })); + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + addPresetFieldDef(defs); + + defs.addAll(Arrays.asList( + FieldDef.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("gui.max", this::getMaxTriggers, this::setMaxTriggers), + FieldDef.intField("gui.cooldown", this::getTriggerCooldown, this::setTriggerCooldown) + ), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("gui.radius", this::getDamageRadius, this::setDamageRadius) + ), + 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 new file mode 100644 index 000000000..8f9b3f3a0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -0,0 +1,411 @@ +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.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.api.ability.type.IAbilityVortex; +import noppes.npcs.client.gui.builder.FieldDef; + +import net.minecraft.entity.player.EntityPlayer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Vortex ability: Pulls targets toward the caster. + * Can pull single target or AOE, with optional damage and stun on arrival. + */ +public class AbilityVortex extends Ability implements IAbilityVortex { + + private float pullRadius = 8.0f; + private float pullStrength = 0.8f; + private float damage = 0.0f; + private float knockback = 0.0f; + private boolean aoe = true; + private boolean damageOnPull = false; + private float pullDamage = 0.0f; + + // 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 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 HashMap<>(); + } + return pulledEntities; + } + + public AbilityVortex() { + this.typeId = "ability.cnpc.vortex"; + this.name = "Vortex"; + this.targetingMode = TargetingMode.AOE_SELF; + this.maxRange = 15.0f; + 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 + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AOE_SELF}; + } + + @Override + public float getTelegraphRadius() { + return pullRadius; + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + getPulledEntities().clear(); + pullComplete = false; + ticksSincePullDamage = 0; + + if (!isPreview() && !caster.worldObj.isRemote) { + AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); + @SuppressWarnings("unchecked") + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); + + 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().put(entity.getEntityId(), new PullState(entity)); + } + } + } else { + // 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().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, int tick) { + if (isPreview()) { + // No entities to pull in preview, just run animation for a duration + if (tick >= 60) signalCompletion(); + return; + } + + if (pullComplete || getPulledEntities().isEmpty()) { + signalCompletion(); + return; + } + + 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 (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(entityId); + continue; + } + + double dx = destX - entity.posX; + double dy = destY - entity.posY; + double dz = destZ - entity.posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + 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 motionX = dx * factor; + double motionY = dy * factor * 0.5; + double motionZ = dz * factor; + + 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); + } + + if (shouldDealPullDamage) { + applyAbilityDamage(caster, entity, pullDamage * 0.5f, 0); + } + } + + if (!anyStillPulling && getPulledEntities().isEmpty()) { + pullComplete = true; + signalCompletion(); + } + } + + private void onTargetArrived(EntityLivingBase caster, EntityLivingBase entity, World world) { + // Apply damage with scripted event support + boolean wasHit = applyAbilityDamage(caster, entity, damage, knockback * 0.5f); + + // Only apply effects if hit wasn't cancelled + if (wasHit) { + applyEffects(entity); + } + } + + /** + * Find an entity by entity ID. + */ + private EntityLivingBase findEntity(World world, int entityId) { + Entity entity = world.getEntityByID(entityId); + if (entity instanceof EntityLivingBase) { + return (EntityLivingBase) entity; + } + return null; + } + + @Override + public void cleanup() { + getPulledEntities().clear(); + pullComplete = false; + ticksSincePullDamage = 0; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("pullRadius", pullRadius); + nbt.setFloat("pullStrength", pullStrength); + nbt.setFloat("damage", damage); + nbt.setFloat("knockback", knockback); + nbt.setBoolean("aoe", aoe); + nbt.setBoolean("damageOnPull", damageOnPull); + nbt.setFloat("pullDamage", pullDamage); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + 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 + public float getPullRadius() { + return pullRadius; + } + + public void setPullRadius(float pullRadius) { + this.pullRadius = pullRadius; + } + + public float getPullStrength() { + return pullStrength; + } + + public void setPullStrength(float pullStrength) { + this.pullStrength = pullStrength; + } + + public float getDamage() { + return damage; + } + + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getDisplayDamage() { return damage; } + + public float getKnockback() { + return knockback; + } + + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + public boolean isAoe() { + return aoe; + } + + public void setAoe(boolean aoe) { + this.aoe = aoe; + } + + public boolean isDamageOnPull() { + return damageOnPull; + } + + public void setDamageOnPull(boolean damageOnPull) { + this.damageOnPull = damageOnPull; + } + + public float getPullDamage() { + return pullDamage; + } + + public void setPullDamage(float pullDamage) { + this.pullDamage = pullDamage; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("ability.pullRadius", this::getPullRadius, this::setPullRadius), + FieldDef.floatField("ability.pullStrength", this::getPullStrength, this::setPullStrength) + ), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + ), + FieldDef.section("ability.section.aoe"), + FieldDef.boolField("gui.enabled", this::isAoe, this::setAoe) + .hover("ability.hover.aoe"), + FieldDef.section("ability.section.pullDamage"), + FieldDef.boolField("gui.enabled", this::isDamageOnPull, this::setDamageOnPull) + .hover("ability.hover.dmgOnPull"), + FieldDef.floatField("enchantment.damage", this::getPullDamage, this::setPullDamage) + .visibleWhen(this::isDamageOnPull), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } +} 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..968ff03ba --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -0,0 +1,772 @@ +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(FieldDef.subGuiField("gui.applyPreset", + SubGuiZonePresetSelector::new, + gui -> { + SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui; + if (selector.selectedPreset != null) { + applyPresetDefaults(selector.selectedPreset); + } + })); + } + + @SideOnly(Side.CLIENT) + protected void addVisualFieldDefs(List defs) { + defs.addAll(Arrays.asList( + FieldDef.section("ability.section.ground").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isGroundFill, this::setGroundFill), + FieldDef.floatField("gui.alpha", this::getGroundAlpha, this::setGroundAlpha) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.rings").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isRings, this::setRings), + FieldDef.intField("gui.count", this::getRingCount, this::setRingCount).range(1, 5) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.border").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isBorder, this::setBorder), + FieldDef.floatField("gui.speed", this::getBorderSpeed, this::setBorderSpeed) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.accents").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isAccents, this::setAccents), + FieldDef.enumField("gui.style", AccentStyle.class, this::getAccentStyleEnum, this::setAccentStyleEnum) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.lightning").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isLightning, this::setLightning), + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.particles").tab("ability.tab.visual"), + FieldDef.boolField("gui.enabled", this::isParticles, this::setParticles) + .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("gui.density", this::getParticleDensity, this::setParticleDensity), + FieldDef.floatField("gui.scale", this::getParticleScale, this::setParticleScale) + ).tab("ability.tab.visual").visibleWhen(this::isParticles), + FieldDef.row( + FieldDef.enumField("gui.motion", ParticleMotion.class, this::getParticleMotionEnum, this::setParticleMotionEnum), + FieldDef.boolField("gui.glow", this::isParticleGlow, this::setParticleGlow) + ).tab("ability.tab.visual").visibleWhen(this::isParticles), + FieldDef.stringField("gui.texture", this::getParticleDir, this::setParticleDir) + .tab("ability.tab.visual").visibleWhen(this::isParticles), + + FieldDef.section("ability.section.animation").tab("ability.tab.visual"), + FieldDef.floatField("gui.speed", this::getAnimSpeed, this::setAnimSpeed) + .tab("ability.tab.visual"), + + FieldDef.section("ability.section.colors").tab("ability.tab.visual"), + FieldDef.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..7e7986d20 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java @@ -0,0 +1,931 @@ +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) { + return isPlayerCaster(caster) ? null : 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/energy/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java new file mode 100644 index 000000000..67c2d9c0d --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -0,0 +1,316 @@ +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.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.EntityEnergySweeper; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.type.IAbilitySweeper; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +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 EntityEnergySweeper entity to ensure + * visual and damage hitbox alignment. + */ +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 = 1.0f; // Beam vertical size in blocks (1 block tall, jumpable) + private float damage = 5.0f; + private int damageInterval = 5; + private boolean piercing = true; + private float sweepSpeed = 3.0f; + private int numberOfRotations = 2; // How many full rotations before ability ends + private boolean lockOnTarget = false; + + // Runtime state (transient) + 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 = 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 + public boolean allowBurst() { + 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; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + 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 EntityEnergySweeper(caster.worldObj, caster, target, + beamLength, beamWidth, beamHeight, + displayData, + sweepSpeed, numberOfRotations, + damage, damageInterval, piercing, + lockOnTarget); + activeEntity.setIgnoreIFrames(this.isIgnoreIFrames()); + activeEntity.setSourceAbility(this); + + if (isPreview()) { + activeEntity.setupPreview(caster); + } + + spawnAbilityEntity(activeEntity); + } + + @Override + 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(); + } + } + + @Override + public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + // Clean up entity if still alive + if (activeEntity != null && !activeEntity.isDead) { + activeEntity.setDead(); + } + activeEntity = null; + } + + @Override + public float getTelegraphRadius() { + return beamLength; + } + + /** + * Override to position telegraph at NPC (not target) since the sweep is centered on NPC. + */ + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || telegraphType == TelegraphType.NONE) { + return null; + } + + // Create circle telegraph centered on caster + Telegraph telegraph = Telegraph.circle(beamLength); + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + // 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 + + return instance; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("beamLength", beamLength); + nbt.setFloat("beamWidth", beamWidth); + nbt.setFloat("beamHeight", beamHeight); + nbt.setFloat("damage", damage); + nbt.setInteger("damageInterval", damageInterval); + nbt.setBoolean("piercing", piercing); + nbt.setFloat("sweepSpeed", sweepSpeed); + nbt.setInteger("numberOfRotations", numberOfRotations); + nbt.setBoolean("lockOnTarget", lockOnTarget); + writeEnergyNBT(nbt); + } + + @Override + public void readTypeNBT(NBTTagCompound 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 (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() { + return (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10; + } + + @SideOnly(Side.CLIENT) + @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).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).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).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 - 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 ccbae74ef..f7d6ded84 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/profile/CNPCData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/profile/CNPCData.java @@ -5,6 +5,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.PlayerTradeData; import java.util.ArrayList; import java.util.List; @@ -19,7 +20,10 @@ public class CNPCData implements IProfileData { @Override public NBTTagCompound getCurrentNBT(EntityPlayer player) { PlayerData customNPCData = PlayerData.get(player); - return customNPCData.getNBT(); + NBTTagCompound compound = customNPCData.getNBT(); + compound.removeTag(PlayerTradeData.NBT_KEY); + + return compound; } @Override @@ -32,6 +36,10 @@ public class CNPCData implements IProfileData { @Override public void setNBT(EntityPlayer player, NBTTagCompound replace) { PlayerData customNPCData = PlayerData.get(player); + + NBTTagCompound sharedData = new NBTTagCompound(); + customNPCData.tradeData.writeToNBT(sharedData); + if (replace.hasNoTags()) { PlayerData newData = new PlayerData(); newData.player = player; @@ -39,6 +47,8 @@ public class CNPCData implements IProfileData { } else { customNPCData.setNBT(replace); } + + customNPCData.tradeData.readFromNBT(sharedData); customNPCData.updateClient = true; } @@ -53,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 new file mode 100644 index 000000000..a12292263 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java @@ -0,0 +1,320 @@ +package kamkeel.npcs.controllers.data.telegraph; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * Telegraph configuration - defines a visual warning shape. + * Telegraphs warn players about incoming attacks or mark areas of effect. + */ +public class Telegraph { + + // Identity + private String id = ""; + private TelegraphType type = TelegraphType.CIRCLE; + + // Shape parameters + private float radius = 3.0f; + private float innerRadius = 0.0f; + private float length = 5.0f; + private float width = 2.0f; + private float angle = 45.0f; + + // Timing + private int durationTicks = 40; + + // Visuals + private int color = 0x80FF0000; // Semi-transparent red + private int warningColor = 0xC0FF0000; // More opaque red + private int warningStartTick = 10; + private boolean animated = true; + private float heightOffset = 0.1f; + private int groundSearchRange = 3; + + // Positioning + private boolean atTarget = true; + private boolean followsTarget = false; + private boolean followsCaster = false; + private float offsetForward = 0.0f; + + public Telegraph() { + } + + public Telegraph(String id, TelegraphType type) { + this.id = id; + this.type = type; + } + + public Telegraph(Telegraph other) { + this.id = other.id; + this.type = other.type; + this.radius = other.radius; + this.innerRadius = other.innerRadius; + this.length = other.length; + this.width = other.width; + this.angle = other.angle; + this.durationTicks = other.durationTicks; + this.color = other.color; + this.warningColor = other.warningColor; + 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; + this.offsetForward = other.offsetForward; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("id", id); + nbt.setString("type", type.name()); + nbt.setFloat("radius", radius); + nbt.setFloat("innerRadius", innerRadius); + nbt.setFloat("length", length); + nbt.setFloat("width", width); + nbt.setFloat("angle", angle); + nbt.setInteger("durationTicks", durationTicks); + nbt.setInteger("color", color); + nbt.setInteger("warningColor", warningColor); + 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); + nbt.setFloat("offsetForward", offsetForward); + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + this.id = nbt.getString("id"); + if (nbt.hasKey("type")) { + try { + this.type = TelegraphType.valueOf(nbt.getString("type")); + } catch (Exception e) { + this.type = TelegraphType.CIRCLE; + } + } + this.radius = nbt.getFloat("radius"); + this.innerRadius = nbt.getFloat("innerRadius"); + this.length = nbt.getFloat("length"); + this.width = nbt.getFloat("width"); + this.angle = nbt.getFloat("angle"); + this.durationTicks = nbt.getInteger("durationTicks"); + this.color = nbt.getInteger("color"); + this.warningColor = nbt.getInteger("warningColor"); + 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"); + this.offsetForward = nbt.getFloat("offsetForward"); + } + + // ═══════════════════════════════════════════════════════════════════ + // FACTORY METHODS + // ═══════════════════════════════════════════════════════════════════ + + public static Telegraph circle(float radius) { + Telegraph t = new Telegraph("", TelegraphType.CIRCLE); + t.radius = radius; + return t; + } + + public static Telegraph ring(float outerRadius, float innerRadius) { + Telegraph t = new Telegraph("", TelegraphType.RING); + t.radius = outerRadius; + t.innerRadius = innerRadius; + return t; + } + + public static Telegraph line(float length, float width) { + Telegraph t = new Telegraph("", TelegraphType.LINE); + t.length = length; + t.width = width; + return t; + } + + public static Telegraph cone(float length, float angle) { + Telegraph t = new Telegraph("", TelegraphType.CONE); + t.length = length; + t.angle = angle; + 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 + // ═══════════════════════════════════════════════════════════════════ + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public TelegraphType getType() { + return type; + } + + public void setType(TelegraphType type) { + this.type = type; + } + + public float getRadius() { + return radius; + } + + public void setRadius(float radius) { + this.radius = radius; + } + + public float getInnerRadius() { + return innerRadius; + } + + public void setInnerRadius(float innerRadius) { + this.innerRadius = innerRadius; + } + + public float getLength() { + return length; + } + + public void setLength(float length) { + this.length = length; + } + + public float getWidth() { + return width; + } + + public void setWidth(float width) { + this.width = width; + } + + public float getAngle() { + return angle; + } + + public void setAngle(float angle) { + this.angle = angle; + } + + public int getDurationTicks() { + return durationTicks; + } + + public void setDurationTicks(int durationTicks) { + this.durationTicks = durationTicks; + } + + public int getColor() { + return color; + } + + public void setColor(int color) { + this.color = color; + } + + public int getWarningColor() { + return warningColor; + } + + public void setWarningColor(int warningColor) { + this.warningColor = warningColor; + } + + public int getWarningStartTick() { + return warningStartTick; + } + + public void setWarningStartTick(int warningStartTick) { + this.warningStartTick = warningStartTick; + } + + public boolean isAnimated() { + return animated; + } + + public void setAnimated(boolean animated) { + this.animated = animated; + } + + public float getHeightOffset() { + return heightOffset; + } + + public void setHeightOffset(float heightOffset) { + this.heightOffset = heightOffset; + } + + public int getGroundSearchRange() { + return groundSearchRange; + } + + public void setGroundSearchRange(int groundSearchRange) { + this.groundSearchRange = groundSearchRange; + } + + public boolean isAtTarget() { + return atTarget; + } + + public void setAtTarget(boolean atTarget) { + this.atTarget = atTarget; + } + + public boolean isFollowsTarget() { + return followsTarget; + } + + public void setFollowsTarget(boolean followsTarget) { + this.followsTarget = followsTarget; + } + + public boolean isFollowsCaster() { + return followsCaster; + } + + public void setFollowsCaster(boolean followsCaster) { + this.followsCaster = followsCaster; + } + + public float getOffsetForward() { + return offsetForward; + } + + public void setOffsetForward(float offsetForward) { + this.offsetForward = offsetForward; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java new file mode 100644 index 000000000..a9ee8e4d7 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java @@ -0,0 +1,397 @@ +package kamkeel.npcs.controllers.data.telegraph; + +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.entity.Entity; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import java.util.UUID; + +/** + * Runtime instance of an active telegraph. + * Tracks position, timing, and state for rendering. + */ +public class TelegraphInstance { + + // Identity + private String instanceId; + private Telegraph telegraph; + + // Position (current) + private double x; + private double y; + private double z; + private float yaw; + + // Position (previous tick - for interpolation) + private double prevX; + private double prevY; + private double prevZ; + private float prevYaw; + + // Entity tracking + 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; + private int totalTicks; + + // State + private boolean isWarning = false; + + // Server-side tracking (for removal) + private transient World world; + private transient int dimensionId; + + public TelegraphInstance() { + this.instanceId = UUID.randomUUID().toString().substring(0, 8); + } + + public TelegraphInstance(Telegraph telegraph, double x, double y, double z, float yaw) { + this(); + this.telegraph = new Telegraph(telegraph); + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + // Initialize prev positions to current for first frame + this.prevX = x; + this.prevY = y; + this.prevZ = z; + this.prevYaw = yaw; + this.remainingTicks = telegraph.getDurationTicks(); + this.totalTicks = telegraph.getDurationTicks(); + } + + // ═══════════════════════════════════════════════════════════════════ + // TICK LOGIC + // ═══════════════════════════════════════════════════════════════════ + + /** + * Called every tick to update telegraph state. + * + * @param world The world (for entity lookup) + * @return false if telegraph should be removed + */ + public boolean tick(World world) { + if (remainingTicks <= 0) { + return false; + } + + // Save previous position for interpolation + this.prevX = this.x; + this.prevY = this.y; + this.prevZ = this.z; + this.prevYaw = this.yaw; + + remainingTicks--; + + // Update position if following an entity + if (entityIdToFollow >= 0 && world != null) { + Entity entity = world.getEntityByID(entityIdToFollow); + if (entity != null) { + this.x = entity.posX; + this.z = entity.posZ; + // Find ground level below the entity for proper telegraph placement + 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; + } + } + } + + // Update yaw to face target entity (for LINE telegraphs) + if (targetEntityId >= 0 && world != null) { + Entity target = world.getEntityByID(targetEntityId); + if (target != null) { + double dx = target.posX - this.x; + double dz = target.posZ - this.z; + this.yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI); + } + } + + // Check for warning phase transition + if (!isWarning && telegraph != null) { + if (remainingTicks <= telegraph.getWarningStartTick()) { + isWarning = true; + } + } + + return true; + } + + /** + * Get progress from 0.0 (just started) to 1.0 (finished). + */ + public float getProgress() { + if (totalTicks <= 0) return 1.0f; + return 1.0f - ((float) remainingTicks / (float) totalTicks); + } + + /** + * Get the current display color (normal or warning). + */ + public int getCurrentColor() { + if (telegraph == null) return 0x80FF0000; + return isWarning ? telegraph.getWarningColor() : telegraph.getColor(); + } + + /** + * Get alpha-modulated color for breathing animation. + */ + public int getAnimatedColor(float partialTicks) { + int baseColor = getCurrentColor(); + if (telegraph == null || !telegraph.isAnimated()) { + return baseColor; + } + + // Breathing animation: slow, smooth modulation of alpha + float time = (totalTicks - remainingTicks) + partialTicks; + // Slower breathing: 0.08 for ~4 second cycle, smoother sine curve + float breathPhase = (float) Math.sin(time * 0.08); + // Smooth easing: square the sine for more organic feel, range 0.5 to 1.0 + float pulse = 0.5f + (breathPhase * breathPhase * 0.5f * Math.signum(breathPhase)); + + int alpha = (baseColor >> 24) & 0xFF; + int r = (baseColor >> 16) & 0xFF; + int g = (baseColor >> 8) & 0xFF; + int b = baseColor & 0xFF; + + alpha = (int) (alpha * pulse); + + return (alpha << 24) | (r << 16) | (g << 8) | b; + } + + // ═══════════════════════════════════════════════════════════════════ + // INTERPOLATED POSITION (for smooth rendering) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Get interpolated X position for smooth rendering. + */ + public double getInterpolatedX(float partialTicks) { + return prevX + (x - prevX) * partialTicks; + } + + /** + * Get interpolated Y position for smooth rendering. + */ + public double getInterpolatedY(float partialTicks) { + return prevY + (y - prevY) * partialTicks; + } + + /** + * Get interpolated Z position for smooth rendering. + */ + public double getInterpolatedZ(float partialTicks) { + return prevZ + (z - prevZ) * partialTicks; + } + + /** + * Get interpolated yaw for smooth rendering. + * Handles angle wrapping for smooth rotation. + */ + public float getInterpolatedYaw(float partialTicks) { + // Handle angle wrapping to prevent spinning the wrong way + float diff = yaw - prevYaw; + while (diff > 180.0f) diff -= 360.0f; + while (diff < -180.0f) diff += 360.0f; + return prevYaw + diff * partialTicks; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("instanceId", instanceId); + + if (telegraph != null) { + nbt.setTag("telegraph", telegraph.writeNBT()); + } + + nbt.setDouble("x", x); + nbt.setDouble("y", y); + nbt.setDouble("z", z); + nbt.setFloat("yaw", yaw); + + nbt.setInteger("entityIdToFollow", entityIdToFollow); + nbt.setInteger("casterEntityId", casterEntityId); + nbt.setInteger("targetEntityId", targetEntityId); + nbt.setBoolean("trackFollowedYaw", trackFollowedEntityYaw); + + nbt.setInteger("remainingTicks", remainingTicks); + nbt.setInteger("totalTicks", totalTicks); + + nbt.setBoolean("isWarning", isWarning); + + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + this.instanceId = nbt.getString("instanceId"); + + if (nbt.hasKey("telegraph")) { + this.telegraph = new Telegraph(); + this.telegraph.readNBT(nbt.getCompoundTag("telegraph")); + } + + this.x = nbt.getDouble("x"); + this.y = nbt.getDouble("y"); + this.z = nbt.getDouble("z"); + this.yaw = nbt.getFloat("yaw"); + + 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"); + + this.isWarning = nbt.getBoolean("isWarning"); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public String getInstanceId() { + return instanceId; + } + + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + public Telegraph getTelegraph() { + return telegraph; + } + + public void setTelegraph(Telegraph telegraph) { + this.telegraph = telegraph; + } + + public double getX() { + return x; + } + + public void setX(double x) { + this.x = x; + } + + public double getY() { + return y; + } + + public void setY(double y) { + this.y = y; + } + + public double getZ() { + return z; + } + + public void setZ(double z) { + this.z = z; + } + + public float getYaw() { + return yaw; + } + + public void setYaw(float yaw) { + this.yaw = yaw; + } + + public int getEntityIdToFollow() { + return entityIdToFollow; + } + + public void setEntityIdToFollow(int entityIdToFollow) { + this.entityIdToFollow = entityIdToFollow; + } + + /** + * Locks the telegraph at its current position and direction. + * Stops following any entity - used when ability commits to action. + */ + public void lockPosition() { + this.entityIdToFollow = -1; + this.targetEntityId = -1; + } + + public int getCasterEntityId() { + return casterEntityId; + } + + public void setCasterEntityId(int casterEntityId) { + this.casterEntityId = casterEntityId; + } + + public int getTargetEntityId() { + return targetEntityId; + } + + public void setTargetEntityId(int targetEntityId) { + this.targetEntityId = targetEntityId; + } + + public boolean isTrackFollowedEntityYaw() { + return trackFollowedEntityYaw; + } + + public void setTrackFollowedEntityYaw(boolean track) { + this.trackFollowedEntityYaw = track; + } + + public int getRemainingTicks() { + return remainingTicks; + } + + public void setRemainingTicks(int remainingTicks) { + this.remainingTicks = remainingTicks; + } + + public int getTotalTicks() { + return totalTicks; + } + + public void setTotalTicks(int totalTicks) { + this.totalTicks = totalTicks; + } + + public boolean isWarning() { + return isWarning; + } + + public void setWarning(boolean warning) { + isWarning = warning; + } + + public World getWorld() { + return world; + } + + public void setWorld(World world) { + this.world = world; + if (world != null) { + this.dimensionId = world.provider.dimensionId; + } + } + + public int getDimensionId() { + return dimensionId; + } + + public void setDimensionId(int dimensionId) { + this.dimensionId = dimensionId; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphManager.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphManager.java new file mode 100644 index 000000000..57b245fd4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphManager.java @@ -0,0 +1,142 @@ +package kamkeel.npcs.controllers.data.telegraph; + +import net.minecraft.world.World; + +import java.util.Collection; +import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Manages active telegraph instances. + * There's one instance per world (client and server). + */ +public class TelegraphManager { + + /** + * Client-side instance for rendering + */ + public static TelegraphManager ClientInstance; + + private final ConcurrentHashMap telegraphs = new ConcurrentHashMap<>(); + + public TelegraphManager() { + } + + /** + * Initialize the client-side manager. + * Call from client proxy during mod init. + */ + public static void initClient() { + ClientInstance = new TelegraphManager(); + } + + // ═══════════════════════════════════════════════════════════════════ + // TELEGRAPH MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Add a new telegraph instance. + */ + public void addTelegraph(TelegraphInstance instance) { + telegraphs.put(instance.getInstanceId(), instance); + } + + /** + * Remove a telegraph by ID. + */ + public void removeTelegraph(String instanceId) { + telegraphs.remove(instanceId); + } + + /** + * Get a telegraph by ID. + */ + public TelegraphInstance getTelegraph(String instanceId) { + return telegraphs.get(instanceId); + } + + /** + * Get all active telegraphs for rendering. + */ + public Collection getTelegraphs() { + return telegraphs.values(); + } + + /** + * Clear all telegraphs. + */ + public void clear() { + telegraphs.clear(); + } + + /** + * Check if any telegraphs are active. + */ + public boolean hasTelegraphs() { + return !telegraphs.isEmpty(); + } + + // ═══════════════════════════════════════════════════════════════════ + // TICK + // ═══════════════════════════════════════════════════════════════════ + + /** + * Tick all telegraphs, removing expired ones. + * Call from client tick handler. + */ + public void tick(World world) { + Iterator iterator = telegraphs.values().iterator(); + while (iterator.hasNext()) { + TelegraphInstance instance = iterator.next(); + if (!instance.tick(world)) { + iterator.remove(); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // HELPER METHODS FOR SPAWNING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Spawn a circle telegraph at a position. + */ + public TelegraphInstance spawnCircle(double x, double y, double z, float radius, int durationTicks, int color) { + Telegraph telegraph = Telegraph.circle(radius); + telegraph.setDurationTicks(durationTicks); + telegraph.setColor(color); + telegraph.setWarningColor((color & 0x00FFFFFF) | 0xC0000000); + + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, 0); + addTelegraph(instance); + return instance; + } + + /** + * Spawn a line telegraph from a position in a direction. + */ + public TelegraphInstance spawnLine(double x, double y, double z, float yaw, float length, float width, int durationTicks, int color) { + Telegraph telegraph = Telegraph.line(length, width); + telegraph.setDurationTicks(durationTicks); + telegraph.setColor(color); + telegraph.setWarningColor((color & 0x00FFFFFF) | 0xC0000000); + + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + addTelegraph(instance); + return instance; + } + + /** + * Spawn a cone telegraph from a position in a direction. + */ + public TelegraphInstance spawnCone(double x, double y, double z, float yaw, float length, float angle, int durationTicks, int color) { + Telegraph telegraph = Telegraph.cone(length, angle); + telegraph.setDurationTicks(durationTicks); + telegraph.setColor(color); + telegraph.setWarningColor((color & 0x00FFFFFF) | 0xC0000000); + + TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw); + addTelegraph(instance); + return instance; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java new file mode 100644 index 000000000..dd080f093 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java @@ -0,0 +1,41 @@ +package kamkeel.npcs.controllers.data.telegraph; + +/** + * Types of telegraph shapes for visual attack warnings. + */ +public enum TelegraphType { + /** + * Filled circle (uses radius) + */ + CIRCLE, + + /** + * Donut shape (uses radius and innerRadius) + */ + RING, + + /** + * Rectangle (uses length, width) + */ + LINE, + + /** + * Fan/wedge shape (uses length, angle) + */ + CONE, + + /** + * Single point indicator + */ + POINT, + + /** + * Filled square (uses radius as half-size) + */ + SQUARE, + + /** + * No telegraph + */ + NONE +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java new file mode 100644 index 000000000..baeb7f81c --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -0,0 +1,846 @@ +package kamkeel.npcs.entity; + +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.Vec3; +import net.minecraft.world.World; + +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 EntityEnergyProjectile { + + private enum BeamMode { + ANCHORED, + FREE_TRAIL + } + + // Beam shape properties + private float beamWidth = 0.3f; + private float headSize = 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; + + // Beam behavior mode (single source of truth). + private BeamMode beamMode = BeamMode.ANCHORED; + + // 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 (beam-specific) + private float chargeOffsetDistance = 1.0f; + private int trailFadeTime = 20; // Ticks for trail to fully fade + private List trailPointAges = new ArrayList<>(); + + public EntityAbilityBeam(World world) { + super(world); + } + + @Override + @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; + } + + private static BeamMode modeFromAnchored(boolean anchored) { + return anchored ? BeamMode.ANCHORED : BeamMode.FREE_TRAIL; + } + + 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). + */ + public EntityAbilityBeam(World world, EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, + float beamWidth, float headSize, + EnergyDisplayData display, EnergyCombatData combat, + EnergyHomingData homing, EnergyLightningData lightning, + EnergyLifespanData lifespan, + boolean anchoredMode) { + super(world); + + // Initialize base properties via parent + initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan); + + // Beam-specific properties from homing data + + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); + this.beamWidth = beamWidth; + this.headSize = headSize; + + // Beam mode controls tail attachment/orb/fading behavior. + setBeamMode(modeFromAnchored(anchoredMode)); + + // Initialize head offset at origin (0,0,0 relative) + resetHeadOffsets(); + + // Add initial trail point at origin (relative 0,0,0) + trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); + + // Calculate initial velocity toward target + calculateInitialVelocity(owner, target, x, y, z); + } + + public void setupCharging(EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { + setupChargingState(anchor, chargeDuration); + this.chargeOffsetDistance = chargeOffsetDistance; + clearMotion(); + } + + public void setupPreview(EntityLivingBase owner, float beamWidth, float headSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { + setupPreviewState(owner, display, lightning, anchor, chargeDuration); + + // Set visual properties + this.beamWidth = beamWidth; + this.headSize = headSize; + setVisualSize(headSize); + + this.chargeOffsetDistance = chargeOffsetDistance; + setChargeOriginFromAnchor(owner, anchorData, chargeOffsetDistance); + + // Initialize head offsets + resetHeadOffsets(); + + // Clear motion + clearMotion(); + } + + /** + * Start preview firing (simulates firing toward a point in front of NPC). + */ + public void startPreviewFiring() { + startPreviewFiringDefault(); + + // Reset head offset to origin + resetHeadOffsets(); + + // Reset trail + resetTrailStorage(); + trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); + if (isFadingMode()) trailPointAges.add(0); + } + + /** + * Start the beam firing (exit charging mode). + * Called by ability when windup ends. + */ + public void startFiring(EntityLivingBase target) { + startMovingTowardTargetFromStartDefault(target); + + // Head starts at the origin (tail position) + resetHeadOffsets(); + + // Initialize trail with just the origin point + resetTrailStorage(); + trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); + if (isFadingMode()) trailPointAges.add(0); + + } + + @Override + protected boolean checkMaxDistance() { + // Check distance using head offset (distance from origin) + double distFromOrigin = Math.sqrt( + headOffsetX * headOffsetX + + headOffsetY * headOffsetY + + headOffsetZ * headOffsetZ + ); + return distFromOrigin >= getMaxDistance(); + } + + @Override + protected void updateProjectile() { + // Handle charging state (windup phase) - use isCharging() for synced value + if (isCharging()) { + updateCharging(); + return; + } + + // Store previous head offset for interpolation + prevHeadOffsetX = headOffsetX; + prevHeadOffsetY = headOffsetY; + prevHeadOffsetZ = headOffsetZ; + + // Age trail points for fading effect + if (isFadingMode()) { + ageTrailPoints(); + } + + // In preview mode, run movement on client (no server) + if (previewMode) { + updatePreviewMovement(); + return; + } + + if (worldObj.isRemote) { + // Client: interpolate entity position + handleClientInterpolation(); + + // Client: derive head offset from entity position and origin + // Entity position = head world position, so headOffset = pos - origin + // Note: During charging, updateCharging() handles origin positioning + // After firing, origin is fixed at the charged position + headOffsetX = posX - startX; + headOffsetY = posY - startY; + headOffsetZ = posZ - startZ; + + // Add trail point on client + addTrailPoint(); + } else { + // Server-side logic + updateHoming(); + + // Move head offset + headOffsetX += motionX; + headOffsetY += motionY; + headOffsetZ += motionZ; + + // Update origin if attached to owner + if (isAnchoredMode()) { + Entity owner = getOwnerEntity(); + if (owner != null) { + startX = owner.posX; + startY = owner.posY + owner.getEyeHeight() * 0.7; + startZ = owner.posZ; + } + } + + // Calculate world position of head for collision detection + double headWorldX = startX + headOffsetX; + double headWorldY = startY + headOffsetY; + double headWorldZ = startZ + headOffsetZ; + + // Update entity position to head (for network sync) + this.setPosition(headWorldX, headWorldY, headWorldZ); + + // Add trail point + addTrailPoint(); + + // Skip collision checks on first few ticks + if (ticksExisted > 2) { + checkBlockCollision(headWorldX, headWorldY, headWorldZ); + checkEntityCollision(headWorldX, headWorldY, headWorldZ); + } + } + } + + /** + * Update during charging state - follow owner based on anchor point. + * Beam-specific: positions based on chargeOffsetDistance and updates startX/Y/Z. + */ + @Override + protected void updateCharging() { + chargeTick++; + + Entity owner = getOwnerEntity(); + 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; + } + } + + /** + * Age trail points and remove old ones (for comet effect). + */ + private void ageTrailPoints() { + 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); + } + + // 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 (isFadingMode()) { + trailPointAges.add(0); + } + return; + } + + 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) + ); + + if (dist >= MIN_POINT_DISTANCE) { + trailPoints.add(Vec3.createVectorHelper(headOffsetX, headOffsetY, headOffsetZ)); + if (isFadingMode()) { + trailPointAges.add(0); + } + + // Limit trail length (only if not using fading - fading handles its own cleanup) + if (!isFadingMode()) { + while (trailPoints.size() > MAX_TRAIL_POINTS) { + trailPoints.remove(0); + } + } + } + } + + /** + * Update movement in preview mode (client-side only, no damage). + */ + private void updatePreviewMovement() { + // Move head offset + headOffsetX += motionX; + headOffsetY += motionY; + headOffsetZ += motionZ; + + // Update origin if attached to owner + if (isAnchoredMode()) { + Entity owner = getOwnerEntity(); + if (owner != null) { + startX = owner.posX; + startY = owner.posY + owner.getEyeHeight() * 0.7; + startZ = owner.posZ; + } + } + + // Calculate world position of head + double headWorldX = startX + headOffsetX; + double headWorldY = startY + headOffsetY; + double headWorldZ = startZ + headOffsetZ; + + // Update entity position to head + this.setPosition(headWorldX, headWorldY, headWorldZ); + + // Add trail point + addTrailPoint(); + } + + /** + * 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(); + if (target == null || !target.isEntityAlive()) return; + + // Calculate world position of head + double headWorldX = startX + headOffsetX; + double headWorldY = startY + headOffsetY; + double headWorldZ = startZ + headOffsetZ; + + double dx = target.posX - headWorldX; + double dy = (target.posY + target.getEyeHeight()) - headWorldY; + double dz = target.posZ - headWorldZ; + 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 checkBlockCollision(double headX, double headY, double headZ) { + // Previous head world position + double prevHeadWorldX = startX + prevHeadOffsetX; + double prevHeadWorldY = startY + prevHeadOffsetY; + double prevHeadWorldZ = startZ + prevHeadOffsetZ; + + handleBlockImpact(rayTraceBlocks(prevHeadWorldX, prevHeadWorldY, prevHeadWorldZ, headX, headY, headZ), true); + } + + private void checkEntityCollision(double headX, double headY, double headZ) { + // 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( + 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 + ); + + processEntitiesInHitBox(hitBox, headX, headY, headZ); + } + + // ==================== DEBUG ==================== + + @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 ==================== + + 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 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. + */ + public double getInterpolatedHeadOffsetX(float partialTicks) { + return prevHeadOffsetX + (headOffsetX - prevHeadOffsetX) * partialTicks; + } + + public double getInterpolatedHeadOffsetY(float partialTicks) { + return prevHeadOffsetY + (headOffsetY - prevHeadOffsetY) * partialTicks; + } + + public double getInterpolatedHeadOffsetZ(float partialTicks) { + return prevHeadOffsetZ + (headOffsetZ - prevHeadOffsetZ) * partialTicks; + } + + /** + * Get trail points. These are RELATIVE to origin (startX/Y/Z). + */ + public List getTrailPoints() { + if (trailStartIndex <= 0) { + return trailPoints; + } + if (trailStartIndex >= trailPoints.size()) { + return Collections.emptyList(); + } + return trailPoints.subList(trailStartIndex, trailPoints.size()); + } + + public double getOriginX() { + return startX; + } + + public double getOriginY() { + return startY; + } + + public double getOriginZ() { + return startZ; + } + + /** + * Whether the tail orb should be rendered (only true in anchored mode). + */ + public boolean shouldRenderTailOrb() { + return isAnchoredMode(); + } + + /** + * Whether the beam is attached to its owner (anchored mode). + */ + public boolean isAttachedToOwner() { + return isAnchoredMode(); + } + + /** + * Whether trail should fade (comet effect for non-anchored beams). + */ + public boolean hasFadingTrail() { + return isFadingMode(); + } + + /** + * Get trail point ages for fading calculation. + */ + public List getTrailPointAges() { + if (trailStartIndex <= 0) { + return trailPointAges; + } + if (trailStartIndex >= trailPointAges.size()) { + return Collections.emptyList(); + } + return trailPointAges.subList(trailStartIndex, trailPointAges.size()); + } + + /** + * Get trail fade time in ticks. + */ + public int getTrailFadeTime() { + 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 = 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.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; + readChargingNBT(nbt); + this.chargeOffsetDistance = nbt.hasKey("ChargeOffsetDistance") ? nbt.getFloat("ChargeOffsetDistance") : 1.0f; + 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++) { + NBTTagCompound point = trailList.getCompoundTagAt(i); + trailPoints.add(Vec3.createVectorHelper( + point.getDouble("X"), + point.getDouble("Y"), + point.getDouble("Z") + )); + } + } + + // 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 + protected void writeProjectileNBT(NBTTagCompound nbt) { + nbt.setFloat("BeamWidth", beamWidth); + nbt.setFloat("HeadSize", headSize); + nbt.setDouble("HeadOffsetX", headOffsetX); + nbt.setDouble("HeadOffsetY", headOffsetY); + nbt.setDouble("HeadOffsetZ", headOffsetZ); + nbt.setBoolean("AttachedToOwner", isAnchoredMode()); + nbt.setString("BeamMode", beamMode.name()); + writeChargingNBT(nbt); + nbt.setFloat("ChargeOffsetDistance", chargeOffsetDistance); + nbt.setBoolean("FreeAim", freeAim); + nbt.setBoolean("FadeTrail", isFadingMode()); + nbt.setInteger("TrailFadeTime", trailFadeTime); + + // Write trail points + NBTTagList trailList = new NBTTagList(); + 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); + pointNbt.setDouble("Z", point.zCoord); + 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 new file mode 100644 index 000000000..817357d9b --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -0,0 +1,486 @@ +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 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.Vec3; +import net.minecraft.world.World; + +/** + * 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 EntityEnergyProjectile { + + // Disc-specific movement propertie + + // Boomerang properties + private boolean boomerang = false; + private int boomerangDelay = 40; // Ticks before returning + private boolean returning = false; + private int ticksSinceMiss = 0; + + // Disc shape properties + private float discRadius = 1.0f; // Width of disc + private float discThickness = 0.2f; // Height of disc + + // Boomerang owner-gone tracking + private int returnOwnerNullTicks = 0; + private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) + + // 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 + + public EntityAbilityDisc(World world) { + super(world); + } + + /** + * Full constructor with all parameters using data classes. + */ + public EntityAbilityDisc(World world, EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, + float discRadius, float discThickness, + EnergyDisplayData display, EnergyCombatData combat, + EnergyHomingData homing, EnergyLightningData lightning, + EnergyLifespanData lifespan, + boolean boomerang, int boomerangDelay) { + super(world); + + // Initialize base properties + initProjectile(owner, target, x, y, z, 1.0f, display, combat, lightning, lifespan); + + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); + + this.boomerang = boomerang; + this.boomerangDelay = boomerangDelay; + + this.discRadius = discRadius; + this.discThickness = discThickness; + + // Calculate initial velocity toward target + calculateInitialVelocity(owner, target, x, y, z); + } + + /** + * Setup this disc in charging mode (for windup phase). + * The disc will grow from 0 to discRadius over chargeDuration ticks. + * Position follows the owner based on anchor point. + */ + public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) { + this.targetDiscRadius = this.discRadius; + this.targetDiscThickness = this.discThickness; + super.setupCharging(anchor, chargeDuration); + this.vertical = vertical; + this.discRadius = 0.01f; + this.discThickness = 0.01f; + } + + /** + * Setup this disc in preview mode for GUI display. + * Follows anchor point and animations like in the real game. + * Can be fired when transitioning to active phase. + */ + public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, boolean vertical) { + setupPreviewState(owner, display, lightning, anchor, chargeDuration); + this.vertical = vertical; + + // Store target size and start at 0 for grow effect + this.targetDiscRadius = discRadius; + this.targetDiscThickness = discThickness; + this.discRadius = 0.01f; + this.discThickness = 0.01f; + setVisualSize(0.01f); + setChargeOriginFromAnchor(owner, anchorData); + clearMotion(); + } + + /** + * Start preview firing (simulates firing toward a point in front of NPC). + */ + public void startPreviewFiring() { + startPreviewFiringDefault(); + } + + /** + * Start the disc moving (exit charging mode). + * Called by ability when windup ends. + */ + public void startMoving(EntityLivingBase target) { + startMovingTowardTargetDefault(target); + } + + @Override + protected void updateRotation() { + // Disc spins ONLY on Y axis (flat spin like a saw blade) + this.rotationValY += getRotationSpeed(); + // No wobble - keep X and Z at 0 for stable flight + if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f; + } + + @Override + protected void updateProjectile() { + // Handle charging state (windup phase) + if (isCharging()) { + updateCharging(); + return; + } + + // In preview mode, run movement on client (no server) + if (previewMode) { + updatePreviewMovement(); + return; + } + + if (worldObj.isRemote) { + handleClientInterpolation(); + } else { + // Server-side logic + if (returning) { + updateReturnToOwner(); + } else { + updateHoming(); + } + + checkBlockCollision(); + checkEntityCollision(); + this.moveEntity(motionX, motionY, motionZ); + + // Track ticks for boomerang delay (checkMaxDistance handles the actual return trigger) + if (boomerang && !returning && !hasHit) { + ticksSinceMiss++; + } + } + + // Check wall collision + handleSolidCollisionTermination(); + } + + @Override + protected boolean checkMaxDistance() { + double distTraveled = Math.sqrt( + (posX - startX) * (posX - startX) + + (posY - startY) * (posY - startY) + + (posZ - startZ) * (posZ - startZ) + ); + + if (boomerang) { + // If not returning yet, check if we should start returning + if (!returning && !hasHit) { + if (distTraveled >= getMaxDistance() * 0.8 || ticksSinceMiss >= boomerangDelay) { + returning = true; + } + } + + // If returning, only die when close to owner + 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) + ); + return distToOwner < 1.5; + } + // 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) + return false; + } + + // Non-boomerang: standard max distance check + return distTraveled >= getMaxDistance(); + } + + /** + * Update movement in preview mode (client-side only, no damage). + */ + private void updatePreviewMovement() { + // Simple movement - just apply motion + this.posX += motionX; + this.posY += motionY; + this.posZ += motionZ; + } + + private void updateReturnToOwner() { + Entity owner = getOwnerEntity(); + + // If owner is gone (unloaded/dead), head back toward start position + double targetX, targetY, targetZ; + if (owner != null) { + targetX = owner.posX; + targetY = owner.posY + owner.height * 0.5; + targetZ = owner.posZ; + } else { + // Return to start position if owner not available + targetX = startX; + targetY = startY; + targetZ = startZ; + } + + double dx = targetX - posX; + double dy = targetY - posY; + double dz = targetZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + if (dist > 0) { + // Stronger homing when returning + double returnStrength = Math.min(1.0, getHomingStrength() * 2.5); + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); + + motionX += (desiredVX - motionX) * returnStrength; + motionY += (desiredVY - motionY) * returnStrength; + motionZ += (desiredVZ - motionZ) * returnStrength; + + double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + if (vLen > 0) { + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); + } + } + } + + private void checkBlockCollision() { + handleBlockImpact(rayTraceBlocks(posX, posY, posZ, posX + motionX, posY + motionY, posZ + motionZ), true); + } + + private void checkEntityCollision() { + // 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( + 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 + ); + + 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. + */ + @Override + protected void updateCharging() { + chargeTick++; + + // Grow size based on charge progress + float progress = getChargeProgress(); + this.discRadius = targetDiscRadius * progress; + this.discThickness = targetDiscThickness * progress; + this.size = 1.0f; // Size acts as a scaling factor; discRadius handles actual dimensions + + Entity owner = getOwnerEntity(); + if (owner instanceof EntityLivingBase) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + } + + // Update rotation during charging (disc still spins) + updateRotation(); + } + + // ==================== DEBUG ==================== + + @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 ==================== + + public float getDiscRadius() { + return discRadius; + } + + public void setDiscRadius(float radius) { + this.discRadius = radius; + } + + public float getDiscThickness() { + return discThickness; + } + + public void setDiscThickness(float thickness) { + this.discThickness = thickness; + } + + public boolean isBoomerang() { + return boomerang; + } + + public void setBoomerang(boolean boomerang) { + this.boomerang = boomerang; + } + + public int getBoomerangDelay() { + return boomerangDelay; + } + + public void setBoomerangDelay(int delay) { + this.boomerangDelay = delay; + } + + public boolean isReturning() { + return returning; + } + + public boolean isVertical() { + return vertical; + } + + public void setVertical(boolean vertical) { + this.vertical = vertical; + } + + /** + * Get the yaw angle (degrees) from motion vector for vertical disc orientation. + * During charging, uses owner's facing direction. + */ + public float getTravelYaw() { + if (isCharging()) { + Entity owner = previewMode ? previewOwner : getOwnerEntity(); + if (owner != null) { + 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; + } + + // ==================== 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 ==================== + + @Override + protected void readProjectileNBT(NBTTagCompound nbt) { + this.boomerang = nbt.hasKey("Boomerang") && nbt.getBoolean("Boomerang"); + this.boomerangDelay = nbt.hasKey("BoomerangDelay") ? nbt.getInteger("BoomerangDelay") : 40; + 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.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false; + this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning"); + // 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 + protected void writeProjectileNBT(NBTTagCompound nbt) { + nbt.setBoolean("Boomerang", boomerang); + nbt.setInteger("BoomerangDelay", boomerangDelay); + nbt.setFloat("DiscRadius", discRadius); + nbt.setFloat("DiscThickness", discThickness); + nbt.setBoolean("Vertical", vertical); + nbt.setBoolean("Returning", returning); + // 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 new file mode 100644 index 000000000..6e40ac999 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -0,0 +1,981 @@ +package kamkeel.npcs.entity; + +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; +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.List; + +/** + * 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 EntityEnergyProjectile { + + // Laser-specific properties + private float laserWidth = 0.2f; + private float expansionSpeed = 2.0f; // Blocks per tick + private float maxLength = 32.0f; // Maximum beam reach in blocks + + // State + private float desiredLength = 0.0f; // Intended beam reach (grows to maxLength) + private float currentLength = 0.0f; // Actual length after block truncation (visual + collision) + private boolean fullyExtended = false; + private boolean trackOwnerOrigin = true; // When false, laser fires independently (fireAt mode) + + // Direction (normalized) + private double dirX, dirY, dirZ; + + // End point for rendering + private double endX, endY, endZ; + + // Previous tick positions for partial tick interpolation + private double prevStartX, prevStartY, prevStartZ; + private double prevEndX, prevEndY, prevEndZ; + + // 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); + } + + /** + * Full constructor with all parameters using data classes. + */ + public EntityAbilityLaser(World world, EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, + float laserWidth, + EnergyDisplayData display, EnergyCombatData combat, + EnergyLightningData lightning, EnergyLifespanData lifespan, + float expansionSpeed, float maxLength) { + super(world); + + initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan); + + // Laser-specific properties + this.laserWidth = laserWidth; + this.expansionSpeed = expansionSpeed; + this.maxLength = maxLength; + + // Calculate direction toward target or forward + if (target != null) { + double dx = target.posX - x; + double dy = (target.posY + target.getEyeHeight() - 0.4) - y; + double dz = target.posZ - z; + 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; + } + } else { + // 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 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; + } + + @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() { + // Beam rotation is handled in the renderer via perpendicular vector rotation + } + + @Override + protected boolean checkMaxDistance() { + // Laser handles distance via maxLength, not max distance + return false; + } + + @Override + protected void updateProjectile() { + if (isCharging()) { + updateCharging(); + return; + } + + // 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) { + desiredLength += expansionSpeed; + if (desiredLength >= maxLength) { + desiredLength = maxLength; + fullyExtended = true; + } + } + + // Start from full desired length, then truncate at block hits + currentLength = desiredLength; + + // 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; + } + + checkEntityCollisionAlongLine(); + // Death handled by base class deathWorldTime (from lifespanData.maxLifetime) + } + } + + /** + * 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 instanceof EntityLivingBase)) { + if (worldObj != null && worldObj.isRemote) { + handleClientInterpolation(); + } + return; + } + EntityLivingBase livingOwner = (EntityLivingBase) owner; + + // 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); + look = Vec3.createVectorHelper( + -Math.sin(yaw) * Math.cos(pitch), + -Math.sin(pitch), + Math.cos(yaw) * Math.cos(pitch) + ); + } + + // 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); + + Entity targetEntity = getTargetEntity(); + if (targetEntity instanceof EntityLivingBase && targetEntity.isEntityAlive()) { + EntityLivingBase target = (EntityLivingBase) targetEntity; + double dx = target.posX - anchorPos.xCoord; + double dy = (target.posY + target.getEyeHeight() - 0.4) - anchorPos.yCoord; + double dz = target.posZ - 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) { + beginLookVectorLaunch(false); + + desiredLength = 0.0f; + currentLength = 0.0f; + fullyExtended = false; + lastBlockHitX = Integer.MIN_VALUE; + lastBlockHitY = Integer.MIN_VALUE; + lastBlockHitZ = Integer.MIN_VALUE; + lastExplosionTick = -100; + + // 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; + } + } + + // Initialize end point at start (will expand from here) + 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() { + 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) { + // 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) + ); + 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; + } + } + + 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; + double minY = Math.min(startY, endY) - expand; + double minZ = Math.min(startZ, endZ) - expand; + double maxX = Math.max(startX, endX) + expand; + double maxY = Math.max(startY, endY) + expand; + double maxZ = Math.max(startZ, endZ) + expand; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + + for (EntityLivingBase entity : entities) { + if (shouldIgnoreEntity(entity)) continue; + if (!canHitEntityNow(entity)) continue; + + // Check if entity's bounding box intersects with the laser line + if (isEntityOnLine(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 a swept segment vs expanded AABB intercept test for reliable hits. + */ + private boolean isEntityOnLine(EntityLivingBase entity) { + AxisAlignedBB bb = entity.boundingBox; + if (bb == null) return false; + + // 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; + } + } + } + return false; + } + + @Override + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { + if (barrier == null) { + 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; + } + + 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]; + 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; + } + + /** + * 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(); + + // 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; + } + + // ==================== 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 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; + } + + public boolean isFullyExtended() { + return fullyExtended; + } + + public double getStartX() { + return startX; + } + + public double getStartY() { + return startY; + } + + public double getStartZ() { + return startZ; + } + + public double getEndX() { + return endX; + } + + public double getEndY() { + return endY; + } + + public double getEndZ() { + 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; + } + + public double getDirY() { + return dirY; + } + + public double getDirZ() { + return dirZ; + } + + @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 = sanitize(nbt.hasKey("LaserWidth") ? nbt.getFloat("LaserWidth") : 0.2f, 0.2f, MAX_ENTITY_SIZE); + 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"); + + readChargingNBT(nbt); + } + + @Override + protected void writeProjectileNBT(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); + 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); + + writeChargingNBT(nbt); + } + + /** + * Setup this laser in preview mode for GUI display. + * Uses charging-orb visuals during windup before firing. + */ + public void setupPreview(EntityLivingBase owner, float laserWidth, EnergyDisplayData display, + EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, + float expansionSpeed, float maxLength) { + setupPreviewState(owner, display, lightning, anchor, chargeDuration); + + // Laser-specific visual/behavior state. + this.laserWidth = laserWidth; + this.expansionSpeed = expansionSpeed; + this.maxLength = Math.min(maxLength, 5.0f); // Limit for GUI preview + this.desiredLength = 0.0f; + this.currentLength = 0.0f; + this.fullyExtended = false; + + // 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; + + // 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 new file mode 100644 index 000000000..07e032829 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -0,0 +1,181 @@ +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.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.world.World; + +/** + * Orb projectile - spherical homing energy ball. + * Extends EntityEnergyAbility for shared functionality. + *

+ * Design inspired by LouisXIV's energy attack system. + */ +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); + } + + /** + * Full constructor using data classes for grouped parameters. + */ + public EntityAbilityOrb(World world, EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, float orbSize, + EnergyDisplayData display, EnergyCombatData combat, + EnergyHomingData homing, EnergyLightningData lightning, + EnergyLifespanData lifespan) { + super(world); + + // Initialize base properties + initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan); + + this.homingData = homing != null ? homing.copy() : new EnergyHomingData(); + + // Calculate initial velocity toward target + calculateInitialVelocity(owner, target, x, y, z); + } + + /** + * Setup this orb in preview mode for GUI display. + * Follows anchor point and animations like in the real game. + * Can be fired when transitioning to active phase. + */ + public void setupPreview(EntityLivingBase owner, float orbSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { + setupPreviewState(owner, display, lightning, anchor, chargeDuration); + + // Store target size and start at 0 for grow effect + this.targetSize = orbSize; + setVisualSize(0.01f); + setChargeOriginFromAnchor(owner, anchorData); + clearMotion(); + } + + /** + * Start preview firing (simulates firing toward a point in front of NPC). + */ + public void startPreviewFiring() { + startPreviewFiringDefault(); + } + + /** + * Start the orb moving (exit charging mode). + * Called by ability when windup ends. + */ + public void startMoving(EntityLivingBase target) { + startMovingTowardTargetDefault(target); + } + + @Override + protected void updateProjectile() { + // Handle charging state (windup phase) + if (isCharging()) { + updateCharging(); + return; + } + + // In preview mode, run movement on client (no server) + if (previewMode) { + updatePreviewMovement(); + return; + } + + if (worldObj.isRemote) { + handleClientInterpolation(); + } else { + // Server-side logic + updateMovement(); + checkBlockCollision(); + checkEntityCollision(); + this.moveEntity(motionX, motionY, motionZ); + } + + // Check wall collision + handleSolidCollisionTermination(); + } + + /** + * Update movement in preview mode (client-side only, no damage). + */ + private void updatePreviewMovement() { + // Simple movement - just apply motion + this.posX += motionX; + this.posY += motionY; + this.posZ += motionZ; + } + + private void updateMovement() { + 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 updateHomingWithRamp(float ramp) { + if (ramp <= 0.0f) return; + float originalStrength = homingData.homingStrength; + homingData.homingStrength = originalStrength * ramp; + updateHoming(); + homingData.homingStrength = originalStrength; + } + + private void checkBlockCollision() { + handleBlockImpact(rayTraceBlocks(posX, posY, posZ, posX + motionX, posY + motionY, posZ + motionZ), true); + } + + private void checkEntityCollision() { + // 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( + 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 + ); + processEntitiesInHitBox(hitBox, nextX, nextY, nextZ); + } + + // ==================== DEBUG ==================== + + @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 ==================== + + // Legacy getter for renderer compatibility + public float getOrbSize() { + return size; + } + + // ==================== NBT ==================== + + @Override + protected void readProjectileNBT(NBTTagCompound nbt) { + readChargingNBT(nbt); + } + + @Override + protected void writeProjectileNBT(NBTTagCompound nbt) { + writeChargingNBT(nbt); + } +} 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..7913386c6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -0,0 +1,984 @@ +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 + // ═══════════════════════════════════════════════════════════════════ + + 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 = 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()); + } + } + zone.ticksSinceDamage = damageInterval; + 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) { + applyDamage(entity, owner, damagePerSecond); + } + + applyEffects(entity); + damagedThisTick.add(entity.getEntityId()); + } + } + + private boolean isInZone(EntityLivingBase entity) { + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + + switch (shape) { + case CIRCLE: + return Math.sqrt(dx * dx + dz * dz) <= radius; + case SQUARE: + return Math.abs(dx) <= radius && Math.abs(dz) <= radius; + default: + return Math.sqrt(dx * dx + dz * dz) <= radius; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // DAMAGE + // ═══════════════════════════════════════════════════════════════════ + + private boolean applyDamage(EntityLivingBase target, Entity owner, float dmg) { + if (dmg <= 0) return false; + + 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 = 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..4ccb01269 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -0,0 +1,917 @@ +package kamkeel.npcs.entity; + +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.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; + + // ==================== 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; + + // Apply magic interactions from attacker's magic vs barrier's magic + Entity attacker = source.getEntity(); + 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; + } + } + } + + // Duration check + if (barrierData.useDuration && ticksAlive >= barrierData.durationTicks) { + onBarrierDestroyed(); + this.setDead(); + return true; + } + + // Absolute hard lifetime cap (safety net for barriers with no duration) + if (ticksAlive > BARRIER_HARD_LIFETIME_CAP) { + 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.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.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..1527f644d --- /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); + } + + 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 + setProjectileSize(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/EntityEnergySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java new file mode 100644 index 000000000..263ecd36c --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java @@ -0,0 +1,474 @@ +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.EnergyDisplayData; +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.world.World; +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; +import java.util.List; +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 EntityEnergySweeper extends EntityEnergyAbility { + + // Beam properties + private float beamLength = 10.0f; + private float beamWidth = 0.3f; // Thin like beam trail + private float beamHeight = 1.0f; + + // Combat properties + private float damage = 5.0f; + private int damageInterval = 5; + private boolean piercing = true; + + // Rotation + private float currentAngle = 0; + private float prevAngle = 0; + private float sweepSpeed = 3.0f; + private int numberOfRotations = 2; + private int completedRotations = 0; + private float baseYaw = 0; // Starting yaw direction + private boolean lockOnTarget = false; + + // Target tracking + private int targetEntityId = -1; + + // Lifetime + private int maxTicks = 400; + private long deathWorldTime = -1; + + // Damage state + private transient int ticksSinceDamage = 0; + private transient Set hitThisTick = new HashSet<>(); + + public EntityEnergySweeper(World world) { + super(world); + this.setSize(0.1f, 0.1f); + this.noClip = true; + } + + 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 != null ? owner.getEntityId() : -1; + this.targetEntityId = target != null ? target.getEntityId() : -1; + this.beamLength = beamLength; + this.beamWidth = beamWidth; + this.beamHeight = beamHeight; + this.displayData = displayData != null ? displayData.copy() : new EnergyDisplayData(); + this.sweepSpeed = sweepSpeed; + this.numberOfRotations = numberOfRotations; + this.damage = damage; + this.damageInterval = damageInterval; + this.piercing = piercing; + this.lockOnTarget = lockOnTarget; + + // Calculate max ticks based on rotations + this.maxTicks = (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10; + + // Calculate base yaw + 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 if (owner != null) { + this.baseYaw = owner.rotationYaw; + } + + // 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; + } + + @Override + protected void entityInit() { + super.entityInit(); + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.prevAngle = this.currentAngle; + + super.onUpdate(); + + // Set death time on first tick + if (deathWorldTime < 0 && worldObj != null) { + deathWorldTime = worldObj.getTotalWorldTime() + maxTicks; + } + + // Check lifetime + if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { + this.setDead(); + return; + } + + // Absolute hard lifetime cap (safety net) + if (ticksExisted > HARD_LIFETIME_CAP) { + this.setDead(); + return; + } + + 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) { + this.setDead(); + return; + } + + // Update rotation + currentAngle += sweepSpeed; + while (currentAngle >= 360) { + currentAngle -= 360; + completedRotations++; + } + + // 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)); + } + } + } + + /** + * Handle damage detection and application. + * This runs on server only. + */ + private void handleDamage(Entity owner) { + hitThisTick.clear(); + ticksSinceDamage++; + + if (ticksSinceDamage < damageInterval) { + return; + } + ticksSinceDamage = 0; + + // Calculate beam direction using the ACTUAL render angle + float beamYaw = baseYaw + currentAngle; + float yawRad = (float) Math.toRadians(beamYaw); + + double startX = posX; + double startY = posY; + double startZ = posZ; + + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); + + // Sample points along the beam for collision + int samples = (int) (beamLength / 0.5); + for (int i = 1; i <= samples; i++) { + double progress = (double) i / samples; + double checkX = startX + dirX * beamLength * progress; + double checkY = startY; + double checkZ = startZ + dirZ * beamLength * progress; + + // Hitbox: beam center ± half-height vertically, generous width for thin beams + AxisAlignedBB checkBox = AxisAlignedBB.getBoundingBox( + checkX - beamWidth * 2, checkY - beamHeight / 2.0, checkZ - beamWidth * 2, + checkX + beamWidth * 2, checkY + beamHeight / 2.0, checkZ + beamWidth * 2 + ); + + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, checkBox); + + for (Entity entity : entities) { + 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; + + // Check if actually in beam path + if (isInBeamPath(livingEntity, startX, startY, startZ, dirX, dirZ)) { + hitThisTick.add(entity.getEntityId()); + applyDamage(livingEntity, owner); + + if (!piercing) { + return; + } + } + } + } + } + + private boolean isInBeamPath(EntityLivingBase entity, double startX, double startY, double startZ, + double dirX, double dirZ) { + double entityX = entity.posX - startX; + double entityZ = entity.posZ - startZ; + + // Dot product to find projection distance + double projectionDist = entityX * dirX + entityZ * dirZ; + + // Check if within beam length + if (projectionDist < 0 || projectionDist > beamLength) { + return false; + } + + // Calculate perpendicular distance + double projX = dirX * projectionDist; + double projZ = dirZ * projectionDist; + double perpX = entityX - projX; + double perpZ = entityZ - projZ; + double perpDist = Math.sqrt(perpX * perpX + perpZ * perpZ); + + // Check if within beam width (use wider hitbox than visual) + if (perpDist > beamWidth * 3 + entity.width / 2) { + return false; + } + + // Height check - entity must overlap beam vertically + double beamTopY = startY + beamHeight / 2.0; + double beamBottomY = startY - beamHeight / 2.0; + double entityFeetY = entity.posY; + double entityTopY = entity.posY + entity.height; + + // 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) { + 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 + target.addVelocity(0, 0.2, 0); + target.velocityChanged = true; + } + + /** + * Set up preview mode. Owner is stored directly since world entity lookup won't work. + */ + public void setupPreview(EntityLivingBase owner) { + this.previewMode = true; + this.previewOwner = owner; + } + + // ==================== RENDERING ==================== + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + return distance < 16384.0D; // 128 blocks squared + } + + // ==================== GETTERS FOR RENDERER ==================== + + public float getBeamLength() { + return beamLength; + } + + public float getBeamWidth() { + return beamWidth; + } + + public float getBeamHeight() { + return beamHeight; + } + + /** + * Get the full interpolated angle INCLUDING base yaw for rendering. + */ + public float getInterpolatedAngle(float partialTicks) { + // Handle wrap-around for the rotating part + float diff = currentAngle - prevAngle; + if (diff > 180) diff -= 360; + if (diff < -180) diff += 360; + float interpAngle = prevAngle + diff * partialTicks; + // Add base yaw for correct world orientation + return baseYaw + interpAngle; + } + + public float getCurrentAngle() { + return currentAngle; + } + + public float getBaseYaw() { + 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 writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + nbt.setFloat("BeamLength", beamLength); + nbt.setFloat("BeamWidth", beamWidth); + nbt.setFloat("BeamHeight", beamHeight); + nbt.setFloat("SweepSpeed", sweepSpeed); + nbt.setInteger("NumRotations", numberOfRotations); + nbt.setInteger("CompletedRotations", completedRotations); + nbt.setInteger("MaxTicks", maxTicks); + nbt.setInteger("TargetId", targetEntityId); + nbt.setFloat("CurrentAngle", currentAngle); + nbt.setFloat("BaseYaw", baseYaw); + nbt.setLong("DeathWorldTime", deathWorldTime); + nbt.setFloat("Damage", damage); + nbt.setInteger("DamageInterval", damageInterval); + nbt.setBoolean("Piercing", piercing); + nbt.setBoolean("LockOnTarget", lockOnTarget); + } + + @Override + 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 745962aba..c0616e89c 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -8,24 +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.gui.GuiClosePacket; import kamkeel.npcs.network.packets.data.gui.GuiErrorPacket; import kamkeel.npcs.network.packets.data.gui.GuiOpenBookPacket; @@ -49,18 +36,32 @@ 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; import kamkeel.npcs.network.packets.player.DialogSelectPacket; 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.MailActionPacket; import kamkeel.npcs.network.packets.player.SaveBookPacket; import kamkeel.npcs.network.packets.player.SaveSignPacket; import kamkeel.npcs.network.packets.player.ScreenSizePacket; import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket; +import kamkeel.npcs.network.packets.player.SyncRevisionInfoPacket; import kamkeel.npcs.network.packets.player.TransportPacket; import kamkeel.npcs.network.packets.player.customgui.CustomGuiButtonPacket; import kamkeel.npcs.network.packets.player.customgui.CustomGuiClosePacket; @@ -72,7 +73,6 @@ import kamkeel.npcs.network.packets.player.item.MagicCyclesPacket; import kamkeel.npcs.network.packets.player.profile.ProfileChangePacket; import kamkeel.npcs.network.packets.player.profile.ProfileCreatePacket; import kamkeel.npcs.network.packets.player.profile.ProfileGetInfoPacket; -import kamkeel.npcs.network.packets.player.SyncRevisionInfoPacket; import kamkeel.npcs.network.packets.player.profile.ProfileGetPacket; import kamkeel.npcs.network.packets.player.profile.ProfileRemovePacket; import kamkeel.npcs.network.packets.player.profile.ProfileRenamePacket; @@ -85,17 +85,42 @@ import kamkeel.npcs.network.packets.request.MountPacket; import kamkeel.npcs.network.packets.request.TileEntityGetPacket; import kamkeel.npcs.network.packets.request.TileEntitySavePacket; 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.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.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; import kamkeel.npcs.network.packets.request.bank.BanksGetPacket; 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.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; @@ -113,6 +138,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; @@ -133,6 +159,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; @@ -211,6 +238,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; @@ -218,6 +247,7 @@ import kamkeel.npcs.network.packets.request.script.GlobalNPCScriptPacket; import kamkeel.npcs.network.packets.request.script.NPCScriptPacket; import kamkeel.npcs.network.packets.request.script.PlayerScriptPacket; import kamkeel.npcs.network.packets.request.script.RecipeScriptPacket; +import kamkeel.npcs.network.packets.request.script.ScriptFilesPacket; import kamkeel.npcs.network.packets.request.script.ScriptInfoPacket; import kamkeel.npcs.network.packets.request.script.item.ItemScriptErrorPacket; import kamkeel.npcs.network.packets.request.script.item.ItemScriptPacket; @@ -298,7 +328,10 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new NPCScriptPacket()); REQUEST_PACKET.registerPacket(new PlayerScriptPacket()); 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()); @@ -310,6 +343,9 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new CloneTagListPacket()); REQUEST_PACKET.registerPacket(new CloneAllTagsPacket()); REQUEST_PACKET.registerPacket(new CloneAllTagsShortPacket()); + REQUEST_PACKET.registerPacket(new CloneFolderListPacket()); + REQUEST_PACKET.registerPacket(new CloneFolderCrudPacket()); + REQUEST_PACKET.registerPacket(new CloneMovePacket()); // Linked Packets @@ -321,6 +357,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 @@ -452,6 +489,7 @@ public class PacketHandler { // Trader Packets REQUEST_PACKET.registerPacket(new TraderMarketSavePacket()); + REQUEST_PACKET.registerPacket(new ManageAuctionPacket()); // Party Packets moved to player channel @@ -460,6 +498,7 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new AnimationGetPacket()); REQUEST_PACKET.registerPacket(new AnimationRemovePacket()); REQUEST_PACKET.registerPacket(new AnimationSavePacket()); + REQUEST_PACKET.registerPacket(new BuiltInAnimationGetPacket()); // Moving Path REQUEST_PACKET.registerPacket(new MovingPathSavePacket()); @@ -475,6 +514,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()); @@ -486,6 +526,30 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new MagicNpcGetPacket()); REQUEST_PACKET.registerPacket(new MagicNpcSavePacket()); + // Ability Packets + REQUEST_PACKET.registerPacket(new AbilitiesGetAllPacket()); + REQUEST_PACKET.registerPacket(new AbilitiesNpcGetPacket()); + REQUEST_PACKET.registerPacket(new AbilitiesNpcSavePacket()); + REQUEST_PACKET.registerPacket(new CustomAbilitiesGetPacket()); + 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()); + + // 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()); REQUEST_PACKET.registerPacket(new GuiRequestPacket()); @@ -550,6 +614,20 @@ public class PacketHandler { DATA_PACKET.registerPacket(new SyncEffectPacket()); DATA_PACKET.registerPacket(new GuiDataPacket()); DATA_PACKET.registerPacket(new PartyDataPacket()); + + // 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() { @@ -572,6 +650,10 @@ public class PacketHandler { PLAYER_PACKET.registerPacket(new CompanionActionPacket()); PLAYER_PACKET.registerPacket(new GetNPCRole()); + PLAYER_PACKET.registerPacket(new GetTraderData()); + + // Auction Packets + PLAYER_PACKET.registerPacket(new AuctionActionPacket()); PLAYER_PACKET.registerPacket(new InputDevicePacket()); @@ -611,6 +693,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/PacketUtil.java b/src/main/java/kamkeel/npcs/network/PacketUtil.java index f262bce45..9235dc1f7 100644 --- a/src/main/java/kamkeel/npcs/network/PacketUtil.java +++ b/src/main/java/kamkeel/npcs/network/PacketUtil.java @@ -15,6 +15,7 @@ import noppes.npcs.NBTTags; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.IScriptHandler; +import noppes.npcs.controllers.data.IScriptUnit; import noppes.npcs.items.ItemNpcTool; import java.io.IOException; @@ -221,9 +222,9 @@ public class PacketUtil { compound.setTag("Languages", ScriptController.Instance.nbtLanguages()); compound.setTag("ScriptConsole", NBTTags.NBTLongStringMap(data.getConsoleText())); GuiDataPacket.sendGuiData(player, compound); - List containers = data.getScripts(); + List containers = data.getScripts(); for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); + IScriptUnit container = containers.get(i); NBTTagCompound tabCompound = new NBTTagCompound(); tabCompound.setInteger("Tab", i); tabCompound.setTag("Script", container.writeToNBT(new NBTTagCompound())); @@ -250,8 +251,8 @@ public class PacketUtil { data.getScripts().add(new ScriptContainer(data)); } NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer); - ScriptContainer script = new ScriptContainer(data); - script.readFromNBT(tabCompound); + // Use factory method to create correct script unit type based on NBT + IScriptUnit script = IScriptUnit.createFromNBT(tabCompound, data); data.getScripts().set(tab, script); } else { NBTTagCompound compound = ByteBufUtils.readNBT(buffer); diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index 874677af9..1a24ac2ef 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -58,4 +58,31 @@ public enum EnumDataPacket { SWING_PLAYER_ARM, DISABLE_MOUSE_INPUT, LOGIN, + + // Ability System + TELEGRAPH_SPAWN, + TELEGRAPH_REMOVE, + PLAYER_ABILITY_SYNC, + PLAYER_ABILITY_STATE, + ABILITY_HOTBAR_SYNC, + ABILITY_COOLDOWN_SYNC, + + // 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 0c1db3cd9..e1587467b 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java @@ -13,6 +13,7 @@ public enum EnumPlayerPacket { SaveBook, CompanionAction, GetRole, + GetTraderData, InputDevice, SpecialKeyState, ScreenSize, @@ -33,4 +34,12 @@ public enum EnumPlayerPacket { ProfileGet, ProfileGetInfo, SyncRevisionInfo, + + // 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 0159fe719..c76e5adb9 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, + BuiltInAnimationGet, RemoteNpcsGet, RemoteTpToNpc, @@ -162,6 +163,9 @@ public enum EnumRequestPacket { CloneAllTags, CloneAllTagsShort, ClonePreSave, + CloneFolderList, + CloneFolderCrud, + CloneMove, EventScript, PlayerScript, @@ -172,6 +176,7 @@ public enum EnumRequestPacket { BlockScript, NPCScript, ScriptInfo, + ScriptFiles, EffectScript, DimensionTeleport, @@ -193,7 +198,34 @@ public enum EnumRequestPacket { MagicSave, NpcMagicGet, NpcMagicSave, + NpcAbilitiesGet, + NpcAbilitiesSave, + AbilitiesGetAll, + CustomAbilitiesGet, + CustomAbilityGet, + CustomAbilityRemove, + CustomAbilitySave, + BuiltInAbilityGet, + ChainedAbilitiesGet, + ChainedAbilityGet, + ChainedAbilitySave, + ChainedAbilityRemove, Hammer, RecipeScript, + ManageAuctionAction, + AbilityScript, + ChainedAbilityScript, + + CategorySave, + CategoryRemove, + CategoryMoveItem, + CategoryListRequest, + CategoryItemsRequest, + AbilityCategoryMoveItem, + + CustomAbilityClone, + ChainedAbilityClone, + LinkedItemClone, + EffectClone, } diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java b/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java index a84e62392..ee6cf352f 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumSyncType.java @@ -12,5 +12,7 @@ public enum EnumSyncType { WORKBENCH_RECIPES, CARPENTRY_RECIPES, ANVIL_RECIPES, - CUSTOM_EFFECTS + CUSTOM_EFFECTS, + CUSTOM_ABILITY, + CHAINED_ABILITY } 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 c341bd02e..da9eb9aa2 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java @@ -12,8 +12,13 @@ import kamkeel.npcs.network.enums.EnumSyncType; 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.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; @@ -57,6 +62,16 @@ public final class LoginPacket extends AbstractPacket { 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); } @SideOnly(Side.CLIENT) @@ -76,6 +91,14 @@ public final class LoginPacket extends AbstractPacket { 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); + PacketClient.sendClient(new SyncRevisionInfoPacket( serverKey, ClientCacheHandler.getLastServerKey(), 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 new file mode 100644 index 000000000..2353623b2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilitySyncPacket.java @@ -0,0 +1,74 @@ +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 net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +/** + * Syncs the player's ability data (unlocked abilities, selected index) to the client. + * Sent on login and whenever abilities change (unlock/lock/select). + */ +public final class PlayerAbilitySyncPacket extends AbstractPacket { + public static final String packetName = "Data|PlayerAbilitySync"; + + private NBTTagCompound abilityNBT; + + public PlayerAbilitySyncPacket() { + } + + public PlayerAbilitySyncPacket(NBTTagCompound abilityNBT) { + this.abilityNBT = abilityNBT; + } + + @Override + public Enum getType() { + return EnumDataPacket.PLAYER_ABILITY_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, abilityNBT); + } + + @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.abilityData.readFromNBT(nbt); + } + } + + /** + * Send the player's ability data to their client. + */ + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + NBTTagCompound nbt = new NBTTagCompound(); + data.abilityData.writeToNBT(nbt); + PacketHandler.Instance.sendToPlayer(new PlayerAbilitySyncPacket(nbt), player); + } +} 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/telegraph/TelegraphRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/data/telegraph/TelegraphRemovePacket.java new file mode 100644 index 000000000..9e84bb224 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/telegraph/TelegraphRemovePacket.java @@ -0,0 +1,84 @@ +package kamkeel.npcs.network.packets.data.telegraph; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; +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 java.io.IOException; + +/** + * Packet to remove a telegraph on the client. + * Sent from server to client when a telegraph should be removed early. + */ +public final class TelegraphRemovePacket extends AbstractPacket { + public static final String packetName = "Data|TelegraphRemove"; + + private String instanceId; + + public TelegraphRemovePacket() { + } + + public TelegraphRemovePacket(String instanceId) { + this.instanceId = instanceId; + } + + @Override + public Enum getType() { + return EnumDataPacket.TELEGRAPH_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 && TelegraphManager.ClientInstance != null) { + TelegraphManager.ClientInstance.removeTelegraph(id); + } + } + + /** + * Send remove to a specific player. + */ + public static void send(String instanceId, EntityPlayerMP player) { + PacketHandler.Instance.sendToPlayer(new TelegraphRemovePacket(instanceId), player); + } + + /** + * Send remove to all players tracking an entity (within range). + */ + public static void sendToTracking(String instanceId, net.minecraft.entity.Entity entity) { + PacketHandler.Instance.sendTracking(new TelegraphRemovePacket(instanceId), entity); + } + + /** + * Send remove to all players in a dimension. + */ + public static void sendToDimension(String instanceId, int dimensionId) { + PacketHandler.Instance.sendToDimension(new TelegraphRemovePacket(instanceId), dimensionId); + } + + /** + * Send remove to all players on the server. + */ + public static void sendToAll(String instanceId) { + PacketHandler.Instance.sendToAll(new TelegraphRemovePacket(instanceId)); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/telegraph/TelegraphSpawnPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/telegraph/TelegraphSpawnPacket.java new file mode 100644 index 000000000..fa30229ce --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/telegraph/TelegraphSpawnPacket.java @@ -0,0 +1,88 @@ +package kamkeel.npcs.network.packets.data.telegraph; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; +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 java.io.IOException; + +/** + * Packet to spawn a telegraph on the client. + * Sent from server to client when a telegraph is created. + */ +public final class TelegraphSpawnPacket extends AbstractPacket { + public static final String packetName = "Data|TelegraphSpawn"; + + private NBTTagCompound telegraphNBT; + + public TelegraphSpawnPacket() { + } + + public TelegraphSpawnPacket(TelegraphInstance instance) { + this.telegraphNBT = instance.writeNBT(); + } + + @Override + public Enum getType() { + return EnumDataPacket.TELEGRAPH_SPAWN; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, telegraphNBT); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt != null && TelegraphManager.ClientInstance != null) { + TelegraphInstance instance = new TelegraphInstance(); + instance.readNBT(nbt); + TelegraphManager.ClientInstance.addTelegraph(instance); + } + } + + /** + * Send telegraph to a specific player. + */ + public static void send(TelegraphInstance instance, EntityPlayerMP player) { + PacketHandler.Instance.sendToPlayer(new TelegraphSpawnPacket(instance), player); + } + + /** + * Send telegraph to all players tracking an entity (within range). + */ + public static void sendToTracking(TelegraphInstance instance, net.minecraft.entity.Entity entity) { + PacketHandler.Instance.sendTracking(new TelegraphSpawnPacket(instance), entity); + } + + /** + * Send telegraph to all players in a dimension. + */ + public static void sendToDimension(TelegraphInstance instance, int dimensionId) { + PacketHandler.Instance.sendToDimension(new TelegraphSpawnPacket(instance), dimensionId); + } + + /** + * Send telegraph to all players on the server. + */ + public static void sendToAll(TelegraphInstance instance) { + PacketHandler.Instance.sendToAll(new TelegraphSpawnPacket(instance)); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java new file mode 100644 index 000000000..cf0fb3a36 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/AuctionActionPacket.java @@ -0,0 +1,539 @@ +package kamkeel.npcs.network.packets.player; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.network.packets.data.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.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; +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.List; + +/** + * Handles all auction-related client-server communication. + */ +public class AuctionActionPacket extends AbstractPacket { + public static final String packetName = "Player|Auction"; + private static final int PAGE_SIZE = 45; // 9x5 grid + + private Action action; + private String listingId; + private long amount; + private NBTTagCompound data; + + public AuctionActionPacket() { + } + + private AuctionActionPacket(Action action) { + this.action = action; + } + + private AuctionActionPacket(Action action, String listingId) { + this.action = action; + this.listingId = listingId; + } + + private AuctionActionPacket(Action action, String listingId, long amount) { + this.action = action; + this.listingId = listingId; + this.amount = amount; + } + + @Override + public boolean needsNPC() { + return false; + } // Allow opening via command without NPC + + // ========================================= + // Client-side static methods + // ========================================= + + @SideOnly(Side.CLIENT) + public static void placeBid(String listingId, long bidAmount) { + AuctionActionPacket packet = new AuctionActionPacket(Action.Bid, listingId, bidAmount); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void buyout(String listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.Buyout, listingId); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void cancelListing(String listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.Cancel, listingId); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void claimItem(String claimId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.ClaimItem, claimId); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void claimCurrency(String claimId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.ClaimCurrency, claimId); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void createListing(ItemStack item, long startingPrice, long buyoutPrice) { + AuctionActionPacket packet = new AuctionActionPacket(Action.CreateListing); + packet.amount = startingPrice; + packet.listingId = String.valueOf(buyoutPrice); + packet.data = new NBTTagCompound(); + item.writeToNBT(packet.data); + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void openPage(int page) { + AuctionActionPacket packet = new AuctionActionPacket(Action.OpenPage); + packet.amount = page; + PacketClient.sendClient(packet); + } + + @SideOnly(Side.CLIENT) + public static void openBidding(String listingId) { + AuctionActionPacket packet = new AuctionActionPacket(Action.OpenBidding, listingId); + PacketClient.sendClient(packet); + } + + /** + * 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); + packet.amount = page; + packet.data = filter.writeToNBT(new NBTTagCompound()); + PacketClient.sendClient(packet); + } + + // ========================================= + // Packet Implementation + // ========================================= + + @Override + public Enum getType() { + return EnumPlayerPacket.AuctionAction; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + @SideOnly(Side.CLIENT) + public void sendData(ByteBuf out) throws IOException { + out.writeInt(action.ordinal()); + + switch (action) { + case Bid: + ByteBufUtils.writeString(out, listingId); + out.writeLong(amount); + break; + case Buyout: + case Cancel: + case ClaimItem: + case ClaimCurrency: + ByteBufUtils.writeString(out, listingId); + break; + case CreateListing: + out.writeLong(amount); + ByteBufUtils.writeString(out, listingId); + ByteBufUtils.writeNBT(out, data); + break; + case OpenPage: + out.writeInt((int) amount); + break; + case OpenBidding: + ByteBufUtils.writeString(out, listingId); + break; + case RequestListings: + out.writeInt((int) amount); + ByteBufUtils.writeNBT(out, data); + break; + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) return; + EntityPlayerMP playerMP = (EntityPlayerMP) player; + + // Skip role check if NPC is null (opened via command/script) + // Otherwise require Auctioneer role + if (npc != null && npc.advanced.role != EnumRoleType.Auctioneer) return; + if (!ConfigMarket.AuctionEnabled) return; + + int actionOrdinal = in.readInt(); + if (actionOrdinal < 0 || actionOrdinal >= Action.values().length) { + return; // Invalid action + } + 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 Bid: + result = handleBid(in, playerMP, controller); + break; + + case Buyout: + result = handleBuyout(in, playerMP, controller); + break; + + case Cancel: + result = handleCancel(in, playerMP, controller); + break; + + case ClaimItem: + result = handleClaimItem(in, playerMP, controller); + break; + + case ClaimCurrency: + result = handleClaimCurrency(in, playerMP, controller); + break; + + case CreateListing: + result = handleCreateListing(in, playerMP, controller); + break; + + case OpenPage: + handleOpenPage(in, playerMP); + break; + + case OpenBidding: + handleOpenBidding(in, playerMP, controller); + break; + + case RequestListings: + handleRequestListings(in, playerMP, controller); + break; + } + + if (result != null) { + sendError(playerMP, result); + } + } + + // ========================================= + // Action Handlers + // ========================================= + + private String handleBid(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String id = ByteBufUtils.readString(in); + long amount = in.readLong(); + String result = controller.placeBid(id, player, amount); + if (result == null) { + sendListingsUpdate(player); + } + return result; + } + + private String handleBuyout(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String id = ByteBufUtils.readString(in); + String result = controller.buyout(id, player); + if (result == null) { + sendListingsUpdate(player); + } + return result; + } + + private String handleCancel(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String id = ByteBufUtils.readString(in); + String result = controller.cancelListing(id, player, false); + if (result == null) { + sendTradesUpdate(player); + } + return result; + } + + private String handleClaimItem(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String id = ByteBufUtils.readString(in); + String result = controller.claimItem(id, player); + if (result == null) { + sendTradesUpdate(player); + } + return result; + } + + private String handleClaimCurrency(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + String id = ByteBufUtils.readString(in); + String result = controller.claimCurrency(id, player); + if (result == null) { + sendTradesUpdate(player); + } + return result; + } + + private String handleCreateListing(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + long startingPrice = in.readLong(); + String buyoutStr = ByteBufUtils.readString(in); + long buyoutPrice = 0; + try { + buyoutPrice = Long.parseLong(buyoutStr); + } catch (NumberFormatException ignored) { + } + + 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."; + + // 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."; + } + + String result = controller.createListing(player, item, startingPrice, buyoutPrice); + if (result != null) { + // Failed - return item (drop if inventory full to prevent item loss) + if (!player.inventory.addItemStackToInventory(item)) { + player.entityDropItem(item, 0.5f); + } + } + return result; + } + + private void handleOpenPage(ByteBuf in, EntityPlayerMP player) { + int page = in.readInt(); + EnumAuctionPage auctionPage = EnumAuctionPage.fromOrdinal(page); + EnumGuiType guiType = auctionPage.getGuiType(); + NoppesUtilServer.sendOpenGui(player, guiType, npc); + + // Send trades data when opening the trades page + if (page == 2) { + AuctionController controller = AuctionController.getInstance(); + if (controller != null) { + sendTradesData(player, controller); + } + } + } + + /** + * Send full trades data to player (listings, bids, claims) + */ + private void sendTradesData(EntityPlayerMP player, AuctionController controller) { + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("TradesData", true); + + // Send player's max trade slots (permission-aware) + response.setInteger("MaxTradeSlots", controller.getMaxTradesForPlayer(player)); + + // Active listings (items player is selling) + List listings = controller.getPlayerActiveListings(player.getUniqueID()); + NBTTagList listingsNBT = new NBTTagList(); + for (AuctionListing listing : listings) { + listingsNBT.appendTag(listing.writeToNBT(new NBTTagCompound())); + } + response.setTag("ActiveListings", listingsNBT); + + // Active bids (items player is bidding on) + List bids = controller.getPlayerActiveBids(player.getUniqueID()); + NBTTagList bidsNBT = new NBTTagList(); + for (AuctionListing bid : bids) { + bidsNBT.appendTag(bid.writeToNBT(new NBTTagCompound())); + } + response.setTag("ActiveBids", bidsNBT); + + // Claims (items/currency to claim) - now from PlayerData + List claims = controller.getPlayerClaims(player); + NBTTagList claimsNBT = new NBTTagList(); + for (AuctionClaim claim : claims) { + claimsNBT.appendTag(claim.writeToNBT(new NBTTagCompound())); + } + response.setTag("Claims", claimsNBT); + + GuiDataPacket.sendGuiData(player, response); + } + + 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; + } + + // Open bidding GUI + NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuctionBidding, npc); + + // Check if this is the player's own listing + boolean isOwnListing = listing.isSeller(player.getUniqueID()); + + // Send listing data + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("BiddingData", true); + response.setTag("Listing", listing.writeToNBT(new NBTTagCompound())); + response.setLong("Balance", controller.getPlayerBalance(player)); + response.setBoolean("IsOwnListing", isOwnListing); + GuiDataPacket.sendGuiData(player, response); + } + + private void handleRequestListings(ByteBuf in, EntityPlayerMP player, AuctionController controller) throws IOException { + int page = in.readInt(); + NBTTagCompound filterNBT = ByteBufUtils.readNBT(in); + + AuctionFilter filter = new AuctionFilter(); + if (filterNBT != null) { + filter.readFromNBT(filterNBT); + } + + // Get listings for this page + List listings = controller.getActiveListings(filter, page, PAGE_SIZE); + int totalListings = controller.getTotalActiveListings(filter); + int totalPages = Math.max(1, (int) Math.ceil((double) totalListings / PAGE_SIZE)); + + // Build response + NBTTagCompound response = new NBTTagCompound(); + response.setBoolean("ListingsData", true); + response.setInteger("Page", page); + response.setInteger("TotalPages", totalPages); + response.setInteger("TotalListings", totalListings); + + NBTTagList listingsList = new NBTTagList(); + for (AuctionListing listing : listings) { + listingsList.appendTag(listing.writeToNBT(new NBTTagCompound())); + } + response.setTag("Listings", listingsList); + + GuiDataPacket.sendGuiData(player, response); + } + + // ========================================= + // Helpers + // ========================================= + + /** + * 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); + } + + /** + * Counts total matching items across all inventory stacks. + */ + 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; + + // First verify player has enough total items + int available = countItemsInInventory(player, target); + if (available < needed) { + return false; + } + + // Consume items from matching stacks + 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) { + // Need entire stack + needed -= stack.stackSize; + player.inventory.mainInventory[i] = null; + } else { + // Need only part of stack + stack.splitStack(needed); + if (stack.stackSize <= 0) { + player.inventory.setInventorySlotContents(i, null); + } + needed = 0; + } + } + + player.inventory.markDirty(); + return true; + } + + private void sendError(EntityPlayerMP player, String message) { + player.addChatMessage(new net.minecraft.util.ChatComponentText( + net.minecraft.util.EnumChatFormatting.RED + "[Auction] " + message)); + } + + private void sendTradesUpdate(EntityPlayerMP player) { + // Send full trades data to refresh the client + AuctionController controller = AuctionController.getInstance(); + if (controller != null) { + sendTradesData(player, controller); + } + } + + private void sendListingsUpdate(EntityPlayerMP player) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setBoolean("ListingsRefresh", true); + GuiDataPacket.sendGuiData(player, compound); + } + + private enum Action { + Bid, + Buyout, + Cancel, + ClaimItem, + ClaimCurrency, + CreateListing, + OpenPage, + OpenBidding, + RequestListings + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/GetTraderData.java b/src/main/java/kamkeel/npcs/network/packets/player/GetTraderData.java new file mode 100644 index 000000000..a04628962 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/GetTraderData.java @@ -0,0 +1,77 @@ +package kamkeel.npcs.network.packets.player; + +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.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.roles.RoleTrader; + +import java.io.IOException; + +/** + * Client requests trader-specific GUI data from server. + * Server responds with player balance, stock info, currency costs via GuiDataPacket. + */ +public class GetTraderData extends AbstractPacket { + public static final String packetName = "Player|GetTraderData"; + + @Override + public Enum getType() { + return EnumPlayerPacket.GetTraderData; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public boolean needsNPC() { + return true; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + // No data needed for request + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!(npc.roleInterface instanceof RoleTrader)) + return; + + RoleTrader role = (RoleTrader) npc.roleInterface; + NBTTagCompound compound = new NBTTagCompound(); + + // Player balance + PlayerData data = PlayerData.get(player); + compound.setLong("Balance", data.tradeData.getBalance()); + + // Stock info + compound.setBoolean("StockEnabled", role.stock.enableStock); + compound.setLong("ResetTimeMillis", role.getResetTimeRemainingMillis()); + + // Available stock per slot (player-specific if perPlayer mode) + String playerName = player.getCommandSenderName(); + int[] stock = new int[18]; + for (int i = 0; i < 18; i++) { + stock[i] = role.getAvailableStock(i, playerName); + } + compound.setIntArray("Stock", stock); + + // Currency cost per slot + for (int i = 0; i < 18; i++) { + compound.setLong("Cost" + i, role.getCurrencyCost(i)); + } + + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} 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 3b9f56690..3592e1a9a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -54,7 +54,23 @@ public final class SpecialKeyStatePacket extends AbstractPacket { PlayerData data = PlayerDataController.Instance.getPlayerData((EntityPlayerMP) player); if (data != null) { + boolean wasDown = data.isSpecialKeyDown(); data.setSpecialKeyDown(keyDown); + + // Trigger ability activation or cancel on key press (rising edge) + if (keyDown && !wasDown) { + // Don't activate if player is riding an entity (mount) + if (player.ridingEntity != null) { + return; + } + + // 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/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..ba97769a0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java @@ -0,0 +1,60 @@ +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 { + int index = data.abilityData.getUnlockedAbilityList().indexOf(key); + if (index >= 0) { + data.abilityData.setSelectedIndex(index); + } + } + 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 new file mode 100644 index 000000000..bf2e4efb4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesGetAllPacket.java @@ -0,0 +1,49 @@ +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; + +public class AbilitiesGetAllPacket extends AbstractPacket { + + public static String packetName = "Request|AbilitiesGetAll"; + + public AbilitiesGetAllPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.AbilitiesGetAll; + } + + @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.sendAbilityTypesInfo((EntityPlayerMP) player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcGetPacket.java new file mode 100644 index 000000000..3ca2f59e1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcGetPacket.java @@ -0,0 +1,54 @@ +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 kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +import java.io.IOException; + +public final class AbilitiesNpcGetPacket extends AbstractPacket { + public static final String packetName = "Request|NpcAbilitiesGet"; + + public AbilitiesNpcGetPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.NpcAbilitiesGet; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public boolean needsNPC() { + return true; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.WAND)) + return; + + NBTTagCompound compound = new NBTTagCompound(); + npc.abilities.writeToNBT(compound); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} 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 new file mode 100644 index 000000000..531e6351d --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/AbilitiesNpcSavePacket.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.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.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; + +import java.io.IOException; + +public final class AbilitiesNpcSavePacket extends AbstractPacket { + public static final String packetName = "Request|NpcAbilitiesSave"; + + private NBTTagCompound abilitiesData; + + public AbilitiesNpcSavePacket() { + } + + public AbilitiesNpcSavePacket(NBTTagCompound abilitiesData) { + this.abilitiesData = abilitiesData; + } + + @Override + public Enum getType() { + return EnumRequestPacket.NpcAbilitiesSave; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public boolean needsNPC() { + return true; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.NPC_ADVANCED_ABILITIES; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + NBTTagCompound compound = new NBTTagCompound(); + if (abilitiesData != null) { + compound = abilitiesData; + } + ByteBufUtils.writeNBT(out, compound); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.WAND)) + 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/CustomAbilitiesGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java new file mode 100644 index 000000000..6097c7483 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java @@ -0,0 +1,52 @@ +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 custom ability preset UUIDs/names. + */ +public final class CustomAbilitiesGetPacket extends AbstractPacket { + public static String packetName = "Request|CustomAbilitiesGet"; + + public CustomAbilitiesGetPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CustomAbilitiesGet; + } + + @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.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 new file mode 100644 index 000000000..b0556926a --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.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.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 custom ability by name. + */ +public final class CustomAbilityGetPacket extends AbstractPacket { + public static String packetName = "Request|CustomAbilityGet"; + + private String name; + + public CustomAbilityGetPacket() { + } + + public CustomAbilityGetPacket(String name) { + this.name = name; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CustomAbilityGet; + } + + @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 abilityName = ByteBufUtils.readString(in); + Ability ability = AbilityController.Instance.getCustomAbility(abilityName); + if (ability != null) { + 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 new file mode 100644 index 000000000..ae65c374f --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityRemovePacket.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 custom ability by name. + */ +public final class CustomAbilityRemovePacket extends AbstractPacket { + public static String packetName = "Request|CustomAbilityRemove"; + + private String name; + + public CustomAbilityRemovePacket() { + } + + public CustomAbilityRemovePacket(String name) { + this.name = name; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CustomAbilityRemove; + } + + @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 id = ByteBufUtils.readString(in); + AbilityController.Instance.deleteCustomAbility(id); + NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); + } +} 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 new file mode 100644 index 000000000..8c075bb25 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java @@ -0,0 +1,78 @@ +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 noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.NoppesUtilServer; + +import java.io.IOException; + +/** + * Request packet to save a custom ability preset. + */ +public final class CustomAbilitySavePacket extends AbstractPacket { + public static String packetName = "Request|CustomAbilitySave"; + + private NBTTagCompound abilityNBT; + + public CustomAbilitySavePacket() { + } + + public CustomAbilitySavePacket(NBTTagCompound abilityNBT) { + this.abilityNBT = abilityNBT; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CustomAbilitySave; + } + + @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, abilityNBT); + } + + @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; + Ability ability = AbilityController.Instance.fromNBT(compound); + if (ability != null) { + AbilityController.Instance.saveCustomAbility(ability); + NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); + NBTTagCompound responseNbt = ability.writeNBT(false); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, responseNbt); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationsGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationsGetPacket.java index a2bc51d0a..39b60a40f 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationsGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/animation/AnimationsGetPacket.java @@ -44,5 +44,6 @@ public final class AnimationsGetPacket extends AbstractPacket { return; NoppesUtilServer.sendAnimationDataAll((EntityPlayerMP) player); + NoppesUtilServer.sendBuiltInAnimationData((EntityPlayerMP) player); } } 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 new file mode 100644 index 000000000..d25935892 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/animation/BuiltInAnimationGetPacket.java @@ -0,0 +1,71 @@ +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 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.AnimationController; +import noppes.npcs.controllers.data.BuiltInAnimation; + +import java.io.IOException; + +/** + * Packet to request a built-in animation by name. + * Built-in animations don't have IDs, so we fetch by name. + */ +public final class BuiltInAnimationGetPacket extends AbstractPacket { + public static String packetName = "Request|BuiltInAnimationGet"; + + private String animationName; + + public BuiltInAnimationGetPacket() { + } + + public BuiltInAnimationGetPacket(String animationName) { + this.animationName = animationName; + } + + @Override + public Enum getType() { + return EnumRequestPacket.BuiltInAnimationGet; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, animationName); + } + + @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); + BuiltInAnimation animation = AnimationController.getInstance().getBuiltInAnimation(name); + if (animation != null) { + NBTTagCompound compound = animation.writeToNBT(); + // Mark as built-in so client knows + compound.setBoolean("BuiltIn", true); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } + } +} 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..9e06ab938 --- /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 && !tagMap.isEmpty()) { + 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/CloneFolderCrudPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderCrudPacket.java new file mode 100644 index 000000000..061700e35 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderCrudPacket.java @@ -0,0 +1,111 @@ +package kamkeel.npcs.network.packets.request.clone; + +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 kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.controllers.ServerCloneController; +import noppes.npcs.controllers.data.CloneFolder; + +import java.io.IOException; + +public final class CloneFolderCrudPacket extends AbstractPacket { + public static String packetName = "Request|CloneFolderCrud"; + + public static final byte ACTION_CREATE = 0; + public static final byte ACTION_RENAME = 1; + public static final byte ACTION_DELETE = 2; + + private byte action; + private String name; + private String newName; + + public CloneFolderCrudPacket() { + } + + public CloneFolderCrudPacket(byte action, String name) { + this.action = action; + this.name = name; + this.newName = ""; + } + + public CloneFolderCrudPacket(byte action, String name, String newName) { + this.action = action; + this.name = name; + this.newName = newName; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CloneFolderCrud; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.NPC_CLONE; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeByte(action); + ByteBufUtils.writeString(out, name); + if (action == ACTION_RENAME) { + ByteBufUtils.writeString(out, newName); + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) + return; + + byte action = in.readByte(); + String name = ByteBufUtils.readString(in); + + boolean success = false; + switch (action) { + case ACTION_CREATE: + if (CloneFolder.isValidName(name)) + success = ServerCloneController.Instance.createFolder(name) != null; + break; + case ACTION_RENAME: + String newName = ByteBufUtils.readString(in); + if (CloneFolder.isValidName(newName)) + success = ServerCloneController.Instance.renameFolder(name, newName); + break; + case ACTION_DELETE: + success = ServerCloneController.Instance.deleteFolder(name); + break; + } + + NBTTagCompound compound = new NBTTagCompound(); + compound.setBoolean("Success", success); + NBTTagList folderList = new NBTTagList(); + for (CloneFolder folder : ServerCloneController.Instance.getFolderList()) { + folderList.appendTag(folder.writeNBT(new NBTTagCompound())); + } + compound.setTag("CloneFolders", folderList); + + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderListPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderListPacket.java new file mode 100644 index 000000000..b7e7fe9f8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderListPacket.java @@ -0,0 +1,59 @@ +package kamkeel.npcs.network.packets.request.clone; + +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 net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.ServerCloneController; +import noppes.npcs.controllers.data.CloneFolder; + +import java.io.IOException; + +public final class CloneFolderListPacket extends AbstractPacket { + public static String packetName = "Request|CloneFolderList"; + + public CloneFolderListPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CloneFolderList; + } + + @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, player, EnumItemPacketType.CLONER)) + return; + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList folderList = new NBTTagList(); + for (CloneFolder folder : ServerCloneController.Instance.getFolderList()) { + folderList.appendTag(folder.writeNBT(new NBTTagCompound())); + } + compound.setTag("CloneFolders", folderList); + + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java index 87bac4a29..e6ce35f40 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java @@ -23,9 +23,16 @@ public final class CloneListPacket extends AbstractPacket { public static String packetName = "Request|CloneList"; private int tab; + private String folderName; public CloneListPacket(int tab) { this.tab = tab; + this.folderName = null; + } + + public CloneListPacket(String folderName) { + this.tab = -1; + this.folderName = folderName; } public CloneListPacket() { @@ -45,6 +52,9 @@ public final class CloneListPacket extends AbstractPacket { @Override public void sendData(ByteBuf out) throws IOException { out.writeInt(tab); + if (tab == -1) { + kamkeel.npcs.util.ByteBufUtils.writeString(out, folderName); + } } @Override @@ -54,14 +64,26 @@ public final class CloneListPacket extends AbstractPacket { if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.MOUNTER, EnumItemPacketType.CLONER)) return; - NBTTagList list = new NBTTagList(); int tab = in.readInt(); - for (String name : ServerCloneController.Instance.getClones(tab)) - list.appendTag(new NBTTagString(name)); + String folder = null; + if (tab == -1) { + folder = kamkeel.npcs.util.ByteBufUtils.readString(in); + } + NBTTagList list = new NBTTagList(); NBTTagList listDate = new NBTTagList(); - for (String name : ServerCloneController.Instance.getClonesDate(tab)) - listDate.appendTag(new NBTTagString(name)); + + if (folder != null) { + for (String name : ServerCloneController.Instance.getClones(folder)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(folder)) + listDate.appendTag(new NBTTagString(name)); + } else { + for (String name : ServerCloneController.Instance.getClones(tab)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(tab)) + listDate.appendTag(new NBTTagString(name)); + } NBTTagCompound compound = new NBTTagCompound(); compound.setTag("List", list); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneMovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneMovePacket.java new file mode 100644 index 000000000..124bd5204 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneMovePacket.java @@ -0,0 +1,97 @@ +package kamkeel.npcs.network.packets.request.clone; + +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 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.ServerCloneController; + +import java.io.IOException; + +public final class CloneMovePacket extends AbstractPacket { + public static String packetName = "Request|CloneMove"; + + private String cloneName; + private int fromTab; + private String fromFolder; + private int toTab; + private String toFolder; + + public CloneMovePacket() { + } + + public CloneMovePacket(String cloneName, int fromTab, String fromFolder, int toTab, String toFolder) { + this.cloneName = cloneName; + this.fromTab = fromTab; + this.fromFolder = fromFolder; + this.toTab = toTab; + this.toFolder = toFolder; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CloneMove; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.NPC_CLONE; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, cloneName); + out.writeInt(fromTab); + ByteBufUtils.writeString(out, fromFolder != null ? fromFolder : ""); + out.writeInt(toTab); + ByteBufUtils.writeString(out, toFolder != null ? toFolder : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) + return; + + String cloneName = ByteBufUtils.readString(in); + int fromTab = in.readInt(); + String fromFolder = ByteBufUtils.readString(in); + if (fromFolder.isEmpty()) fromFolder = null; + int toTab = in.readInt(); + String toFolder = ByteBufUtils.readString(in); + if (toFolder.isEmpty()) toFolder = null; + + boolean success = false; + if (fromFolder != null && toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder); + } else if (fromFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab); + } else if (toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder); + } else { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab); + } + + NBTTagCompound compound = new NBTTagCompound(); + compound.setBoolean("MoveSuccess", success); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java index 378145ddb..4d36eb531 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java @@ -24,6 +24,7 @@ public final class ClonePreSavePacket extends AbstractPacket { private String name; private int tab; + private String folderName; public ClonePreSavePacket() { } @@ -31,6 +32,13 @@ public final class ClonePreSavePacket extends AbstractPacket { public ClonePreSavePacket(String name, int tab) { this.name = name; this.tab = tab; + this.folderName = null; + } + + public ClonePreSavePacket(String name, String folderName) { + this.name = name; + this.tab = -1; + this.folderName = folderName; } @Override @@ -53,6 +61,9 @@ public final class ClonePreSavePacket extends AbstractPacket { public void sendData(ByteBuf out) throws IOException { ByteBufUtils.writeString(out, this.name); out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } } @Override @@ -62,7 +73,15 @@ public final class ClonePreSavePacket extends AbstractPacket { if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) return; - boolean bo = ServerCloneController.Instance.getCloneData(null, ByteBufUtils.readString(in), in.readInt()) != null; + String name = ByteBufUtils.readString(in); + int tab = in.readInt(); + boolean bo; + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + bo = ServerCloneController.Instance.getCloneData(null, name, folder) != null; + } else { + bo = ServerCloneController.Instance.getCloneData(null, name, tab) != null; + } NBTTagCompound compound = new NBTTagCompound(); compound.setBoolean("NameExists", bo); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java index ce1fcb367..96069f414 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java @@ -25,6 +25,7 @@ public final class CloneRemovePacket extends AbstractPacket { public static String packetName = "Request|CloneRemove"; private int tab; + private String folderName; private String name; public CloneRemovePacket() { @@ -32,6 +33,13 @@ public final class CloneRemovePacket extends AbstractPacket { public CloneRemovePacket(int tab, String name) { this.tab = tab; + this.folderName = null; + this.name = name; + } + + public CloneRemovePacket(String folderName, String name) { + this.tab = -1; + this.folderName = folderName; this.name = name; } @@ -54,6 +62,9 @@ public final class CloneRemovePacket extends AbstractPacket { @Override public void sendData(ByteBuf out) throws IOException { out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } ByteBufUtils.writeString(out, this.name); } @@ -65,16 +76,28 @@ public final class CloneRemovePacket extends AbstractPacket { return; int tab = in.readInt(); - ServerCloneController.Instance.removeClone(ByteBufUtils.readString(in), tab); + String folder = null; + if (tab == -1) { + folder = ByteBufUtils.readString(in); + } + String cloneName = ByteBufUtils.readString(in); NBTTagList list = new NBTTagList(); - - for (String name : ServerCloneController.Instance.getClones(tab)) - list.appendTag(new NBTTagString(name)); - NBTTagList listDate = new NBTTagList(); - for (String name : ServerCloneController.Instance.getClonesDate(tab)) - listDate.appendTag(new NBTTagString(name)); + + if (folder != null) { + ServerCloneController.Instance.removeClone(cloneName, folder); + for (String name : ServerCloneController.Instance.getClones(folder)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(folder)) + listDate.appendTag(new NBTTagString(name)); + } else { + ServerCloneController.Instance.removeClone(cloneName, tab); + for (String name : ServerCloneController.Instance.getClones(tab)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(tab)) + listDate.appendTag(new NBTTagString(name)); + } NBTTagCompound compound = new NBTTagCompound(); compound.setTag("List", list); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java index 3a8abd9c0..2c66572e3 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java @@ -25,6 +25,7 @@ public final class CloneSavePacket extends AbstractPacket { private String name; private int tab; + private String folderName; private NBTTagCompound tagExtra; private NBTTagCompound tagCompound; @@ -34,6 +35,15 @@ public final class CloneSavePacket extends AbstractPacket { public CloneSavePacket(String name, int tab, NBTTagCompound tagExtra, NBTTagCompound tagCompound) { this.name = name; this.tab = tab; + this.folderName = null; + this.tagExtra = tagExtra; + this.tagCompound = tagCompound; + } + + public CloneSavePacket(String name, String folderName, NBTTagCompound tagExtra, NBTTagCompound tagCompound) { + this.name = name; + this.tab = -1; + this.folderName = folderName; this.tagExtra = tagExtra; this.tagCompound = tagCompound; } @@ -58,6 +68,9 @@ public final class CloneSavePacket extends AbstractPacket { public void sendData(ByteBuf out) throws IOException { ByteBufUtils.writeString(out, this.name); out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } ByteBufUtils.writeNBT(out, this.tagExtra); ByteBufUtils.writeNBT(out, this.tagCompound); } @@ -75,11 +88,20 @@ public final class CloneSavePacket extends AbstractPacket { String name = ByteBufUtils.readString(in); int tab = in.readInt(); + String folder = null; + if (tab == -1) { + folder = ByteBufUtils.readString(in); + } NBTTagCompound tagExtra = ByteBufUtils.readNBT(in); NBTTagCompound tagCompound = ByteBufUtils.readNBT(in); NBTTagList tagList = tagCompound.getTagList("TagUUIDs", 8); data.cloned.setTag("TagUUIDs", tagList); - ServerCloneController.Instance.addClone(data.cloned, name, tab, tagExtra); + + if (folder != null) { + ServerCloneController.Instance.addClone(data.cloned, name, folder, tagExtra); + } else { + ServerCloneController.Instance.addClone(data.cloned, name, tab, tagExtra); + } } } 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 4d7b21aac..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,6 +10,7 @@ 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; @@ -22,9 +23,16 @@ public final class CloneTagListPacket extends AbstractPacket { public static String packetName = "Request|CloneTagList"; private int tab; + private String folderName; public CloneTagListPacket(int tab) { this.tab = tab; + this.folderName = null; + } + + public CloneTagListPacket(String folderName) { + this.tab = -1; + this.folderName = folderName; } public CloneTagListPacket() { @@ -44,6 +52,9 @@ public final class CloneTagListPacket extends AbstractPacket { @Override public void sendData(ByteBuf out) throws IOException { out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, folderName); + } } @Override @@ -54,7 +65,13 @@ public final class CloneTagListPacket extends AbstractPacket { return; int tab = in.readInt(); - TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); + TagMap tagMap; + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + tagMap = ServerTagMapController.Instance.getTagMap(folder); + } else { + tagMap = ServerTagMapController.Instance.getTagMap(tab); + } NBTTagCompound compound = new NBTTagCompound(); compound.setTag("CloneTags", tagMap.writeNBT()); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java index cc4dfb3ed..0ad817b06 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java @@ -31,6 +31,7 @@ public class MobSpawnerPacket extends AbstractPacket { private String selectedName; private int tab; + private String folderName; private NBTTagCompound compound; @@ -44,6 +45,17 @@ public class MobSpawnerPacket extends AbstractPacket { this.posz = posz; this.selectedName = selectedName; this.tab = tab; + this.folderName = null; + } + + public MobSpawnerPacket(Action type, int posX, int posY, int posz, String selectedName, String folderName) { + this.type = type; + this.posX = posX; + this.posY = posY; + this.posz = posz; + this.selectedName = selectedName; + this.tab = -1; + this.folderName = folderName; } public MobSpawnerPacket(Action type, int posX, int posY, int posz, NBTTagCompound compound) { @@ -58,6 +70,10 @@ public class MobSpawnerPacket extends AbstractPacket { PacketClient.sendClient(new MobSpawnerPacket(Action.Server, x, y, z, name, tab)); } + public static void ServerFolder(int x, int y, int z, String name, String folderName) { + PacketClient.sendClient(new MobSpawnerPacket(Action.Server, x, y, z, name, folderName)); + } + public static void Client(int x, int y, int z, NBTTagCompound compound) { PacketClient.sendClient(new MobSpawnerPacket(Action.Client, x, y, z, compound)); } @@ -88,6 +104,9 @@ public class MobSpawnerPacket extends AbstractPacket { if (type == Action.Server) { ByteBufUtils.writeString(out, this.selectedName); out.writeInt(this.tab); + if (this.tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } } else { ByteBufUtils.writeNBT(out, this.compound); } @@ -107,10 +126,18 @@ public class MobSpawnerPacket extends AbstractPacket { int z = in.readInt(); NBTTagCompound compound; - if (requestedAction == Action.Server) - compound = ServerCloneController.Instance.getCloneData(player, ByteBufUtils.readString(in), in.readInt()); - else + if (requestedAction == Action.Server) { + String name = ByteBufUtils.readString(in); + int tab = in.readInt(); + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + compound = ServerCloneController.Instance.getCloneData(player, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(player, name, tab); + } + } else { compound = ByteBufUtils.readNBT(in); + } if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) { return; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java index b83fb9286..8afde02cf 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java @@ -37,6 +37,7 @@ public class SpawnMobPacket extends AbstractPacket { private String selectedName; private int tab; + private String folderName; private NBTTagCompound compound; @@ -50,6 +51,17 @@ public class SpawnMobPacket extends AbstractPacket { this.posz = posz; this.selectedName = selectedName; this.tab = tab; + this.folderName = null; + } + + public SpawnMobPacket(Action type, int posX, int posY, int posz, String selectedName, String folderName) { + this.type = type; + this.posX = posX; + this.posY = posY; + this.posz = posz; + this.selectedName = selectedName; + this.tab = -1; + this.folderName = folderName; } public SpawnMobPacket(Action type, int posX, int posY, int posz, NBTTagCompound compound) { @@ -64,6 +76,10 @@ public class SpawnMobPacket extends AbstractPacket { PacketClient.sendClient(new SpawnMobPacket(Action.Server, x, y, z, name, tab)); } + public static void ServerFolder(int x, int y, int z, String name, String folderName) { + PacketClient.sendClient(new SpawnMobPacket(Action.Server, x, y, z, name, folderName)); + } + public static void Client(int x, int y, int z, NBTTagCompound compound) { PacketClient.sendClient(new SpawnMobPacket(Action.Client, x, y, z, compound)); } @@ -94,6 +110,9 @@ public class SpawnMobPacket extends AbstractPacket { if (type == Action.Server) { ByteBufUtils.writeString(out, this.selectedName); out.writeInt(this.tab); + if (this.tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } } else { ByteBufUtils.writeNBT(out, this.compound); } @@ -113,10 +132,18 @@ public class SpawnMobPacket extends AbstractPacket { int z = in.readInt(); NBTTagCompound compound; - if (requestedAction == Action.Server) - compound = ServerCloneController.Instance.getCloneData(player, ByteBufUtils.readString(in), in.readInt()); - else + if (requestedAction == Action.Server) { + String name = ByteBufUtils.readString(in); + int tab = in.readInt(); + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + compound = ServerCloneController.Instance.getCloneData(player, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(player, name, tab); + } + } else { compound = ByteBufUtils.readNBT(in); + } if (compound == null) return; 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/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/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/BlockScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/BlockScriptPacket.java index 0fd7de927..ce94c98f9 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/script/BlockScriptPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/BlockScriptPacket.java @@ -84,6 +84,10 @@ public final class BlockScriptPacket extends AbstractPacket { NBTTagCompound compound = ((TileScripted) tile).getNBT(new NBTTagCompound()); compound.setTag("Languages", ScriptController.Instance.nbtLanguages()); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + + NBTTagCompound loadComplete = new NBTTagCompound(); + loadComplete.setInteger("LoadComplete", 1); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, loadComplete); } else { if (!player.capabilities.isCreativeMode) { return; 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 new file mode 100644 index 000000000..8930fabc3 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java @@ -0,0 +1,105 @@ +package kamkeel.npcs.network.packets.request.script; + +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.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.NBTTags; +import noppes.npcs.client.ScriptClientConfig; +import noppes.npcs.config.ConfigScript; +import noppes.npcs.controllers.ScriptController; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public final class ScriptFilesPacket extends AbstractPacket { + public static String packetName = "Request|ScriptFiles"; + + private String lang; + + public ScriptFilesPacket() { + } + + public ScriptFilesPacket(String lang) { + this.lang = lang; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ScriptFiles; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.SCRIPT_GLOBAL; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, getScriptsNbt(lang)); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + NBTTagCompound compound = ByteBufUtils.readNBT(in); + + String lang = compound.getString("Lang"); + String ext = compound.getString("Ext"); + Map scripts = NBTTags.getStringStringMap(compound.getTagList("Scripts", 10)); + + ScriptController cont = ScriptController.Instance; + if (!cont.languages.containsKey(lang) && ext != null) + cont.languages.put(lang, ext); + + for (Map.Entry script : scripts.entrySet()) { + cont.scripts.put(script.getKey(), script.getValue()); + } + + //Set client side configs + ScriptClientConfig.setScriptingEnabled(compound.getBoolean("ScriptingEnabled")); + ScriptClientConfig.setRunLoadedScriptsFirst(compound.getBoolean("LoadedFirst")); + ScriptController.Instance.globalRevision = compound.getInteger("GlobalRevision"); + } + + public NBTTagCompound getScriptsNbt(String lang) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setString("Lang", lang); + + Map scriptss = new HashMap<>(); + String ext = ScriptController.Instance.languages.get(lang); + if (ext != null) { + for (Map.Entry script : ScriptController.Instance.scripts.entrySet()) { + if (script.getKey().endsWith(ext)) + scriptss.put(script.getKey(), script.getValue()); + } + compound.setString("Ext", ext); + } + + //Send server configs to client + compound.setBoolean("ScriptingEnabled", ConfigScript.ScriptingEnabled); + compound.setBoolean("LoadedFirst", ConfigScript.RunLoadedScriptsFirst); + compound.setInteger("GlobalRevision", ScriptController.Instance.globalRevision); + compound.setTag("Scripts", NBTTags.nbtStringStringMap(scriptss)); + return compound; + } + + public static void sendToAll(String lang) { + PacketHandler.Instance.sendToAll(new ScriptFilesPacket(lang)); + } + + public static void sendToPlayer(EntityPlayerMP player, String lang) { + PacketHandler.Instance.sendToPlayer(new ScriptFilesPacket(lang), player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptErrorPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptErrorPacket.java index b4a8c619e..c1a7c74c5 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptErrorPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptErrorPacket.java @@ -16,7 +16,7 @@ import noppes.npcs.CustomNpcsPermissions; import noppes.npcs.NBTTags; import noppes.npcs.api.item.IItemStack; import noppes.npcs.config.ConfigScript; -import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.controllers.data.IScriptUnit; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.item.ScriptCustomItem; @@ -72,10 +72,10 @@ public final class ItemScriptErrorPacket extends AbstractPacket { if (requestedAction == Action.GET) { TreeMap map = new TreeMap<>(); int tab = 0; - for (ScriptContainer script : ((ScriptCustomItem) iw).scripts) { + for (IScriptUnit script : ((ScriptCustomItem) iw).scripts) { ++tab; - for (Map.Entry longStringEntry : script.console.entrySet()) { + for (Map.Entry longStringEntry : script.getConsole().entrySet()) { map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + longStringEntry.getValue()); } } @@ -84,8 +84,8 @@ public final class ItemScriptErrorPacket extends AbstractPacket { compound.setTag("ItemScriptConsole", NBTTags.NBTLongStringMap(map)); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); } else { - for (ScriptContainer script : ((ScriptCustomItem) iw).scripts) { - script.console.clear(); + for (IScriptUnit script : ((ScriptCustomItem) iw).scripts) { + script.clearConsole(); } } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptPacket.java index 478340a63..7d21242bd 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/item/ItemScriptPacket.java @@ -75,6 +75,10 @@ public final class ItemScriptPacket extends AbstractPacket { NBTTagCompound compound = iw.getMCNbt(); compound.setTag("Languages", ScriptController.Instance.nbtLanguages()); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + + NBTTagCompound loadComplete = new NBTTagCompound(); + loadComplete.setInteger("LoadComplete", 1); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, loadComplete); } else { if (!player.capabilities.isCreativeMode) { return; diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java new file mode 100644 index 000000000..415262da7 --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -0,0 +1,602 @@ +package kamkeel.npcs.util; + +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; +import noppes.npcs.controllers.data.AnimationData; +import noppes.npcs.controllers.data.Frame; +import noppes.npcs.controllers.data.FramePart; +import noppes.npcs.entity.EntityCustomNpc; +import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.entity.data.ModelScalePart; + +/** + * Utility class for calculating world positions based on anchor points. + * Supports both EntityNPCInterface and EntityPlayer with animation and model size awareness. + */ +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; + + // Shoulder position relative to model origin + private static final float SHOULDER_Y = 2f; + private static final float SHOULDER_X_OFFSET = 5f; // Distance from center to shoulder + + // Palm position (in arm's local space, relative to shoulder) + // Arm is 12 units long; palm is near the end + private static final float PALM_DOWN = 11f; // Distance down the arm to palm center + private static final float PALM_FORWARD = 2f; // Forward offset to palm surface (not center of hand) + private static final float PALM_INWARD = 0f; // Lateral offset (0 = centered on arm) + + // Default height offsets as fraction of entity height + private static final float FRONT_HEIGHT = 0.7f; + private static final float CENTER_HEIGHT = 0.5f; + 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; + + // Fallback arm positioning (when no animation, arms hang at sides) + private static final float FALLBACK_LATERAL = 0.35f; // Distance from body center to arm + 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. + */ + public static Vec3 calculateAnchorPosition(EntityLivingBase entity, EnergyAnchorData anchorData) { + return calculateAnchorPosition(entity, anchorData, DEFAULT_FRONT_DISTANCE); + } + + /** + * Calculate world position for an anchor point with custom front offset. + */ + public static Vec3 calculateAnchorPosition(EntityLivingBase entity, EnergyAnchorData anchorData, float frontOffset) { + float scale = getModelScale(entity); + float height = entity.height; + + AnchorPoint anchor = anchorData.anchorPoint; + + float anchorX = anchorData.anchorOffsetX; + float anchorY = anchorData.anchorOffsetY; + float anchorZ = anchorData.anchorOffsetZ; + + double x = entity.posX; + // 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 bodyYaw = (float) Math.toRadians(entity.renderYawOffset); + + switch (anchor) { + case FRONT: + Vec3 look = entity.getLookVec(); + x += look.xCoord * frontOffset * scale; + y += height * FRONT_HEIGHT + look.yCoord * frontOffset * scale; + z += look.zCoord * frontOffset * scale; + break; + + case CENTER: + y += height * CENTER_HEIGHT; + break; + + case RIGHT_HAND: + return calculateHandPosition(entity, anchorData, true, scale); + + case LEFT_HAND: + return calculateHandPosition(entity, anchorData, false, scale); + + case ABOVE_HEAD: + y += height * ABOVE_HEAD_HEIGHT; + break; + + case CHEST: + y += height * CHEST_HEIGHT; + break; + + case EYE: + return calculateEyePosition(entity, anchorData, scale); + } + + // Rotate offsets relative to entity's body yaw + // +X = entity's right, +Y = up, +Z = entity's forward + Vec3 rotatedOffset = rotateOffsetByYaw(anchorX * scale, anchorY * scale, anchorZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; + + // Apply FULL_MODEL rotation if active + FramePart fullModel = getFullModelPart(entity); + if (fullModel != null) { + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + Vec3 rotated = applyFullModelToWorldOffset(fullModel, entity, dx, dy, dz, bodyYaw, scale); + return Vec3.createVectorHelper( + entity.posX + rotated.xCoord, + entity.posY + rotated.yCoord, + entity.posZ + rotated.zCoord + ); + } + + return Vec3.createVectorHelper(x, y, z); + } + + 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. + */ + private static float getModelScale(EntityLivingBase entity) { + if (entity instanceof EntityNPCInterface) { + int modelSize = ((EntityNPCInterface) entity).display.modelSize; + return modelSize / 5f; // modelSize 5 = 100% scale + } + return 1f; + } + + /** + * Returns Y offset correction for the local client player. + * On the client, EntityPlayerSP.posY is at feet level but the renderer adds yOffset (1.62), + * causing anchor positions to appear ~1.6 blocks too high. This matches DBC's correction. + */ + private static double getClientPlayerYCorrection(EntityLivingBase entity) { + if (entity.worldObj.isRemote && entity instanceof EntityPlayerSP) { + return CLIENT_PLAYER_Y_OFFSET; + } + return 0.0; + } + + /** + * Get arm scale for an entity. + * EntityCustomNpc has per-part scaling, others use default (1,1,1). + */ + private static ModelScalePart getArmScale(EntityLivingBase entity) { + if (entity instanceof EntityCustomNpc) { + return ((EntityCustomNpc) entity).modelData.modelScale.arms; + } + return DEFAULT_ARM_SCALE; + } + + /** + * 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 pos = getAnimatedHandPosition(entity, anchor, rightHand, scale); + if (pos == null) { + // Fallback to static position + pos = 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; + } + + /** + * Calculate hand position from animation data. + * Works for both NPCs and Players. + */ + private static Vec3 getAnimatedHandPosition(EntityLivingBase entity, EnergyAnchorData anchor, boolean rightHand, float scale) { + 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; + } + + EnumAnimationPart armPart = rightHand ? EnumAnimationPart.RIGHT_ARM : EnumAnimationPart.LEFT_ARM; + FramePart part = frame.frameParts.get(armPart); + if (part == null) { + return null; + } + + // Get arm scale for EntityCustomNpc + ModelScalePart armScale = getArmScale(entity); + + // Get rotation and pivot values + float[] rotations = getRotations(part, entity); + float[] pivots = getPivots(part, entity); + + // Shoulder position in model space + float shoulderX = rightHand ? -SHOULDER_X_OFFSET : SHOULDER_X_OFFSET; + float shoulderY = SHOULDER_Y; + float shoulderZ = 0f; + + // Add pivot offsets + shoulderX += pivots[0]; + shoulderY += pivots[1]; + shoulderZ += pivots[2]; + + // Palm offset in arm's local space (before rotation) + // Apply arm scaling to the palm position + float palmX = (rightHand ? -PALM_INWARD : PALM_INWARD) * armScale.scaleX; + float palmY = PALM_DOWN * armScale.scaleY; + float palmZ = PALM_FORWARD * armScale.scaleZ; + + // Apply arm rotations (order: X -> Y -> Z, matching GL's reverse application) + double hx = palmX, hy = palmY, hz = palmZ; + + // X rotation first + double cosX = Math.cos(rotations[0]); + double sinX = Math.sin(rotations[0]); + double newY = hy * cosX - hz * sinX; + double newZ = hy * sinX + hz * cosX; + hy = newY; + hz = newZ; + + // Y rotation second + double cosY = Math.cos(rotations[1]); + double sinY = Math.sin(rotations[1]); + double newX = hx * cosY + hz * sinY; + newZ = -hx * sinY + hz * cosY; + hx = newX; + hz = newZ; + + // Z rotation last + double cosZ = Math.cos(rotations[2]); + double sinZ = Math.sin(rotations[2]); + newX = hx * cosZ - hy * sinZ; + newY = hx * sinZ + hy * cosZ; + hx = newX; + hy = newY; + + // Combine shoulder + rotated hand offset + double modelX = shoulderX + hx; + double modelY = shoulderY + hy; + double modelZ = shoulderZ + hz; + + // Convert to blocks and apply model scale + double blockX = modelX * MODEL_SCALE * scale; + double blockY = modelY * MODEL_SCALE * scale; + double blockZ = modelZ * MODEL_SCALE * scale; + + // Apply body yaw rotation + // Renderer applies glRotatef(180 - yaw) then glScalef(-1, -1, 1). + // Combined transform: x' = mx*cos(yaw) + mz*sin(yaw), z' = mx*sin(yaw) - mz*cos(yaw) + float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); + double cosYaw = Math.cos(bodyYaw); + double sinYaw = Math.sin(bodyYaw); + + double worldOffsetX = blockX * cosYaw + blockZ * sinYaw; + double worldOffsetZ = blockX * sinYaw - blockZ * cosYaw; + + // Calculate shoulder height based on entity and scale + float shoulderHeight = entity.height * ARM_HEIGHT; + + // Final world position + double worldX = entity.posX + worldOffsetX; + double worldY = entity.posY + getClientPlayerYCorrection(entity) + shoulderHeight - blockY; + double worldZ = entity.posZ + worldOffsetZ; + + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + worldX += rotatedOffset.xCoord; + worldY += rotatedOffset.yCoord; + worldZ += rotatedOffset.zCoord; + + return Vec3.createVectorHelper(worldX, worldY, worldZ); + } + + /** + * Get rotation values from FramePart. + * Uses interpolated values on client, raw values on server. + */ + private static float[] getRotations(FramePart part, EntityLivingBase entity) { + if (entity.worldObj.isRemote) { + // Client side - use interpolated values (already in radians) + part.interpolateAngles(); + return part.prevRotations; + } else { + // Server side - convert raw degrees to radians + float pi = (float) Math.PI / 180f; + return new float[]{ + part.rotation[0] * pi, + part.rotation[1] * pi, + part.rotation[2] * pi + }; + } + } + + /** + * Get pivot values from FramePart. + * Uses interpolated values on client, raw values on server. + */ + private static float[] getPivots(FramePart part, EntityLivingBase entity) { + if (entity.worldObj.isRemote) { + // Client side - use interpolated values + part.interpolateOffset(); + return part.prevPivots; + } else { + // Server side - use raw values + return part.pivot; + } + } + + /** + * Calculate fallback hand position when no animation is active. + * Represents arms hanging at sides in default idle pose. + */ + private static Vec3 calculateFallbackHandPosition(EntityLivingBase entity, EnergyAnchorData anchor, boolean rightHand, float scale) { + float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); + + // Get arm scale for EntityCustomNpc + ModelScalePart armScale = getArmScale(entity); + + // Perpendicular direction for lateral offset (right = +90°, left = -90° from body facing) + float perpYaw = bodyYaw + (rightHand ? (float) (Math.PI / 2) : (float) (-Math.PI / 2)); + + // Calculate lateral offset - arms hang at sides + // Scale by model size, but not by arm scale (lateral distance is fixed by skeleton) + double lateralX = -Math.sin(perpYaw) * FALLBACK_LATERAL * scale; + double lateralZ = Math.cos(perpYaw) * FALLBACK_LATERAL * scale; + + // Small forward offset + double forwardX = -Math.sin(bodyYaw) * FALLBACK_FORWARD * scale; + double forwardZ = Math.cos(bodyYaw) * FALLBACK_FORWARD * scale; + + // Arm length affects vertical position - longer arms = lower hands + double armLengthOffset = armScale.scaleY * 0.3 * scale; + + double x = entity.posX + lateralX + forwardX; + 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 + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; + + return Vec3.createVectorHelper(x, y, z); + } + + /** + * Get default height multiplier for an anchor point. + */ + public static float getHeightMultiplier(AnchorPoint anchor) { + switch (anchor) { + case FRONT: + return FRONT_HEIGHT; + case CENTER: + return CENTER_HEIGHT; + case RIGHT_HAND: + case LEFT_HAND: + return ARM_HEIGHT; + case ABOVE_HEAD: + return ABOVE_HEAD_HEIGHT; + case CHEST: + return CHEST_HEIGHT; + case EYE: + return EYE_HEIGHT; + default: + return FRONT_HEIGHT; + } + } + + /** + * Rotate an offset vector by the entity's body yaw so offsets are entity-relative. + * +X = entity's right, +Y = up, +Z = entity's forward. + * + * @param bodyYawRad body yaw in radians + */ + private static Vec3 rotateOffsetByYaw(double offsetX, double offsetY, double offsetZ, float bodyYawRad) { + double cos = Math.cos(bodyYawRad); + double sin = Math.sin(bodyYawRad); + double worldX = -offsetX * cos - offsetZ * sin; + double worldZ = -offsetX * sin + offsetZ * cos; + return Vec3.createVectorHelper(worldX, offsetY, worldZ); + } + + // ==================== FULL_MODEL ANIMATION SUPPORT ==================== + + /** + * Get the FULL_MODEL FramePart if the entity has an active animation with it. + * Returns null if no FULL_MODEL animation is active. + */ + private static FramePart getFullModelPart(EntityLivingBase entity) { + AnimationData animData = AnimationData.getData(entity); + if (animData == null || !animData.isActive() || animData.animation == null) { + return null; + } + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame == null) { + return null; + } + FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); + return part; + } + + /** + * Apply FULL_MODEL rotation to a world-space offset from entity position. + * Converts the offset to model space, applies FULL_MODEL rotation and pivots, + * then converts back to world space. + *

+ * The rendering pipeline is: entity_pos * body_yaw * scale(-1,-1,1) * FULL_MODEL * parts + * Combined body_yaw + scale maps model space to world space: + * worldX = mx*cos(yaw) + mz*sin(yaw) + * worldY = -my (model Y-down → world Y-up) + * worldZ = mx*sin(yaw) - mz*cos(yaw) + * This transform is its own inverse for X,Z. + *

+ * FULL_MODEL rotation order matches renderer: vertex sees Z, then Y, then X. + */ + private static Vec3 applyFullModelToWorldOffset(FramePart fullModel, EntityLivingBase entity, + double worldDX, double worldDY, double worldDZ, + float bodyYaw, float scale) { + float[] rotations = getRotations(fullModel, entity); + float[] pivots = getPivots(fullModel, entity); + + // Quick exit if no transform needed + boolean hasRotation = rotations[0] != 0 || rotations[1] != 0 || rotations[2] != 0; + boolean hasPivot = pivots[0] != 0 || pivots[1] != 0 || pivots[2] != 0; + if (!hasRotation && !hasPivot) { + return Vec3.createVectorHelper(worldDX, worldDY, worldDZ); + } + + // Convert world offset to model space + // Body yaw + scale combined transform is an involution (self-inverse) for X,Z + double cosYaw = Math.cos(bodyYaw); + double sinYaw = Math.sin(bodyYaw); + + double mx = worldDX * cosYaw + worldDZ * sinYaw; + double mz = worldDX * sinYaw - worldDZ * cosYaw; + double my = -worldDY; // Invert Y (world Y-up → model Y-down) + + // Apply FULL_MODEL rotations (vertex order: Z first, then Y, then X) + // Matches renderer: glRotatef(X), glRotatef(Y), glRotatef(Z) → vertex sees Z,Y,X + + // Z rotation + double cosZ = Math.cos(rotations[2]); + double sinZ = Math.sin(rotations[2]); + double nx = mx * cosZ - my * sinZ; + double ny = mx * sinZ + my * cosZ; + mx = nx; + my = ny; + + // Y rotation + double cosY = Math.cos(rotations[1]); + double sinY = Math.sin(rotations[1]); + nx = mx * cosY + mz * sinY; + double nz = -mx * sinY + mz * cosY; + mx = nx; + mz = nz; + + // X rotation + double cosX = Math.cos(rotations[0]); + double sinX = Math.sin(rotations[0]); + ny = my * cosX - mz * sinX; + nz = my * sinX + mz * cosX; + my = ny; + mz = nz; + + // Apply pivots in model space (after rotation, matching GL vertex ordering) + // Renderer: glTranslatef(px, -py, pz) → pivot Y is negated for model Y-down space + mx += pivots[0] * MODEL_SCALE * scale; + my -= pivots[1] * MODEL_SCALE * scale; + mz += pivots[2] * MODEL_SCALE * scale; + + // Convert back to world space (same involution for X,Z; invert Y back) + double newDX = mx * cosYaw + mz * sinYaw; + double newDZ = mx * sinYaw - mz * cosYaw; + double newDY = -my; + + return Vec3.createVectorHelper(newDX, newDY, newDZ); + } +} diff --git a/src/main/java/kamkeel/npcs/util/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 new file mode 100644 index 000000000..1252fc67c --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/BukkitUtil.java @@ -0,0 +1,201 @@ +package kamkeel.npcs.util; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Method; + +/** + * Utility class for Bukkit integration detection and common operations. + * Must be initialized after the server has fully started to ensure Bukkit plugins are loaded. + */ +public class BukkitUtil { + private static final Logger logger = LogManager.getLogger(BukkitUtil.class); + + private static boolean initialized = false; + private static boolean bukkitEnabled = false; + + // Bukkit classes + private static Class bukkitClass; + private static Class serverClass; + private static Class servicesManagerClass; + private static Class registeredServiceProviderClass; + private static Class offlinePlayerClass; + private static Class playerClass; + + // Bukkit methods + private static Method getServer; + private static Method getServicesManager; + private static Method getRegistration; + private static Method getProvider; + private static Method getOfflinePlayer; + private static Method getPlayer; + private static Method getPluginManager; + private static Method isPluginEnabled; + + private static Method getPlugin; + + /** + * Initializes Bukkit integration using reflection. + * Should be called during FMLServerStartedEvent to ensure Bukkit is fully loaded. + */ + public static void init() { + if (initialized) { + return; + } + initialized = true; + + try { + // Load Bukkit classes + bukkitClass = Class.forName("org.bukkit.Bukkit"); + serverClass = Class.forName("org.bukkit.Server"); + servicesManagerClass = Class.forName("org.bukkit.plugin.ServicesManager"); + registeredServiceProviderClass = Class.forName("org.bukkit.plugin.RegisteredServiceProvider"); + offlinePlayerClass = Class.forName("org.bukkit.OfflinePlayer"); + playerClass = Class.forName("org.bukkit.entity.Player"); + + // Get Bukkit methods + getServer = bukkitClass.getMethod("getServer"); + getServicesManager = bukkitClass.getMethod("getServicesManager"); + getRegistration = servicesManagerClass.getMethod("getRegistration", Class.class); + getProvider = registeredServiceProviderClass.getMethod("getProvider"); + getOfflinePlayer = bukkitClass.getMethod("getOfflinePlayer", String.class); + getPlayer = bukkitClass.getMethod("getPlayer", String.class); + getPluginManager = bukkitClass.getMethod("getPluginManager"); + + Class pluginManagerClass = Class.forName("org.bukkit.plugin.PluginManager"); + isPluginEnabled = pluginManagerClass.getMethod("isPluginEnabled", String.class); + getPlugin = pluginManagerClass.getMethod("getPlugin", String.class); + + bukkitEnabled = true; + logger.info("Bukkit integration enabled"); + + // Initialize Vault after Bukkit is confirmed + VaultUtil.init(); + + } catch (ClassNotFoundException e) { + logger.debug("Bukkit not found, Bukkit integration disabled"); + } catch (NoSuchMethodException e) { + logger.error("Bukkit API method not found", e); + } catch (Exception e) { + logger.error("Error initializing Bukkit integration", e); + } + } + + /** + * @return true if Bukkit integration is enabled + */ + public static boolean isEnabled() { + return bukkitEnabled; + } + + /** + * @return true if Bukkit has been initialized (may or may not be enabled) + */ + public static boolean isInitialized() { + return initialized; + } + + /** + * Checks if a specific Bukkit plugin is enabled. + * + * @param pluginName the plugin name to check + * @return true if the plugin is enabled + */ + public static boolean isPluginEnabled(String pluginName) { + if (!bukkitEnabled) return false; + + try { + Object pluginManager = getPluginManager.invoke(null); + return (Boolean) isPluginEnabled.invoke(pluginManager, pluginName); + } catch (Exception e) { + logger.error("Error checking if plugin is enabled: " + pluginName, e); + return false; + } + } + + /** + * Gets a Bukkit OfflinePlayer by name. + * + * @param playerName the player name + * @return the OfflinePlayer object, or null if not available + */ + public static Object getOfflinePlayer(String playerName) { + if (!bukkitEnabled) return null; + + try { + return getOfflinePlayer.invoke(null, playerName); + } catch (Exception e) { + logger.error("Error getting OfflinePlayer: " + playerName, e); + return null; + } + } + + /** + * 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 + */ + public static Object getPlayer(String playerName) { + if (!bukkitEnabled) return null; + + try { + return getPlayer.invoke(null, playerName); + } catch (Exception e) { + logger.error("Error getting Player: " + playerName, e); + return null; + } + } + + /** + * Gets a service provider from Bukkit's ServicesManager. + * + * @param serviceClass the service class to get + * @return the service provider, or null if not available + */ + public static Object getServiceProvider(Class serviceClass) { + if (!bukkitEnabled) return null; + + try { + Object servicesManager = getServicesManager.invoke(null); + Object registration = getRegistration.invoke(servicesManager, serviceClass); + if (registration != null) { + return getProvider.invoke(registration); + } + } catch (Exception e) { + logger.error("Error getting service provider: " + serviceClass.getName(), e); + } + return null; + } + + // Getters for classes (for use by other utils like VaultUtil) + public static Class getBukkitClass() { + return bukkitClass; + } + + public static Class getServicesManagerClass() { + return servicesManagerClass; + } + + public static Class getRegisteredServiceProviderClass() { + return registeredServiceProviderClass; + } + + public static Class getOfflinePlayerClass() { + return offlinePlayerClass; + } + + public static Class getPlayerClass() { + return playerClass; + } + + public static Object getPlugin(String plugin) { + try { + return getPlugin.invoke(getPluginManager.invoke(null), plugin); + } catch (Throwable ignored) { + + } + return null; + } +} 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 new file mode 100644 index 000000000..53f4f092b --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -0,0 +1,243 @@ +package kamkeel.npcs.util; + +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.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.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<>(); + protected final String registryKey; + protected final String namespace; + protected final Map> entries = new LinkedHashMap<>(); + + private Register(String registryKey, String namespace) { + this.registryKey = registryKey; + this.namespace = namespace; + } + + public T register(String factoryName, Supplier factory) { + entries.put(registryKey + "." + namespace + "." + factoryName, factory); + return factory.get(); + } + + public static boolean isEmpty(String registryKey) { + if (REGISTERED_NAMESPACES.isEmpty()) return true; + + List list = REGISTERED_NAMESPACES.get(registryKey); + if (list == null || list.isEmpty()) return true; + + return false; + } + + 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()); + 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()); + } + } + } + + public static Register.Abilities create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("ability")) + REGISTERED_NAMESPACES.put("ability", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("ability").contains(namespace)) { + LogWriter.error("REGISTER ABILITIES: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("ability").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.Abilities(namespace); + } + } + + public static class Animations extends Register { + private final Class modClass; + private final String animationsPath; + + private Animations(Class modClass, String animationsPath, String namespace) { + super("animation", namespace); + this.animationsPath = animationsPath; + this.modClass = modClass; + } + + @Override + public Animation register(String factoryName, Supplier factory) { + 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 prefix = registryKey + "." + namespace + "."; + String key = entry.getKey(); + String name = key.substring(prefix.length()); + AnimationController.Instance.loadBuiltInAnimation(modClass, path, name); + } + } catch (Exception e) { + LogWriter.error("Error scanning built-in animations folder", e); + } + } + + public static Register.Animations create(Class modClass, String animationsPath, String namespace) { + if (!REGISTERED_NAMESPACES.containsKey("animation")) + REGISTERED_NAMESPACES.put("animation", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("animation").contains(namespace)) { + LogWriter.error("REGISTER ANIMATIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("animation").add(namespace); + + 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 new file mode 100644 index 000000000..47e294e57 --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/VaultUtil.java @@ -0,0 +1,603 @@ +package kamkeel.npcs.util; + +import net.minecraft.entity.player.EntityPlayer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Method; + +/** + * Utility class for Vault Economy integration. + * Uses reflection to access Vault API when available. + * Requires BukkitUtil to be initialized first. + */ +public class VaultUtil { + private static final Logger logger = LogManager.getLogger(VaultUtil.class); + + private static boolean initialized = false; + private static boolean vaultEnabled = false; + + // Vault classes + private static Class economyClass; + private static Class economyResponseClass; + + // Economy methods + private static Method isEnabled; + private static Method getName; + private static Method hasAccount; + private static Method hasAccountOffline; + private static Method getBalance; + private static Method getBalanceOffline; + private static Method has; + private static Method hasOffline; + private static Method withdrawPlayer; + private static Method withdrawPlayerOffline; + private static Method depositPlayer; + private static Method depositPlayerOffline; + private static Method format; + private static Method currencyNamePlural; + private static Method currencyNameSingular; + private static Method createPlayerAccount; + private static Method createPlayerAccountOffline; + private static Method hasBankSupport; + private static Method getBanks; + private static Method bankBalance; + private static Method bankHas; + private static Method bankWithdraw; + private static Method bankDeposit; + + // EconomyResponse methods + private static Method transactionSuccess; + + // Cached economy instance + private static Object economyInstance; + + /** + * Initializes the Vault integration using reflection. + * Called automatically by BukkitUtil after Bukkit is confirmed available. + */ + public static void init() { + if (initialized) { + return; + } + initialized = true; + + if (!BukkitUtil.isEnabled()) { + logger.debug("Bukkit not available, Vault integration disabled"); + return; + } + + try { + Class offlinePlayerClass = BukkitUtil.getOfflinePlayerClass(); + if (offlinePlayerClass == null) { + logger.error("Could not get OfflinePlayer class from BukkitUtil"); + return; + } + + // Load Vault classes + Object vault = BukkitUtil.getPlugin("Vault"); + if (vault == null) + return; + ClassLoader vaultLoader = vault.getClass().getClassLoader(); + economyClass = vaultLoader.loadClass("net.milkbowl.vault.economy.Economy"); + economyResponseClass = vaultLoader.loadClass("net.milkbowl.vault.economy.EconomyResponse"); + + // Get Economy methods (using deprecated String methods for broader compatibility) + isEnabled = economyClass.getMethod("isEnabled"); + getName = economyClass.getMethod("getName"); + hasAccount = economyClass.getMethod("hasAccount", String.class); + hasAccountOffline = economyClass.getMethod("hasAccount", offlinePlayerClass); + getBalance = economyClass.getMethod("getBalance", String.class); + getBalanceOffline = economyClass.getMethod("getBalance", offlinePlayerClass); + has = economyClass.getMethod("has", String.class, double.class); + hasOffline = economyClass.getMethod("has", offlinePlayerClass, double.class); + withdrawPlayer = economyClass.getMethod("withdrawPlayer", String.class, double.class); + withdrawPlayerOffline = economyClass.getMethod("withdrawPlayer", offlinePlayerClass, double.class); + depositPlayer = economyClass.getMethod("depositPlayer", String.class, double.class); + depositPlayerOffline = economyClass.getMethod("depositPlayer", offlinePlayerClass, double.class); + format = economyClass.getMethod("format", double.class); + currencyNamePlural = economyClass.getMethod("currencyNamePlural"); + currencyNameSingular = economyClass.getMethod("currencyNameSingular"); + createPlayerAccount = economyClass.getMethod("createPlayerAccount", String.class); + createPlayerAccountOffline = economyClass.getMethod("createPlayerAccount", offlinePlayerClass); + hasBankSupport = economyClass.getMethod("hasBankSupport"); + getBanks = economyClass.getMethod("getBanks"); + bankBalance = economyClass.getMethod("bankBalance", String.class); + bankHas = economyClass.getMethod("bankHas", String.class, double.class); + bankWithdraw = economyClass.getMethod("bankWithdraw", String.class, double.class); + bankDeposit = economyClass.getMethod("bankDeposit", String.class, double.class); + + // Get EconomyResponse methods + transactionSuccess = economyResponseClass.getMethod("transactionSuccess"); + + // Get the economy instance + economyInstance = BukkitUtil.getServiceProvider(economyClass); + + if (economyInstance != null) { + vaultEnabled = true; + logger.info("Vault Economy integration enabled - Provider: " + getEconomyName()); + } else { + logger.info("Vault found but no Economy provider registered"); + } + + } catch (ClassNotFoundException e) { + logger.debug("Vault not found, economy integration disabled"); + } catch (NoSuchMethodException e) { + logger.error("Vault API method not found, economy integration disabled", e); + } catch (Exception e) { + logger.error("Error initializing Vault integration", e); + } + } + + /** + * Refreshes the economy provider. Call this if the economy plugin loads after initialization. + */ + public static void refreshEconomyProvider() { + if (!initialized || !BukkitUtil.isEnabled()) { + return; + } + + try { + economyInstance = BukkitUtil.getServiceProvider(economyClass); + if (economyInstance != null) { + vaultEnabled = true; + logger.info("Vault Economy provider refreshed: " + getEconomyName()); + } + } catch (Exception e) { + logger.error("Error refreshing Vault economy provider", e); + } + } + + /** + * @return true if Vault economy integration is enabled and working + */ + public static boolean isEnabled() { + if (!vaultEnabled || economyInstance == null) return false; + + try { + return (Boolean) isEnabled.invoke(economyInstance); + } catch (Exception e) { + logger.error("Error checking if economy is enabled", e); + return false; + } + } + + /** + * @return the name of the economy provider, or null if not available + */ + public static String getEconomyName() { + if (!vaultEnabled || economyInstance == null) return null; + + try { + return (String) getName.invoke(economyInstance); + } catch (Exception e) { + logger.error("Error getting economy name", e); + return null; + } + } + + /** + * 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 + */ + public static boolean hasAccount(EntityPlayer player) { + return hasAccount(player.getCommandSenderName()); + } + + /** + * 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 + */ + public static boolean hasAccount(String playerName) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object offlinePlayer = BukkitUtil.getOfflinePlayer(playerName); + if (offlinePlayer != null) { + return (Boolean) hasAccountOffline.invoke(economyInstance, offlinePlayer); + } + return (Boolean) hasAccount.invoke(economyInstance, playerName); + } catch (Exception e) { + logger.error("Error checking if player has account: " + playerName, e); + return false; + } + } + + /** + * Gets the balance of a player. + * + * @param player the player + * @return the player's balance, or 0 if not available + */ + public static double getBalance(EntityPlayer player) { + return getBalance(player.getCommandSenderName()); + } + + /** + * Gets the balance of a player by name. + * + * @param playerName the player name + * @return the player's balance, or 0 if not available + */ + public static double getBalance(String playerName) { + if (!vaultEnabled || economyInstance == null) return 0; + + try { + Object offlinePlayer = BukkitUtil.getOfflinePlayer(playerName); + if (offlinePlayer != null) { + return (Double) getBalanceOffline.invoke(economyInstance, offlinePlayer); + } + return (Double) getBalance.invoke(economyInstance, playerName); + } catch (Exception e) { + logger.error("Error getting balance for player: " + playerName, e); + return 0; + } + } + + /** + * 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 + */ + public static boolean has(EntityPlayer player, double amount) { + return has(player.getCommandSenderName(), amount); + } + + /** + * Checks if a player has at least the specified amount. + * + * @param playerName the player name + * @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) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object offlinePlayer = BukkitUtil.getOfflinePlayer(playerName); + if (offlinePlayer != null) { + return (Boolean) hasOffline.invoke(economyInstance, offlinePlayer, amount); + } + return (Boolean) has.invoke(economyInstance, playerName, amount); + } catch (Exception e) { + logger.error("Error checking if player has amount: " + playerName, e); + return false; + } + } + + /** + * Withdraws money from a player's account. + * + * @param player the player + * @param amount the amount to withdraw + * @return true if the transaction was successful + */ + public static boolean withdrawMoney(EntityPlayer player, double amount) { + return withdrawMoney(player.getCommandSenderName(), amount); + } + + /** + * Withdraws money from a player's account. + * + * @param playerName the player name + * @param amount the amount to withdraw + * @return true if the transaction was successful + */ + public static boolean withdrawMoney(String playerName, double amount) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object offlinePlayer = BukkitUtil.getOfflinePlayer(playerName); + Object response; + if (offlinePlayer != null) { + response = withdrawPlayerOffline.invoke(economyInstance, offlinePlayer, amount); + } else { + response = withdrawPlayer.invoke(economyInstance, playerName, amount); + } + return (Boolean) transactionSuccess.invoke(response); + } catch (Exception e) { + logger.error("Error withdrawing money from player: " + playerName, e); + return false; + } + } + + /** + * 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 + */ + public static boolean addMoney(EntityPlayer player, double amount) { + return addMoney(player.getCommandSenderName(), amount); + } + + /** + * Adds money to a player's account (deposit). + * + * @param playerName the player name + * @param amount the amount to add + * @return true if the transaction was successful + */ + public static boolean addMoney(String playerName, double amount) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object offlinePlayer = BukkitUtil.getOfflinePlayer(playerName); + Object response; + if (offlinePlayer != null) { + response = depositPlayerOffline.invoke(economyInstance, offlinePlayer, amount); + } else { + response = depositPlayer.invoke(economyInstance, playerName, amount); + } + return (Boolean) transactionSuccess.invoke(response); + } catch (Exception e) { + logger.error("Error adding money to player: " + playerName, e); + return false; + } + } + + /** + * 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 + */ + public static boolean setBalance(EntityPlayer player, double amount) { + return setBalance(player.getCommandSenderName(), amount); + } + + /** + * 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 + * @return true if the transaction was successful + */ + public static boolean setBalance(String playerName, double amount) { + if (!vaultEnabled || economyInstance == null) return false; + + double currentBalance = getBalance(playerName); + if (currentBalance > 0) { + if (!withdrawMoney(playerName, currentBalance)) { + return false; + } + } + if (amount > 0) { + return addMoney(playerName, amount); + } + return true; + } + + /** + * 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 + */ + public static String format(double amount) { + if (!vaultEnabled || economyInstance == null) return String.valueOf(amount); + + try { + return (String) format.invoke(economyInstance, amount); + } catch (Exception e) { + logger.error("Error formatting amount", e); + return String.valueOf(amount); + } + } + + /** + * Gets the plural currency name (e.g., "Dollars"). + * + * @return the plural currency name, or "coins" if not available + */ + public static String getCurrencyNamePlural() { + if (!vaultEnabled || economyInstance == null) return "coins"; + + try { + return (String) currencyNamePlural.invoke(economyInstance); + } catch (Exception e) { + logger.error("Error getting currency name plural", e); + return "coins"; + } + } + + /** + * Gets the singular currency name (e.g., "Dollar"). + * + * @return the singular currency name, or "coin" if not available + */ + public static String getCurrencyNameSingular() { + if (!vaultEnabled || economyInstance == null) return "coin"; + + try { + return (String) currencyNameSingular.invoke(economyInstance); + } catch (Exception e) { + logger.error("Error getting currency name singular", e); + return "coin"; + } + } + + /** + * 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 + */ + public static boolean createAccount(EntityPlayer player) { + return createAccount(player.getCommandSenderName()); + } + + /** + * 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 + */ + public static boolean createAccount(String playerName) { + if (!vaultEnabled || economyInstance == null) return false; + + if (hasAccount(playerName)) return true; + + try { + Object offlinePlayer = BukkitUtil.getOfflinePlayer(playerName); + if (offlinePlayer != null) { + return (Boolean) createPlayerAccountOffline.invoke(economyInstance, offlinePlayer); + } + return (Boolean) createPlayerAccount.invoke(economyInstance, playerName); + } catch (Exception e) { + logger.error("Error creating account for player: " + playerName, e); + return false; + } + } + + /** + * @return true if the economy supports bank accounts + */ + public static boolean hasBankSupport() { + if (!vaultEnabled || economyInstance == null) return false; + + try { + return (Boolean) hasBankSupport.invoke(economyInstance); + } catch (Exception e) { + logger.error("Error checking bank support", e); + return false; + } + } + + /** + * Gets a list of all bank names. + * + * @return list of bank names, or empty list if not available + */ + @SuppressWarnings("unchecked") + public static java.util.List getBanks() { + if (!vaultEnabled || economyInstance == null) return java.util.Collections.emptyList(); + + try { + return (java.util.List) getBanks.invoke(economyInstance); + } catch (Exception e) { + logger.error("Error getting banks", e); + return java.util.Collections.emptyList(); + } + } + + /** + * Gets the balance of a bank. + * + * @param bankName the bank name + * @return the bank balance, or 0 if not available + */ + public static double getBankBalance(String bankName) { + if (!vaultEnabled || economyInstance == null) return 0; + + try { + Object response = bankBalance.invoke(economyInstance, bankName); + return economyResponseClass.getField("balance").getDouble(response); + } catch (Exception e) { + logger.error("Error getting bank balance: " + bankName, e); + return 0; + } + } + + /** + * Checks if a bank has at least the specified amount. + * + * @param bankName the bank name + * @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) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object response = bankHas.invoke(economyInstance, bankName, amount); + return (Boolean) transactionSuccess.invoke(response); + } catch (Exception e) { + logger.error("Error checking bank balance: " + bankName, e); + return false; + } + } + + /** + * Withdraws money from a bank. + * + * @param bankName the bank name + * @param amount the amount to withdraw + * @return true if the transaction was successful + */ + public static boolean bankWithdraw(String bankName, double amount) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object response = bankWithdraw.invoke(economyInstance, bankName, amount); + return (Boolean) transactionSuccess.invoke(response); + } catch (Exception e) { + logger.error("Error withdrawing from bank: " + bankName, e); + return false; + } + } + + /** + * Deposits money into a bank. + * + * @param bankName the bank name + * @param amount the amount to deposit + * @return true if the transaction was successful + */ + public static boolean bankDeposit(String bankName, double amount) { + if (!vaultEnabled || economyInstance == null) return false; + + try { + Object response = bankDeposit.invoke(economyInstance, bankName, amount); + return (Boolean) transactionSuccess.invoke(response); + } catch (Exception e) { + logger.error("Error depositing to bank: " + bankName, e); + return false; + } + } + + /** + * Transfers money from one player to another. + * + * @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 + */ + public static boolean transfer(EntityPlayer from, EntityPlayer to, double amount) { + return transfer(from.getCommandSenderName(), to.getCommandSenderName(), amount); + } + + /** + * 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 + * @return true if the transfer was successful + */ + public static boolean transfer(String fromPlayerName, String toPlayerName, double amount) { + if (!has(fromPlayerName, amount)) { + return false; + } + if (!withdrawMoney(fromPlayerName, amount)) { + return false; + } + if (!addMoney(toPlayerName, amount)) { + // Rollback + addMoney(fromPlayerName, amount); + return false; + } + return true; + } +} diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java new file mode 100644 index 000000000..244ed91d1 --- /dev/null +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -0,0 +1,1357 @@ +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 || !currentAbility.isExecuting()) 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 58f931ab8..6229b0f4e 100644 --- a/src/main/java/noppes/npcs/CommonProxy.java +++ b/src/main/java/noppes/npcs/CommonProxy.java @@ -13,13 +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.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.ContainerMerchantAdd; import noppes.npcs.containers.ContainerNPCBankLarge; @@ -92,6 +98,18 @@ public class CommonProxy implements IGuiHandler { if (gui == EnumGuiType.PlayerTrader) return new ContainerNPCTrader(npc, player); + if (gui == EnumGuiType.PlayerAuction) + return new ContainerAuctionListing(npc, player); + + if (gui == EnumGuiType.PlayerAuctionSell) + return new ContainerAuctionSell(npc, player); + + if (gui == EnumGuiType.PlayerAuctionTrades) + return new ContainerAuctionTrades(npc, player); + + if (gui == EnumGuiType.PlayerAuctionBidding) + return new ContainerAuctionBidding(npc, player); + if (gui == EnumGuiType.PlayerCarpentryBench) return new ContainerCarpentryBench(player.inventory, player.worldObj, x, y, z); @@ -119,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); @@ -200,4 +221,27 @@ public class CommonProxy implements IGuiHandler { public boolean isGUIOpen() { return false; } + + public void buildPackageIndex() { + } + + public boolean isScriptingEnabled() { + return ConfigScript.ScriptingEnabled; + } + + public boolean isRunLoadedScriptsFirst() { + return ConfigScript.RunLoadedScriptsFirst; + } + + public boolean isGlobalPlayerScripts() { + return ConfigScript.GlobalPlayerScripts; + } + + public boolean isGlobalForgeScripts() { + return ConfigScript.GlobalForgeScripts; + } + + public boolean isGlobalNPCScripts() { + return ConfigScript.GlobalNPCScripts; + } } diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 4b5750c6a..5f020e507 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -5,6 +5,7 @@ import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; +import cpw.mods.fml.common.event.FMLLoadCompleteEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerAboutToStartEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; @@ -13,16 +14,34 @@ import cpw.mods.fml.common.event.FMLServerStoppedEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import foxz.command.CommandNoppes; +import io.github.somehussar.janinoloader.api.IDynamicCompiler; +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.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; import net.minecraft.block.BlockIce; import net.minecraft.block.BlockLeavesBase; @@ -49,6 +68,7 @@ import noppes.npcs.config.ConfigMain; import noppes.npcs.config.LoadConfiguration; import noppes.npcs.config.legacy.LegacyConfig; import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.AuctionController; import noppes.npcs.controllers.BankController; import noppes.npcs.controllers.ChunkController; import noppes.npcs.controllers.CustomEffectController; @@ -62,6 +82,7 @@ import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.QuestController; import noppes.npcs.controllers.RecipeController; import noppes.npcs.controllers.ScriptController; +import noppes.npcs.controllers.ScriptHookController; import noppes.npcs.controllers.ServerCloneController; import noppes.npcs.controllers.ServerTagMapController; import noppes.npcs.controllers.SpawnController; @@ -96,11 +117,14 @@ import noppes.npcs.entity.old.EntityNpcNagaFemale; import noppes.npcs.entity.old.EntityNpcNagaMale; import noppes.npcs.entity.old.EntityNpcSkeleton; import noppes.npcs.scripted.NpcAPI; +import somehussar.janino.AdvancedClassFilter; import java.io.File; +import java.util.HashSet; import java.util.Set; +import java.util.function.Consumer; -@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.10.3") +@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11") public class CustomNpcs { @SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy") @@ -137,10 +161,56 @@ public class CustomNpcs { public static MinecraftServer Server; + private static IDynamicCompiler globalJaninoCompiler; + @SideOnly(Side.CLIENT) + private static IDynamicCompiler clientJaninoCompiler; + @SideOnly(Side.CLIENT) + private static Set> clientClassFilterConsumer; + + static { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + clientClassFilterConsumer = new HashSet<>(); + } + } + + @SideOnly(Side.CLIENT) + public static void addClassesToClientClassFilter(Consumer consumer) { + clientClassFilterConsumer.add(consumer); + } + public CustomNpcs() { instance = this; } + public static IDynamicCompiler getDynamicCompiler() { + if (globalJaninoCompiler == null) { + globalJaninoCompiler = IDynamicCompilerBuilder.createBuilder().getCompiler(); + } + + return globalJaninoCompiler; + } + + @SideOnly(Side.CLIENT) + public static IDynamicCompiler getClientCompiler() { + + if (clientJaninoCompiler == null) { + AdvancedClassFilter filter = new AdvancedClassFilter() + .addRegexes("noppes\\.npcs\\.api\\..*") + .banRegexes(".*ClassLoader.*", + ".*File*.", + "java\\.lang\\.reflect\\..*"); + + for (Consumer consumer : clientClassFilterConsumer) { + consumer.accept(filter); + } + + + clientJaninoCompiler = IDynamicCompilerBuilder.createBuilder().setClassFilter(filter).getCompiler(); + } + + return clientJaninoCompiler; + } + @EventHandler public void load(FMLPreInitializationEvent ev) { PacketHandler.Instance = new PacketHandler(); @@ -180,6 +250,7 @@ public class CustomNpcs { MinecraftForge.EVENT_BUS.register(new ServerEventsHandler()); MinecraftForge.EVENT_BUS.register(new ScriptController()); + new ScriptHookController(); ScriptPlayerEventHandler scriptPlayerEventHandler = new ScriptPlayerEventHandler(); MinecraftForge.EVENT_BUS.register(scriptPlayerEventHandler); @@ -223,6 +294,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, 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(); @@ -255,9 +335,27 @@ public class CustomNpcs { PacketHandler.Instance.registerChannels(); } + @EventHandler + public void loadComplete(FMLLoadCompleteEvent ev) { + 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 public void setAboutToStart(FMLServerAboutToStartEvent event) { + globalJaninoCompiler = null; + if (FMLCommonHandler.instance().getSide().isClient()) + clientJaninoCompiler = null; + Server = event.getServer(); + AnimationController.Instance.load(); ChunkController.Instance.clear(); FactionController.getInstance().load(); MagicController.getInstance().load(); @@ -267,7 +365,8 @@ public class CustomNpcs { new GlobalDataController(); new SpawnController(); new LinkedNpcController(); - new AnimationController(); + AbilityController.Instance.load(); + TelegraphController.init(); LinkedItemController.getInstance().load(); @@ -306,12 +405,17 @@ public class CustomNpcs { public void started(FMLServerStartedEvent event) { RecipeController.Instance.load(); new BankController(); + new AuctionController(); DialogController.Instance.load(); QuestController.Instance.load(); ScriptController.HasStart = true; ServerCloneController.Instance = new ServerCloneController(); ServerTagMapController.Instance = new ServerTagMapController(); SyncController.load(); + + // Initialize Bukkit integration (loads Vault and Permissions) + BukkitUtil.init(); + CustomNpcsPermissions.Instance.init(); } @@ -322,6 +426,19 @@ public class CustomNpcs { ScriptController.Instance.saveForgeScripts(); ScriptController.Instance.savePlayerScripts(); ScriptController.Instance.saveGlobalNpcScripts(); + + // Save auction data synchronously on shutdown + if (AuctionController.Instance != null) { + AuctionController.Instance.save(); + } + + EntityEnergyProjectile.clearAllProjectiles(); + EntityEnergyBarrier.clearAllBarriers(); + EnergyChargeTracker.Instance.clear(); + + if (FMLCommonHandler.instance().getSide().isClient()) + clientJaninoCompiler = null; + globalJaninoCompiler = null; } @EventHandler diff --git a/src/main/java/noppes/npcs/CustomNpcsPermissions.java b/src/main/java/noppes/npcs/CustomNpcsPermissions.java index 3363c0351..d27a509e5 100644 --- a/src/main/java/noppes/npcs/CustomNpcsPermissions.java +++ b/src/main/java/noppes/npcs/CustomNpcsPermissions.java @@ -3,6 +3,7 @@ package noppes.npcs; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.developer.Developer; +import kamkeel.npcs.util.BukkitUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import org.apache.logging.log4j.LogManager; @@ -47,7 +48,8 @@ public class CustomNpcsPermissions { public static final Permission NPC_ADVANCED_TRANSPORT = new Permission("customnpcs.npc.advanced.transport"); public static final Permission NPC_ADVANCED_TRANSFORM = new Permission("customnpcs.npc.advanced.transform"); public static final Permission NPC_ADVANCED_LINKED = new Permission("customnpcs.npc.advanced.linked"); - public static final Permission NPC_ADVANCED_MAGIC = new Permission("customnpcs.npc.advanced.linked"); + public static final Permission NPC_ADVANCED_MAGIC = new Permission("customnpcs.npc.advanced.magic"); + public static final Permission NPC_ADVANCED_ABILITIES = new Permission("customnpcs.npc.advanced.abilities"); public static final Permission NPC_ADVANCED_TAGS = new Permission("customnpcs.npc.advanced.tags"); public static final Permission GLOBAL_REMOTE = new Permission("customnpcs.global.remote"); @@ -65,7 +67,9 @@ public class CustomNpcsPermissions { public static final Permission GLOBAL_TAG = new Permission("customnpcs.global.tag"); public static final Permission GLOBAL_ANIMATION = new Permission("customnpcs.global.animation"); 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"); @@ -109,24 +113,29 @@ public class CustomNpcsPermissions { public static final Permission PROFILE_MAX = new Permission("customnpcs.profile.max.*"); public static CustomNpcsPermissions Instance; - private Class bukkit; - private Method getPlayer; private Method hasPermission; public CustomNpcsPermissions() { Instance = this; + } + + /** + * Initializes permission checking using BukkitUtil. + * Called after BukkitUtil is initialized on server start. + */ + public void init() { + if (!BukkitUtil.isEnabled()) { + return; + } + try { - bukkit = Class.forName("org.bukkit.Bukkit"); - getPlayer = bukkit.getMethod("getPlayer", String.class); - hasPermission = Class.forName("org.bukkit.entity.Player").getMethod("hasPermission", String.class); + hasPermission = BukkitUtil.getPlayerClass().getMethod("hasPermission", String.class); LogManager.getLogger(CustomNpcs.class).info("Bukkit permissions enabled"); LogManager.getLogger(CustomNpcs.class).info("Permissions available:"); Collections.sort(Permission.permissions, String.CASE_INSENSITIVE_ORDER); for (String p : Permission.permissions) { LogManager.getLogger(CustomNpcs.class).info(p); } - } catch (ClassNotFoundException e) { - // bukkit/mcpc+ is not loaded } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { @@ -141,7 +150,7 @@ public class CustomNpcsPermissions { if (Developer.Instance.hasUniversal(player.getUniqueID())) return true; if (permission != null) { - if (Instance.bukkit != null) { + if (BukkitUtil.isEnabled()) { return Instance.bukkitPermission(player.getCommandSenderName(), permission.name); } } @@ -155,7 +164,7 @@ public class CustomNpcsPermissions { return true; if (Developer.Instance.hasUniversal(player.getUniqueID())) return true; - if (Instance.bukkit != null) { + if (BukkitUtil.isEnabled()) { return Instance.bukkitPermission(player.getCommandSenderName(), permission); } } @@ -163,8 +172,11 @@ public class CustomNpcsPermissions { } private boolean bukkitPermission(String username, String permission) { + if (hasPermission == null) return false; + try { - Object player = getPlayer.invoke(null, username); + Object player = BukkitUtil.getPlayer(username); + if (player == null) return false; return (Boolean) hasPermission.invoke(player, permission); } catch (IllegalAccessException e) { e.printStackTrace(); @@ -188,13 +200,13 @@ public class CustomNpcsPermissions { } public static boolean hasPermissionString(EntityPlayerMP player, String permission) { - if (Instance.bukkit != null) { + if (BukkitUtil.isEnabled()) { return Instance.bukkitPermission(player.getCommandSenderName(), permission); } return true; } public static boolean enabled() { - return Instance.bukkit != null; + return BukkitUtil.isEnabled(); } } diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java new file mode 100644 index 000000000..74b8b057f --- /dev/null +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -0,0 +1,1171 @@ +package noppes.npcs; + +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.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.data.Animation; +import noppes.npcs.entity.EntityNPCInterface; +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. + * Extends AbstractDataAbilities for shared ability lifecycle logic. + */ +public class DataAbilities extends AbstractDataAbilities { + + private final EntityNPCInterface npc; + private final Random random = new Random(); + + // ═══════════════════════════════════════════════════════════════════ + // CONFIGURATION (saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Unified list of action slots (abilities and chained abilities). + */ + private List actionSlots = new ArrayList<>(); + + /** + * Whether the ability system is enabled for this NPC + */ + public boolean enabled = true; + + /** + * Minimum cooldown ticks between abilities (global minimum) + */ + public int minCooldown = 80; + + /** + * Maximum cooldown ticks between abilities (global maximum) + */ + public int maxCooldown = 200; + + // ═══════════════════════════════════════════════════════════════════ + // NPC-SPECIFIC RUNTIME STATE (not saved) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Last target used for ability execution + */ + private transient EntityLivingBase lastTarget; + + /** + * Recent hit timestamps for hit count condition + */ + private transient List recentHitTimes = new ArrayList<>(); + + /** + * NPC-specific locked rotation fields (yawHead, renderYawOffset). + * Base class handles lockedYaw and lockedPitch. + */ + private transient float lockedYawHead = 0; + private transient float lockedRenderYawOffset = 0; + + /** + * Hit scan state - forces NPC to face target. + * 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 + // ═══════════════════════════════════════════════════════════════════ + + public DataAbilities(EntityNPCInterface npc) { + 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); + } + cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + ability.getCooldownTicks(); + + // Additionally set per-ability cooldown if enabled + if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) { + long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks(); + setPerAbilityCooldown(ability.getName(), endTime, ability.getCooldownTicks()); + } + } + + @Override + protected void rollChainCooldown(ChainedAbility chain) { + int baseCooldown = minCooldown; + if (maxCooldown > minCooldown) { + baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); + } + cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + 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() + // ═══════════════════════════════════════════════════════════════════ + + /** + * Main tick method - handles ability execution and cooldown management. + * Should be called every tick from onLivingUpdate(). + */ + public void tick() { + if (npc.worldObj.isRemote) { + return; + } + + // Force-stop any running ability when NPC is killed or abilities are disabled + if (!enabled || npc.isKilled()) { + if (currentAbility != null) { + removeTelegraph(currentAbility); + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + currentAbility = null; + lastTarget = null; + } else { + // No ability but locks could be orphaned + if (rotationLocked || hitScanActive) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + // 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()) && chainDelayRemaining <= 0) { + if (rotationLocked || hitScanActive) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + + // 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(); + } + } + + /** + * Apply movement control based on lock movement settings. + * Called every tick during ability execution via onPostPhaseTick(). + */ + private void applyMovementControl() { + if (currentAbility == null) return; + + // Check if movement should be locked for the current phase + if (currentAbility.isMovementLockedForCurrentPhase()) { + // Clear navigator to prevent AI pathfinding + npc.getNavigator().clearPathEntity(); + + // Zero motion if ability doesn't have its own movement + // This allows abilities like Charge/Slam to control their own motion + if (!currentAbility.hasAbilityMovement()) { + npc.motionX = 0; + npc.motionZ = 0; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ABILITY SELECTION - Called from CombatHandler + // ═══════════════════════════════════════════════════════════════════ + + /** + * 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 + * @return true if an ability was started + */ + public boolean trySelectAndStart(EntityLivingBase target) { + if (!canSelectAbility()) { + return false; + } + + // 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; + } + + // 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 || 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; + } + return true; + } + + /** + * Check if an action (ability or chain) is eligible for use. + */ + private boolean isActionEligible(AbilityAction slot, IAbilityAction action, EntityLivingBase target) { + if (!action.getAllowedBy().allowsNpc()) { + return false; + } + if (!slot.isSlotEnabled()) { + return false; + } + + // Ability-specific: check if already executing + if (!action.isChain() && ((Ability) action).isExecuting()) { + return false; + } + + // Chain-specific: must have entries + if (action.isChain() && ((ChainedAbility) action).getEntries().isEmpty()) { + return false; + } + + // Range check + if (target != null) { + float distance = npc.getDistanceToEntity(target); + if (distance < action.getMinRange() || distance > action.getMaxRange()) { + return false; + } + } + + // Conditions + if (!action.checkConditions(npc, target)) { + return false; + } + + // Per-ability cooldown filter: ability may have its own independent cooldown + if (!action.isChain()) { + Ability ab = (Ability) action; + if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) { + return false; + } + } + + return true; + } + + /** + * Start executing an ability. + */ + private boolean startAbility(Ability ability, EntityLivingBase target) { + // Fire start event (cancelable) + 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; + } + + currentAbility = ability; + lastTarget = target; + 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; + } + + // ═══════════════════════════════════════════════════════════════════ + // INTERRUPTION - Called from CombatHandler on damage + // ═══════════════════════════════════════════════════════════════════ + + /** + * Handle damage taken - may interrupt current ability or trigger guard counter. + * + * @param source The damage source + * @param amount The damage amount + * @return true if ability was interrupted + */ + public boolean onDamage(DamageSource source, float amount) { + if (currentAbility == null || !currentAbility.isExecuting()) { + return false; + } + if (currentAbility.isInvulnerableForCurrentPhase()) { + return false; + } + + // Track hit for hit count condition + recordHit(); + if (currentAbility.canInterrupt(source)) { + interruptCurrentAbility(source, amount); + return true; + } + + return false; + } + + /** + * Record a hit for the hit count condition. + * Includes periodic cleanup to prevent memory leak. + */ + private void recordHit() { + long currentTime = npc.worldObj.getTotalWorldTime(); + recentHitTimes.add(currentTime); + + // Cleanup old entries periodically to prevent unbounded growth + // Keep only hits from last 5 minutes (6000 ticks) max + if (recentHitTimes.size() > 50) { + long cutoff = currentTime - 6000; + recentHitTimes.removeIf(time -> time < cutoff); + } + } + + /** + * Get the number of hits received within the specified tick window. + * + * @param withinTicks The time window in ticks + * @return Number of hits in that window + */ + public int getRecentHitCount(int withinTicks) { + long currentTime = npc.worldObj.getTotalWorldTime(); + long cutoff = currentTime - withinTicks; + + // Clean up old entries and count + int count = 0; + recentHitTimes.removeIf(time -> time < cutoff); + for (Long time : recentHitTimes) { + if (time >= cutoff) { + count++; + } + } + return count; + } + + /** + * Force stop the current ability (no interrupt event). + */ + public void stopCurrentAbility() { + if (currentAbility != null) { + removeTelegraph(currentAbility); + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + currentAbility.interrupt(); + currentAbility = null; + lastTarget = null; + } + // Also clear chain state + if (currentChain != null) currentChain.clearInstanceScript(); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + } + + /** + * Force start a specific ability, bypassing normal selection and cooldown. + * 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) + * @return true if the ability was started successfully + */ + public boolean forceStartAbility(Ability ability, EntityLivingBase target) { + if (ability == null || npc.worldObj.isRemote) { + return false; + } + + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + + // Stop any currently executing ability + stopCurrentAbility(); + + // Reset the ability state + ability.reset(); + + // Start the ability directly + return startAbility(ability, target); + } + + /** + * 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 target The target entity (can be null for self-targeted abilities) + * @return true if the ability was started successfully + */ + public boolean executeAbility(String key, EntityLivingBase target) { + if (key == null || key.isEmpty() || npc.worldObj.isRemote) { + return false; + } + + Ability resolved = AbilityController.Instance.resolveAbility(key); + if (resolved == null) { + return false; + } + + return forceStartAbility(resolved, target); + } + + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT EVENTS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Get the NPC this DataAbilities belongs to. + */ + public EntityNPCInterface getNpc() { + return npc; + } + + // ═══════════════════════════════════════════════════════════════════ + // RESET - Called on NPC death/respawn + // ═══════════════════════════════════════════════════════════════════ + + /** + * Reset all runtime state (cooldowns, current ability). + * Called when NPC respawns or combat ends. + * Rolls cooldown so NPC doesn't immediately use an ability. + */ + public void reset() { + stopCurrentAbility(); + clearActiveToggles(); + interruptConcurrentSlots(); + resetAllPerAbilityCooldowns(); + + // Roll cooldown so NPC doesn't immediately attack after reset + rollCooldownOnReset(); + + // Reset execution state on all resolved abilities + for (Ability ability : getAbilities()) { + ability.reset(); + } + } + + /** + * Roll a new cooldown using the min/max range (without ability offset). + * Called on reset when no ability is involved. + */ + private void rollCooldownOnReset() { + int baseCooldown = minCooldown; + if (maxCooldown > minCooldown) { + baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); + } + cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown; + } + + // ═══════════════════════════════════════════════════════════════════ + // ACTION SLOT MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * 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 (AbilityAction slot : actionSlots) { + Ability a = slot.getAbility(); + if (a != null) { + resolved.add(a); + } + } + return resolved; + } + + /** + * Add an inline ability. + */ + public void addAbility(Ability ability) { + actionSlots.add(AbilityAction.inline(ability)); + } + + /** + * Add a reference ability by key (built-in name or custom ability name). + */ + public void addAbilityReference(String key) { + actionSlots.add(AbilityAction.abilityReference(key)); + } + + /** + * 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) { + 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 (AbilityAction slot : actionSlots) { + Ability a = slot.getAbility(); + if (a != null && a.getId().equals(id)) { + return a; + } + } + return null; + } + + /** + * Check if a slot at a given index is a reference. + */ + public boolean isSlotReference(int index) { + if (index < 0 || index >= actionSlots.size()) return false; + return actionSlots.get(index).isReference(); + } + + /** + * Convert a reference slot to inline. Returns false if resolution fails or is a chain. + */ + public boolean convertToInline(int index) { + if (index < 0 || index >= actionSlots.size()) return false; + return actionSlots.get(index).convertToInline(); + } + + public void clearAbilities() { + actionSlots.clear(); + } + + public boolean isEmpty() { + return actionSlots.isEmpty(); + } + + // ═══════════════════════════════════════════════════════════════════ + // STATE QUERIES (NPC-specific) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if ability is controlling NPC movement (AI pathfinding should be blocked). + * Called by AI tasks to determine if they should try to path. + *

+ * Rules: + * - WINDUP phase: Block AI if movement is locked during windup + * - ACTIVE phase: Block AI if movement is locked during active OR hasAbilityMovement is true + * - DAZED phase: Always block AI (NPC is stunned) + */ + public boolean isAbilityControllingMovement() { + if (currentAbility == null || !currentAbility.isExecuting()) { + return false; + } + + AbilityPhase phase = currentAbility.getPhase(); + + switch (phase) { + case WINDUP: + // During windup, only block if movement is locked during windup + // This allows NPC to keep chasing while winding up if not locked + return currentAbility.isMovementLockedDuringWindup(); + + case ACTIVE: + // During active phase, block if either: + // - movement is locked during active (stationary ability) + // - hasAbilityMovement is true (ability is moving the NPC itself) + return currentAbility.isMovementLockedDuringActive() || currentAbility.hasAbilityMovement(); + + case DAZED: + // During dazed phase, always block - NPC is stunned from interrupt + return true; + + default: + return false; + } + } + + /** + * Check if NPC's look direction should be locked to target. + * Only locks during ACTIVE phase when movement is locked during active. + * This allows the NPC to freely track target during WINDUP and DAZED. + */ + public boolean shouldLockLookDirection() { + if (currentAbility == null || !currentAbility.isExecuting()) { + return false; + } + + // Only lock look direction during ACTIVE phase + if (currentAbility.getPhase() != AbilityPhase.ACTIVE) { + return false; + } + + return currentAbility.isMovementLockedDuringActive(); + } + + /** + * Check if NPC should skip normal attacks during ability execution. + */ + public boolean shouldBlockAttack() { + if (currentAbility == null || !currentAbility.isExecuting()) { + return false; + } + AbilityPhase phase = currentAbility.getPhase(); + return phase == AbilityPhase.WINDUP || phase == AbilityPhase.ACTIVE; + } + + // ═══════════════════════════════════════════════════════════════════ + // ROTATION CONTROL (NPC-specific: hit scan + 4-field rotation) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Enable hit scan tracking for the given 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; + + /** + * 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, 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 targetYaw = (float) (Math.atan2(-dx, dz) * RAD_TO_DEG); + float targetPitch = (float) (-(Math.atan2(dy, distXZ)) * RAD_TO_DEG); + + 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. + */ + public void applyRotationControl() { + if (npc.worldObj.isRemote) { + // Client: check single flag for any rotation control + if (!npc.getBoolFlag(ROTATION_CONTROLLED_FLAG)) { + rotationLocked = false; + return; + } + // Trust server rotation, prevent body smoothing from overriding + npc.prevRotationYaw = npc.rotationYaw; + npc.prevRotationYawHead = npc.rotationYawHead; + npc.renderYawOffset = npc.rotationYawHead; + npc.prevRenderYawOffset = npc.rotationYawHead; + npc.prevRotationPitch = npc.rotationPitch; + return; + } + + // Server: apply the appropriate rotation + if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) { + faceTarget(hitScanTarget, currentTrackSpeed); + } else if (rotationLocked) { + npc.rotationYaw = lockedYaw; + npc.rotationYawHead = lockedYawHead; + npc.renderYawOffset = lockedRenderYawOffset; + npc.rotationPitch = lockedPitch; + npc.prevRotationYaw = lockedYaw; + npc.prevRotationYawHead = lockedYawHead; + npc.prevRenderYawOffset = lockedRenderYawOffset; + npc.prevRotationPitch = lockedPitch; + } + } + + /** + * Check if rotation is currently controlled (locked or tracking target). + * Used by AI tasks to determine if they should try to change NPC look direction. + */ + public boolean isRotationLocked() { + return rotationLocked || hitScanActive; + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING (NPC-specific: data watcher + client-side logic) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Apply locked position values to the NPC. + * Called AFTER super.onLivingUpdate() in EntityNPCInterface to override + * any position changes from AI pathfinding, physics, or entity collisions. + * Runs on both client and server. + */ + public void applyLockedPosition() { + if (npc.worldObj.isRemote) { + // Client-side: check flag via data watcher + boolean flagActive = npc.getBoolFlag(POSITION_LOCKED_FLAG); + if (!flagActive) { + positionLocked = false; + return; + } + // First tick the flag is active: capture current position + if (!positionLocked) { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + } + // Snap position back and set prev to prevent interpolation jitter + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; + return; + } + + // Server-side: use stored locked values + if (!positionLocked) { + return; + } + + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("AbilitiesEnabled", enabled); + compound.setInteger("AbilityMinCooldown", minCooldown); + compound.setInteger("AbilityMaxCooldown", maxCooldown); + + NBTTagList actionList = new NBTTagList(); + for (AbilityAction slot : actionSlots) { + actionList.appendTag(slot.writeNBT(true)); + } + 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.hasKey("AbilitiesEnabled") ? compound.getBoolean("AbilitiesEnabled") : true; + minCooldown = compound.getInteger("AbilityMinCooldown"); + maxCooldown = compound.getInteger("AbilityMaxCooldown"); + + 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/DataAdvanced.java b/src/main/java/noppes/npcs/DataAdvanced.java index 45ecfe4a8..f03714506 100644 --- a/src/main/java/noppes/npcs/DataAdvanced.java +++ b/src/main/java/noppes/npcs/DataAdvanced.java @@ -18,6 +18,7 @@ import noppes.npcs.roles.JobGuard; import noppes.npcs.roles.JobHealer; import noppes.npcs.roles.JobItemGiver; import noppes.npcs.roles.JobSpawner; +import noppes.npcs.roles.RoleAuctioneer; import noppes.npcs.roles.RoleBank; import noppes.npcs.roles.RoleCompanion; import noppes.npcs.roles.RoleFollower; @@ -218,6 +219,8 @@ public class DataAdvanced { npc.roleInterface = new RoleCompanion(npc); else if (role == EnumRoleType.Mount && !(npc.roleInterface instanceof RoleMount)) npc.roleInterface = new RoleMount(npc); + else if (role == EnumRoleType.Auctioneer && !(npc.roleInterface instanceof RoleAuctioneer)) + npc.roleInterface = new RoleAuctioneer(npc); } public void setJob(int i) { 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 9cb5b1669..b783f98e0 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; @@ -38,9 +42,7 @@ import noppes.npcs.controllers.CustomGuiController; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.Dialog; -import noppes.npcs.controllers.data.EffectScript; import noppes.npcs.controllers.data.ForgeDataScript; -import noppes.npcs.controllers.data.INpcScriptHandler; import noppes.npcs.controllers.data.IScriptBlockHandler; import noppes.npcs.controllers.data.IScriptHandler; import noppes.npcs.controllers.data.Party; @@ -51,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; @@ -61,6 +73,7 @@ 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; @@ -85,7 +98,7 @@ public class EventHooks { } public static void onScriptItemInit(IItemCustomizable item) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); if (handler != null && !handler.isClient()) { ItemEvent.InitEvent event = new ItemEvent.InitEvent(item); handler.callScript(EnumScriptType.INIT, event); @@ -94,7 +107,7 @@ public class EventHooks { } public static void onScriptItemUpdate(IItemCustomizable item, EntityLivingBase player) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); if (handler != null && !handler.isClient()) { ItemEvent.UpdateEvent event = new ItemEvent.UpdateEvent(item, NpcAPI.Instance().getIEntity(player)); handler.callScript(EnumScriptType.TICK, event); @@ -103,7 +116,7 @@ public class EventHooks { } public static boolean onScriptItemTossed(IItemCustomizable item, EntityPlayer player, EntityItem entity) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.TossedEvent event = new ItemEvent.TossedEvent(item, (IPlayer) NpcAPI.Instance().getIEntity(player), NpcAPI.Instance().getIEntity(entity)); if (handler != null) { handler.callScript(EnumScriptType.TOSSED, event); @@ -112,7 +125,7 @@ public class EventHooks { } public static boolean onScriptItemPickedUp(IItemCustomizable item, EntityPlayer player) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.PickedUpEvent event = new ItemEvent.PickedUpEvent(item, (IPlayer) NpcAPI.Instance().getIEntity(player)); if (handler != null) { handler.callScript(EnumScriptType.PICKEDUP, event); @@ -121,7 +134,7 @@ public class EventHooks { } public static boolean onScriptItemSpawn(IItemCustomizable item, EntityItem entity) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.SpawnEvent event = new ItemEvent.SpawnEvent(item, NpcAPI.Instance().getIEntity(entity)); if (handler != null) { handler.callScript(EnumScriptType.SPAWN, event); @@ -130,7 +143,7 @@ public class EventHooks { } public static boolean onScriptItemInteract(IItemCustomizable item, noppes.npcs.scripted.event.ItemEvent.InteractEvent event) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); if (handler != null) { handler.callScript(EnumScriptType.INTERACT, event); } @@ -138,7 +151,7 @@ public class EventHooks { } public static boolean onScriptItemRightClick(IItemCustomizable item, noppes.npcs.scripted.event.ItemEvent.RightClickEvent event) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); if (handler != null) { handler.callScript(EnumScriptType.RIGHT_CLICK, event); } @@ -146,7 +159,7 @@ public class EventHooks { } public static boolean onScriptItemAttack(IItemCustomizable item, noppes.npcs.scripted.event.ItemEvent.AttackEvent event) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); if (handler != null) { handler.callScript(EnumScriptType.ATTACK, event); } @@ -154,7 +167,7 @@ public class EventHooks { } public static boolean onStartUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.StartUsingItem event = new ItemEvent.StartUsingItem(item, player, duration); if (handler != null) { handler.callScript(EnumScriptType.START_USING_ITEM, event); @@ -163,7 +176,7 @@ public class EventHooks { } public static boolean onUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.UsingItem event = new ItemEvent.UsingItem(item, player, duration); if (handler != null) { handler.callScript(EnumScriptType.USING_ITEM, event); @@ -172,7 +185,7 @@ public class EventHooks { } public static boolean onStopUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.StopUsingItem event = new ItemEvent.StopUsingItem(item, player, duration); if (handler != null) { handler.callScript(EnumScriptType.STOP_USING_ITEM, event); @@ -181,7 +194,7 @@ public class EventHooks { } public static boolean onFinishUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.FinishUsingItem event = new ItemEvent.FinishUsingItem(item, player, duration); if (handler != null) { handler.callScript(EnumScriptType.FINISH_USING_ITEM, event); @@ -190,7 +203,7 @@ public class EventHooks { } public static void onRepairCustomItem(IItemCustomizable item, IPlayer player, IItemStack left, IItemStack right, float anvilBreakChance) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.RepairItem event = new ItemEvent.RepairItem(item, player, left, right, anvilBreakChance); if (handler != null) { handler.callScript(EnumScriptType.REPAIR_ITEM, event); @@ -199,7 +212,7 @@ public class EventHooks { } public static void onBreakCustomItem(IItemCustomizable item, IPlayer player) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); ItemEvent.BreakItem event = new ItemEvent.BreakItem(item, player); if (handler != null) { handler.callScript(EnumScriptType.BREAK_ITEM, event); @@ -242,7 +255,7 @@ public class EventHooks { public static void onLinkedItemVersionChange(IItemLinked item, int version, int prevVersion) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); LinkedItemEvent.VersionChangeEvent event = new LinkedItemEvent.VersionChangeEvent(item, version, prevVersion); if (handler != null) { handler.callScript(EnumScriptType.LINKED_ITEM_VERSION, event); @@ -251,7 +264,7 @@ public class EventHooks { } public static void onLinkedItemBuild(IItemLinked item) { - INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler(); + IScriptHandler handler = (IScriptHandler) item.getScriptHandler(); LinkedItemEvent.BuildEvent event = new LinkedItemEvent.BuildEvent(item); if (handler != null) { handler.callScript(EnumScriptType.LINKED_ITEM_BUILD, event); @@ -298,7 +311,6 @@ public class EventHooks { NpcEvent.DialogClosedEvent event = new NpcEvent.DialogClosedEvent(npc.wrappedNPC, player, dialogId, optionId, dialog); ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.DIALOG_CLOSE, event); npc.script.callScript(EnumScriptType.DIALOG_CLOSE, event, "player", event.getPlayer(), "dialog", event.getDialogId(), "option", event.getOptionId(), "dialogObj", event.getDialog()); - NpcAPI.EVENT_BUS.post(event); } @@ -421,7 +433,9 @@ public class EventHooks { EntityLivingBase thrower = projectile.getThrower(); if (thrower != null) { if (thrower instanceof EntityNPCInterface) { - ((EntityNPCInterface) thrower).script.callScript(EnumScriptType.PROJECTILE_TICK, event); + EntityNPCInterface npc = (EntityNPCInterface) thrower; + + npc.script.callScript(EnumScriptType.PROJECTILE_TICK, event); } } @@ -439,13 +453,167 @@ public class EventHooks { EntityLivingBase thrower = projectile.getThrower(); if (thrower != null) { if (thrower instanceof EntityNPCInterface) { - ((EntityNPCInterface) thrower).script.callScript(EnumScriptType.PROJECTILE_IMPACT, event); + EntityNPCInterface npc = (EntityNPCInterface) thrower; + + npc.script.callScript(EnumScriptType.PROJECTILE_IMPACT, event); } } 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) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.UpdateEvent event = new EnergyProjectileEvent.UpdateEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + /** + * Fires the entity impact event. Returns the (possibly modified) damage, or -1 if cancelled. + */ + public static float onEnergyProjectileEntityImpact(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); @@ -489,21 +657,21 @@ public class EventHooks { public static boolean onEffectAdded(IPlayer player, IPlayerEffect effect) { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); PlayerEvent.EffectEvent.Added event = new PlayerEvent.EffectEvent.Added(player, effect); - handler.callScript(EffectScript.ScriptType.OnEffectAdd.function, event); + handler.callScript(EnumScriptType.ON_EFFECT_ADD.function, event); return NpcAPI.EVENT_BUS.post(event); } public static boolean onEffectTick(IPlayer player, IPlayerEffect effect) { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); PlayerEvent.EffectEvent.Ticked event = new PlayerEvent.EffectEvent.Ticked(player, effect); - handler.callScript(EffectScript.ScriptType.OnEffectTick.function, event); + handler.callScript(EnumScriptType.ON_EFFECT_TICK.function, event); return NpcAPI.EVENT_BUS.post(event); } public static boolean onEffectRemove(IPlayer player, IPlayerEffect effect, EffectEvent.ExpirationType type) { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); PlayerEvent.EffectEvent.Removed event = new PlayerEvent.EffectEvent.Removed(player, effect, type); - handler.callScript(EffectScript.ScriptType.OnEffectRemove.function, event); + handler.callScript(EnumScriptType.ON_EFFECT_REMOVE.function, event); return NpcAPI.EVENT_BUS.post(event); } @@ -691,6 +859,150 @@ public class EventHooks { return NpcAPI.EVENT_BUS.post(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 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); @@ -1064,4 +1376,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/NBTTags.java b/src/main/java/noppes/npcs/NBTTags.java index ebf30ab94..6eec4c14d 100644 --- a/src/main/java/noppes/npcs/NBTTags.java +++ b/src/main/java/noppes/npcs/NBTTags.java @@ -6,8 +6,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagDouble; import net.minecraft.nbt.NBTTagInt; import net.minecraft.nbt.NBTTagList; -import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.data.IScriptHandler; +import noppes.npcs.controllers.data.IScriptUnit; import java.util.ArrayList; import java.util.HashMap; @@ -540,38 +540,33 @@ public class NBTTags { } } - public static List GetScriptOld(NBTTagList list, IScriptHandler handler) { - ArrayList scripts = new ArrayList(); + public static List GetScriptOld(NBTTagList list, IScriptHandler handler) { + ArrayList scripts = new ArrayList<>(); for (int i = 0; i < list.tagCount(); ++i) { NBTTagCompound compoundd = list.getCompoundTagAt(i); - ScriptContainer script = new ScriptContainer(handler); - script.readFromNBT(compoundd); + IScriptUnit script = IScriptUnit.createFromNBT(compoundd, handler); scripts.add(script); } return scripts; } - public static List GetScript(NBTTagCompound compound, IScriptHandler handler) { - ArrayList scripts = new ArrayList<>(); + public static List GetScript(NBTTagCompound compound, IScriptHandler handler) { + ArrayList scripts = new ArrayList<>(); for (int i = 0; i < compound.getInteger("TotalScripts"); ++i) { NBTTagCompound containerCompound = compound.getCompoundTag("Tab" + i); - ScriptContainer script = new ScriptContainer(handler); - script.readFromNBT(containerCompound); + IScriptUnit script = IScriptUnit.createFromNBT(containerCompound, handler); scripts.add(script); } return scripts; } - public static NBTTagList NBTScript(List scripts) { + public static NBTTagList NBTScript(List scripts) { NBTTagList list = new NBTTagList(); - Iterator var2 = scripts.iterator(); - - while (var2.hasNext()) { - ScriptContainer script = (ScriptContainer) var2.next(); + for (IScriptUnit script : scripts) { NBTTagCompound compound = new NBTTagCompound(); script.writeToNBT(compound); list.appendTag(compound); 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/NoppesStringUtils.java b/src/main/java/noppes/npcs/NoppesStringUtils.java index cd7031ef0..ddc11d5c6 100644 --- a/src/main/java/noppes/npcs/NoppesStringUtils.java +++ b/src/main/java/noppes/npcs/NoppesStringUtils.java @@ -4,7 +4,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.StatCollector; import noppes.npcs.entity.EntityNPCInterface; -import java.awt.*; +import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; diff --git a/src/main/java/noppes/npcs/NoppesUtilPlayer.java b/src/main/java/noppes/npcs/NoppesUtilPlayer.java index c78ffdf46..7f9753104 100644 --- a/src/main/java/noppes/npcs/NoppesUtilPlayer.java +++ b/src/main/java/noppes/npcs/NoppesUtilPlayer.java @@ -306,18 +306,18 @@ public class NoppesUtilPlayer { if (dialog == null) return; DialogOption option = dialog.options.get(optionId); - if (EventHooks.onDialogOption(player, new DialogEvent.DialogOption((IPlayer) NpcAPI.Instance().getIEntity(player), dialog))) + if (EventHooks.onDialogOption(player, new DialogEvent.DialogOption((IPlayer) NpcAPI.Instance().getIEntity(player), dialogId, optionId, dialog))) return; if (!npc.isRemote()) { EventHooks.onNPCDialogClosed(npc, player, dialogId, optionId + 1, dialog); if (!dialog.hasDialogs(player) && !dialog.hasOtherOptions()) { - EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialog)); + EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialogId, optionId, dialog)); return; } if (option == null || option.optionType == EnumOptionType.DialogOption && (!option.isAvailable(player) || !option.hasDialog()) || option.optionType == EnumOptionType.Disabled || option.optionType == EnumOptionType.QuitOption) { - EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialog)); + EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialogId, optionId, dialog)); return; } } diff --git a/src/main/java/noppes/npcs/NoppesUtilServer.java b/src/main/java/noppes/npcs/NoppesUtilServer.java index 7d06d4e52..53dbfb239 100644 --- a/src/main/java/noppes/npcs/NoppesUtilServer.java +++ b/src/main/java/noppes/npcs/NoppesUtilServer.java @@ -1,7 +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.network.PacketHandler; import kamkeel.npcs.network.packets.data.ParticlePacket; import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket; @@ -163,7 +165,16 @@ public class NoppesUtilServer { for (Animation animation : AnimationController.getInstance().animations.values()) { map.put(animation.name, animation.id); } - sendScrollData(player, map, EnumScrollData.OPTIONAL); + sendScrollData(player, map, EnumScrollData.ANIMATIONS); + } + + public static void sendBuiltInAnimationData(EntityPlayerMP player) { + Map map = new HashMap(); + for (String name : AnimationController.getInstance().builtInAnimations.keySet()) { + // Use -1 as a marker for built-in animations (they have no ID) + map.put(AnimationController.getInstance().builtInAnimations.get(name).getName(), -1); + } + sendScrollData(player, map, EnumScrollData.BUILTIN_ANIMATIONS); } public static void sendTagDataAll(EntityPlayerMP player) { @@ -241,7 +252,7 @@ public class NoppesUtilServer { if (EventHooks.onNPCDialog(npc, player, dialog.id, optionId, dialog)) { return; } - if (EventHooks.onDialogOpen(player, new DialogEvent.DialogOpen((IPlayer) NpcAPI.Instance().getIEntity(player), dialog))) { + if (EventHooks.onDialogOpen(player, new DialogEvent.DialogOpen((IPlayer) NpcAPI.Instance().getIEntity(player), dialog.id, optionId, dialog))) { return; } } @@ -384,6 +395,7 @@ public class NoppesUtilServer { if (gui == EnumGuiType.PlayerFollower || gui == EnumGuiType.PlayerFollowerHire || gui == EnumGuiType.PlayerTrader || gui == EnumGuiType.PlayerTransporter) { sendRoleData(player, npc); } + // Note: Trader-specific data (balance, stock, costs) is requested by client via GetTraderData packet } private static ArrayList getScrollData(EntityPlayer player, EnumGuiType gui, EntityNPCInterface npc) { @@ -763,6 +775,57 @@ public class NoppesUtilServer { } } + public static void sendAbilityTypesInfo(EntityPlayerMP player) { + HashMap map = new HashMap(); + AbilityController controller = AbilityController.Instance; + 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(); + AbilityController controller = AbilityController.Instance; + if (controller != null) { + 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)); } diff --git a/src/main/java/noppes/npcs/ScriptForgeEventHandler.java b/src/main/java/noppes/npcs/ScriptForgeEventHandler.java index 649557b43..abc5a80ee 100644 --- a/src/main/java/noppes/npcs/ScriptForgeEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptForgeEventHandler.java @@ -36,6 +36,10 @@ public class ScriptForgeEventHandler { @SubscribeEvent public void forgeEntity(Event event) { if (CustomNpcs.getServer() != null && ScriptController.Instance.forgeScripts.isEnabled()) { + if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) { + return; + } + if (event instanceof TickEvent && !(((TickEvent) event).side == Side.SERVER && ((TickEvent) event).phase == TickEvent.Phase.START)) { return; } diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index e9531296a..3133fb43c 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -6,10 +6,20 @@ 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.data.attribute.tracker.PlayerAttributeTracker; import kamkeel.npcs.controllers.SyncController; +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; @@ -62,7 +72,6 @@ import noppes.npcs.items.ItemNpcTool; import noppes.npcs.quests.QuestItem; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.item.ScriptCustomizableItem; -import noppes.npcs.scripted.item.ScriptItemStack; import static noppes.npcs.config.ConfigMain.TrackedQuestUpdateFrequency; @@ -98,6 +107,38 @@ public class ScriptPlayerEventHandler { if (PlayerDataController.Instance != null) { PlayerData playerData = PlayerData.get(player); playerData.actionManager.tick(); + 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()) { + 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); @@ -108,8 +149,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; + SyncController.syncEffects(mp); + SyncController.syncAbilityCooldowns(mp); + PlayerAbilitySyncPacket.sendToPlayer(mp); + playerData.abilityData.ensureLockStateClear(); + } if (player.ticksExisted % 10 == 0) CustomEffectController.Instance.runEffects(player); @@ -316,6 +362,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); @@ -466,6 +518,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); @@ -520,6 +579,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(); } @@ -541,6 +602,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); @@ -549,7 +611,7 @@ public class ScriptPlayerEventHandler { if (event.source.getEntity() instanceof EntityPlayerMP) { EntityPlayerMP playerMP = (EntityPlayerMP) event.source.getEntity(); - if(playerMP.getHeldItem() != null) { + if (playerMP.getHeldItem() != null) { IItemStack itemStack = NpcAPI.Instance().getIItemStack(playerMP.getHeldItem()); if (itemStack instanceof ScriptCustomizableItem) { ScriptCustomizableItem sci = (ScriptCustomizableItem) itemStack; @@ -562,12 +624,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); } } @@ -586,13 +677,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; } @@ -613,6 +732,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 47a1148df..04e0406d8 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -4,6 +4,9 @@ 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.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; @@ -51,7 +54,6 @@ import noppes.npcs.controllers.ServerCloneController; import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.controllers.data.Line; -import noppes.npcs.controllers.data.LinkedItem; import noppes.npcs.controllers.data.MarkData; import noppes.npcs.controllers.data.Party; import noppes.npcs.controllers.data.PlayerData; @@ -60,7 +62,6 @@ import noppes.npcs.controllers.data.Quest; import noppes.npcs.controllers.data.QuestData; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.items.ItemExcalibur; -import noppes.npcs.items.ItemLinked; import noppes.npcs.items.ItemShield; import noppes.npcs.items.ItemSoulstoneEmpty; import noppes.npcs.quests.QuestKill; @@ -153,6 +154,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()) @@ -254,6 +301,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); @@ -484,12 +532,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 3648f00d7..12a0f29ce 100644 --- a/src/main/java/noppes/npcs/ServerTickHandler.java +++ b/src/main/java/noppes/npcs/ServerTickHandler.java @@ -7,15 +7,12 @@ import cpw.mods.fml.common.gameevent.TickEvent.Phase; import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.SyncController; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; -import noppes.npcs.client.AnalyticsTracking; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.PlayerData; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.controllers.data.action.ActionManager; - -import java.net.InetAddress; -import java.net.UnknownHostException; +import noppes.npcs.entity.EntityNPCInterface; public class ServerTickHandler { @@ -23,6 +20,11 @@ public class ServerTickHandler { public void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == Phase.END) { ActionManager.GLOBAL.tick(); + + // Process auction system tick + if (AuctionController.Instance != null) { + AuctionController.Instance.onServerTick(); + } } } @@ -38,25 +40,6 @@ public class ServerTickHandler { @SubscribeEvent public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) { EntityPlayerMP player = (EntityPlayerMP) event.player; - // Temporary Disabled -// if (serverName == null) { -// String e = "local"; -// MinecraftServer server = MinecraftServer.getServer(); -// if (server.isDedicatedServer()) { -// try { -// e = InetAddress.getByName(server.getServerHostname()).getCanonicalHostName(); -// } catch (UnknownHostException e1) { -// e = MinecraftServer.getServer().getServerHostname(); -// } -// if (server.getPort() != 25565) -// e += ":" + server.getPort(); -// } -// if (e == null || e.startsWith("192.168") || e.contains("127.0.0.1") || e.startsWith("localhost")) -// e = "local"; -// serverName = e; -// } -// AnalyticsTracking.sendData(event.player, "join", serverName); - PlayerData playerData = PlayerData.get(event.player); if (playerData != null) { playerData.onLogin(); @@ -65,6 +48,15 @@ public class ServerTickHandler { ProfileController.Instance.login(player); SyncController.beginLogin(player); SyncController.syncEffects(player); + ScriptController.Instance.syncClientScripts(player); + + // Sync clean ability state to the new client (after beginLogin initializes sync state) + SyncController.syncAbilities(player); + + // Send auction notifications on login + if (AuctionController.Instance != null) { + AuctionController.Instance.onPlayerLogin(player); + } } @SubscribeEvent @@ -79,6 +71,11 @@ public class ServerTickHandler { playerData.onLogout(); } + // Clear auction permission cache on logout + if (AuctionController.Instance != null) { + AuctionController.Instance.onPlayerLogout(event.player.getUniqueID()); + } + // Save and unload the player's profile data on logout ProfileController.Instance.logout(event.player); } diff --git a/src/main/java/noppes/npcs/ai/CombatHandler.java b/src/main/java/noppes/npcs/ai/CombatHandler.java index 2a2319c4f..6947a986e 100644 --- a/src/main/java/noppes/npcs/ai/CombatHandler.java +++ b/src/main/java/noppes/npcs/ai/CombatHandler.java @@ -42,8 +42,14 @@ public class CombatHandler { return; } combatResetTimer = 0; - } + // Try to select and start an ability if not currently executing one + // Ability ticking is handled by DataAbilities in onLivingUpdate + EntityLivingBase target = npc.getAttackTarget(); + if (target != null && npc.abilities.enabled && !npc.abilities.isExecutingAbility()) { + npc.abilities.trySelectAndStart(target); + } + } private boolean shouldCombatContinue() { if (npc.getAttackTarget() == null) @@ -72,6 +78,9 @@ public class CombatHandler { } aggressors.put(el, f + damageAmount); } + + // Check for ability interruption + npc.abilities.onDamage(source, damageAmount); } public void start() { @@ -86,6 +95,9 @@ public class CombatHandler { aggressors.clear(); recentDamages.clear(); npc.setBoolFlag(false, 4); + + // Reset ability state when combat ends + npc.abilities.reset(); } public boolean checkTarget() { @@ -148,4 +160,26 @@ public class CombatHandler { } return newThreat > currentThreat; } + + /** + * Check if NPC is currently executing an ability. + * Used by AI tasks to avoid conflicting with ability execution. + */ + public boolean isExecutingAbility() { + return npc.abilities.isExecutingAbility(); + } + + /** + * Check if ability is controlling NPC movement (AI pathfinding should be blocked). + */ + public boolean isAbilityControllingMovement() { + return npc.abilities.isAbilityControllingMovement(); + } + + /** + * Check if NPC should skip normal attacks during ability execution. + */ + public boolean shouldBlockAttack() { + return npc.abilities.shouldBlockAttack(); + } } diff --git a/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java b/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java index 4ee229b0e..3ba29ecd1 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java @@ -93,7 +93,9 @@ public class EntityAIAmbushTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!this.theEntity.abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } } private Vec3 findHidingSpot() { diff --git a/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java b/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java index 967c3cf73..473c0bfb8 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java @@ -50,6 +50,11 @@ public class EntityAIAttackTarget extends EntityAIBase { return false; } + // Don't start pathfinding if ability is controlling movement + if (this.npc.abilities.isAbilityControllingMovement()) { + return false; + } + double var2 = this.npc.getDistanceSq(entitylivingbase.posX, entitylivingbase.boundingBox.minY, entitylivingbase.posZ); double var3 = this.npc.ais.distanceToMelee * this.npc.ais.distanceToMelee; @@ -113,15 +118,22 @@ public class EntityAIAttackTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F); + if (!this.npc.abilities.isRotationLocked()) { + this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F); + } - - if (!navOverride && --this.field_75445_i <= 0) { + // Skip pathfinding updates if ability is controlling movement + if (!navOverride && !this.npc.abilities.isAbilityControllingMovement() && --this.field_75445_i <= 0) { this.field_75445_i = 4 + this.npc.getRNG().nextInt(7); this.npc.getNavigator().tryMoveToEntityLiving(this.entityTarget, 1.3f); } this.attackTick = Math.max(this.attackTick - 1, 0); + // Skip attacks if ability is blocking them + if (this.npc.abilities.shouldBlockAttack()) { + return; + } + double distance = this.npc.getDistanceSq(this.entityTarget.posX, this.entityTarget.boundingBox.minY, this.entityTarget.posZ); double range = npc.stats.attackRange * npc.stats.attackRange + entityTarget.width; double minRange = this.npc.width * 2.0F * this.npc.width * 2.0F + entityTarget.width; diff --git a/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java b/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java index ef7b3f5ac..b07b911f4 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java +++ b/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java @@ -63,7 +63,7 @@ public class EntityAIDodgeShoot extends EntityAIBase { * Updates the task */ public void updateTask() { - if (this.entity.getAttackTarget() != null) + if (this.entity.getAttackTarget() != null && !this.entity.abilities.isRotationLocked()) this.entity.getLookHelper().setLookPositionWithEntity(this.entity.getAttackTarget(), 30.0F, 30.0F); } } diff --git a/src/main/java/noppes/npcs/ai/EntityAIFollow.java b/src/main/java/noppes/npcs/ai/EntityAIFollow.java index 61cabd38f..f236c0727 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIFollow.java +++ b/src/main/java/noppes/npcs/ai/EntityAIFollow.java @@ -55,7 +55,9 @@ public class EntityAIFollow extends EntityAIBase { if (updateTick < 10) return; updateTick = 0; - this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed()); + if (!this.npc.abilities.isRotationLocked()) { + this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed()); + } double speed = 1 + distance / 150; if (speed > 3) diff --git a/src/main/java/noppes/npcs/ai/EntityAILeapAtTargetNpc.java b/src/main/java/noppes/npcs/ai/EntityAILeapAtTargetNpc.java index 437dbd6d3..e14f2e833 100644 --- a/src/main/java/noppes/npcs/ai/EntityAILeapAtTargetNpc.java +++ b/src/main/java/noppes/npcs/ai/EntityAILeapAtTargetNpc.java @@ -18,6 +18,11 @@ public class EntityAILeapAtTargetNpc extends EntityAIBase { @Override public boolean shouldExecute() { + // Don't leap if ability is controlling movement + if (this.npc.abilities.isAbilityControllingMovement()) { + return false; + } + this.leapTarget = this.npc.getAttackTarget(); if (this.leapTarget == null) { return false; diff --git a/src/main/java/noppes/npcs/ai/EntityAILook.java b/src/main/java/noppes/npcs/ai/EntityAILook.java index 3448fc4ed..b9474a60c 100644 --- a/src/main/java/noppes/npcs/ai/EntityAILook.java +++ b/src/main/java/noppes/npcs/ai/EntityAILook.java @@ -26,7 +26,7 @@ public class EntityAILook extends EntityAIBase { */ @Override public boolean shouldExecute() { - return !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive(); + return !npc.abilities.isRotationLocked() && !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive(); } /** diff --git a/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java b/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java index 4c72ec278..0a9532261 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java @@ -91,7 +91,9 @@ public class EntityAIOrbitTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!this.theEntity.abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } if (this.theEntity.getNavigator().noPath() && this.tick >= 0) { if (this.theEntity.onGround && !this.theEntity.isInWater()) { double d0 = this.targetDistance * (double) (MathHelper.cos(angle / 180.0F * (float) Math.PI)); diff --git a/src/main/java/noppes/npcs/ai/EntityAIPounceTarget.java b/src/main/java/noppes/npcs/ai/EntityAIPounceTarget.java index 4f87575bf..d3354cdfe 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIPounceTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIPounceTarget.java @@ -17,6 +17,11 @@ public class EntityAIPounceTarget extends EntityAIBase { @Override public boolean shouldExecute() { + // Don't pounce if ability is controlling movement + if (this.npc.abilities.isAbilityControllingMovement()) { + return false; + } + if (!this.npc.onGround) return false; diff --git a/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java b/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java index af88ac905..5e8fa6ec0 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java +++ b/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java @@ -100,7 +100,9 @@ public class EntityAIRangedAttack extends EntityAIBase { * Updates the task */ public void updateTask() { - this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F); + if (!this.entityHost.abilities.isRotationLocked()) { + this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F); + } double var1 = this.entityHost.getDistanceSq(this.attackTarget.posX, this.attackTarget.boundingBox.minY, this.attackTarget.posZ); float field_82642_h = this.entityHost.stats.rangedRange * this.entityHost.stats.rangedRange; diff --git a/src/main/java/noppes/npcs/ai/EntityAISprintToTarget.java b/src/main/java/noppes/npcs/ai/EntityAISprintToTarget.java index 0d8d100c2..2ba100d10 100644 --- a/src/main/java/noppes/npcs/ai/EntityAISprintToTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAISprintToTarget.java @@ -15,6 +15,11 @@ public class EntityAISprintToTarget extends EntityAIBase { @Override public boolean shouldExecute() { + // Don't sprint if ability is controlling movement + if (this.npc.abilities.isAbilityControllingMovement()) { + return false; + } + EntityLivingBase runTarget = this.npc.getAttackTarget(); if (runTarget == null || this.npc.getNavigator().noPath()) { diff --git a/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java b/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java index 1b64a12b7..8adad1ee2 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java @@ -68,7 +68,9 @@ public class EntityAIStalkTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!this.theEntity.abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } if (this.theEntity.getNavigator().noPath() || this.overRide) { if (this.isLookingAway()) { diff --git a/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java b/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java index d30ae3183..159c38fc9 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java +++ b/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java @@ -31,7 +31,7 @@ public class EntityAIWatchClosest extends EntityAIBase { */ @Override public boolean shouldExecute() { - if (this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) { + if (this.theWatcher.abilities.isRotationLocked() || this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) { return false; } else { if (this.theWatcher.getAttackTarget() != null) { diff --git a/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java b/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java index 3e91cc84b..e99d31ca2 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java @@ -8,6 +8,7 @@ import net.minecraft.pathfinding.PathPoint; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import noppes.npcs.constants.AiMutex; +import noppes.npcs.entity.EntityNPCInterface; public class EntityAIZigZagTarget extends EntityAIBase { private EntityCreature theEntity; @@ -82,6 +83,8 @@ public class EntityAIZigZagTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!(this.theEntity instanceof EntityNPCInterface) || !((EntityNPCInterface) this.theEntity).abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } } } diff --git a/src/main/java/noppes/npcs/blocks/BlockWaypoint.java b/src/main/java/noppes/npcs/blocks/BlockWaypoint.java index 7e0fd2601..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 { @@ -41,8 +39,14 @@ public class BlockWaypoint extends BlockContainer { @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.Waypoint, (EntityPlayer) entityliving); + if (entityliving instanceof EntityPlayer) { + if (!world.isRemote) { + // Server-side: sync TileEntity data to client and open GUI (same as onBlockActivated) + TileEntity tile = world.getTileEntity(i, j, k); + NBTTagCompound compound = new NBTTagCompound(); + tile.writeToNBT(compound); + PacketHandler.Instance.sendToPlayer(new GuiWaypointPacket(compound), (EntityPlayerMP) entityliving); + } } } diff --git a/src/main/java/noppes/npcs/blocks/tiles/TileScripted.java b/src/main/java/noppes/npcs/blocks/tiles/TileScripted.java index 8babf8936..64dbb767b 100644 --- a/src/main/java/noppes/npcs/blocks/tiles/TileScripted.java +++ b/src/main/java/noppes/npcs/blocks/tiles/TileScripted.java @@ -3,6 +3,7 @@ package noppes.npcs.blocks.tiles; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.network.packets.request.script.BlockScriptPacket; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.ITickable; import net.minecraft.item.Item; @@ -25,9 +26,11 @@ import noppes.npcs.api.IBlock; import noppes.npcs.api.block.ITextPlane; import noppes.npcs.client.renderer.blocks.BlockScriptedRenderer; import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.IScriptBlockHandler; +import noppes.npcs.controllers.data.IScriptHandlerPacket; +import noppes.npcs.controllers.data.IScriptUnit; import noppes.npcs.entity.data.DataTimers; import noppes.npcs.scripted.BlockScriptedWrapper; import noppes.npcs.util.ValueUtil; @@ -36,11 +39,9 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; -public class TileScripted extends TileEntity implements IScriptBlockHandler { - public List scripts = new ArrayList<>(); +public class TileScripted extends TileEntity implements IScriptBlockHandler, IScriptHandlerPacket { + public List scripts = new ArrayList<>(); public Map tempData = new HashMap<>(); @@ -161,6 +162,36 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler { text6.setNBT(compound.getCompoundTag("Text6")); } + @Override + public ScriptContext getContext() { + return ScriptContext.BLOCK; + } + + @Override + public void requestData() { + BlockScriptPacket.Get(this.xCoord, this.yCoord, this.zCoord); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + BlockScriptPacket.Save(this.xCoord, this.yCoord, this.zCoord, nbt); + } + + @Override + public GuiDataResult setGuiData(NBTTagCompound compound) { + if (compound.hasKey("LoadComplete")) { + return new GuiDataResult(GuiDataKind.LOAD_COMPLETE, -1); + } + + setNBT(compound); + return new GuiDataResult(GuiDataKind.METADATA, -1); + } + + @Override + public void sync() { + sendSavePacket(-1, getScripts().size(), getNBT(new NBTTagCompound())); + } + @Override public void writeToNBT(NBTTagCompound compound) { super.writeToNBT(compound); @@ -367,7 +398,7 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler { EventHooks.onScriptBlockInit(this); } - for (ScriptContainer script : scripts) { + for (IScriptUnit script : scripts) { script.run(type, event); } } @@ -408,34 +439,15 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler { } @Override - public void setScripts(List list) { + public void setScripts(List list) { scripts = list; } @Override - public List getScripts() { + public List getScripts() { return scripts; } - @Override - public Map getConsoleText() { - Map map = new TreeMap<>(); - int tab = 0; - for (ScriptContainer script : getScripts()) { - tab++; - for (Entry entry : script.console.entrySet()) { - map.put(entry.getKey(), " tab " + tab + ":\n" + entry.getValue()); - } - } - return map; - } - - @Override - public void clearConsole() { - for (ScriptContainer script : getScripts()) { - script.console.clear(); - } - } @SideOnly(Side.CLIENT) @Override diff --git a/src/main/java/noppes/npcs/client/AnalyticsTracking.java b/src/main/java/noppes/npcs/client/AnalyticsTracking.java deleted file mode 100644 index ba745346d..000000000 --- a/src/main/java/noppes/npcs/client/AnalyticsTracking.java +++ /dev/null @@ -1,53 +0,0 @@ -package noppes.npcs.client; - -import net.minecraft.entity.player.EntityPlayer; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.UUID; - -public class AnalyticsTracking { - - public static void sendData(final EntityPlayer player, final String event, final String data) { - Runnable r = new Runnable() { - - @Override - public void run() { - try { - UUID uuid = player.getUniqueID(); - - String analyticsPostData = "v=1" + - "&tid=UA-29079943-5" + - "&cid=" + uuid.toString() + - "&t=event" + - "&ec=customnpcs_1.7d" + - "&ea=" + event + - "&el=" + data + - "&ev=300"; - - URL url = new URL("http://www.google-analytics.com/collect"); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setConnectTimeout(10000); - connection.setReadTimeout(10000); - connection.setDoOutput(true); - connection.setUseCaches(false); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestProperty("Content-Length", Integer.toString(analyticsPostData.getBytes().length)); - OutputStream dataOutput = connection.getOutputStream(); - dataOutput.write(analyticsPostData.getBytes()); - dataOutput.close(); - connection.getInputStream().close(); - } catch (IOException e) { - - } - - } - }; - Thread t = new Thread(r); - t.start(); - } - -} diff --git a/src/main/java/noppes/npcs/client/AuctionClientConfig.java b/src/main/java/noppes/npcs/client/AuctionClientConfig.java new file mode 100644 index 000000000..a94bab504 --- /dev/null +++ b/src/main/java/noppes/npcs/client/AuctionClientConfig.java @@ -0,0 +1,86 @@ +package noppes.npcs.client; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +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 volatile long listingFee = 0; + private static String currencyName = "Coins"; + private static int auctionDurationHours = 24; + private static volatile double minBidIncrement = 0.05; + private static int maxActiveListings = 8; + private static int claimExpirationDays = 20; + private static boolean auctionEnabled = false; + + /** + * Update cached config from server NBT data. + * Called when receiving login packet. + */ + public static void readFromNBT(NBTTagCompound compound) { + if (compound == null) return; + + auctionEnabled = compound.getBoolean("AuctionEnabled"); + listingFee = compound.getLong("ListingFee"); + currencyName = compound.getString("CurrencyName"); + auctionDurationHours = compound.getInteger("AuctionDurationHours"); + minBidIncrement = compound.getDouble("MinBidIncrement"); + maxActiveListings = compound.getInteger("MaxActiveListings"); + claimExpirationDays = compound.getInteger("ClaimExpirationDays"); + + if (currencyName.isEmpty()) { + currencyName = "Coins"; + } + } + + /** + * Reset to defaults (called on disconnect). + */ + public static void reset() { + listingFee = 0; + currencyName = "Coins"; + auctionDurationHours = 24; + minBidIncrement = 0.05; + maxActiveListings = 8; + claimExpirationDays = 20; + auctionEnabled = false; + } + + // 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; + } +} 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 2c6a368c2..30b14be83 100644 --- a/src/main/java/noppes/npcs/client/ClientCacheHandler.java +++ b/src/main/java/noppes/npcs/client/ClientCacheHandler.java @@ -1,5 +1,6 @@ package noppes.npcs.client; +import kamkeel.npcs.network.enums.EnumSyncType; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.controllers.MusicController; @@ -15,7 +16,6 @@ import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.controllers.data.Party; import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.controllers.data.SkinOverlay; -import kamkeel.npcs.network.enums.EnumSyncType; import noppes.npcs.util.CacheHashMap; import java.util.EnumMap; diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index 7a839fbb5..bffda878d 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -19,11 +19,15 @@ import net.minecraftforge.client.event.RenderGameOverlayEvent; 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.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; @@ -75,11 +79,50 @@ public class ClientEventHandler { } } + @SubscribeEvent + public void onItemTooltip(ItemTooltipEvent event) { + AuctionTooltipHandler.onItemTooltip(event); + } + @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) { @@ -107,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 7cc3d7b76..481e6ada8 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -6,6 +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; @@ -21,11 +47,14 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; import net.minecraft.stats.Achievement; +import net.minecraft.tileentity.TileEntity; 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; @@ -72,6 +101,7 @@ import noppes.npcs.client.gui.GuiBorderBlock; import noppes.npcs.client.gui.GuiMerchantAdd; import noppes.npcs.client.gui.GuiNpcDimension; import noppes.npcs.client.gui.GuiNpcMobSpawner; +import noppes.npcs.client.gui.GuiNpcMobSpawnerFullscreen; import noppes.npcs.client.gui.GuiNpcMobSpawnerMounter; import noppes.npcs.client.gui.GuiNpcPather; import noppes.npcs.client.gui.GuiNpcRedstoneBlock; @@ -88,6 +118,8 @@ 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; @@ -99,6 +131,10 @@ 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; @@ -120,9 +156,11 @@ import noppes.npcs.client.gui.roles.GuiNpcFollowerSetup; import noppes.npcs.client.gui.roles.GuiNpcItemGiver; import noppes.npcs.client.gui.roles.GuiNpcTraderSetup; import noppes.npcs.client.gui.roles.GuiNpcTransporter; -import noppes.npcs.client.gui.script.GuiScriptBlock; import noppes.npcs.client.gui.script.GuiScriptGlobal; -import noppes.npcs.client.gui.script.GuiScriptItem; +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; @@ -177,11 +215,16 @@ 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; @@ -209,6 +252,7 @@ import noppes.npcs.entity.data.ModelPartData; import noppes.npcs.items.ItemLinked; import noppes.npcs.items.ItemNpcTool; import noppes.npcs.items.ItemScripted; +import noppes.npcs.scripted.item.ScriptCustomItem; import org.lwjgl.input.Keyboard; import tconstruct.client.tabs.InventoryTabCustomNpc; import tconstruct.client.tabs.InventoryTabVanilla; @@ -223,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; @@ -237,12 +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 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()); @@ -289,11 +347,19 @@ public class ClientProxy extends CommonProxy { Minecraft mc = Minecraft.getMinecraft(); NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc"); - SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_C, "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) { @@ -303,9 +369,22 @@ public class ClientProxy extends CommonProxy { ClientCloneController.Instance = new ClientCloneController(); 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()) { @@ -352,7 +431,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; @@ -435,7 +515,7 @@ public class ClientProxy extends CommonProxy { animNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png"; save = false; } - return new GuiNPCManageAnimations(animNpc, save); + return new GuiNPCManageAnimations(animNpc, save, npc != null); } else if (gui == EnumGuiType.ManageLinked) return new GuiNPCManageLinked(npc); @@ -448,6 +528,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); @@ -460,7 +543,21 @@ public class ClientProxy extends CommonProxy { else if (gui == EnumGuiType.ManageEffects) return new GuiNPCManageEffects(npc); - else if (gui == EnumGuiType.MainMenuGlobal) + else if (gui == EnumGuiType.ManageAbilities) { + EntityCustomNpc abilityNpc; + if (npc != null) { + abilityNpc = new EntityCustomNpc(npc.worldObj); + abilityNpc.copyDataFrom(npc, true); + abilityNpc.display.showName = 1; + abilityNpc.display.showBossBar = 0; + } else { + abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld); + abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png"; + abilityNpc.height = 1.8f; + abilityNpc.width = 0.6f; + } + return new GuiNpcManageAbilities(abilityNpc, npc != null); + } else if (gui == EnumGuiType.MainMenuGlobal) return new GuiNPCGlobalMainMenu(npc); else if (gui == EnumGuiType.MainMenuAI) @@ -475,6 +572,18 @@ public class ClientProxy extends CommonProxy { else if (gui == EnumGuiType.PlayerTrader) return new GuiNPCTrader(npc, (ContainerNPCTrader) container); + else if (gui == EnumGuiType.PlayerAuction) + return new GuiAuctionListing(npc, (ContainerAuctionListing) container); + + else if (gui == EnumGuiType.PlayerAuctionSell) + return new GuiAuctionSell(npc, (ContainerAuctionSell) container); + + else if (gui == EnumGuiType.PlayerAuctionTrades) + return new GuiAuctionTrades(npc, (ContainerAuctionTrades) container); + + else if (gui == EnumGuiType.PlayerAuctionBidding) + return new GuiAuctionBidding(npc, (ContainerAuctionBidding) container); + else if (gui == EnumGuiType.PlayerBankSmall || gui == EnumGuiType.PlayerBankUnlock || gui == EnumGuiType.PlayerBankUprade || gui == EnumGuiType.PlayerBankLarge) return new GuiNPCBankChest(npc, (ContainerNPCBankInterface) container); @@ -485,7 +594,7 @@ public class ClientProxy extends CommonProxy { return new GuiScript(npc); else if (gui == EnumGuiType.ScriptItem) - return new GuiScriptItem(); + return GuiScriptInterface.create(null, new ScriptCustomItem(new ItemStack(CustomItems.scripted_item))); else if (gui == EnumGuiType.PlayerCarpentryBench) return new GuiNpcCarpentryBench((ContainerCarpentryBench) container); @@ -539,7 +648,9 @@ public class ClientProxy extends CommonProxy { return new GuiNpcRedstoneBlock(x, y, z); else if (gui == EnumGuiType.Cloner) - return new GuiNpcMobSpawner(x, y, z); + return GuiNpcMobSpawner.isFullscreen + ? new GuiNpcMobSpawnerFullscreen(x, y, z) + : new GuiNpcMobSpawner(x, y, z); else if (gui == EnumGuiType.MobSpawnerMounter) return new GuiNpcMobSpawnerMounter(x, y, z); @@ -560,7 +671,7 @@ public class ClientProxy extends CommonProxy { return new GuiCustom((ContainerCustomGui) container); else if (gui == EnumGuiType.ScriptBlock) - return new GuiScriptBlock(x, y, z); + return getScriptBlockGui(x, y, z); else if (gui == EnumGuiType.Paintbrush) return new GuiNpcPaintbrush(); @@ -612,9 +723,22 @@ public class ClientProxy extends CommonProxy { if (guiscreen != null) { minecraft.displayGuiScreen((GuiScreen) guiscreen); } - } + + private GuiScreen getScriptBlockGui(int x, int y, int z) { + World world = Minecraft.getMinecraft().theWorld; + if (world == null) + return null; + + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileScripted)) + return null; + + return GuiScriptInterface.create(null, (TileScripted) tile); + } + + @Override public void spawnParticle(EntityLivingBase player, String string, Object... ob) { if (string.equals("Spell")) { @@ -738,6 +862,40 @@ public class ClientProxy extends CommonProxy { return Minecraft.getMinecraft().currentScreen != null; } + public void buildPackageIndex() { + try { + PackageFinder.init(Thread.currentThread().getContextClassLoader()); + ClassIndex.init(); + JSTypeRegistry.getInstance().initializeFromResources(); + } catch (IOException e) { + } + } + + @Override + public boolean isScriptingEnabled() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isScriptingEnabled(); + } + + @Override + public boolean isRunLoadedScriptsFirst() { + return ScriptClientConfig.isRunLoadedScriptsFirst(); + } + + @Override + public boolean isGlobalPlayerScripts() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalPlayerScripts(); + } + + @Override + public boolean isGlobalForgeScripts() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalForgeScripts(); + } + + @Override + public boolean isGlobalNPCScripts() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalNPCScripts(); + } + public static class FontContainer { public StringCache textFont = null; public boolean useCustomFont = true; diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index af44405dc..1fa03a34a 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -2,37 +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.SpecialKeyStatePacket; import kamkeel.npcs.network.packets.player.ScreenSizePacket; 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; @@ -43,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) { @@ -54,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) { @@ -82,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) { @@ -109,6 +186,7 @@ public class ClientTickHandler { MusicController.Instance.onUpdate(); ScriptSoundController.Instance.onUpdate(); + if (Minecraft.getMinecraft().thePlayer != null && (prevWidth != mc.displayWidth || prevHeight != mc.displayHeight)) { prevWidth = mc.displayWidth; prevHeight = mc.displayHeight; @@ -123,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 132805af1..14bb52e71 100644 --- a/src/main/java/noppes/npcs/client/CustomNpcResourceListener.java +++ b/src/main/java/noppes/npcs/client/CustomNpcResourceListener.java @@ -9,9 +9,10 @@ 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 javax.imageio.ImageIO; -import java.awt.*; +import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; @@ -30,6 +31,11 @@ public class CustomNpcResourceListener implements FolderResourcePack pack = new FolderResourcePack(CustomNpcs.Dir); simplemanager.reloadResourcePack(pack); + + // 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/ScriptClientConfig.java b/src/main/java/noppes/npcs/client/ScriptClientConfig.java new file mode 100644 index 000000000..2af091723 --- /dev/null +++ b/src/main/java/noppes/npcs/client/ScriptClientConfig.java @@ -0,0 +1,89 @@ +package noppes.npcs.client; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +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. + */ +@SideOnly(Side.CLIENT) +public class ScriptClientConfig { + // Cached values from server + private static boolean scriptingEnabled = true; + private static boolean runLoadedScriptsFirst = true; + private static boolean globalPlayerScripts = true; + private static boolean globalForgeScripts = true; + private static boolean globalNPCScripts = false; + + /** + * Update cached config from server NBT data. + * Called when receiving login packet or script sync packets. + */ + public static void readFromNBT(NBTTagCompound compound) { + if (compound == null) return; + + scriptingEnabled = compound.getBoolean("ScriptingEnabled"); + runLoadedScriptsFirst = compound.getBoolean("RunLoadedScriptsFirst"); + globalPlayerScripts = compound.getBoolean("GlobalPlayerScripts"); + globalForgeScripts = compound.getBoolean("GlobalForgeScripts"); + globalNPCScripts = compound.getBoolean("GlobalNPCScripts"); + } + + /** + * Reset to defaults (called on disconnect). + */ + public static void reset() { + scriptingEnabled = true; + runLoadedScriptsFirst = true; + globalPlayerScripts = true; + globalForgeScripts = true; + globalNPCScripts = false; + } + + // 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; + } + + // 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; + } +} diff --git a/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java b/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java index 81f174170..9e62177f0 100644 --- a/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java +++ b/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java @@ -41,6 +41,26 @@ public class ClientCloneController extends ServerCloneController { return true; } + @Override + public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) { + HashSet tagUUIDs = new HashSet<>(); + if (nbttagcompound.hasKey("TagUUIDs")) { + NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8); + for (int i = 0; i < nbtTagList.tagCount(); i++) { + tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i))); + } + } + + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + if (!tagUUIDs.isEmpty()) { + tagMap.putClone(name, tagUUIDs); + } else { + tagMap.removeClone(name); + } + ClientTagMapController.Instance.saveTagMap(tagMap); + return true; + } + @Override public boolean removeFromTagMap(String name, int tab) { TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab); @@ -51,4 +71,43 @@ public class ClientCloneController extends ServerCloneController { return false; } + @Override + public boolean removeFromTagMap(String name, String folderName) { + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + if (tagMap.removeClone(name)) { + ClientTagMapController.Instance.saveTagMap(tagMap); + return true; + } + return false; + } + + @Override + protected HashSet getTagUUIDsFromTab(String cloneName, int tab) { + TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + @Override + protected HashSet getTagUUIDsFromFolder(String cloneName, String folderName) { + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + @Override + protected void setTagUUIDsForTab(String cloneName, int tab, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab); + tagMap.putClone(cloneName, tagUUIDs); + ClientTagMapController.Instance.saveTagMap(tagMap); + } + + @Override + protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + tagMap.putClone(cloneName, tagUUIDs); + ClientTagMapController.Instance.saveTagMap(tagMap); + } } diff --git a/src/main/java/noppes/npcs/client/controllers/MusicController.java b/src/main/java/noppes/npcs/client/controllers/MusicController.java index 98c30f2ac..172152f51 100644 --- a/src/main/java/noppes/npcs/client/controllers/MusicController.java +++ b/src/main/java/noppes/npcs/client/controllers/MusicController.java @@ -199,6 +199,7 @@ public class MusicController { /** * Stops a specific sound by its resource key. * This is used to stop dialog sounds without affecting Bard music. + * * @param soundKey The sound resource key to stop */ public void stopSound(String soundKey) { 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/GuiNpcMobSpawner.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java index b3670d9e8..7fd5c174e 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java @@ -2,6 +2,7 @@ package noppes.npcs.client.gui; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; import kamkeel.npcs.network.packets.request.clone.CloneListPacket; import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket; import kamkeel.npcs.network.packets.request.clone.CloneTagListPacket; @@ -26,6 +27,8 @@ 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.client.gui.util.IClonerGui; +import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.controllers.data.Tag; import noppes.npcs.controllers.data.TagMap; @@ -38,52 +41,84 @@ import java.util.List; import java.util.Map; import java.util.UUID; -public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { +public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData, ICustomScrollListener, IClonerGui { + + // ==================== STATIC STATE (persists across GUI opens, shared with fullscreen) ==================== + public static boolean isFullscreen = false; + public static int activeTab = 1; + public static String activeFolder = null; + public static int showingClones = 0; // 0=Clones, 1=Entities, 2=Server, 3=Filters + public static String search = ""; + public static String tagSearch = ""; + public static HashMap tags = new HashMap<>(); public static HashMap tagNames = new HashMap<>(); public static HashSet tagFilters = new HashSet<>(); public static byte displayTags = 0; - // 0 - Any, 1 - All, 2 - Not Any, 3 - Not All public static byte filterCondition = 0; - public static byte ascending = 0; - // 0 - By Name, 1 - By Date public static byte sortType = 0; - public TagMap tagMap; + // Scroll position preservation (shared with fullscreen) + public static int savedContentScrollY = 0; + public static int savedNavScrollY = 0; + // ==================== INSTANCE STATE ==================== + public TagMap tagMap; private final GuiCustomScrollCloner scroll = new GuiCustomScrollCloner(this, 0); private final GuiCustomScroll filterScroll = new GuiCustomScroll(this, 1); - private int posX, posY, posZ; - + public int posX, posY, posZ; private List list; private List rawList; private List tagList; - private static int showingClones = 0; - - private static String search = ""; - private static String tagSearch = ""; - - private int activeTab = 1; - + // ==================== CONSTRUCTOR ==================== public GuiNpcMobSpawner(int i, int j, int k) { super(); - xSize = 354; posX = i; posY = j; posZ = k; - - this.closeOnEsc = true; - + closeOnEsc = true; + xSize = 354; setBackground("menubg.png"); PacketClient.sendClient(new CloneAllTagsPacket()); + if (showingClones == 2) { + PacketClient.sendClient(new CloneFolderListPacket()); + } + + // Minimized view doesn't support folders — ensure we're on a tab + if (activeFolder != null) { + if (activeTab < 1 || activeTab > 15) { + activeTab = 1; + } + activeFolder = null; + } } + // ==================== IClonerGui ==================== + @Override + public int getShowingClones() { + return showingClones; + } + + @Override + public HashMap getTags() { + return tags; + } + + @Override + public TagMap getTagMap() { + return tagMap; + } + + // ==================== INIT GUI ==================== public void initGui() { + // Save scroll position before clear + savedContentScrollY = scroll.scrollY; + super.initGui(); guiTop += 10; guiLeft += 30; @@ -92,6 +127,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { scroll.setSize(293, 188); scroll.guiLeft = guiLeft + 4; scroll.guiTop = guiTop + 26; + filterScroll.clear(); filterScroll.setSize(140, 166); filterScroll.guiLeft = guiLeft + 4; @@ -99,112 +135,133 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { filterScroll.multipleSelection = true; filterScroll.setSelectedList(tagFilters); - GuiMenuTopButton button; - addTopButton(button = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones")); - button.active = showingClones == 0; - addTopButton(button = new GuiMenuTopButton(5, button, "gui.server")); - button.active = showingClones == 2; - addTopButton(button = new GuiMenuTopButton(4, button, "spawner.entities")); - button.active = showingClones == 1; - addTopButton(button = new GuiMenuTopButton(16, guiLeft + (xSize - 67), guiTop - 17, "gui.filters")); - button.active = showingClones == 3; - addTopButton(button = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X")); + // Top buttons — build right-to-left to avoid overlap + GuiMenuTopButton closeBtn = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"); + addTopButton(closeBtn); + + // Position "+" dynamically to the left of "X" + int plusX = closeBtn.xPosition - (fontRendererObj.getStringWidth("+") + 12) - 2; + GuiMenuTopButton fullscreenBtn = new GuiMenuTopButton(61, plusX, guiTop - 17, "+"); + addTopButton(fullscreenBtn); + + // Position "Filters" dynamically to the left of "+" + int filterBtnW = fontRendererObj.getStringWidth(StatCollector.translateToLocal("gui.filters")) + 12; + int filterX = fullscreenBtn.xPosition - filterBtnW - 2; + GuiMenuTopButton filterBtn = new GuiMenuTopButton(16, filterX, guiTop - 17, "gui.filters"); + filterBtn.active = showingClones == 3; + addTopButton(filterBtn); + + // Mode buttons from left + GuiMenuTopButton btn; + addTopButton(btn = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones")); + btn.active = showingClones == 0; + addTopButton(btn = new GuiMenuTopButton(5, btn, "gui.server")); + btn.active = showingClones == 2; + addTopButton(btn = new GuiMenuTopButton(4, btn, "spawner.entities")); + btn.active = showingClones == 1; if (showingClones < 3) { addScroll(scroll); addTextField(new GuiNpcTextField(1, this, fontRendererObj, guiLeft + 4, guiTop + 4, 293, 20, search)); + addButton(new GuiNpcButton(1, guiLeft + 298, guiTop + 6, 52, 20, "item.monsterPlacer.name")); addButton(new GuiNpcButton(2, guiLeft + 298, guiTop + 140, 52, 20, "spawner.mobspawner")); if (showingClones == 0 || showingClones == 2) { - - addSideButton(new GuiMenuSideButton(21, guiLeft - 70, this.guiTop + 2, 70, 22, "1")); - addSideButton(new GuiMenuSideButton(22, guiLeft - 70, this.guiTop + 23, 70, 22, "2")); - addSideButton(new GuiMenuSideButton(23, guiLeft - 70, this.guiTop + 44, 70, 22, "3")); - addSideButton(new GuiMenuSideButton(24, guiLeft - 70, this.guiTop + 65, 70, 22, "4")); - addSideButton(new GuiMenuSideButton(25, guiLeft - 70, this.guiTop + 86, 70, 22, "5")); - addSideButton(new GuiMenuSideButton(26, guiLeft - 70, this.guiTop + 107, 35, 22, "6")); - addSideButton(new GuiMenuSideButton(27, guiLeft - 35, this.guiTop + 107, 35, 22, "7")); - addSideButton(new GuiMenuSideButton(28, guiLeft - 70, this.guiTop + 128, 35, 22, "8")); - addSideButton(new GuiMenuSideButton(29, guiLeft - 35, this.guiTop + 128, 35, 22, "9")); - addSideButton(new GuiMenuSideButton(30, guiLeft - 70, this.guiTop + 149, 35, 22, "10")); - addSideButton(new GuiMenuSideButton(31, guiLeft - 35, this.guiTop + 149, 35, 22, "11")); - addSideButton(new GuiMenuSideButton(32, guiLeft - 70, this.guiTop + 170, 35, 22, "12")); - addSideButton(new GuiMenuSideButton(33, guiLeft - 35, this.guiTop + 170, 35, 22, "13")); - addSideButton(new GuiMenuSideButton(34, guiLeft - 70, this.guiTop + 191, 35, 22, "14")); - addSideButton(new GuiMenuSideButton(35, guiLeft - 35, this.guiTop + 191, 35, 22, "15")); - addButton(new GuiNpcButton(6, guiLeft + 298, guiTop + 190, 52, 20, "gui.remove")); - getSideButton(20 + activeTab).active = true; + initTabSideButtons(); showClones(); + + // Restore scroll position + scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY)); } else { showEntities(); + scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY)); } } else { - // Show Filters - addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), guiLeft + 7, guiTop + 7)); - addScroll(filterScroll); - addTextField(new GuiNpcTextField(2, this, fontRendererObj, guiLeft + 4, guiTop + 190, 140, 20, tagSearch)); - - addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), guiLeft + 150, guiTop + 27)); - addButton(new GuiNpcButton(12, guiLeft + 215, guiTop + 20, new String[]{"display.show", "display.all", "display.hide"}, displayTags)); - - addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), guiLeft + 150, guiTop + 50)); - addButton(new GuiNpcButton(13, guiLeft + 215, guiTop + 43, new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition)); - - addButton(new GuiNpcButton(11, guiLeft + 150, guiTop + 66, 130, 20, "gui.deselectAll")); - - - addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), guiLeft + 150, guiTop + 112)); - addButton(new GuiNpcButton(14, guiLeft + 215, guiTop + 105, new String[]{"cloner.ascending", "cloner.descending"}, ascending)); - - addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), guiLeft + 150, guiTop + 135)); - addButton(new GuiNpcButton(15, guiLeft + 215, guiTop + 128, new String[]{"cloner.name", "cloner.date"}, sortType)); - - - getButton(12).width = 65; - getButton(12).height = 20; - - getButton(13).width = 65; - getButton(13).height = 20; - - getButton(14).width = 65; - getButton(14).height = 20; - - getButton(15).width = 65; - getButton(15).height = 20; - - showFilters(); + showFiltersPage(); } } - public int getShowingClones() { - return showingClones; + private void initTabSideButtons() { + // Tabs 1-5: full width (70px) + addSideButton(new GuiMenuSideButton(21, guiLeft - 70, guiTop + 2, 70, 22, "1")); + addSideButton(new GuiMenuSideButton(22, guiLeft - 70, guiTop + 23, 70, 22, "2")); + addSideButton(new GuiMenuSideButton(23, guiLeft - 70, guiTop + 44, 70, 22, "3")); + addSideButton(new GuiMenuSideButton(24, guiLeft - 70, guiTop + 65, 70, 22, "4")); + addSideButton(new GuiMenuSideButton(25, guiLeft - 70, guiTop + 86, 70, 22, "5")); + // Tabs 6-15: half width (35px), 2-column grid + addSideButton(new GuiMenuSideButton(26, guiLeft - 70, guiTop + 107, 35, 22, "6")); + addSideButton(new GuiMenuSideButton(27, guiLeft - 35, guiTop + 107, 35, 22, "7")); + addSideButton(new GuiMenuSideButton(28, guiLeft - 70, guiTop + 128, 35, 22, "8")); + addSideButton(new GuiMenuSideButton(29, guiLeft - 35, guiTop + 128, 35, 22, "9")); + addSideButton(new GuiMenuSideButton(30, guiLeft - 70, guiTop + 149, 35, 22, "10")); + addSideButton(new GuiMenuSideButton(31, guiLeft - 35, guiTop + 149, 35, 22, "11")); + addSideButton(new GuiMenuSideButton(32, guiLeft - 70, guiTop + 170, 35, 22, "12")); + addSideButton(new GuiMenuSideButton(33, guiLeft - 35, guiTop + 170, 35, 22, "13")); + addSideButton(new GuiMenuSideButton(34, guiLeft - 70, guiTop + 191, 35, 22, "14")); + addSideButton(new GuiMenuSideButton(35, guiLeft - 35, guiTop + 191, 35, 22, "15")); + + if (activeTab >= 1 && activeTab <= 15) { + GuiMenuSideButton active = getSideButton(20 + activeTab); + if (active != null) active.active = true; + } } - public void showFilters() { + // ==================== FILTERS PAGE ==================== + private void showFiltersPage() { + int baseY = guiTop; + + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), + guiLeft + 7, baseY + 7)); + + filterScroll.clear(); + filterScroll.setSize(140, 166); + filterScroll.guiLeft = guiLeft + 4; + filterScroll.guiTop = baseY + 19; + filterScroll.multipleSelection = true; + filterScroll.setSelectedList(tagFilters); + addScroll(filterScroll); + + addTextField(new GuiNpcTextField(2, this, fontRendererObj, + guiLeft + 4, baseY + 190, 140, 20, tagSearch)); + + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), + guiLeft + 150, baseY + 27)); + addButton(new GuiNpcButton(12, guiLeft + 215, baseY + 20, + new String[]{"display.show", "display.all", "display.hide"}, displayTags)); + + addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), + guiLeft + 150, baseY + 50)); + addButton(new GuiNpcButton(13, guiLeft + 215, baseY + 43, + new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition)); + + addButton(new GuiNpcButton(11, guiLeft + 150, baseY + 66, 130, 20, "gui.deselectAll")); + + addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), + guiLeft + 150, baseY + 112)); + addButton(new GuiNpcButton(14, guiLeft + 215, baseY + 105, + new String[]{"cloner.ascending", "cloner.descending"}, ascending)); + + addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), + guiLeft + 150, baseY + 135)); + addButton(new GuiNpcButton(15, guiLeft + 215, baseY + 128, + new String[]{"cloner.name", "cloner.date"}, sortType)); + + getButton(12).width = 65; + getButton(12).height = 20; + getButton(13).width = 65; + getButton(13).height = 20; + getButton(14).width = 65; + getButton(14).height = 20; + getButton(15).width = 65; + getButton(15).height = 20; + filterScroll.setList(getTagList()); } - private void showEntities() { - Map data = EntityList.stringToClassMapping; - ArrayList list = new ArrayList(); - for (Object name : data.keySet()) { - Class c = (Class) data.get(name); - try { - if (EntityLiving.class.isAssignableFrom(c) && c.getConstructor(new Class[]{World.class}) != null && !Modifier.isAbstract(c.getModifiers())) - list.add(name.toString()); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - } - } - this.list = list; - this.rawList = new ArrayList(this.list); - scroll.setList(getSearchList(), ascending == 0, sortType == 0); - } - + // ==================== CLONE / ENTITY DISPLAY ==================== private void showClones() { if (showingClones == 2) { PacketClient.sendClient(new CloneTagListPacket(activeTab)); @@ -219,16 +276,41 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } this.tagMap = ClientTagMapController.Instance.getTagMap(activeTab); + populateRawListWithTags(); + scroll.setList(getSearchList(), ascending == 0, sortType == 0); + } + + private void showEntities() { + Map data = EntityList.stringToClassMapping; + ArrayList list = new ArrayList(); + for (Object name : data.keySet()) { + Class c = (Class) data.get(name); + try { + if (EntityLiving.class.isAssignableFrom(c) + && c.getConstructor(new Class[]{World.class}) != null + && !Modifier.isAbstract(c.getModifiers())) + list.add(name.toString()); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + } + } + this.list = list; this.rawList = new ArrayList(this.list); + scroll.setList(getSearchList(), ascending == 0, sortType == 0); + } + + private void populateRawListWithTags() { + this.rawList = new ArrayList<>(this.list); if (this.tagMap != null) { - if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { + if (displayTags == 0 || displayTags == 1) { for (int i = 0; i < this.list.size(); i++) { StringBuilder npcName = new StringBuilder(list.get(i)); if (this.tagMap.hasClone(list.get(i))) { for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) { Tag tag = tags.get(tagUUID); if (tag != null) { - if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { + if (displayTags == 1 || !tag.getIsHidden()) { npcName.append(" [" + tag.name + "]"); } } @@ -238,27 +320,26 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } } - - scroll.setList(getSearchList(), ascending == 0, sortType == 0); } - public void keyTyped(char c, int i) { - super.keyTyped(c, i); - if (getTextField(1) != null) { - if (search.equals(getTextField(1).getText())) - return; - search = getTextField(1).getText().toLowerCase(); - scroll.setList(getSearchList(), ascending == 0, sortType == 0); - } - if (getTextField(2) != null) { - if (tagSearch.equals(getTextField(2).getText())) - return; - tagSearch = getTextField(2).getText().toLowerCase(); - filterScroll.setList(getTagList()); - } + private NBTTagCompound getCompound() { + String sel = scroll.getSelected(); + if (sel == null) + return null; + if (showingClones == 0) { + return ClientCloneController.Instance.getCloneData(player, sel, activeTab); + } else { + Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld); + if (entity == null) + return null; + NBTTagCompound compound = new NBTTagCompound(); + entity.writeToNBTOptional(compound); + return compound; + } } + // ==================== SEARCH / FILTER ==================== private List getSearchList() { if (this.list == null) { this.list = new ArrayList(); @@ -269,10 +350,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { // No Filters - or - Entities if (tagFilters.size() == 0 || showingClones == 1) { - // No Search if (search.isEmpty()) return new ArrayList(this.list); - // Yes Search else { List list = new ArrayList(); for (int i = 0; i < this.list.size(); i++) { @@ -284,10 +363,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } - //////////////////////// - //// WITH FILTERS - - // No Search + // With Filters if (search.isEmpty()) { List list = new ArrayList(); for (String name : this.list) { @@ -300,7 +376,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { return list; } - // Yes Search List list = new ArrayList(); for (int i = 0; i < this.list.size(); i++) { if (this.rawList.get(i).toLowerCase().contains(search)) { @@ -311,7 +386,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } } - } return list; } @@ -346,7 +420,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } } - return conditionMet; } @@ -354,10 +427,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { if (this.tagList == null) { this.tagList = new ArrayList(); } - // No Search // No Filters - or - Entities if (tagSearch.isEmpty()) return new ArrayList(tagNames.keySet()); - // Yes Search // No Filters - or - Entities List list = new ArrayList(); for (String name : this.tagList) { @@ -367,125 +438,162 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { return list; } - private NBTTagCompound getCompound() { - String sel = scroll.getSelected(); - if (sel == null) - return null; - - if (showingClones == 0) { - return ClientCloneController.Instance.getCloneData(player, sel, activeTab); - } else { - Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld); - if (entity == null) - return null; - NBTTagCompound compound = new NBTTagCompound(); - entity.writeToNBTOptional(compound); - return compound; - } + // ==================== MOUSE / KEYBOARD EVENTS ==================== + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { } + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + } + + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + + GuiNpcTextField searchField = getTextField(1); + if (searchField != null) { + String newText = searchField.getText().toLowerCase(); + if (!search.equals(newText)) { + search = newText; + scroll.setList(getSearchList(), ascending == 0, sortType == 0); + } + } + + GuiNpcTextField tagSearchField = getTextField(2); + if (tagSearchField != null) { + String newText = tagSearchField.getText().toLowerCase(); + if (!tagSearch.equals(newText)) { + tagSearch = newText; + filterScroll.setList(getTagList()); + } + } + } + + // ==================== BUTTON ACTIONS ==================== @Override protected void actionPerformed(GuiButton guibutton) { int id = guibutton.id; - if (id == 0) { - close(); - } - if (id == 1) { - if (showingClones == 2) { - String sel = scroll.getSelected(); - if (sel == null) - return; - SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab); - close(); - } else { - NBTTagCompound compound = getCompound(); - if (compound == null) - return; - SpawnMobPacket.Client(posX, posY, posZ, compound); - close(); - } - } - if (id == 2) { - if (showingClones == 2) { - String sel = scroll.getSelected(); - if (sel == null) - return; - MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab); - close(); - } else { - NBTTagCompound compound = getCompound(); - if (compound == null) - return; - MobSpawnerPacket.Client(posX, posY, posZ, compound); - close(); - } + // Tab side buttons (IDs 21-35) + if (id >= 21 && id <= 35) { + activeTab = id - 20; + activeFolder = null; + initGui(); + return; } + + // Mode buttons if (id == 3) { + savedContentScrollY = 0; showingClones = 0; initGui(); } if (id == 4) { + savedContentScrollY = 0; showingClones = 1; initGui(); } if (id == 5) { + savedContentScrollY = 0; showingClones = 2; + PacketClient.sendClient(new CloneFolderListPacket()); initGui(); } if (id == 16) { + savedContentScrollY = 0; showingClones = 3; initGui(); } if (id == 17) { close(); } + + // Open fullscreen GUI + if (id == 61) { + isFullscreen = true; + Minecraft.getMinecraft().displayGuiScreen( + new GuiNpcMobSpawnerFullscreen(posX, posY, posZ)); + } + + // Spawn + if (id == 1) { + if (showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + SpawnMobPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Mob Spawner + if (id == 2) { + if (showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + MobSpawnerPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Remove if (id == 6) { if (scroll.getSelected() != null) { + int prevSelected = scroll.selected; if (showingClones == 2) { PacketClient.sendClient(new CloneRemovePacket(activeTab, scroll.getSelected())); return; } ClientCloneController.Instance.removeClone(scroll.getSelected(), activeTab); - scroll.selected = -1; initGui(); + if (scroll.list != null && !scroll.list.isEmpty()) { + scroll.selected = Math.min(prevSelected, scroll.list.size() - 1); + } else { + scroll.selected = -1; + } } } + + // Filter controls if (id == 11) { tagFilters = new HashSet<>(); filterScroll.setSelectedList(tagFilters); initGui(); } if (id == 12) { - GuiNpcButton button = (GuiNpcButton) guibutton; - displayTags = (byte) button.getValue(); + displayTags = (byte) ((GuiNpcButton) guibutton).getValue(); } if (id == 13) { - GuiNpcButton button = (GuiNpcButton) guibutton; - filterCondition = (byte) button.getValue(); + filterCondition = (byte) ((GuiNpcButton) guibutton).getValue(); } if (id == 14) { - GuiNpcButton button = (GuiNpcButton) guibutton; - ascending = (byte) button.getValue(); + ascending = (byte) ((GuiNpcButton) guibutton).getValue(); } if (id == 15) { - GuiNpcButton button = (GuiNpcButton) guibutton; - sortType = (byte) button.getValue(); - } - if (id > 20) { - activeTab = id - 20; - initGui(); + sortType = (byte) ((GuiNpcButton) guibutton).getValue(); } } + // ==================== DATA FROM SERVER ==================== @Override public void save() { - } @Override public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("CloneTags")) { + if (compound.hasKey("CloneFolders")) { + // Minimized doesn't use folders, but still handle the packet + initGui(); + } else if (compound.hasKey("CloneTags")) { this.tagMap = new TagMap(activeTab); NBTTagCompound cloneTags = compound.getCompoundTag("CloneTags"); this.tagMap.readNBT(cloneTags); @@ -521,29 +629,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } this.list = list; - - this.rawList = new ArrayList(this.list); - if (this.tagMap != null) { - if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { - for (int i = 0; i < this.list.size(); i++) { - StringBuilder npcName = new StringBuilder(list.get(i)); - if (this.tagMap.hasClone(list.get(i))) { - for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) { - Tag tag = tags.get(tagUUID); - if (tag != null) { - if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { - npcName.append(" [" + tag.name + "]"); - } - } - } - } - this.rawList.set(i, npcName.toString()); - } - } - } - + populateRawListWithTags(); scroll.setList(getSearchList(), ascending == 0, sortType == 0); } } - } diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java index d2895fc44..5cea7fe28 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java @@ -2,6 +2,7 @@ package noppes.npcs.client.gui; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket; import kamkeel.npcs.network.packets.request.clone.CloneSavePacket; import net.minecraft.client.Minecraft; @@ -22,12 +23,14 @@ import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.ISubGuiListener; import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; import noppes.npcs.controllers.data.Tag; import noppes.npcs.entity.EntityNPCInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.UUID; public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ISubGuiListener { @@ -35,9 +38,16 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall private Entity toClone; private NBTTagCompound compound; private static boolean serverSide = false; + private static int saveMode = 0; // 0=Tab, 1=Folder private static int tab = 1; + private static String folder = null; public boolean isNPC = false; + // Client-side folder names + private ArrayList clientFolderNames = new ArrayList<>(); + // Server-side folder names (populated via CloneFolderListPacket) + private static ArrayList serverFolderNames = new ArrayList<>(); + // Selected Tags to Add public static NBTTagList tagsCompound; public static HashSet addTags; @@ -68,6 +78,37 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall if (isNPC) { PacketClient.sendClient(new CloneAllTagsShortPacket()); } + + buildClientFolderNames(); + + // Request server folders if in server mode + if (serverSide) { + PacketClient.sendClient(new CloneFolderListPacket()); + } + + // Validate saved folder selection + validateFolder(); + } + + private void buildClientFolderNames() { + clientFolderNames.clear(); + if (ClientCloneController.Instance != null) { + for (CloneFolder f : ClientCloneController.Instance.getFolderList()) { + clientFolderNames.add(f.name); + } + } + } + + private List getActiveFolderList() { + return serverSide ? serverFolderNames : clientFolderNames; + } + + private void validateFolder() { + if (saveMode == 1 && folder != null) { + if (!getActiveFolderList().contains(folder)) { + folder = null; + } + } } @Override @@ -77,61 +118,138 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall addLabel(new GuiNpcLabel(0, "Save as", guiLeft + 4, guiTop + 6)); addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 4, guiTop + 18, 200, 20, name)); + // Tab/Folder toggle + addButton(new GuiNpcButton(6, guiLeft + 4, guiTop + 45, 50, 20, + new String[]{"Tab", "Folder"}, saveMode)); - addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50)); - addButton(new GuiButtonBiDirectional(2, guiLeft + 40, guiTop + 45, 60, 20, new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}, tab - 1)); + // Destination selector based on saveMode + if (saveMode == 0) { + // Tab selector: 1-15 + String[] tabLabels = new String[15]; + for (int i = 0; i < 15; i++) tabLabels[i] = String.valueOf(i + 1); + int selectedTab = (tab >= 1 && tab <= 15) ? tab - 1 : 0; + addButton(new GuiButtonBiDirectional(2, guiLeft + 56, guiTop + 45, 90, 20, tabLabels, selectedTab)); + } else { + // Folder selector button — opens SubGuiFolderSelect + String btnText = folder != null ? folder : "Select a Folder"; + addButton(new GuiNpcButton(2, guiLeft + 56, guiTop + 45, 148, 20, btnText)); + } - addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0)); - addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50)); - - addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save")); + // Save / Cancel + GuiNpcButton saveBtn = new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save"); + if (saveMode == 1 && folder == null) { + saveBtn.enabled = false; + } + addButton(saveBtn); addButton(new GuiNpcButton(1, guiLeft + 86, guiTop + 70, 80, 20, "gui.cancel")); + // Client / Server toggle + addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0)); + if (isNPC) { addButton(new GuiNpcButton(4, guiLeft + 4, guiTop + 120, 99, 20, "cloner.wandTags")); addButton(new GuiNpcButton(5, guiLeft + 106, guiTop + 120, 99, 20, "cloner.npcTags")); if (addTags.size() > 0) { - addLabel(new GuiNpcLabel(6, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160)); + addLabel(new GuiNpcLabel(8, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160)); } } } + private void updateDestinationFromSelector() { + if (saveMode == 0) { + GuiNpcButton selector = getButton(2); + if (selector == null) return; + tab = selector.getValue() + 1; + folder = null; + } + // In folder mode, folder is already set via SubGuiFolderSelect + } + public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; + + // Save if (id == 0) { + updateDestinationFromSelector(); String name = getTextField(0).getText(); if (name.isEmpty()) return; - int tab = ((GuiNpcButton) guibutton).getValue() + 1; + + if (saveMode == 1 && folder == null) + return; + if (!serverSide) { - if (ClientCloneController.Instance.getCloneData(null, name, tab) != null) + boolean exists; + if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) { + exists = ClientCloneController.Instance.getCloneData(null, name, folder) != null; + } else { + exists = ClientCloneController.Instance.getCloneData(null, name, tab) != null; + } + if (exists) displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1)); else confirmClicked(true, 0); - } else - PacketClient.sendClient(new ClonePreSavePacket(name, tab)); + } else { + if (saveMode == 1 && folder != null) { + PacketClient.sendClient(new ClonePreSavePacket(name, folder)); + } else { + PacketClient.sendClient(new ClonePreSavePacket(name, tab)); + } + } } + + // Cancel if (id == 1) { close(); } + + // Destination selector if (id == 2) { - tab = ((GuiNpcButton) guibutton).getValue() + 1; + if (saveMode == 0) { + // Tab mode — update from BiDirectional + updateDestinationFromSelector(); + } else { + // Folder mode — open folder selector Sub GUI + List folders = getActiveFolderList(); + setSubGui(new SubGuiFolderSelect(folders, folder)); + } } + + // Client / Server toggle if (id == 3) { + boolean wasServerSide = serverSide; serverSide = ((GuiNpcButton) guibutton).getValue() == 1; + + if (serverSide && !wasServerSide) { + // Switching to server mode — request fresh folder list + PacketClient.sendClient(new CloneFolderListPacket()); + } + + // Validate folder exists on the new side + validateFolder(); + initGui(); } + + // Wand Tags if (id == 4) { if (isNPC) { this.setSubGui(new SubGuiClonerQuickTags(this)); } } + + // NPC Tags if (id == 5) { if (isNPC) { this.setSubGui(new SubGuiClonerNPCTags((EntityNPCInterface) toClone, this)); } } - } + // Tab/Folder mode toggle + if (id == 6) { + saveMode = ((GuiNpcButton) guibutton).getValue(); + initGui(); + } + } @Override public void confirmClicked(boolean confirm, int id) { @@ -145,13 +263,21 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall if (isNPC) { compound.setTag("TagUUIDs", tagsCompound); } - ClientCloneController.Instance.addClone(compound, name, tab, extraTags); + if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) { + ClientCloneController.Instance.addClone(compound, name, folder, extraTags); + } else { + ClientCloneController.Instance.addClone(compound, name, tab, extraTags); + } } else { NBTTagCompound compounder = new NBTTagCompound(); if (isNPC) { compounder.setTag("TagUUIDs", tagsCompound); } - PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder)); + if (saveMode == 1 && folder != null) { + PacketClient.sendClient(new CloneSavePacket(name, folder, extraTags, compounder)); + } else { + PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder)); + } } close(); @@ -159,7 +285,6 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall displayGuiScreen(this); } - @Override public void save() { } @@ -171,6 +296,17 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1)); else confirmClicked(true, 0); + } else if (compound.hasKey("CloneFolders")) { + // Server folder list arrived + NBTTagList folderList = compound.getTagList("CloneFolders", 10); + serverFolderNames.clear(); + for (int i = 0; i < folderList.tagCount(); i++) { + CloneFolder f = new CloneFolder(); + f.readNBT(folderList.getCompoundTagAt(i)); + serverFolderNames.add(f.name); + } + validateFolder(); + initGui(); } else if (compound.hasKey("ShortTags")) { NBTTagList validTags = compound.getTagList("ShortTags", 10); tagMap.clear(); @@ -193,6 +329,12 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall @Override public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiFolderSelect) { + SubGuiFolderSelect sel = (SubGuiFolderSelect) subgui; + if (sel.selectedFolder != null) { + folder = sel.selectedFolder; + } + } initGui(); } diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java new file mode 100644 index 000000000..eabc33fee --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java @@ -0,0 +1,1045 @@ +package noppes.npcs.client.gui; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderCrudPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; +import kamkeel.npcs.network.packets.request.clone.CloneListPacket; +import kamkeel.npcs.network.packets.request.clone.CloneMovePacket; +import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket; +import kamkeel.npcs.network.packets.request.clone.CloneTagListPacket; +import kamkeel.npcs.network.packets.request.clone.MobSpawnerPacket; +import kamkeel.npcs.network.packets.request.clone.SpawnMobPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityList; +import net.minecraft.entity.EntityLiving; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; +import noppes.npcs.client.controllers.ClientCloneController; +import noppes.npcs.client.controllers.ClientTagMapController; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiCustomScrollCloner; +import noppes.npcs.client.gui.util.GuiCustomScrollIcons; +import noppes.npcs.client.gui.util.GuiDirectory; +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.IClonerGui; +import noppes.npcs.client.gui.util.IGuiData; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; +import noppes.npcs.controllers.data.Tag; +import noppes.npcs.controllers.data.TagMap; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class GuiNpcMobSpawnerFullscreen extends GuiDirectory implements IGuiData, IClonerGui { + + // ==================== INSTANCE STATE ==================== + public TagMap tagMap; + private final GuiCustomScrollCloner scroll = new GuiCustomScrollCloner(this, 0); + private final GuiCustomScroll filterScroll = new GuiCustomScroll(this, 1); + private final GuiCustomScrollIcons navScroll = new GuiCustomScrollIcons(this, 2); + + private int posX, posY, posZ; + private List list; + private List rawList; + private List tagList; + private List folderNames = new ArrayList<>(); + + // Left nav list data + private List navNames = new ArrayList<>(); + private List navIcons = new ArrayList<>(); + private String navSearch = ""; + + // Move workflow state + private int movePhase = 0; // 0=off, 1=selecting clones, 2=selecting destination + private HashSet moveSelection = new HashSet<>(); + + // ==================== CONSTRUCTOR ==================== + public GuiNpcMobSpawnerFullscreen(int posX, int posY, int posZ) { + super(); + this.posX = posX; + this.posY = posY; + this.posZ = posZ; + + // Configure GuiDirectory layout percentages + leftPanelPercent = 0.15f; + rightPanelPercent = 0.08f; + minLeftPanelW = 120; + minRightPanelW = 62; + + PacketClient.sendClient(new CloneAllTagsPacket()); + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderListPacket()); + } + loadFolderNames(); + } + + private void loadFolderNames() { + folderNames.clear(); + if (ClientCloneController.Instance != null) { + for (CloneFolder folder : ClientCloneController.Instance.getFolderList()) { + folderNames.add(folder.name); + } + } + } + + // ==================== IClonerGui ==================== + @Override + public int getShowingClones() { + return GuiNpcMobSpawner.showingClones; + } + + @Override + public HashMap getTags() { + return GuiNpcMobSpawner.tags; + } + + @Override + public TagMap getTagMap() { + return tagMap; + } + + // ==================== GuiDirectory HOOKS ==================== + @Override + public void initGui() { + // Save scroll positions before super.initGui() clears everything + GuiNpcMobSpawner.savedContentScrollY = scroll.scrollY; + GuiNpcMobSpawner.savedNavScrollY = navScroll.scrollY; + + super.initGui(); + } + + @Override + protected void drawPanels() { + if (GuiNpcMobSpawner.showingClones < 3) { + super.drawPanels(); + } else { + // Filters page: only draw top bar, no side panels + } + } + + @Override + protected void initTopBar(int topBtnY) { + int topBtnW = 55; + int x = originX + 2; + + GuiNpcButton clonesBtn = new GuiNpcButton(3, x, topBtnY, topBtnW, btnH, "spawner.clones"); + clonesBtn.enabled = GuiNpcMobSpawner.showingClones != 0; + addButton(clonesBtn); + x += topBtnW + 2; + + GuiNpcButton serverBtn = new GuiNpcButton(5, x, topBtnY, topBtnW, btnH, "gui.server"); + serverBtn.enabled = GuiNpcMobSpawner.showingClones != 2; + addButton(serverBtn); + x += topBtnW + 2; + + GuiNpcButton entitiesBtn = new GuiNpcButton(4, x, topBtnY, topBtnW, btnH, "spawner.entities"); + entitiesBtn.enabled = GuiNpcMobSpawner.showingClones != 1; + addButton(entitiesBtn); + + // Top bar right side + int closeX = originX + usableW - btnH - 2; + addButton(new GuiNpcButton(17, closeX, topBtnY, btnH, btnH, "X")); + int minimizeX = closeX - btnH - 2; + addButton(new GuiNpcButton(61, minimizeX, topBtnY, btnH, btnH, "-")); + int filterBtnW = 50; + int filterX = minimizeX - filterBtnW - 2; + GuiNpcButton filterBtn = new GuiNpcButton(16, filterX, topBtnY, filterBtnW, btnH, "gui.filters"); + filterBtn.enabled = GuiNpcMobSpawner.showingClones != 3; + addButton(filterBtn); + + // Clone search field in top bar (only when not on filters page) + if (GuiNpcMobSpawner.showingClones < 3) { + int searchX = x + topBtnW + 6; + int searchW = filterX - searchX - 4; + if (searchW > 20) { + addTextField(new GuiNpcTextField(1, this, fontRendererObj, + searchX, topBtnY, searchW, btnH, GuiNpcMobSpawner.search)); + } + } + + // Disable mode buttons during move + if (movePhase > 0) { + clonesBtn.enabled = false; + serverBtn.enabled = false; + entitiesBtn.enabled = false; + filterBtn.enabled = false; + } + } + + @Override + protected void initLeftPanel() { + if (GuiNpcMobSpawner.showingClones >= 3) return; + + boolean folderSelected = GuiNpcMobSpawner.activeFolder != null; + int bottomRows = folderSelected ? 3 : 2; + int bottomH = bottomRows * (btnH + gap); + int navH = contentH - bottomH; + buildNavList(); + + int savedNavScroll = GuiNpcMobSpawner.savedNavScrollY; + navScroll.clear(); + navScroll.colors.clear(); + navScroll.setSize(leftPanelW, navH); + navScroll.guiLeft = originX; + navScroll.guiTop = contentY; + navScroll.setListWithIcons(navNames, navIcons); + navScroll.setSelected(getNavSelection()); + navScroll.scrollY = Math.min(savedNavScroll, Math.max(0, navScroll.maxScrollY)); + + // Phase 2: color nav items orange (selectable) or red (current location) + if (movePhase == 2) { + String currentNav = getNavSelection(); + for (String name : navNames) { + navScroll.colors.put(name, name.equals(currentNav) ? 0xFF5555 : 0xFFAA00); + } + } + + addScroll(navScroll); + + // Nav search field below the scroll + int navSearchY = contentY + navH + gap; + addTextField(new GuiNpcTextField(3, this, fontRendererObj, + originX, navSearchY, leftPanelW, btnH, navSearch)); + + // Add folder button + int addFolderY = navSearchY + btnH + gap; + GuiNpcButton addFolderBtn = new GuiNpcButton(40, originX, addFolderY, leftPanelW, btnH, "+ Add Folder"); + if (movePhase > 0) addFolderBtn.enabled = false; + addButton(addFolderBtn); + + // Rename/Delete folder buttons (only when a folder is selected) + if (folderSelected) { + int folderCrudY = addFolderY + btnH + gap; + int halfW = (leftPanelW - gap) / 2; + GuiNpcButton renameBtn = new GuiNpcButton(41, originX, folderCrudY, halfW, btnH, "Rename"); + if (movePhase > 0) renameBtn.enabled = false; + addButton(renameBtn); + GuiNpcButton delBtn = new GuiNpcButton(42, originX + halfW + gap, folderCrudY, halfW, btnH, "gui.remove"); + if (ClientCloneController.Instance != null) { + List clones = ClientCloneController.Instance.getClones(GuiNpcMobSpawner.activeFolder); + delBtn.enabled = clones == null || clones.isEmpty(); + } + if (movePhase > 0) delBtn.enabled = false; + addButton(delBtn); + } + } + + @Override + protected void initCenterPanel() { + if (GuiNpcMobSpawner.showingClones >= 3) { + showFiltersPage(); + return; + } + + int savedScroll = GuiNpcMobSpawner.savedContentScrollY; + scroll.clear(); + scroll.setSize(contentW, contentH); + scroll.guiLeft = contentX; + scroll.guiTop = contentY; + addScroll(scroll); + + if (GuiNpcMobSpawner.showingClones == 0 || GuiNpcMobSpawner.showingClones == 2) { + // Always clear colors — only phase 2 re-populates them + scroll.colors.clear(); + + // Multi-select mode during move phase 1 + if (movePhase == 1) { + scroll.multipleSelection = true; + scroll.setSelectable(true); + scroll.setSelectedList(moveSelection); + } else if (movePhase == 2) { + // Phase 2: show selection as yellow, freeze scroll + scroll.multipleSelection = true; + scroll.setSelectedList(moveSelection); + scroll.setSelectable(false); + } else { + scroll.multipleSelection = false; + scroll.setSelectable(true); + } + + showClones(); + + // Phase 2: color selected clones yellow + if (movePhase == 2) { + for (String name : moveSelection) { + scroll.colors.put(name, 0xFFFF55); + } + } + + // Restore scroll position after list is populated + scroll.scrollY = Math.min(savedScroll, Math.max(0, scroll.maxScrollY)); + } else { + showEntities(); + scroll.scrollY = Math.min(savedScroll, Math.max(0, scroll.maxScrollY)); + } + } + + @Override + protected void initRightPanel(int startY) { + if (GuiNpcMobSpawner.showingClones >= 3) return; + + int btnGap = 4; + int panelH = contentH - 4; + int midY = startY + (panelH / 2); + int bottomY = contentY + contentH - btnH; + + // Spawn — top + GuiNpcButton spawnBtn = new GuiNpcButton(1, rightX, startY, rightPanelW, btnH, "item.monsterPlacer.name"); + if (movePhase > 0) spawnBtn.enabled = false; + addButton(spawnBtn); + + // Spawner — below midpoint + GuiNpcButton spawnerBtn = new GuiNpcButton(2, rightX, midY + btnGap / 2, rightPanelW, btnH, "spawner.mobspawner"); + if (movePhase > 0) spawnerBtn.enabled = false; + addButton(spawnerBtn); + + if (GuiNpcMobSpawner.showingClones == 0 || GuiNpcMobSpawner.showingClones == 2) { + // Move — above midpoint + String moveLabel = movePhase > 0 ? "Moving" : "Move"; + GuiNpcButton moveBtn = new GuiNpcButton(50, rightX, midY - btnH - btnGap / 2, rightPanelW, btnH, moveLabel); + addButton(moveBtn); + + // Confirm — below Move (only visible during phase 1) + if (movePhase == 1) { + GuiNpcButton confirmBtn = new GuiNpcButton(51, rightX, midY - btnH - btnGap / 2 + btnH + btnGap, rightPanelW, btnH, "Confirm"); + confirmBtn.enabled = !moveSelection.isEmpty(); + addButton(confirmBtn); + } + + // Remove — bottom + GuiNpcButton removeBtn = new GuiNpcButton(6, rightX, bottomY, rightPanelW, btnH, "gui.remove"); + if (movePhase > 0) removeBtn.enabled = false; + addButton(removeBtn); + } + } + + // ==================== OVERLAY DRAWING ==================== + @Override + protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { + if (movePhase == 1) { + String text = "Select Clones to Move"; + int textW = fontRendererObj.getStringWidth(text); + fontRendererObj.drawStringWithShadow(text, width / 2 - textW / 2, height - pad - 10, 0x55FF55); + } else if (movePhase == 2) { + String text = "Select a Tab or Folder"; + int textW = fontRendererObj.getStringWidth(text); + fontRendererObj.drawStringWithShadow(text, width / 2 - textW / 2, height - pad - 10, 0xFF5555); + } + } + + // ==================== LEFT NAVIGATION ==================== + private void buildNavList() { + navNames.clear(); + navIcons.clear(); + + String searchLower = navSearch.toLowerCase(); + + for (int i = 1; i <= 15; i++) { + String name = "Tab " + i; + if (searchLower.isEmpty() || name.toLowerCase().contains(searchLower)) { + navNames.add(name); + navIcons.add(GuiCustomScrollIcons.ICON_TAB); + } + } + for (String folder : folderNames) { + if (searchLower.isEmpty() || folder.toLowerCase().contains(searchLower)) { + navNames.add(folder); + navIcons.add(GuiCustomScrollIcons.ICON_FOLDER); + } + } + } + + private String getNavSelection() { + if (GuiNpcMobSpawner.activeFolder != null) return GuiNpcMobSpawner.activeFolder; + if (GuiNpcMobSpawner.activeTab >= 1 && GuiNpcMobSpawner.activeTab <= 15) { + return "Tab " + GuiNpcMobSpawner.activeTab; + } + return "Tab 1"; + } + + private void handleNavClick(String selected) { + if (selected == null) return; + + if (selected.startsWith("Tab ")) { + try { + int tabNum = Integer.parseInt(selected.substring(4)); + if (tabNum >= 1 && tabNum <= 15) { + GuiNpcMobSpawner.activeTab = tabNum; + GuiNpcMobSpawner.activeFolder = null; + initGui(); + return; + } + } catch (NumberFormatException ignored) { + } + } + + GuiNpcMobSpawner.activeFolder = selected; + GuiNpcMobSpawner.activeTab = -1; + initGui(); + } + + // ==================== FILTERS PAGE ==================== + private void showFiltersPage() { + int scrollW = Math.min(usableW / 2 - gap * 2, 240); + int scrollX = originX + gap; + int scrollTopY = contentY + 16; + int scrollH = contentH - 16 - btnH - gap * 2; + + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), + scrollX + 2, contentY + 4, 0xFFFFFF)); + + filterScroll.clear(); + filterScroll.setSize(scrollW, scrollH); + filterScroll.guiLeft = scrollX; + filterScroll.guiTop = scrollTopY; + filterScroll.multipleSelection = true; + filterScroll.setSelectedList(GuiNpcMobSpawner.tagFilters); + addScroll(filterScroll); + + addTextField(new GuiNpcTextField(2, this, fontRendererObj, + scrollX, scrollTopY + scrollH + gap, scrollW, btnH, GuiNpcMobSpawner.tagSearch)); + + // Settings column + int col2X = scrollX + scrollW + gap * 4; + int controlW = 90; + int controlX = col2X + 80; + int rowH = 28; + int rowY = scrollTopY; + + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(12, controlX, rowY, controlW, btnH, + new String[]{"display.show", "display.all", "display.hide"}, GuiNpcMobSpawner.displayTags)); + + rowY += rowH; + addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(13, controlX, rowY, controlW, btnH, + new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, GuiNpcMobSpawner.filterCondition)); + + rowY += rowH + 4; + addButton(new GuiNpcButton(11, col2X, rowY, controlW + 80, btnH, "gui.deselectAll")); + + rowY += rowH + 12; + addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(14, controlX, rowY, controlW, btnH, + new String[]{"cloner.ascending", "cloner.descending"}, GuiNpcMobSpawner.ascending)); + + rowY += rowH; + addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(15, controlX, rowY, controlW, btnH, + new String[]{"cloner.name", "cloner.date"}, GuiNpcMobSpawner.sortType)); + + filterScroll.setList(getTagList()); + } + + // ==================== CLONE / ENTITY DISPLAY ==================== + private void showClones() { + if (GuiNpcMobSpawner.activeFolder != null) { + showFolderClones(); + return; + } + + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneTagListPacket(GuiNpcMobSpawner.activeTab)); + PacketClient.sendClient(new CloneListPacket(GuiNpcMobSpawner.activeTab)); + return; + } + + if (GuiNpcMobSpawner.sortType == 0) { + this.list = ClientCloneController.Instance.getClones(GuiNpcMobSpawner.activeTab); + } else { + this.list = ClientCloneController.Instance.getClonesDate(GuiNpcMobSpawner.activeTab); + } + + this.tagMap = ClientTagMapController.Instance.getTagMap(GuiNpcMobSpawner.activeTab); + populateRawListWithTags(); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + + private void showFolderClones() { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneTagListPacket(GuiNpcMobSpawner.activeFolder)); + PacketClient.sendClient(new CloneListPacket(GuiNpcMobSpawner.activeFolder)); + return; + } + + if (ClientCloneController.Instance != null) { + if (GuiNpcMobSpawner.sortType == 0) { + this.list = ClientCloneController.Instance.getClones(GuiNpcMobSpawner.activeFolder); + } else { + this.list = ClientCloneController.Instance.getClonesDate(GuiNpcMobSpawner.activeFolder); + } + this.tagMap = ClientTagMapController.Instance.getTagMap(GuiNpcMobSpawner.activeFolder); + } else { + this.list = new ArrayList<>(); + this.tagMap = null; + } + + populateRawListWithTags(); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + + private void showEntities() { + Map data = EntityList.stringToClassMapping; + ArrayList list = new ArrayList(); + for (Object name : data.keySet()) { + Class c = (Class) data.get(name); + try { + if (EntityLiving.class.isAssignableFrom(c) + && c.getConstructor(new Class[]{World.class}) != null + && !Modifier.isAbstract(c.getModifiers())) + list.add(name.toString()); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + } + } + this.list = list; + this.rawList = new ArrayList(this.list); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + + private void populateRawListWithTags() { + this.rawList = new ArrayList<>(this.list); + if (this.tagMap != null) { + if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { + for (int i = 0; i < this.list.size(); i++) { + StringBuilder npcName = new StringBuilder(list.get(i)); + if (this.tagMap.hasClone(list.get(i))) { + for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) { + Tag tag = GuiNpcMobSpawner.tags.get(tagUUID); + if (tag != null) { + if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { + npcName.append(" [" + tag.name + "]"); + } + } + } + } + this.rawList.set(i, npcName.toString()); + } + } + } + } + + private NBTTagCompound getCompound() { + String sel = scroll.getSelected(); + if (sel == null) + return null; + + if (GuiNpcMobSpawner.showingClones == 0) { + if (GuiNpcMobSpawner.activeFolder != null && ClientCloneController.Instance != null) { + return ClientCloneController.Instance.getCloneData(player, sel, GuiNpcMobSpawner.activeFolder); + } + return ClientCloneController.Instance.getCloneData(player, sel, GuiNpcMobSpawner.activeTab); + } else { + Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld); + if (entity == null) + return null; + NBTTagCompound compound = new NBTTagCompound(); + entity.writeToNBTOptional(compound); + return compound; + } + } + + // ==================== SEARCH / FILTER ==================== + private List getSearchList() { + if (this.list == null) { + this.list = new ArrayList(); + } + if (this.rawList == null) { + this.rawList = new ArrayList(); + } + + if (GuiNpcMobSpawner.tagFilters.size() == 0 || GuiNpcMobSpawner.showingClones == 1) { + if (GuiNpcMobSpawner.search.isEmpty()) + return new ArrayList(this.list); + else { + List list = new ArrayList(); + for (int i = 0; i < this.list.size(); i++) { + if (this.rawList.get(i).toLowerCase().contains(GuiNpcMobSpawner.search)) { + list.add(this.list.get(i)); + } + } + return list; + } + } + + if (GuiNpcMobSpawner.search.isEmpty()) { + List list = new ArrayList(); + for (String name : this.list) { + if (tagMap.hasClone(name)) { + if (meetsCondition(name)) { + list.add(name); + } + } + } + return list; + } + + List list = new ArrayList(); + for (int i = 0; i < this.list.size(); i++) { + if (this.rawList.get(i).toLowerCase().contains(GuiNpcMobSpawner.search)) { + String npcName = this.list.get(i); + if (tagMap.hasClone(npcName)) { + if (meetsCondition(npcName)) { + list.add(npcName); + } + } + } + } + return list; + } + + private boolean meetsCondition(String name) { + if (tagMap == null) { + return true; + } + boolean conditionMet = true; + boolean allRequirement = GuiNpcMobSpawner.filterCondition == 1 || GuiNpcMobSpawner.filterCondition == 3; + + for (String tagName : GuiNpcMobSpawner.tagFilters) { + UUID tagUUID = GuiNpcMobSpawner.tagNames.get(tagName); + if (tagUUID != null) { + boolean hasTag = tagMap.hasTag(name, tagUUID); + if (!allRequirement) { + if (!hasTag && GuiNpcMobSpawner.filterCondition == 0) { + conditionMet = false; + break; + } else if (hasTag && GuiNpcMobSpawner.filterCondition == 2) { + conditionMet = false; + break; + } + } else { + if (!hasTag && GuiNpcMobSpawner.filterCondition == 1) { + conditionMet = false; + break; + } else if (hasTag && GuiNpcMobSpawner.filterCondition == 3) { + conditionMet = false; + break; + } + } + } + } + return conditionMet; + } + + private List getTagList() { + if (this.tagList == null) { + this.tagList = new ArrayList(); + } + if (GuiNpcMobSpawner.tagSearch.isEmpty()) + return new ArrayList(GuiNpcMobSpawner.tagNames.keySet()); + + List list = new ArrayList(); + for (String name : this.tagList) { + if (name.toLowerCase().contains(GuiNpcMobSpawner.tagSearch)) + list.add(name); + } + return list; + } + + // ==================== SCROLL EVENTS ==================== + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + // Phase 2: ignore clicks on the center clone scroll + if (guiCustomScroll.id == 0 && movePhase == 2) { + return; + } + + if (guiCustomScroll.id == 0 && movePhase == 1) { + moveSelection = scroll.getSelectedList(); + GuiNpcButton confirmBtn = getButton(51); + if (confirmBtn != null) { + confirmBtn.enabled = !moveSelection.isEmpty(); + } + return; + } + + if (guiCustomScroll.id == 2) { + String selected = navScroll.getSelected(); + if (selected == null) return; + + if (movePhase == 2) { + // Cannot move to the same location + if (selected.equals(getNavSelection())) { + return; + } + // Selecting destination from nav + if (selected.startsWith("Tab ")) { + try { + int tabNum = Integer.parseInt(selected.substring(4)); + setSubGui(new SubGuiMoveConfirm(moveSelection.size(), tabNum, null)); + } catch (NumberFormatException ignored) { + } + } else { + setSubGui(new SubGuiMoveConfirm(moveSelection.size(), -1, selected)); + } + return; + } + + if (movePhase == 1) { + movePhase = 0; + moveSelection.clear(); + } + + handleNavClick(selected); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + } + + // ==================== KEYBOARD ==================== + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + + GuiNpcTextField searchField = getTextField(1); + if (searchField != null) { + String newText = searchField.getText().toLowerCase(); + if (!GuiNpcMobSpawner.search.equals(newText)) { + GuiNpcMobSpawner.search = newText; + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + } + + GuiNpcTextField tagSearchField = getTextField(2); + if (tagSearchField != null) { + String newText = tagSearchField.getText().toLowerCase(); + if (!GuiNpcMobSpawner.tagSearch.equals(newText)) { + GuiNpcMobSpawner.tagSearch = newText; + filterScroll.setList(getTagList()); + } + } + + GuiNpcTextField navSearchField = getTextField(3); + if (navSearchField != null) { + String newNavSearch = navSearchField.getText().toLowerCase(); + if (!navSearch.equals(newNavSearch)) { + navSearch = newNavSearch; + buildNavList(); + navScroll.setListWithIcons(navNames, navIcons); + navScroll.setSelected(getNavSelection()); + } + } + } + + // ==================== BUTTON ACTIONS ==================== + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + + if (id == 3) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 0; + loadFolderNames(); + initGui(); + } + if (id == 4) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 1; + initGui(); + } + if (id == 5) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 2; + PacketClient.sendClient(new CloneFolderListPacket()); + initGui(); + } + if (id == 16) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 3; + initGui(); + } + if (id == 17) { + close(); + } + + // Minimize — return to normal GUI + if (id == 61) { + GuiNpcMobSpawner.isFullscreen = false; + Minecraft.getMinecraft().displayGuiScreen( + new GuiNpcMobSpawner(posX, posY, posZ)); + } + + // Spawn + if (id == 1) { + if (GuiNpcMobSpawner.showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + if (GuiNpcMobSpawner.activeFolder != null) + SpawnMobPacket.ServerFolder(posX, posY, posZ, sel, GuiNpcMobSpawner.activeFolder); + else + SpawnMobPacket.Server(posX, posY, posZ, sel, GuiNpcMobSpawner.activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + SpawnMobPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Mob Spawner + if (id == 2) { + if (GuiNpcMobSpawner.showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + if (GuiNpcMobSpawner.activeFolder != null) + MobSpawnerPacket.ServerFolder(posX, posY, posZ, sel, GuiNpcMobSpawner.activeFolder); + else + MobSpawnerPacket.Server(posX, posY, posZ, sel, GuiNpcMobSpawner.activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + MobSpawnerPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Remove + if (id == 6) { + if (scroll.getSelected() != null) { + int prevSelected = scroll.selected; + if (GuiNpcMobSpawner.showingClones == 2) { + if (GuiNpcMobSpawner.activeFolder != null) + PacketClient.sendClient(new CloneRemovePacket(GuiNpcMobSpawner.activeFolder, scroll.getSelected())); + else + PacketClient.sendClient(new CloneRemovePacket(GuiNpcMobSpawner.activeTab, scroll.getSelected())); + return; + } + if (GuiNpcMobSpawner.activeFolder != null && ClientCloneController.Instance != null) + ClientCloneController.Instance.removeClone(scroll.getSelected(), GuiNpcMobSpawner.activeFolder); + else + ClientCloneController.Instance.removeClone(scroll.getSelected(), GuiNpcMobSpawner.activeTab); + initGui(); + if (scroll.list != null && !scroll.list.isEmpty()) { + scroll.selected = Math.min(prevSelected, scroll.list.size() - 1); + } else { + scroll.selected = -1; + } + } + } + + // Move toggle + if (id == 50) { + if (movePhase == 0) { + movePhase = 1; + moveSelection.clear(); + } else { + movePhase = 0; + moveSelection.clear(); + } + initGui(); + } + // Confirm move selection + if (id == 51) { + if (movePhase == 1 && !moveSelection.isEmpty()) { + movePhase = 2; + initGui(); + } + } + + // Filter controls + if (id == 11) { + GuiNpcMobSpawner.tagFilters = new HashSet<>(); + filterScroll.setSelectedList(GuiNpcMobSpawner.tagFilters); + initGui(); + } + if (id == 12) { + GuiNpcMobSpawner.displayTags = (byte) ((GuiNpcButton) guibutton).getValue(); + } + if (id == 13) { + GuiNpcMobSpawner.filterCondition = (byte) ((GuiNpcButton) guibutton).getValue(); + } + if (id == 14) { + GuiNpcMobSpawner.ascending = (byte) ((GuiNpcButton) guibutton).getValue(); + } + if (id == 15) { + GuiNpcMobSpawner.sortType = (byte) ((GuiNpcButton) guibutton).getValue(); + } + + // Create folder + if (id == 40) { + setSubGui(new SubGuiCloneFolderName("")); + } + // Rename folder + if (id == 41) { + if (GuiNpcMobSpawner.activeFolder != null) + setSubGui(new SubGuiCloneFolderName(GuiNpcMobSpawner.activeFolder)); + } + // Delete folder + if (id == 42) { + if (GuiNpcMobSpawner.activeFolder != null) { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderCrudPacket( + CloneFolderCrudPacket.ACTION_DELETE, GuiNpcMobSpawner.activeFolder)); + } else if (ClientCloneController.Instance != null) { + ClientCloneController.Instance.deleteFolder(GuiNpcMobSpawner.activeFolder); + loadFolderNames(); + } + GuiNpcMobSpawner.activeFolder = null; + GuiNpcMobSpawner.activeTab = 1; + initGui(); + } + } + } + + // ==================== SUB GUI ==================== + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiCloneFolderName) { + SubGuiCloneFolderName folderGui = (SubGuiCloneFolderName) subgui; + if (folderGui.cancelled) return; + + String newName = folderGui.getFolderName(); + if (newName == null || newName.isEmpty()) return; + + if (folderGui.isRename()) { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderCrudPacket( + CloneFolderCrudPacket.ACTION_RENAME, folderGui.getOriginalName(), newName)); + } else if (ClientCloneController.Instance != null) { + ClientCloneController.Instance.renameFolder(folderGui.getOriginalName(), newName); + loadFolderNames(); + } + GuiNpcMobSpawner.activeFolder = newName; + GuiNpcMobSpawner.activeTab = -1; + } else { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderCrudPacket( + CloneFolderCrudPacket.ACTION_CREATE, newName)); + } else if (ClientCloneController.Instance != null) { + ClientCloneController.Instance.createFolder(newName); + loadFolderNames(); + } + GuiNpcMobSpawner.activeFolder = newName; + GuiNpcMobSpawner.activeTab = -1; + } + initGui(); + } + + if (subgui instanceof SubGuiMoveConfirm) { + SubGuiMoveConfirm confirm = (SubGuiMoveConfirm) subgui; + if (confirm.confirmed && !moveSelection.isEmpty()) { + int fromTab = GuiNpcMobSpawner.activeFolder != null ? -1 : GuiNpcMobSpawner.activeTab; + String fromFolder = GuiNpcMobSpawner.activeFolder; + int toTab = confirm.destTab; + String toFolder = confirm.destFolder; + + for (String cloneName : moveSelection) { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneMovePacket( + cloneName, fromTab, fromFolder, toTab, toFolder)); + } else if (ClientCloneController.Instance != null) { + if (fromFolder != null && toFolder != null) { + ClientCloneController.Instance.moveClone(cloneName, fromFolder, toFolder); + } else if (fromFolder != null) { + ClientCloneController.Instance.moveClone(cloneName, fromFolder, toTab); + } else if (toFolder != null) { + ClientCloneController.Instance.moveClone(cloneName, fromTab, toFolder); + } else { + ClientCloneController.Instance.moveClone(cloneName, fromTab, toTab); + } + } + } + } + movePhase = 0; + moveSelection.clear(); + initGui(); + } + } + + // ==================== DATA FROM SERVER ==================== + @Override + public void save() { + } + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("CloneFolders")) { + NBTTagList folderList = compound.getTagList("CloneFolders", 10); + folderNames.clear(); + for (int i = 0; i < folderList.tagCount(); i++) { + CloneFolder folder = new CloneFolder(); + folder.readNBT(folderList.getCompoundTagAt(i)); + folderNames.add(folder.name); + } + initGui(); + } else if (compound.hasKey("MoveSuccess")) { + initGui(); + } else if (compound.hasKey("CloneTags")) { + if (GuiNpcMobSpawner.activeFolder != null) { + this.tagMap = new TagMap(GuiNpcMobSpawner.activeFolder); + } else { + this.tagMap = new TagMap(GuiNpcMobSpawner.activeTab); + } + NBTTagCompound cloneTags = compound.getCompoundTag("CloneTags"); + this.tagMap.readNBT(cloneTags); + } else if (compound.hasKey("AllTags")) { + NBTTagList validTags = compound.getTagList("AllTags", 10); + if (validTags != null) { + HashMap tagsUpdate = new HashMap<>(); + HashMap tagNamesUpdate = new HashMap<>(); + for (int j = 0; j < validTags.tagCount(); j++) { + NBTTagCompound tagStructure = validTags.getCompoundTagAt(j); + Tag tag = new Tag(); + tag.readNBT(tagStructure); + tagsUpdate.put(tag.uuid, tag); + tagNamesUpdate.put(tag.name, tag.uuid); + } + GuiNpcMobSpawner.tags = tagsUpdate; + GuiNpcMobSpawner.tagNames = tagNamesUpdate; + this.tagList = new ArrayList(GuiNpcMobSpawner.tagNames.keySet()); + filterScroll.setList(getTagList()); + } + } else { + List list = new ArrayList(); + if (GuiNpcMobSpawner.sortType == 1) { + NBTTagList nbtlist = compound.getTagList("ListDate", 8); + for (int i = 0; i < nbtlist.tagCount(); i++) { + list.add(nbtlist.getStringTagAt(i)); + } + } else { + NBTTagList nbtlist = compound.getTagList("List", 8); + for (int i = 0; i < nbtlist.tagCount(); i++) { + list.add(nbtlist.getStringTagAt(i)); + } + } + + this.list = list; + populateRawListWithTags(); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + } +} 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 ea9941b69..b8309b955 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiScript.java +++ b/src/main/java/noppes/npcs/client/gui/GuiScript.java @@ -4,25 +4,21 @@ 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.client.gui.GuiYesNoCallback; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import net.minecraft.util.StatCollector; import noppes.npcs.NoppesStringUtils; import noppes.npcs.client.NoppesUtil; -import noppes.npcs.client.gui.script.GuiNPCEventScripts; +import noppes.npcs.client.gui.script.GuiScriptInterface; 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.IGuiData; -import noppes.npcs.client.gui.util.IJTextAreaListener; -import noppes.npcs.client.gui.util.ITextChangeListener; +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; import noppes.npcs.controllers.data.DataScript; @@ -30,83 +26,185 @@ import noppes.npcs.entity.EntityNPCInterface; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; -public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCallback, ICustomScrollListener, IJTextAreaListener, ITextChangeListener { +/** + * NPC Script GUI - extends GuiScriptInterface but with unique behavior: + * - Uses scroll-based tab selection instead of top buttons + * - Shows settings/script toggle + * - Uses DataScript with getNPCScript(index) access pattern + * - Has console filtering by hook type + */ +public class GuiScript extends GuiScriptInterface { public boolean showScript = false; - private int activeTab = 0; public DataScript script; - public Map> languages = new HashMap>(); private static int activeConsole = 0; - boolean loaded = false; public GuiScript(EntityNPCInterface npc) { - super(npc); - script = npc.script; - drawDefaultBackground = true; - closeOnEsc = true; - xSize = 420; + super(); + this.npc = npc; + this.script = npc.script; + this.handler = script; + this.useScrollTabs = true; + this.useSettingsToggle = true; + + // Initialize hook list for NPC scripts + hookList.add("script.init"); + hookList.add("script.update"); + hookList.add("script.interact"); + hookList.add("dialog.dialog"); + hookList.add("script.damaged"); + hookList.add("script.killed"); + hookList.add("script.attack"); + hookList.add("script.target"); + hookList.add("script.collide"); + hookList.add("script.kills"); + hookList.add("script.dialog_closed"); + hookList.add("script.timer"); + hookList.add("script.targetLost"); + hookList.add("script.projectileTick"); + hookList.add("script.projectileImpact"); - setBackground("menubg.png"); NPCScriptPacket.Get(); } + @Override + protected ScriptContext getScriptContext() { + return ScriptContext.NPC; + } + + @Override + protected int getActiveScriptIndex() { + return this.activeTab; + } + + @Override + protected ScriptContainer getCurrentContainer() { + return script.getNPCScript(activeTab); + } + + @Override public void initGui() { super.initGui(); - guiTop += 10; + this.guiTop += 10; + + 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, 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")); + 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.website")); - List list = new ArrayList(); - list.add("script.init"); - list.add("script.update"); - list.add("script.interact"); - list.add("dialog.dialog"); - list.add("script.damaged"); - list.add("script.killed"); - list.add("script.attack"); - list.add("script.target"); - list.add("script.collide"); - list.add("script.kills"); - list.add("script.dialog_closed"); - list.add("script.timer"); - list.add("script.targetLost"); - list.add("script.projectileTick"); - list.add("script.projectileImpact"); - if (showScript) { + initScriptView(); + } else { + initSettingsView(); + } + } + + private void initScriptView() { + ScriptContainer container = getCurrentContainer(); + + // ==================== CALCULATE VIEWPORT BOUNDS ==================== + int editorX, editorY, editorWidth, editorHeight; + + if (isFullscreen) { + // Fullscreen: viewport fills screen with configured padding + FullscreenConfig.paddingTop = 30; + FullscreenConfig.paddingBottom = 20; + FullscreenConfig.paddingLeft = 20; + FullscreenConfig.paddingRight = 20; + editorX = FullscreenConfig.paddingLeft; + editorY = FullscreenConfig.paddingTop; + editorWidth = this.width - FullscreenConfig.paddingLeft - FullscreenConfig.paddingRight; + editorHeight = this.height - FullscreenConfig.paddingTop - FullscreenConfig.paddingBottom; + } else { + // Normal: fixed layout with hooks on left + editorX = guiLeft + 74; + editorY = guiTop + 4; + editorWidth = 239; + editorHeight = 208; + } + + // ==================== HOOKS SCROLL (hidden in fullscreen) ==================== + if (!isFullscreen) { addLabel(new GuiNpcLabel(0, "script.hooks", guiLeft + 4, guiTop + 5)); + GuiCustomScroll hooks = new GuiCustomScroll(this, 1); hooks.setSize(68, 198); hooks.guiLeft = guiLeft + 4; hooks.guiTop = guiTop + 14; - hooks.setUnsortedList(list); + hooks.setUnsortedList(hookList); hooks.selected = activeTab; addScroll(hooks); + } - ScriptContainer container = script.getNPCScript(activeTab); + // ==================== SCRIPT TEXT AREA ==================== + int idx = getActiveScriptIndex(); + GuiScriptTextArea activeArea = getActiveScriptArea(); + if (activeArea == null) { + activeArea = new GuiScriptTextArea(this, 2, editorX, editorY, editorWidth, editorHeight, + container == null ? "" : container.script); + activeArea.setListener(this); + this.closeOnEsc(activeArea::closeOnEsc); + textAreas.put(idx, activeArea); + } else { + activeArea.init(editorX, editorY, editorWidth, editorHeight, + container == null ? "" : container.script); + } - GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, guiLeft + 74, guiTop + 4, 239, 208, container == null ? "" : container.script); - ta.enableCodeHighlighting(); - ta.setListener(this); - this.addTextField(ta); + // 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 -> { + if (e.isPress()) { + toggleFullscreen(); + } + }); + + activeArea.enableCodeHighlighting(); + addTextField(activeArea); + + // Initialize fullscreen button + int scrollbarOffset = activeArea.hasVerticalScrollbar() ? -8 : -2; + fullscreenButton.initGui(editorX + editorWidth, editorY, scrollbarOffset); + + // ==================== RIGHT PANEL (hidden in fullscreen) ==================== + if (!isFullscreen) { addButton(new GuiNpcButton(102, guiLeft + 315, guiTop + 4, 50, 20, "gui.clear")); addButton(new GuiNpcButton(101, guiLeft + 366, guiTop + 4, 50, 20, "gui.paste")); 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; @@ -114,55 +212,74 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall if (container != null) scroll.setList(container.scripts); addScroll(scroll); - } else { - addLabel(new GuiNpcLabel(0, "script.console", guiLeft + 4, guiTop + 16)); + } + } + + + private void initSettingsView() { + addLabel(new GuiNpcLabel(0, "script.console", guiLeft + 4, guiTop + 16)); + if (getTopButton(14) != null) getTopButton(14).active = true; - addTextField(new GuiNpcTextArea(2, this, guiLeft + 4, guiTop + 26, 226, 186, getConsoleText())); - getTextField(2).canEdit = false; - addButton(new GuiNpcButton(100, guiLeft + 232, guiTop + 170, 56, 20, "gui.copy")); - addButton(new GuiNpcButton(102, guiLeft + 232, guiTop + 192, 56, 20, "gui.clear")); - List l = new ArrayList(); - l.add("All"); - l.addAll(list); - addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20, l.toArray(new String[l.size()]), activeConsole)); + GuiNpcTextArea consoleArea = new GuiNpcTextArea(2, this, guiLeft + 4, guiTop + 26, 226, 186, getConsoleText()); + consoleArea.canEdit = false; + addTextField(consoleArea); - addLabel(new GuiNpcLabel(1, "script.language", guiLeft + 232, guiTop + 30)); - addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20, languages.keySet().toArray(new String[languages.keySet().size()]), getScriptIndex())); - getButton(103).enabled = languages.size() > 0; + addButton(new GuiNpcButton(100, guiLeft + 232, guiTop + 170, 56, 20, "gui.copy")); + addButton(new GuiNpcButton(102, guiLeft + 232, guiTop + 192, 56, 20, "gui.clear")); - addLabel(new GuiNpcLabel(2, "gui.enabled", guiLeft + 232, guiTop + 53)); - addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20, new String[]{"gui.no", "gui.yes"}, script.enabled ? 1 : 0)); + List consoleOptions = new ArrayList<>(); + consoleOptions.add("All"); + consoleOptions.addAll(hookList); + addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20, + consoleOptions.toArray(new String[0]), activeConsole)); - if (MinecraftServer.getServer() != null) - addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder")); + 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))); + + addLabel(new GuiNpcLabel(2, "gui.enabled", guiLeft + 232, guiTop + 53)); + addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20, + new String[]{"gui.no", "gui.yes"}, script.enabled ? 1 : 0)); + + 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; } } - private int getScriptIndex() { - int i = 0; - for (String language : languages.keySet()) { - if (language.equalsIgnoreCase(script.scriptLanguage)) - return i; - i++; - } - return 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)); } - private String getConsoleText() { + @Override + protected String getConsoleText() { Map map = this.script.getOldConsoleText(); StringBuilder builder = new StringBuilder(); - Iterator var3 = map.entrySet().iterator(); - - while (var3.hasNext()) { - Map.Entry entry = (Map.Entry) var3.next(); - builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n"); + for (Map.Entry entry : map.entrySet()) { + builder.insert(0, new Date(entry.getKey()) + entry.getValue() + "\n"); } - return builder.toString(); } - @Override public void confirmClicked(boolean result, int id) { NoppesUtil.openGUI(player, this); @@ -187,8 +304,6 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall } } } - - displayGuiScreen(this); } @@ -204,12 +319,11 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall initGui(); } if (guibutton.id == 15) { - GuiConfirmOpenLink guiyesno = new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true); - mc.displayGuiScreen(guiyesno); + displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true)); } if (guibutton.id == 16) { close(); - mc.displayGuiScreen(new GuiNPCEventScripts(npc)); + GuiScriptInterface.open(this, this.script); } if (guibutton.id == 17) { close(); @@ -218,12 +332,12 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall NoppesStringUtils.setClipboardContents(getTextField(2).getText()); } if (guibutton.id == 101) { - GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101); - displayGuiScreen(guiyesno); + displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), + StatCollector.translateToLocal("gui.sure"), 101)); } if (guibutton.id == 102) { - GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102); - displayGuiScreen(guiyesno); + displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), + StatCollector.translateToLocal("gui.sure"), 102)); } if (guibutton.id == 103) { script.scriptLanguage = ((GuiNpcButton) guibutton).displayString; @@ -236,23 +350,29 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall initGui(); } if (guibutton.id == 106) { - // TODO: Uses ScriptController.Instance.dir (shared script repository); this GUI is gated behind the scripter tool - // and CustomNpcsPermissions.TOOL_SCRIPTER so only authorized editors touch the controller-backed scripts. NoppesUtil.openFolder(ScriptController.Instance.dir); } if (guibutton.id == 107) { - ScriptContainer container = script.getNPCScript(activeTab); - if (container == null) - script.setNPCScript(activeTab, container = new ScriptContainer(this.script)); - setSubGui(new GuiScriptList(languages.get(script.scriptLanguage), container)); + ScriptContainer container = getCurrentContainer(); + 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)); } } - private void setScript() { + @Override + protected void setScript() { if (showScript) { - ScriptContainer container = script.getNPCScript(activeTab); - if (container == null) - script.setNPCScript(activeTab, container = new ScriptContainer(this.script)); + ScriptContainer container = getCurrentContainer(); + 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"); @@ -262,26 +382,19 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall @Override public void setGuiData(NBTTagCompound compound) { - script.readFromNBT(compound); - NBTTagList data = compound.getTagList("Languages", 10); - Map> languages = new HashMap>(); - for (int i = 0; i < data.tagCount(); i++) { - NBTTagCompound comp = data.getCompoundTagAt(i); - List scripts = new ArrayList(); - NBTTagList list = comp.getTagList("Scripts", 8); - for (int j = 0; j < list.tagCount(); j++) { - scripts.add(list.getStringTagAt(j)); - } - languages.put(comp.getString("Language"), scripts); + // 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; } - this.languages = languages; - initGui(); + script.readFromNBT(compound); + loadLanguagesData(compound); loaded = true; } @Override public void save() { - if (loaded) { + if (loaded && serverDataReceived) { setScript(); NPCScriptPacket.Save(script.writeToNBT(new NBTTagCompound())); } @@ -295,20 +408,4 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall initGui(); } } - - public void textUpdate(String text) { - ScriptContainer container = script.getNPCScript(activeTab); - if (container != null) - container.script = text; - } - - @Override - public void saveText(String text) { - ScriptContainer container = script.getNPCScript(activeTab); - if (container != null) - container.script = text; - initGui(); - } - } - diff --git a/src/main/java/noppes/npcs/client/gui/GuiScriptList.java b/src/main/java/noppes/npcs/client/gui/GuiScriptList.java index 0d03d13cd..a13f2a056 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiScriptList.java +++ b/src/main/java/noppes/npcs/client/gui/GuiScriptList.java @@ -6,6 +6,7 @@ import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.controllers.data.IScriptUnit; import java.util.ArrayList; import java.util.List; @@ -13,16 +14,20 @@ import java.util.List; public class GuiScriptList extends SubGuiInterface { private GuiCustomScroll scroll1; private GuiCustomScroll scroll2; - private ScriptContainer container; + private IScriptUnit scriptUnit; private List scripts; public GuiScriptList(List scripts, ScriptContainer container) { - this.container = container; + this(scripts, (IScriptUnit) container); + } + + public GuiScriptList(List scripts, IScriptUnit scriptUnit) { + this.scriptUnit = scriptUnit; setBackground("menubg.png"); xSize = 346; ySize = 216; if (scripts == null) - scripts = new ArrayList(); + scripts = new ArrayList<>(); this.scripts = scripts; } @@ -46,10 +51,10 @@ public class GuiScriptList extends SubGuiInterface { scroll2.guiTop = guiTop + 14; this.addScroll(scroll2); addLabel(new GuiNpcLabel(2, "script.loadedScripts", guiLeft + 200, guiTop + 4)); - List temp = new ArrayList(scripts); - temp.removeAll(container.scripts); + List temp = new ArrayList<>(scripts); + temp.removeAll(scriptUnit.getExternalScripts()); scroll1.setList(temp); - scroll2.setList(container.scripts); + scroll2.setList(scriptUnit.getExternalScripts()); addButton(new GuiNpcButton(1, guiLeft + 145, guiTop + 40, 55, 20, ">")); addButton(new GuiNpcButton(2, guiLeft + 145, guiTop + 62, 55, 20, "<")); @@ -64,7 +69,7 @@ public class GuiScriptList extends SubGuiInterface { GuiNpcButton button = (GuiNpcButton) guibutton; if (button.id == 1) { if (scroll1.hasSelected()) { - container.scripts.add(scroll1.getSelected()); + scriptUnit.getExternalScripts().add(scroll1.getSelected()); scroll1.selected = -1; scroll2.selected = -1; initGui(); @@ -72,22 +77,22 @@ public class GuiScriptList extends SubGuiInterface { } if (button.id == 2) { if (scroll2.hasSelected()) { - container.scripts.remove(scroll2.getSelected()); + scriptUnit.getExternalScripts().remove(scroll2.getSelected()); scroll2.selected = -1; initGui(); } } if (button.id == 3) { - container.scripts.clear(); + scriptUnit.getExternalScripts().clear(); for (String script : scripts) { - container.scripts.add(script); + scriptUnit.getExternalScripts().add(script); } scroll1.selected = -1; scroll2.selected = -1; initGui(); } if (button.id == 4) { - container.scripts.clear(); + scriptUnit.getExternalScripts().clear(); scroll1.selected = -1; scroll2.selected = -1; initGui(); 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/SubGuiCloneFolderName.java b/src/main/java/noppes/npcs/client/gui/SubGuiCloneFolderName.java new file mode 100644 index 000000000..508b00518 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiCloneFolderName.java @@ -0,0 +1,67 @@ +package noppes.npcs.client.gui; + +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.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; + +public class SubGuiCloneFolderName extends SubGuiInterface { + private String originalName; + public boolean cancelled = true; + private String folderName = ""; + + public SubGuiCloneFolderName(String existingName) { + this.originalName = existingName; + this.folderName = existingName; + xSize = 200; + ySize = 80; + this.closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + String title = isRename() ? "Rename Folder" : "New Folder"; + addLabel(new GuiNpcLabel(0, title, guiLeft + 5, guiTop + 5)); + addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 5, guiTop + 20, 190, 20, folderName)); + + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 50, 90, 20, "gui.done")); + addButton(new GuiNpcButton(1, guiLeft + 100, guiTop + 50, 90, 20, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + // Done + folderName = getTextField(0).getText().trim(); + if (CloneFolder.isValidName(folderName)) { + cancelled = false; + close(); + } + } + if (guibutton.id == 1) { + // Cancel + cancelled = true; + close(); + } + } + + public boolean isRename() { + return originalName != null && !originalName.isEmpty(); + } + + public String getFolderName() { + return folderName; + } + + public String getOriginalName() { + return originalName; + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiColorSelector.java b/src/main/java/noppes/npcs/client/gui/SubGuiColorSelector.java index 947825f5a..be8c07f8a 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiColorSelector.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiColorSelector.java @@ -25,10 +25,10 @@ public class SubGuiColorSelector extends SubGuiInterface implements ITextfieldLi public int color; public SubGuiColorSelector(int color) { - xSize = 176; + xSize = 182; ySize = 222; this.color = color; - setBackground("smallbg.png"); + setBackground("menubg.png"); } @Override @@ -40,7 +40,7 @@ public class SubGuiColorSelector extends SubGuiInterface implements ITextfieldLi this.addTextField(textfield = new GuiNpcTextField(0, this, guiLeft + 53, guiTop + 20, 70, 20, getColor())); textfield.setTextColor(color); - addButton(new GuiNpcButton(66, guiLeft + 112, guiTop + 198, 60, 20, "gui.done")); + addButton(new GuiNpcButton(66, guiLeft + 112, guiTop + 175, 60, 20, "gui.done")); } public String getColor() { 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 19903229b..77d72442c 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java @@ -6,17 +6,21 @@ 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 noppes.npcs.client.gui.script.GuiScriptEffect; +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; +import noppes.npcs.controllers.data.EffectScript; import org.lwjgl.opengl.GL11; import java.util.ArrayList; @@ -25,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; @@ -61,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; @@ -107,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); @@ -126,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); @@ -182,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); } @@ -202,15 +245,21 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi } if (id == -2) { PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), originalName)); - GuiScriptEffect scriptGUI = new GuiScriptEffect(parent, effect); - scriptGUI.setWorldAndResolution(mc, width, height); - scriptGUI.initGui(); - mc.currentScreen = scriptGUI; + 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 @@ -250,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/SubGuiFolderSelect.java b/src/main/java/noppes/npcs/client/gui/SubGuiFolderSelect.java new file mode 100644 index 000000000..3ec727543 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiFolderSelect.java @@ -0,0 +1,74 @@ +package noppes.npcs.client.gui; + +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.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +public class SubGuiFolderSelect extends SubGuiInterface implements ICustomScrollListener { + + public String selectedFolder; + private final List folderList; + private GuiCustomScroll folderScroll; + + public SubGuiFolderSelect(List folders, String currentSelection) { + this.folderList = new ArrayList<>(folders); + this.selectedFolder = currentSelection; + setBackground("menubg.png"); + xSize = 200; + ySize = 220; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + folderScroll = new GuiCustomScroll(this, 0); + folderScroll.setSize(xSize - 8, ySize - 50); + folderScroll.guiLeft = guiLeft + 4; + folderScroll.guiTop = guiTop + 4; + folderScroll.setList(new ArrayList<>(folderList)); + if (selectedFolder != null) { + folderScroll.setSelected(selectedFolder); + } + addScroll(folderScroll); + + int btnW = (xSize - 12) / 2; + addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + ySize - 44, btnW, 20, "gui.done")); + addButton(new GuiNpcButton(1, guiLeft + 4 + btnW + 4, guiTop + ySize - 44, btnW, 20, "gui.cancel")); + + getButton(0).enabled = folderScroll.hasSelected(); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + getButton(0).enabled = folderScroll.hasSelected(); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + selectedFolder = selection; + close(); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + selectedFolder = folderScroll.getSelected(); + close(); + } + if (guibutton.id == 1) { + selectedFolder = null; + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiMoveConfirm.java b/src/main/java/noppes/npcs/client/gui/SubGuiMoveConfirm.java new file mode 100644 index 000000000..ee70367f7 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiMoveConfirm.java @@ -0,0 +1,57 @@ +package noppes.npcs.client.gui; + +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; + +public class SubGuiMoveConfirm extends SubGuiInterface { + public boolean confirmed = false; + + private final int count; + public final int destTab; + public final String destFolder; + + public SubGuiMoveConfirm(int count, int destTab, String destFolder) { + this.count = count; + this.destTab = destTab; + this.destFolder = destFolder; + xSize = 220; + ySize = 90; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + String line1 = "Move " + count + " clone" + (count != 1 ? "s" : "") + " to:"; + addLabel(new GuiNpcLabel(0, line1, guiLeft + 10, guiTop + 10, 0xFFFFFF)); + + String dest; + if (destFolder != null) { + dest = "Folder: \"" + destFolder + "\""; + } else { + dest = "Tab: " + destTab; + } + 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/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 72481f133..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; @@ -98,7 +95,7 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis getTextField(18).setVisible(dialog.renderGradual); getLabel(18).enabled = dialog.renderGradual; - addTextField(new GuiNpcTextField(19, this, guiLeft + 125, y += 22, 40, 20, String.valueOf(dialog.textPitch))); + addTextField(new GuiNpcTextField(19, this, guiLeft + 125, y += 22, 40, 20, "" + dialog.textPitch)); addLabel(new GuiNpcLabel(19, "dialog.textPitch", guiLeft + 4, y + 5)); getTextField(19).floatsOnly = true; getTextField(19).setVisible(dialog.renderGradual); @@ -110,48 +107,48 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis addButton(new GuiNpcButton(24, guiLeft + 192, y, 50, 20, new String[]{"display.bottom", "display.top"}, dialog.alignment)); addLabel(new GuiNpcLabel(27, "display.alignment", guiLeft + 126, y + 5)); - addTextField(new GuiNpcTextField(11, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.textWidth))); - addTextField(new GuiNpcTextField(12, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.textHeight))); + addTextField(new GuiNpcTextField(11, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.textWidth)); + addTextField(new GuiNpcTextField(12, this, guiLeft + 165, y, 40, 20, "" + dialog.textHeight)); addLabel(new GuiNpcLabel(12, "gui.widthHeight", guiLeft + 4, y + 5)); getTextField(11).integersOnly = true; getTextField(11).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); getTextField(12).integersOnly = true; getTextField(12).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - addTextField(new GuiNpcTextField(13, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.textOffsetX))); - addTextField(new GuiNpcTextField(14, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.textOffsetY))); + addTextField(new GuiNpcTextField(13, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.textOffsetX)); + addTextField(new GuiNpcTextField(14, this, guiLeft + 165, y, 40, 20, "" + dialog.textOffsetY)); addLabel(new GuiNpcLabel(15, "dialog.textOffset", guiLeft + 4, y + 5)); getTextField(13).integersOnly = true; getTextField(13).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); getTextField(14).integersOnly = true; getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.titleOffsetX))); - addTextField(new GuiNpcTextField(16, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.titleOffsetY))); + addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.titleOffsetX)); + addTextField(new GuiNpcTextField(16, this, guiLeft + 165, y, 40, 20, "" + dialog.titleOffsetY)); addLabel(new GuiNpcLabel(18, "dialog.titleOffset", guiLeft + 4, y + 5)); getTextField(15).integersOnly = true; getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); getTextField(16).integersOnly = true; getTextField(16).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - addTextField(new GuiNpcTextField(17, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.optionOffsetX))); - addTextField(new GuiNpcTextField(18, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.optionOffsetY))); + addTextField(new GuiNpcTextField(17, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.optionOffsetX)); + addTextField(new GuiNpcTextField(18, this, guiLeft + 165, y, 40, 20, "" + dialog.optionOffsetY)); addLabel(new GuiNpcLabel(21, "dialog.optionOffset", guiLeft + 4, y + 5)); getTextField(17).integersOnly = true; getTextField(17).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); getTextField(18).integersOnly = true; getTextField(18).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - addTextField(new GuiNpcTextField(19, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.optionSpaceX))); - addTextField(new GuiNpcTextField(20, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.optionSpaceY))); + addTextField(new GuiNpcTextField(19, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.optionSpaceX)); + addTextField(new GuiNpcTextField(20, this, guiLeft + 165, y, 40, 20, "" + dialog.optionSpaceY)); addLabel(new GuiNpcLabel(24, "dialog.optionSpacing", guiLeft + 4, y + 5)); getTextField(19).integersOnly = true; getTextField(19).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); getTextField(20).integersOnly = true; getTextField(20).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - addTextField(new GuiNpcTextField(21, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.npcOffsetX))); - addTextField(new GuiNpcTextField(22, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.npcOffsetY))); + addTextField(new GuiNpcTextField(21, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.npcOffsetX)); + addTextField(new GuiNpcTextField(22, this, guiLeft + 165, y, 40, 20, "" + dialog.npcOffsetY)); addLabel(new GuiNpcLabel(25, "dialog.npcOffset", guiLeft + 4, y + 5)); getTextField(21).integersOnly = true; getTextField(21).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); @@ -161,7 +158,7 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis getTextField(22).setVisible(!dialog.hideNPC); getLabel(25).enabled = !dialog.hideNPC; - addTextField(new GuiNpcTextField(23, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.npcScale))); + addTextField(new GuiNpcTextField(23, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.npcScale)); addLabel(new GuiNpcLabel(26, "dialog.npcScale", guiLeft + 4, y + 5)); getTextField(23).floatsOnly = true; getTextField(23).setMinMaxDefaultFloat(-Float.MAX_VALUE, Float.MAX_VALUE, 0); @@ -182,30 +179,30 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis DialogImage dialogImage = getSelectedImage(); addButton(new GuiNpcButton(2, guiLeft + xSize + 24, guiTop + 5, 20, 20, "-")); - addTextField(new GuiNpcTextField(10, this, guiLeft + 17, y += 25, 30, 20, String.valueOf(dialogImage.id))); + addTextField(new GuiNpcTextField(10, this, guiLeft + 17, y += 25, 30, 20, "" + dialogImage.id)); addTextField(new GuiNpcTextField(11, this, guiLeft + 92, y, 150, 20, dialogImage.texture)); addLabel(new GuiNpcLabel(10, "gui.id", guiLeft + 4, y + 5)); addLabel(new GuiNpcLabel(11, "display.texture", guiLeft + 50, y + 5)); getTextField(10).integersOnly = true; - addTextField(new GuiNpcTextField(12, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialogImage.x))); - addTextField(new GuiNpcTextField(13, this, guiLeft + 165, y, 40, 20, String.valueOf(dialogImage.y))); + addTextField(new GuiNpcTextField(12, this, guiLeft + 120, y += 25, 40, 20, "" + dialogImage.x)); + addTextField(new GuiNpcTextField(13, this, guiLeft + 165, y, 40, 20, "" + dialogImage.y)); addLabel(new GuiNpcLabel(12, "gui.position", guiLeft + 4, y + 5)); getTextField(12).integersOnly = true; getTextField(12).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); getTextField(13).integersOnly = true; getTextField(13).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); - addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialogImage.width))); - addTextField(new GuiNpcTextField(15, this, guiLeft + 165, y, 40, 20, String.valueOf(dialogImage.height))); + addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 25, 40, 20, "" + dialogImage.width)); + addTextField(new GuiNpcTextField(15, this, guiLeft + 165, y, 40, 20, "" + dialogImage.height)); addLabel(new GuiNpcLabel(13, "gui.widthHeight", 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); - addTextField(new GuiNpcTextField(16, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialogImage.textureX))); - addTextField(new GuiNpcTextField(17, this, guiLeft + 165, y, 40, 20, String.valueOf(dialogImage.textureY))); + addTextField(new GuiNpcTextField(16, this, guiLeft + 120, y += 25, 40, 20, "" + dialogImage.textureX)); + addTextField(new GuiNpcTextField(17, this, guiLeft + 165, y, 40, 20, "" + dialogImage.textureY)); addLabel(new GuiNpcLabel(14, "dialog.textureOffset", guiLeft + 4, y + 5)); getTextField(16).integersOnly = true; getTextField(16).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0); @@ -229,9 +226,9 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis getButton(19).setVisible(dialogImage.imageType == 2); getLabel(16).enabled = dialogImage.imageType == 2; - addTextField(new GuiNpcTextField(20, this, guiLeft + 33, y += 25, 30, 20, String.valueOf(dialogImage.scale))); - addTextField(new GuiNpcTextField(21, this, guiLeft + 102, y, 30, 20, String.valueOf(dialogImage.alpha))); - addTextField(new GuiNpcTextField(22, this, guiLeft + 183, y, 45, 20, String.valueOf(dialogImage.rotation))); + addTextField(new GuiNpcTextField(20, this, guiLeft + 33, y += 25, 30, 20, "" + dialogImage.scale)); + addTextField(new GuiNpcTextField(21, this, guiLeft + 102, y, 30, 20, "" + dialogImage.alpha)); + addTextField(new GuiNpcTextField(22, this, guiLeft + 183, y, 45, 20, "" + dialogImage.rotation)); addLabel(new GuiNpcLabel(17, "model.scale", guiLeft + 4, y + 5)); addLabel(new GuiNpcLabel(18, "display.alpha", guiLeft + 72, y + 5)); addLabel(new GuiNpcLabel(19, "movement.rotation", guiLeft + 140, y + 5)); @@ -306,13 +303,13 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis Collections.sort(ids); ArrayList strings = new ArrayList<>(); for (int i : ids) { - strings.add(String.valueOf(i)); + strings.add("" + i); } imageScroll.setUnsortedList(strings); if (changedId != -1) { - selected = imageScroll.getList().indexOf(String.valueOf(changedId)); - imageScroll.setSelected(String.valueOf(changedId)); + selected = imageScroll.getList().indexOf("" + changedId); + imageScroll.setSelected("" + changedId); changedId = -1; } @@ -402,7 +399,7 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis dialog.dialogImages.put(addId, new DialogImage(addId)); updateScrollData(); - selected = imageScroll.getList().indexOf(String.valueOf(addId)); + selected = imageScroll.getList().indexOf("" + addId); } if (button.id == 2) { if (imageScroll.getSelected() != null) { @@ -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() { @@ -598,8 +593,8 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis } if (textfield.id == 10) { - if (imageScroll.getList().contains(String.valueOf(textfield.getInteger()))) { - textfield.setText(String.valueOf(dialogImage.id)); + if (imageScroll.getList().contains("" + textfield.getInteger())) { + textfield.setText("" + dialogImage.id); return; } 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/SubGuiNpcPartyOptions.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcPartyOptions.java index 10420a65d..c5a0769a3 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcPartyOptions.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcPartyOptions.java @@ -71,7 +71,7 @@ public class SubGuiNpcPartyOptions extends SubGuiInterface implements ITextfield y += 23; //min party size - number field GuiNpcTextField minField = new GuiNpcTextField(21, this, guiLeft + 60, guiTop + 10 + y, - 30, 20, String.valueOf(options.minPartySize)); + 30, 20, "" + options.minPartySize); minField.integersOnly = true; minField.setMinMaxDefault(1, Integer.MAX_VALUE, 1); addTextField(minField); @@ -79,7 +79,7 @@ public class SubGuiNpcPartyOptions extends SubGuiInterface implements ITextfield //max party size - number field GuiNpcTextField maxField = new GuiNpcTextField(20, this, guiLeft + 160, guiTop + 10 + y, - 30, 20, String.valueOf(options.maxPartySize)); + 30, 20, "" + options.maxPartySize); maxField.integersOnly = true; maxField.setMinMaxDefault(1, Integer.MAX_VALUE, 4); addTextField(maxField); 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/SubGuiPlayerData.java b/src/main/java/noppes/npcs/client/gui/SubGuiPlayerData.java index 9025023b1..c3d85c8ad 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiPlayerData.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiPlayerData.java @@ -36,7 +36,7 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Fields - //////////////////////////////////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////////////////////////////// // Current tab (10=Quest, 11=Dialog, 12=Transport, 13=Bank, 14=Faction, 15=Magic) private int currentTab = 10; @@ -99,7 +99,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Constructor - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// public SubGuiPlayerData(String playerName) { this.playerName = playerName; xSize = 420; @@ -112,7 +113,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Layout Helpers - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// private int getPaddedLeft() { return guiLeft + leftPadding; } @@ -135,7 +137,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Component Setup Helpers - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// private void setupTopButtons() { // Show General Display Information GuiMenuTopButton playerTab = new GuiMenuTopButton(-10, guiLeft + 4, guiTop - 10, playerName); @@ -192,7 +195,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // initGui() & Tab Initialization - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// @Override public void initGui() { super.initGui(); @@ -489,7 +493,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Drawing Helpers - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { super.drawScreen(mouseX, mouseY, partialTicks); @@ -525,7 +530,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Mouse & Resizing Handlers - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// @Override public void mouseClicked(int mouseX, int mouseY, int mouseButton) { int hitMargin = 3; @@ -672,7 +678,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Key & Search Field Handling - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// @Override public void keyTyped(char c, int i) { super.keyTyped(c, i); @@ -894,7 +901,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Action Handling - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// @Override public void actionPerformed(GuiButton button) { if (button.id == -5) { @@ -1043,7 +1051,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo //////////////////////////////////////////////////////////////////////////////// // Data Setting Methods (IPlayerDataInfo) - //////////////////////////////////////////////////////////////////////////////// + + /// ///////////////////////////////////////////////////////////////////////////// @Override public void setQuestData(Map questCategories, Map questActive, Map questFinished) { this.questCatData = new HashMap<>(questCategories); diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiSpawningOptions.java b/src/main/java/noppes/npcs/client/gui/SubGuiSpawningOptions.java index c15f9162f..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, String.valueOf(data.spawnHeightMin))); - addLabel(new GuiNpcLabel(14, "spawning.minHeight", guiLeft + 4, y + 5)); - addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 22, 40, 20, String.valueOf(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..b8fb9e376 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; + +@SideOnly(Side.CLIENT) +public class SubGuiTrapPresetSelector extends SubGuiInterface { + + public String selectedPreset = null; + + private static final String[] PRESET_NAMES = {"HIDDEN", "VENOM", "EXPLOSIVE", "CURSED", "SHOCK", "SNARE"}; + private static final String[] PRESET_LABELS = { + "ability.preset.hidden", "ability.preset.venom", "ability.preset.explosive", + "ability.preset.cursed", "ability.preset.shock", "ability.preset.snare" + }; + private static final int[] PRESET_COLORS = {0x888888, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF}; + + public SubGuiTrapPresetSelector() { + xSize = 170; + ySize = 135; + setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + int btnW = 72; + int btnH = 20; + int gapY = 4; + int col1 = guiLeft + 7; + int col2 = col1 + btnW + 6; + int startY = guiTop + 22; + + for (int i = 0; i < 6; i++) { + int x = (i % 2 == 0) ? col1 : col2; + int y = startY + (i / 2) * (btnH + gapY); + addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i])); + } + + int cancelY = startY + 3 * (btnH + gapY) + 4; + addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton btn) { + super.actionPerformed(btn); + if (btn.id >= 0 && btn.id < 6) { + selectedPreset = PRESET_NAMES[btn.id]; + close(); + } else if (btn.id == 10) { + close(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + super.drawScreen(mouseX, mouseY, f); + drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF); + for (int i = 0; i < 6; i++) { + GuiNpcButton btn = getButton(i); + if (btn != null && btn.visible) { + int x = btn.xPosition + 4; + int y = btn.yPosition + 5; + drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]); + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java new file mode 100644 index 000000000..f67ef3db1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; + +@SideOnly(Side.CLIENT) +public class SubGuiZonePresetSelector extends SubGuiInterface { + + public String selectedPreset = null; + + private static final String[] PRESET_NAMES = {"DEFAULT", "TOXIC", "INFERNO", "ARCANE", "ELECTRIC", "FROST"}; + private static final String[] PRESET_LABELS = { + "ability.preset.default", "ability.preset.toxic", "ability.preset.inferno", + "ability.preset.arcane", "ability.preset.electric", "ability.preset.frost" + }; + private static final int[] PRESET_COLORS = {0xCCCCCC, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF}; + + public SubGuiZonePresetSelector() { + xSize = 170; + ySize = 135; + setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + int btnW = 72; + int btnH = 20; + int gapY = 4; + int col1 = guiLeft + 7; + int col2 = col1 + btnW + 6; + int startY = guiTop + 22; + + for (int i = 0; i < 6; i++) { + int x = (i % 2 == 0) ? col1 : col2; + int y = startY + (i / 2) * (btnH + gapY); + addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i])); + } + + int cancelY = startY + 3 * (btnH + gapY) + 4; + addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton btn) { + super.actionPerformed(btn); + if (btn.id >= 0 && btn.id < 6) { + selectedPreset = PRESET_NAMES[btn.id]; + close(); + } else if (btn.id == 10) { + close(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + super.drawScreen(mouseX, mouseY, f); + drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF); + for (int i = 0; i < 6; i++) { + GuiNpcButton btn = getButton(i); + if (btn != null && btn.visible) { + int x = btn.xPosition + 4; + int y = btn.yPosition + 5; + drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]); + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java new file mode 100644 index 000000000..295716a92 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -0,0 +1,1184 @@ +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 kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket; +import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket; +import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; +import kamkeel.npcs.util.Register; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.resources.I18n; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNPCInterface2; +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; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.entity.EntityNPCInterface; + +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, 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; + + // ── Available type data ─────────────────────────────────────────────────── + private final HashMap allAbilityTypes = new HashMap<>(); + private final HashMap filteredAbilityTypes = new HashMap<>(); + private final HashMap displayNameToTypeId = new HashMap<>(); + + // ── NPC slot data ───────────────────────────────────────────────────────── + private final List npcSlots = new ArrayList<>(); + private final List rowMapping = new ArrayList<>(); // [slotIdx, entryIdx], entryIdx=-1 = header/standalone + + // ── 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; + + // ── 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 ──────────────────────────────────────────── + private String pendingTypeId = null; + + // ── Static view state (persists across GUI opens) ───────────────────────── + public static int modIndex = 0; + public static ScrollType scrollType = ScrollType.CNPC; + + public GuiNPCAbilities(EntityNPCInterface npc) { + super(npc); + PacketClient.sendClient(new AbilitiesGetAllPacket()); + PacketClient.sendClient(new AbilitiesNpcGetPacket()); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } + + public enum ScrollType { + CNPC, + MODDED, + ALL; + + @Override + public String toString() { + switch (this) { + case CNPC: + return "CustomNPCs"; + case MODDED: + if (Register.isEmpty("ability")) + return "modded"; + + 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(); + } + } + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + + 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(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(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); + + y += 28; + + // Enabled checkbox + 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(LBL_TYPES, "ability.availableTypes", guiLeft + 5, y)); + if (availableTypesScroll == null) { + availableTypesScroll = new GuiCustomScroll(this, SCROLL_TYPES); + availableTypesScroll.setSize(140, 130); + } + availableTypesScroll.guiLeft = guiLeft + 5; + availableTypesScroll.guiTop = y + 12; + availableTypesScroll.setUnsortedList(getFilteredTypeList()); + addScroll(availableTypesScroll); + + // Search bar for types + 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(LBL_NPC, "ability.npcAbilities", guiLeft + 210, y)); + if (npcAbilitiesScroll == null) { + npcAbilitiesScroll = new GuiCustomScroll(this, SCROLL_NPC); + npcAbilitiesScroll.setSize(200, 130); + } else { + npcAbilitiesScroll.setSize(200, 130); + } + npcAbilitiesScroll.guiLeft = guiLeft + 210; + npcAbilitiesScroll.guiTop = y + 12; + updateNpcAbilitiesList(); + addScroll(npcAbilitiesScroll); + + // Center buttons: Add/Remove + int centerX = guiLeft + 158; + 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(BTN_LOAD, centerX, y + 60, 40, 20, "gui.load")); + + // 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(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(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 — 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 + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + + // Enabled toggle + if (id == BTN_ENABLED) { + abilitiesEnabled = ((GuiNpcButton) guibutton).getValue() == 1; + initGui(); + save(); + return; + } + + // Add ability + if (id == BTN_ADD_ABILITY) { + if (availableTypesScroll.hasSelected()) { + String displayName = availableTypesScroll.getSelected(); + String typeId = displayNameToTypeId.get(displayName); + if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } + Ability newAbility = AbilityController.Instance.create(typeId); + if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } + newAbility.setId(UUID.randomUUID().toString()); + npcSlots.add(AbilityAction.inline(newAbility)); + selectedAbilityIndex = npcSlots.size() - 1; + updateNpcAbilitiesList(); + selectAbilityByIndex(selectedAbilityIndex); + initGui(); + save(); + } + } + } + return; + } + + // 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(); + } + return; + } + + // 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)); + } + } + } + return; + } + + // Move up (carrot left = earlier in list) + 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(); + initGui(); + save(); + } + return; + } + + // Move down (carrot right = later in list) + 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(); + initGui(); + save(); + } + return; + } + + // Load ability or chain (opens type choice first) + if (id == BTN_LOAD) { + setSubGui(new SubGuiLoadTypeChoice()); + return; + } + + // 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)); + } + } + } + return; + } + + // 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; + } + + // 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]; + // Skip MODDED if no namespaces are registered + if (next == ScrollType.MODDED && Register.isEmpty("ability")) { + next = ScrollType.ALL; + } + scrollType = next; + } else { + List list = Register.REGISTERED_NAMESPACES.get("ability"); + + if (list != null && !list.isEmpty()) { + if (modIndex == list.size() - 1) { + scrollType = ScrollType.ALL; + } else { + modIndex = (modIndex + 1) % list.size(); + } + } else { + modIndex = 0; + scrollType = ScrollType.ALL; + } + } + + Map dummyMap = new HashMap<>(allAbilityTypes); + filteredAbilityTypes.clear(); + filteredAbilityTypes.putAll(getFilteredData(dummyMap)); + + // Reset scroll position when changing category + if (availableTypesScroll != null) { + availableTypesScroll.resetScroll(); + } + } + + initGui(); + } + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.ABILITY_TYPES) { + allAbilityTypes.clear(); + allAbilityTypes.putAll(data); + + filteredAbilityTypes.putAll(getFilteredData(allAbilityTypes)); + if (availableTypesScroll != null) { + availableTypesScroll.setUnsortedList(getFilteredTypeList()); + } + } else if (type == EnumScrollData.CUSTOM_ABILITIES) { + existingPresetNames.clear(); + for (String key : data.keySet()) { + int tabIndex = key.indexOf('\t'); + if (tabIndex > 0) { + existingPresetNames.add(key.substring(0, tabIndex)); + } else { + existingPresetNames.add(key); + } + } + } + initGui(); + } + + @Override + public void setGuiData(NBTTagCompound compound) { + // 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("AbilityActions") && !compound.hasKey("Abilities")) { + return; + } + + abilitiesEnabled = compound.getBoolean("AbilitiesEnabled"); + + minCooldown = compound.getInteger("AbilityMinCooldown"); + maxCooldown = compound.getInteger("AbilityMaxCooldown"); + if (minCooldown == 0 && maxCooldown == 0) { + minCooldown = 20; + maxCooldown = 60; + } + + npcSlots.clear(); + // 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); + } + } + + initGui(); + } + + @Override + public void mouseClicked(int i, int j, int k) { + super.mouseClicked(i, j, k); + if (k == 0 && availableTypesScroll != null) { + availableTypesScroll.mouseClicked(i, j, k); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) { + if (search.equals(getTextField(TF_SEARCH).getText())) + return; + search = getTextField(TF_SEARCH).getText().toLowerCase(); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); + availableTypesScroll.resetScroll(); + } + } + + private HashMap getFilteredData(Map data) { + HashMap filteredData = new HashMap<>(); + if (scrollType == ScrollType.CNPC) { + data.entrySet().stream() + .filter(e -> e.getKey().startsWith("ability.cnpc.")) + .forEach(e -> filteredData.put(e.getKey(), e.getValue())); + } else if (scrollType == ScrollType.MODDED) { + if (!Register.isEmpty("ability")) { + List registerList = Register.REGISTERED_NAMESPACES.get("ability"); + + if (!registerList.isEmpty()) { + String namespace = registerList.get(modIndex); + + data.entrySet().stream() + .filter(e -> e.getKey().startsWith("ability." + namespace + ".")) + .forEach(e -> filteredData.put(e.getKey(), e.getValue())); + } + } + } else { + filteredData.putAll(data); + } + + return filteredData; + } + + private List getFilteredTypeList() { + List list = new ArrayList<>(); + displayNameToTypeId.clear(); + for (String typeId : filteredAbilityTypes.keySet()) { + String displayName = I18n.format(typeId); + // 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++) { + 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.setUnsortedList(list); + } + } + + /** + * Creates the display entry for an ability slot in the list. + * Inline: "[●] 1. Custom Name (Type)" or "[●] 1. Type" + * Reference: "[●] 1. > Name (Type)" in yellow + * Broken: "[●] 1. > [Missing: id...]" in red + */ + private String getAbilityListEntry(int index) { + AbilityAction slot = npcSlots.get(index); + Ability ability = slot.getAbility(); + + if (ability == null) { + 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"; + } + + String typeName = getDisplayName(ability.getTypeId()); + String customName = ability.getName(); + String colorPrefix = slot.isSlotEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; + + String nameDisplay; + if (customName != null && !customName.isEmpty() && !customName.equals(typeName)) { + nameDisplay = customName + " (" + typeName + ")"; + } else { + nameDisplay = typeName; + } + + 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); + if (npcAbilitiesScroll != null) { + npcAbilitiesScroll.setSelected(entry); + } + } + } + + /** + * Gets the localized display name for an ability type. + * The typeId IS the lang key (e.g., "ability.cnpc.slam"). + */ + private String getDisplayName(String typeId) { + return I18n.format(typeId); + } + + public void save() { + NBTTagCompound compound = new NBTTagCompound(); + compound.setBoolean("AbilitiesEnabled", abilitiesEnabled); + compound.setInteger("AbilityMinCooldown", minCooldown); + compound.setInteger("AbilityMaxCooldown", maxCooldown); + + NBTTagList actionList = new NBTTagList(); + for (AbilityAction slot : npcSlots) { + actionList.appendTag(slot.writeNBT(false)); + } + compound.setTag("AbilityActions", actionList); + + PacketClient.sendClient(new AbilitiesNpcSavePacket(compound)); + } + + /** + * Called from SubGuiAbilityLoad when a cloned ability is loaded. + * Adds as an inline slot. + */ + public void loadAbility(Ability loadedAbility) { + if (loadedAbility != null) { + loadedAbility.setId(UUID.randomUUID().toString()); + npcSlots.add(AbilityAction.inline(loadedAbility)); + selectedAbilityIndex = npcSlots.size() - 1; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); + updateNpcAbilitiesList(); + selectAbilityByIndex(selectedAbilityIndex); + initGui(); + save(); + } + } + + /** + * Called from SubGuiAbilityLoad when a reference is loaded. + * Adds as a reference slot. + */ + public void loadAbilityReference(String referenceId) { + if (referenceId != null && !referenceId.isEmpty()) { + npcSlots.add(AbilityAction.abilityReference(referenceId)); + selectedAbilityIndex = npcSlots.size() - 1; + if (npcAbilitiesScroll != null) npcAbilitiesScroll.resetScroll(); + updateNpcAbilitiesList(); + selectAbilityByIndex(selectedAbilityIndex); + initGui(); + save(); + } + } + + @Override + public void setSelected(String selected) { + if (availableTypesScroll != null) { + availableTypesScroll.setSelected(selected); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll == npcAbilitiesScroll) { + 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(); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + 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 == TF_MIN_COOLDOWN) { + minCooldown = textField.getInteger(); + // Ensure min <= max + if (minCooldown > maxCooldown) { + maxCooldown = minCooldown; + initGui(); + } + save(); + } else if (textField.id == TF_MAX_COOLDOWN) { + maxCooldown = textField.getInteger(); + // Ensure min <= max + if (maxCooldown < minCooldown) { + minCooldown = maxCooldown; + initGui(); + } + save(); + } + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiAbilityVariantSelect) { + 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) { + if (slot.convertToInline()) { + ChainedAbility chain = slot.getInlineChain(); + if (chain != null) { + pendingChain = chain; + pendingChainSlotIdx = selectedSlotIndex; + setSubGui(new SubGuiChainedAbilityConfig(chain, this, true, npcSlots)); + } + updateNpcAbilitiesList(); + 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; + } + + 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); + 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)); + } + } + } + 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 (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { + // Standalone ability reference → convert to inline + Ability preCheck = slot.getAbility(); + if (preCheck != null && preCheck.isBuiltIn()) return; + if (slot.convertToInline()) { + Ability ability = slot.getAbility(); + if (ability != null && !ability.isBuiltIn()) { + ability.setId(UUID.randomUUID().toString()); + ability.setNpcInlineEdit(true); + setSubGui(ability.createConfigGui(this)); + } + 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()) { + AbilityAction slot = npcSlots.get(selectedAbilityIndex); + if (slot.isReference()) { + // Modify Parent on standalone reference — save to global preset + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); + } else { + // 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 new file mode 100644 index 000000000..6d101d3c4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -0,0 +1,452 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; +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; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.GuiScrollWindow; +import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +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; + private static final int CLEAR_ID_START = 2000; + private static final int LABEL_ID_START = 3000; + + // Fixed tab indices + private static final int TAB_GENERAL = 0; + private static final int TAB_TYPE = 1; + private static final int TAB_TARGET = 2; + private static final int TAB_EFFECTS = 3; + // Custom tabs start at index 4 + + // Tab name strings (matching FieldDef.tab() values) + private static final String TAB_NAME_GENERAL = "General"; + private static final String TAB_NAME_TYPE = "Type"; + private static final String TAB_NAME_TARGET = "Target"; + private static final String TAB_NAME_EFFECTS = "Effects"; + + 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; + + private List fieldDefs; + private List customTabNames; + + private List conditions; + private int editingConditionIndex = -1; + + private AbilityFieldBuilder builder; + + // Scroll position preservation per tab + private float[] tabScrollY; + + public SubGuiAbilityConfig(Ability ability, IAbilityConfigCallback callback) { + this.ability = ability; + this.callback = callback; + this.conditions = new ArrayList<>(ability.getConditions()); + + this.fieldDefs = ability.getAllDefinitions(); + discoverCustomTabs(); + + setBackground("menubg.png", 217); + xSize = 356; + ySize = 200; + } + + private void discoverCustomTabs() { + customTabNames = new ArrayList<>(); + 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)) { + customTabNames.add(tab); + } + } + tabScrollY = new float[4 + customTabNames.size()]; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // INIT GUI + // ═══════════════════════════════════════════════════════════════════════════ + + @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) { + tabScrollY[activeTab] = oldSw.nextScrollY; + } + + super.initGui(); + + // Tab buttons — always show General, Type, Target, Effects + GuiMenuTopButton generalTab = new GuiMenuTopButton(90, guiLeft + 4, guiTop - 17, "menu.general"); + generalTab.active = (activeTab == TAB_GENERAL); + addTopButton(generalTab); + GuiMenuTopButton lastTab = generalTab; + + GuiMenuTopButton typeTab = new GuiMenuTopButton(91, lastTab, "gui.type"); + typeTab.active = (activeTab == TAB_TYPE); + addTopButton(typeTab); + lastTab = typeTab; + + GuiMenuTopButton targetTab = new GuiMenuTopButton(92, lastTab, "script.target"); + targetTab.active = (activeTab == TAB_TARGET); + addTopButton(targetTab); + lastTab = targetTab; + + GuiMenuTopButton effectsTab = new GuiMenuTopButton(93, lastTab, "ability.tab.effects"); + effectsTab.active = (activeTab == TAB_EFFECTS); + addTopButton(effectsTab); + lastTab = effectsTab; + + // Custom tabs (Visual, etc.) + for (int i = 0; i < customTabNames.size(); i++) { + GuiMenuTopButton ct = new GuiMenuTopButton(94 + i, lastTab, customTabNames.get(i)); + ct.active = (activeTab == 4 + i); + addTopButton(ct); + lastTab = ct; + } + + 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; + int swW = xSize - 8; + int swH = ySize - 10; + + int y = 5; + int labelCounter = LABEL_ID_START; + + // 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 + List tabFields = getVisibleFieldsForTab(activeTab); + builder = new AbilityFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, labelCounter); + builder.startY(y); + + GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); + + // General tab: add type label + optional info labels at top of scroll window + if (activeTab == TAB_GENERAL) { + 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 + if (activeTab == TAB_TARGET) { + int condY = renderConditions(sw, builder.getLastBuildY(), builder.getNextLabelId()); + sw.maxScrollY = Math.max(condY - swH, 0); + } + + // Restore scroll position + if (activeTab < tabScrollY.length) { + float restored = Math.min(tabScrollY[activeTab], sw.maxScrollY); + sw.nextScrollY = restored; + sw.scrollY = restored; + } + } + + private List getVisibleFieldsForTab(int tabIndex) { + List result = new ArrayList<>(); + + String tabName; + if (tabIndex >= 4) { + int customIndex = tabIndex - 4; + if (customIndex >= 0 && customIndex < customTabNames.size()) { + tabName = customTabNames.get(customIndex); + } else { + return result; + } + } 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; + } + } + + for (FieldDef def : fieldDefs) { + if (tabName.equals(def.getTab()) && def.isVisible()) { + result.add(def); + } + } + + return result; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CONDITIONS (Target tab) + // ═══════════════════════════════════════════════════════════════════════════ + + 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); + 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() < 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); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // BUTTON EVENTS + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void buttonEvent(GuiButton guibutton) { + 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; + } + // Custom tabs (94+) + if (id >= 94 && id < 94 + customTabNames.size()) { + activeTab = 4 + (id - 94); + initGui(); + 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; + + // Declarative field handling (effects list, booleans, enums, sub-guis, clear buttons) + if (builder.handleButtonEvent(id, guibutton)) { + // SUB_GUI fields are opened directly by the builder via setSubGuiWithResult(). + // Only rebuild if no sub-gui was opened (e.g. boolean toggle, enum change). + if (!hasSubGui()) { + initGui(); + } + return; + } + } + + 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) { + if (textField.id < DECLARATIVE_ID_START) return; + if (builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // SUB GUI CLOSED + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (builder.handleSubGuiClosed(subgui)) { + initGui(); + return; + } + + if (subgui instanceof SubGuiConditionEdit) { + SubGuiConditionEdit condEdit = (SubGuiConditionEdit) subgui; + AbilityCondition result = condEdit.getResult(); + if (result != null && editingConditionIndex >= 0) { + if (editingConditionIndex < conditions.size()) { + conditions.set(editingConditionIndex, result); + } else { + conditions.add(result); + } + } + editingConditionIndex = -1; + initGui(); + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CLOSE / APPLY + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void close() { + GuiNpcTextField.unfocus(); + applyToAbility(); + callback.onAbilitySaved(ability); + super.close(); + } + + protected void applyToAbility() { + ability.getConditions().clear(); + for (AbilityCondition c : conditions) ability.addCondition(c); + } + + public void loadAbility(Ability loadedAbility) { + if (loadedAbility == null) return; + NBTTagCompound nbt = loadedAbility.writeNBT(false); + nbt.setString("typeId", ability.getTypeId()); + ability.readNBT(nbt); + + this.conditions = new ArrayList<>(ability.getConditions()); + this.fieldDefs = ability.getAllDefinitions(); + discoverCustomTabs(); + initGui(); + } + + protected Ability getAbility() { + return ability; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityDeleteConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityDeleteConfirm.java new file mode 100644 index 000000000..c0517257b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityDeleteConfirm.java @@ -0,0 +1,63 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.SubGuiInterface; + +/** + * Confirmation dialog for deleting an ability preset. + * Uses packet-based communication for proper client-server architecture. + */ +public class SubGuiAbilityDeleteConfirm extends SubGuiInterface { + + private final String abilityName; + private final Runnable onDeleted; + + public SubGuiAbilityDeleteConfirm(String abilityName) { + this(abilityName, null); + } + + public SubGuiAbilityDeleteConfirm(String abilityName, Runnable onDeleted) { + this.abilityName = abilityName; + this.onDeleted = onDeleted; + + setBackground("menubg.png"); + xSize = 200; + ySize = 100; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + + addLabel(new GuiNpcLabel(0, "ability.delete.confirm", guiLeft + 10, y)); + y += 12; + addLabel(new GuiNpcLabel(1, "'" + abilityName + "'?", guiLeft + 10, y)); + + y += 30; + + addButton(new GuiNpcButton(0, guiLeft + 30, y, 60, 20, "gui.yes")); + addButton(new GuiNpcButton(1, guiLeft + 110, y, 60, 20, "gui.no")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + + if (id == 0) { + // Delete the ability via packet + PacketClient.sendClient(new CustomAbilityRemovePacket(abilityName)); + if (onDeleted != null) { + onDeleted.run(); + } + close(); + } else if (id == 1) { + close(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java new file mode 100644 index 000000000..9e3856a14 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityEditMode.java @@ -0,0 +1,48 @@ +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; + +/** + * Dialog asking the user whether to clone-and-modify (convert to inline) or modify the parent ability. + */ +public class SubGuiAbilityEditMode extends SubGuiSimpleChoice { + + public static final int MODE_CLONE_MODIFY = 0; + public static final int MODE_MODIFY_PARENT = 1; + + public SubGuiAbilityEditMode() { + setBackground("menubg.png"); + xSize = 220; + ySize = 90; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.edit.mode", guiLeft + 10, y)); + + y += 25; + addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "ability.cloneModify")); + addButton(new GuiNpcButton(1, guiLeft + 115, y, 95, 20, "ability.modifyParent")); + + y += 25; + addButton(new GuiNpcButton(2, guiLeft + 65, y, 90, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + setResult(MODE_CLONE_MODIFY); + close(); + } else if (guibutton.id == 1) { + setResult(MODE_MODIFY_PARENT); + close(); + } else if (guibutton.id == 2) { + close(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java new file mode 100644 index 000000000..568f60883 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java @@ -0,0 +1,233 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +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; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.nbt.NBTTagCompound; +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.IGuiData; +import noppes.npcs.client.gui.util.IScrollData; +import noppes.npcs.client.gui.util.ISubGuiListener; +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; + +/** + * Dialog for loading a saved ability preset. + * Shows custom abilities from the server, then asks Clone/Reference via SubGuiAbilityLoadMode. + */ +public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollListener, IScrollData, IGuiData, ISubGuiListener { + + private final SubGuiAbilityConfig parentConfig; + private final GuiNPCAbilities parentAbilities; + private String selectedDisplayName = null; + private String selectedName = null; + + private HashMap rawData = new HashMap<>(); + private GuiCustomScroll scroll; + + private String search = ""; + private boolean waitingForLoad = false; + private int pendingLoadMode = -1; + + public SubGuiAbilityLoad(SubGuiAbilityConfig parentConfig) { + this.parentConfig = parentConfig; + this.parentAbilities = null; + + setBackground("menubg.png"); + xSize = 220; + ySize = 216; + + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } + + public SubGuiAbilityLoad(GuiNPCAbilities parentAbilities) { + this.parentConfig = null; + this.parentAbilities = parentAbilities; + + 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.load.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 (selectedDisplayName != null) { + scroll.setSelected(selectedDisplayName); + } + addScroll(scroll); + + y += 143; + + // Search bar + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 10, y, 200, 20, search)); + + y += 24; + + 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(selectedName != null); + } + + private List getFilteredList() { + List list = new ArrayList<>(); + 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; + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + + if (id == 0 && selectedName != null) { + if (parentAbilities != null) { + // From NPC abilities GUI - ask clone/reference + setSubGui(new SubGuiAbilityLoadMode()); + } else { + // From config GUI - always clone + waitingForLoad = true; + pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE; + PacketClient.sendClient(new CustomAbilityGetPacket(selectedName)); + } + } else if (id == 2) { + 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 subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiAbilityLoadMode) { + int mode = ((SubGuiAbilityLoadMode) subgui).getResult(); + if (mode < 0) return; // cancelled + + if (mode == SubGuiAbilityLoadMode.MODE_REFERENCE) { + // 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(selectedName)); + } + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0) { + selectedDisplayName = scroll.getSelected(); + selectedName = selectedDisplayName; + initGui(); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (scroll.id == 0 && selection != null && !selection.isEmpty()) { + selectedDisplayName = selection; + selectedName = selection; + if (parentAbilities != null) { + setSubGui(new SubGuiAbilityLoadMode()); + } else { + waitingForLoad = true; + pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE; + PacketClient.sendClient(new CustomAbilityGetPacket(selectedName)); + } + } + } + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.CUSTOM_ABILITIES) { + rawData = data; + if (scroll != null) { + scroll.setList(getFilteredList()); + if (selectedDisplayName != null && rawData.containsKey(selectedDisplayName)) { + scroll.setSelected(selectedDisplayName); + } + } + initGui(); + } + } + + @Override + public void setGuiData(NBTTagCompound compound) { + if (waitingForLoad) { + waitingForLoad = false; + Ability loaded = AbilityController.Instance.fromNBT(compound); + if (loaded != null) { + if (parentConfig != null) { + parentConfig.loadAbility(loaded); + } else if (parentAbilities != null) { + parentAbilities.loadAbility(loaded); + } + } + close(); + } + } + + @Override + public void setSelected(String selected) { + this.selectedDisplayName = selected; + if (scroll != null) { + scroll.setSelected(selected); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java new file mode 100644 index 000000000..5995c0e9e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoadMode.java @@ -0,0 +1,48 @@ +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; + +/** + * Dialog asking the user whether to Clone (inline copy) or Reference the loaded ability. + */ +public class SubGuiAbilityLoadMode extends SubGuiSimpleChoice { + + public static final int MODE_CLONE = 0; + public static final int MODE_REFERENCE = 1; + + public SubGuiAbilityLoadMode() { + setBackground("menubg.png"); + xSize = 200; + ySize = 90; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.load.mode", guiLeft + 10, y)); + + y += 25; + addButton(new GuiNpcButton(0, guiLeft + 15, y, 80, 20, "ability.clone")); + addButton(new GuiNpcButton(1, guiLeft + 105, y, 80, 20, "ability.reference")); + + y += 25; + addButton(new GuiNpcButton(2, guiLeft + 55, y, 90, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + setResult(MODE_CLONE); + close(); + } else if (guibutton.id == 1) { + setResult(MODE_REFERENCE); + close(); + } else if (guibutton.id == 2) { + close(); + } + } +} 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..8543ad208 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityMagic.java @@ -0,0 +1,250 @@ +package noppes.npcs.client.gui.advanced; + +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.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 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; + + 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 new file mode 100644 index 000000000..7f51b15e0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java @@ -0,0 +1,98 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.Set; + +/** + * Confirmation dialog for saving an ability preset. + * Uses packet-based communication for proper client-server architecture. + */ +public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGuiListener { + + private final Ability ability; + private final IAbilityConfigCallback callback; + private final Set existingNames; + private boolean saved = false; + + public SubGuiAbilitySaveConfirm(Ability ability) { + this(ability, null, null); + } + + public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback, Set existingNames) { + this.ability = ability; + this.callback = callback; + this.existingNames = existingNames; + + setBackground("menubg.png"); + xSize = 200; + ySize = 100; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + + addLabel(new GuiNpcLabel(0, "ability.save.confirm", guiLeft + 10, y)); + y += 12; + addLabel(new GuiNpcLabel(1, "'" + ability.getName() + "'?", guiLeft + 10, y)); + + y += 30; + + addButton(new GuiNpcButton(0, guiLeft + 30, y, 60, 20, "gui.yes")); + addButton(new GuiNpcButton(1, guiLeft + 110, y, 60, 20, "gui.no")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + + if (id == 0) { + if (existingNames != null && existingNames.contains(ability.getName())) { + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + doSave(); + } else if (id == 1) { + close(); + } + } + + private void doSave() { + 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) { + 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 new file mode 100644 index 000000000..46975f289 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -0,0 +1,222 @@ +package noppes.npcs.client.gui.advanced; + +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; +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 java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * SubGui for selecting an ability type when creating a new ability. + */ +public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, 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<>(); + private String selectedTypeId = null; + private String search = ""; + + public SubGuiAbilityTypeSelect() { + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + 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, 121); + } + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = y; + addScroll(scroll); + + buildAllTypes(); + scroll.setUnsortedList(getFilteredTypeList()); + + 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(); + 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) { + int id = guibutton.id; + + if (id == BTN_ADD && scroll.hasSelected()) { + String displayName = scroll.getSelected(); + selectedTypeId = displayNameToTypeId.get(displayName); + close(); + } 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(BTN_ADD).setEnabled(scroll.hasSelected()); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && selection != null) { + selectedTypeId = displayNameToTypeId.get(selection); + close(); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + 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(); + } + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + } + + public String getSelectedTypeId() { + return selectedTypeId; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java new file mode 100644 index 000000000..be7ba5645 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java @@ -0,0 +1,157 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +/** + * SubGui for selecting a variant/template when creating a new ability. + * Uses a scroll list with group headers for external addon variants. + */ +public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICustomScrollListener { + + private final List variants; + private int selectedIndex = -1; + + // Maps each scroll list index to a variant list index (-1 for non-selectable entries) + private final List scrollToVariantIndex = new ArrayList<>(); + + public SubGuiAbilityVariantSelect(List variants) { + this.variants = variants; + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + addLabel(new GuiNpcLabel(0, "ability.selectVariant", guiLeft + 10, guiTop + 8)); + + // Build the unsorted scroll list with group headers + List scrollList = new ArrayList<>(); + scrollToVariantIndex.clear(); + + boolean hasBaseVariants = false; + boolean hasGroupedVariants = false; + + for (AbilityVariant v : variants) { + if (v.getGroup() == null) + hasBaseVariants = true; + else + hasGroupedVariants = true; + } + + // Add base (non-grouped) variants first + for (int i = 0; i < variants.size(); i++) { + if (variants.get(i).getGroup() == null) { + scrollList.add(variants.get(i).getDisplayKey()); + scrollToVariantIndex.add(i); + } + } + + // Blank separator between base and grouped variants + if (hasBaseVariants && hasGroupedVariants) { + scrollList.add(""); + scrollToVariantIndex.add(-1); + } + + // Add grouped variants with group headers + String lastGroup = null; + for (int i = 0; i < variants.size(); i++) { + AbilityVariant v = variants.get(i); + if (v.getGroup() == null) + continue; + + if (!v.getGroup().equals(lastGroup)) { + scrollList.add(v.getGroup()); + scrollToVariantIndex.add(-1); + lastGroup = v.getGroup(); + } + + scrollList.add(v.getDisplayKey()); + scrollToVariantIndex.add(i); + } + + GuiCustomScroll scroll = new GuiCustomScroll(this, 0); + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = guiTop + 22; + scroll.setUnsortedList(scrollList); + scroll.setSize(190, 155); + + // Mark blank separators and group headers as non-interactive colored entries + scroll.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) { + scroll.nonInteractive.add(group); + scroll.colors.put(group, 0xFFFF00); // Yellow + } + } + } + + // Restore selection in scroll + if (selectedIndex >= 0) { + for (int s = 0; s < scrollToVariantIndex.size(); s++) { + if (scrollToVariantIndex.get(s) == selectedIndex) { + scroll.selected = s; + break; + } + } + } + + addScroll(scroll); + + // Select / Cancel buttons + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); + getButton(0).setEnabled(selectedIndex >= 0); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0 && scroll.selected >= 0 && scroll.selected < scrollToVariantIndex.size()) { + int variantIdx = scrollToVariantIndex.get(scroll.selected); + if (variantIdx >= 0) { + selectedIndex = variantIdx; + getButton(0).setEnabled(true); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (selectedIndex >= 0) { + close(); + } + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + if (id == 0 && selectedIndex >= 0) { + close(); + } else if (id == 1) { + selectedIndex = -1; + close(); + } + } + + public int getSelectedIndex() { + return selectedIndex; + } + + public List getVariants() { + return variants; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/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..4e271893c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -0,0 +1,936 @@ +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 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.intField("ability.cooldown", chain::getCooldownTicks, chain::setCooldownTicks).range(0, 12000).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); + 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")); + fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f)); + fieldDefs.add(FieldDef.intField("ability.icon.layers", chainIcon::getLayerCount, chainIcon::setLayerCount) + .tab("Icon").range(1, AbilityIconData.MAX_LAYERS)); + for (int i = 0; i < AbilityIconData.MAX_LAYERS; i++) { + final int idx = i; + java.util.function.BooleanSupplier layerVisible = () -> chainIcon.getLayerCount() > idx; + String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1); + fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.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")); + fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover")); + fieldDefs.add(FieldDef.intField("gui.frameCount", chainIcon::getFrameCount, chainIcon::setFrameCount) + .tab("Icon").range(1, 256).visibleWhen(chainIcon::isAnimated)); + fieldDefs.add(FieldDef.intField("gui.frameTime", chainIcon::getFrameTime, chainIcon::setFrameTime) + .tab("Icon").range(1, 100).visibleWhen(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 new file mode 100644 index 000000000..b0ed1d635 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java @@ -0,0 +1,310 @@ +package noppes.npcs.client.gui.advanced; + +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 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 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, ISubGuiListener, ICustomScrollListener { + + 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 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; + + // Left panel + private static final int LEFT_WIDTH = 110; + private static final int LEFT_MARGIN = 5; + + // Right panel + private static final int RIGHT_GAP = 5; + + 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) { + 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); + } + } + + setBackground("menubg.png", 217); + xSize = 356; + ySize = 200; + } + + 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 leftX = guiLeft + LEFT_MARGIN; + int btnY = guiTop + ySize - 26; + + // Namespace filter button (above left scroll only) + addButton(new GuiNpcButton(BTN_NAMESPACE, leftX, guiTop + 5, LEFT_WIDTH, 20, getNamespaceFilterLabel())); + + // 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(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 == BTN_NAMESPACE) { + cycleNamespaceFilter(); + initGui(); + return; + } + + if (id == BTN_CANCEL) { + result = null; + close(); + 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) { + 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(); + } + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (builder != null && builder.handleSubGuiClosed(subgui)) { + initGui(); + } + } + + 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..411d03351 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java @@ -0,0 +1,220 @@ +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 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 { + + 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 new file mode 100644 index 000000000..5d316f416 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java @@ -0,0 +1,69 @@ +package noppes.npcs.client.gui.advanced; + +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.SubGuiInterface; + +/** + * Confirmation dialog shown when saving an ability preset with a name that already exists. + */ +public class SubGuiDuplicateNameConfirm extends SubGuiInterface { + + public enum Result { + CONTINUE, + BACK, + CANCEL + } + + private Result result = Result.CANCEL; + + public SubGuiDuplicateNameConfirm() { + setBackground("menubg.png"); + xSize = 220; + ySize = 80; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.duplicate.name", guiLeft + 10, y)); + + y += 30; + addButton(new GuiNpcButton(0, guiLeft + 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) { + result = Result.CONTINUE; + close(); + } else if (guibutton.id == 1) { + result = Result.BACK; + close(); + } else if (guibutton.id == 2) { + result = Result.CANCEL; + close(); + } + } + + public Result getResult() { + return result; + } + + public boolean isConfirmed() { + 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 new file mode 100644 index 000000000..a2b523ec6 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -0,0 +1,455 @@ +package noppes.npcs.client.gui.builder; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import noppes.npcs.client.gui.SubGuiColorSelector; +import noppes.npcs.client.gui.select.GuiAnimationSelection; +import noppes.npcs.client.gui.select.GuiSoundSelection; +import noppes.npcs.client.gui.select.GuiTexturePathSelection; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.Animation; + +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Declarative field definition for GUI rendering. + * Built via static factories and chaining methods. + * Client-side only — never instantiate or reference on the server. + */ +@SideOnly(Side.CLIENT) +public class FieldDef { + + private final String label; + private final FieldType type; + private String tab = null; + private Supplier getter; + private Consumer setter; + private BooleanSupplier visibleWhen = () -> true; + private BooleanSupplier enabledWhen = () -> true; + private String hoverText = null; + + // Numeric range + private float min = 0; + private float max = Float.POSITIVE_INFINITY; + + // Enum support + private Class> enumClass; + private String[] stringEnumValues; + private Supplier stringEnumGetter; + private Consumer stringEnumSetter; + + // Sub-gui support + private Supplier subGuiFactory; + private Consumer subGuiResultHandler; + + // Button display + private Supplier buttonLabelSupplier; + private Supplier buttonTextColorSupplier; + private Runnable clearAction; + + // Row pairing (ROW type only) + private FieldDef leftChild; + private FieldDef rightChild; + + private FieldDef(String label, FieldType type) { + this.label = label; + this.type = type; + } + + // ═══════════════════════════════════════════════════════════════════ + // STATIC FACTORIES + // ═══════════════════════════════════════════════════════════════════ + + public static FieldDef section(String label) { + return new FieldDef(label, FieldType.SECTION_HEADER); + } + + public static FieldDef floatField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.FLOAT); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept(((Number) v).floatValue()); + return def; + } + + public static FieldDef intField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.INT); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept(((Number) v).intValue()); + return def; + } + + public static FieldDef boolField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.BOOLEAN); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept((Boolean) v); + return def; + } + + @SuppressWarnings("unchecked") + public static > FieldDef enumField(String label, Class enumClass, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.ENUM); + def.enumClass = enumClass; + def.getter = () -> getter.get(); + def.setter = v -> setter.accept((E) v); + return def; + } + + public static FieldDef stringEnumField(String label, String[] values, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.STRING_ENUM); + def.stringEnumValues = values; + def.stringEnumGetter = getter; + def.stringEnumSetter = setter; + return def; + } + + public static FieldDef stringField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.STRING); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept((String) v); + return def; + } + + public static FieldDef labelField(String label, Supplier textSupplier) { + FieldDef def = new FieldDef(label, FieldType.LABEL); + def.getter = () -> textSupplier.get(); + return def; + } + + @SuppressWarnings("unchecked") + public static FieldDef subGuiField(String label, Supplier factory, Consumer resultHandler) { + FieldDef def = new FieldDef(label, FieldType.SUB_GUI); + def.subGuiFactory = (Supplier) (Supplier) factory; + def.subGuiResultHandler = (Consumer) (Consumer) resultHandler; + return def; + } + + /** + * Creates a FieldDef with a custom FieldType. Used by extension code + * (e.g. AbilityFieldDefs) to create fields with types like EFFECTS_LIST + * that the base GuiFieldBuilder does not handle. + */ + public static FieldDef custom(String label, FieldType type, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, type); + def.getter = getter; + def.setter = setter; + return def; + } + + /** + * Creates a two-column row pairing two fields side by side. + * If one child is hidden (via visibleWhen), the other renders full-width. + */ + public static FieldDef row(FieldDef left, FieldDef right) { + FieldDef def = new FieldDef("", FieldType.ROW); + def.leftChild = left; + def.rightChild = right; + return def; + } + + // ═══════════════════════════════════════════════════════════════════ + // CONVENIENCE FACTORIES (SUB_GUI wrappers) + // ═══════════════════════════════════════════════════════════════════ + + public static FieldDef colorSubGui(String label, Supplier getter, Consumer setter) { + return subGuiField(label, + () -> 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); + } + + public static FieldDef soundSubGui(String label, Supplier getter, Consumer setter) { + return subGuiField(label, + () -> new GuiSoundSelection(getter.get()), + gui -> { + GuiSoundSelection s = (GuiSoundSelection) gui; + if (s.selectedResource != null) setter.accept(s.selectedResource.toString()); + }) + .buttonLabel(() -> { + String s = getter.get(); + return s == null || s.isEmpty() ? "gui.none" : s; + }) + .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) { + return subGuiField(label, + () -> new GuiAnimationSelection(idGetter.get(), nameGetter.get()), + gui -> { + GuiAnimationSelection sel = (GuiAnimationSelection) gui; + if (sel.isBuiltInSelected()) { + nameSetter.accept(sel.selectedBuiltInName); + idSetter.accept(-1); + } else { + idSetter.accept(sel.selectedAnimationId); + String customName = sel.getSelectedName(); + nameSetter.accept(customName != null ? customName : ""); + } + }) + .buttonLabel(() -> { + String name = nameGetter.get(); + 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 + ") " + animName : String.valueOf(id); + } + return "gui.none"; + }) + .clearable(() -> { + idSetter.accept(-1); + nameSetter.accept(""); + }); + } + + // ═══════════════════════════════════════════════════════════════════ + // CHAINING METHODS + // ═══════════════════════════════════════════════════════════════════ + + public FieldDef tab(String tabName) { + this.tab = tabName; + return this; + } + + public FieldDef range(float min, float max) { + this.min = min; + this.max = max; + return this; + } + + public FieldDef min(float min) { + this.min = min; + return this; + } + + public FieldDef max(float max) { + this.max = max; + return this; + } + + public FieldDef visibleWhen(BooleanSupplier condition) { + this.visibleWhen = condition; + return this; + } + + public FieldDef enabledWhen(BooleanSupplier condition) { + this.enabledWhen = condition; + return this; + } + + public FieldDef hover(String hoverText) { + this.hoverText = hoverText; + return this; + } + + public FieldDef buttonLabel(Supplier supplier) { + this.buttonLabelSupplier = supplier; + return this; + } + + public FieldDef buttonTextColor(Supplier supplier) { + this.buttonTextColorSupplier = supplier; + return this; + } + + public FieldDef clearable(Runnable action) { + this.clearAction = action; + return this; + } + + // ═══════════════════════════════════════════════════════════════════ + // 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 != 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; + } + + public void setValue(Object value) { + if (setter != null) setter.accept(value); + } + + public String getStringEnumValue() { + return stringEnumGetter != null ? stringEnumGetter.get() : null; + } + + public void setStringEnumValue(String value) { + if (stringEnumSetter != null) stringEnumSetter.accept(value); + } + + public String getButtonLabel() { + if (buttonLabelSupplier != null) return buttonLabelSupplier.get(); + return label; + } + + public Integer getButtonTextColor() { + return buttonTextColorSupplier != null ? buttonTextColorSupplier.get() : null; + } + + public FieldDef getLeftChild() { + return leftChild; + } + + public FieldDef getRightChild() { + return rightChild; + } + + // ═══════════════════════════════════════════════════════════════════ + // LIST MANIPULATION (for mod injection) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Insert a field before the first field matching the target label. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to insert before + * @param newField The field to insert + * @return true if the target was found and the field was inserted + */ + public static boolean insertBefore(java.util.List fields, String targetLabel, FieldDef newField) { + for (int i = 0; i < fields.size(); i++) { + if (matchesLabel(fields.get(i), targetLabel)) { + fields.add(i, newField); + return true; + } + } + return false; + } + + /** + * Insert a field after the first field matching the target label. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to insert after + * @param newField The field to insert + * @return true if the target was found and the field was inserted + */ + public static boolean insertAfter(List fields, String targetLabel, FieldDef newField) { + for (int i = 0; i < fields.size(); i++) { + if (matchesLabel(fields.get(i), targetLabel)) { + fields.add(i + 1, newField); + return true; + } + } + return false; + } + + /** + * Modify the visibility condition of a field. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to modify + * @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) { + for (FieldDef field : fields) { + if (matchesLabel(field, targetLabel)) { + field.visibleWhen(condition); + return true; + } + } + return false; + } + + private static boolean matchesLabel(FieldDef def, String targetLabel) { + if (targetLabel.equals(def.label)) return true; + if (def.type == FieldType.ROW) { + if (def.leftChild != null && targetLabel.equals(def.leftChild.label)) return true; + if (def.rightChild != null && targetLabel.equals(def.rightChild.label)) return true; + } + return false; + } + +} diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldType.java b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java new file mode 100644 index 000000000..347086b78 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java @@ -0,0 +1,22 @@ +package noppes.npcs.client.gui.builder; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public enum FieldType { + FLOAT, + INT, + BOOLEAN, + ENUM, + STRING_ENUM, + SUB_GUI, + STRING, + SECTION_HEADER, + LABEL, + EFFECTS_LIST, + 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 new file mode 100644 index 000000000..3f1d06b89 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -0,0 +1,559 @@ +package noppes.npcs.client.gui.builder; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNPCInterface; +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.SubGuiInterface; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * General-purpose builder that converts a list of {@link FieldDef} into positioned + * GUI widgets inside a {@link GuiScrollWindow}. + *

+ * Uses {@link FieldDef#row(FieldDef, FieldDef)} for two-column layouts. + * Subclasses can override {@link #buildField} to handle custom field types. + */ +@SideOnly(Side.CLIENT) +public class GuiFieldBuilder { + + // Layout defaults (2-column mode) + protected int contentRight = 330; + protected int colLLabel = 5; + protected int colLField = 75; + protected int colLWidth = 70; + protected int colRLabel = 178; + protected int colRField = 248; + protected int colRWidth = 70; + protected int rowHeight = 24; + protected int labelPadding = 8; + + // Dependencies + protected final GuiNPCInterface parent; + protected GuiScrollWindow sw; + protected final FontRenderer fontRenderer; + + // Scroll window ID + protected int scrollWindowId = 0; + + // ID counters + protected int widgetId; + protected int clearId; + protected int labelId; + + // Starting Y + protected int startY = 5; + protected int lastBuildY = 0; + + // Output maps + protected final Map buttonFieldMap = new HashMap<>(); + protected final Map textFieldMap = new HashMap<>(); + protected final Map clearFieldMap = new HashMap<>(); + + public GuiFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { + this.parent = parent; + this.fontRenderer = fontRenderer; + } + + // ═══════════════════════════════════════════════════════════════════ + // 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 startY(int y) { + this.startY = y; + return this; + } + + public GuiFieldBuilder rowHeight(int h) { + this.rowHeight = h; + return this; + } + + // ═══════════════════════════════════════════════════════════════════ + // BUILD + // ═══════════════════════════════════════════════════════════════════ + + /** + * Creates a {@link GuiScrollWindow} at the given position/size, builds all fields into it, + * and sets maxScrollY automatically. The returned window is ready to use. + */ + public GuiScrollWindow buildScrollWindow(List fields, int x, int y, int width, int height) { + this.sw = new GuiScrollWindow(parent, x, y, width, height, 0); + sw.backgroundColor = 0x88000000; + // Register with parent first — this calls initGui() which clears widget lists, + // so we must add widgets AFTER this point + parent.addScrollableGui(scrollWindowId, sw); + int finalY = build(fields); + sw.maxScrollY = Math.max(finalY - height, 0); + return sw; + } + + /** + * Processes all fields and adds widgets to the scroll window. + * + * @return the final Y position after all fields + */ + protected int build(List fields) { + buttonFieldMap.clear(); + textFieldMap.clear(); + clearFieldMap.clear(); + + int y = startY; + + for (int i = 0; i < fields.size(); i++) { + FieldDef def = fields.get(i); + + // Let subclasses handle custom types; returns -1 if not handled + int customResult = buildField(def, y, fields, i); + if (customResult >= 0) { + // Subclass handled it, check if index was advanced + int newIndex = getLastHandledIndex(); + if (newIndex > i) i = newIndex; + y = customResult; + continue; + } + + // Skip invisible fields + if (!def.isVisible()) continue; + + // Section header + if (def.getType() == FieldType.SECTION_HEADER) { + y += 3; + GuiNpcLabel sectionLabel = new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55); + if (def.getHoverText() != null && !def.getHoverText().isEmpty()) { + sectionLabel.setHoverText(def.getHoverText()); + } + sw.addLabel(sectionLabel); + y += 15; + continue; + } + + // ROW: explicit two-column pair + if (def.getType() == FieldType.ROW) { + FieldDef left = def.getLeftChild(); + FieldDef right = def.getRightChild(); + boolean leftVis = left != null && left.isVisible(); + boolean rightVis = right != null && right.isVisible(); + + if (leftVis && rightVis) { + renderFieldAt(left, colLLabel, colLField, colLWidth, y); + renderFieldAt(right, colRLabel, colRField, colRWidth, y); + } else if (leftVis) { + renderFullWidth(left, y); + } else if (rightVis) { + renderFullWidth(right, y); + } + if (leftVis || rightVis) y += rowHeight; + continue; + } + + // Full-width field + renderFullWidth(def, y); + y += rowHeight; + } + + lastBuildY = y; + return y; + } + + /** + * Hook for subclasses to handle custom field types (e.g. EFFECTS_LIST). + * Return the new Y position if handled, or -1 if not handled (base class will process it). + * If handling advances the field index, call {@link #setLastHandledIndex(int)}. + */ + protected int buildField(FieldDef def, int y, List fields, int index) { + return -1; + } + + private int lastHandledIndex = -1; + + protected void setLastHandledIndex(int index) { + this.lastHandledIndex = index; + } + + protected int getLastHandledIndex() { + return lastHandledIndex; + } + + // ═══════════════════════════════════════════════════════════════════ + // FIELD RENDERING + // ═══════════════════════════════════════════════════════════════════ + + @SuppressWarnings({"unchecked", "rawtypes"}) + protected void renderFieldAt(FieldDef def, int labelX, int fieldX, int fieldW, int y) { + GuiNpcLabel fieldLabel = new GuiNpcLabel(labelId++, def.getLabel(), labelX, y + 5, 0xFFFFFF); + String hover = def.getHoverText(); + if (hover != null && !hover.isEmpty()) { + fieldLabel.setHoverText(hover); + } + sw.addLabel(fieldLabel); + + switch (def.getType()) { + case FLOAT: { + 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(); + tf.setMinMaxDefaultFloat(def.getMin(), def.getMax(), fVal); + if (!def.isEnabled()) tf.setEnabled(false); + if (hover != null) tf.setHoverText(hover); + sw.addTextField(tf); + textFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case INT: { + 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(); + tf.setMinMaxDefault((int) def.getMin(), (int) def.getMax(), iVal); + if (!def.isEnabled()) tf.setEnabled(false); + if (hover != null) tf.setHoverText(hover); + sw.addTextField(tf); + textFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + 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); + textFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case LABEL: { + String text = def.getValue() != null ? def.getValue().toString() : ""; + sw.addLabel(new GuiNpcLabel(labelId++, text, fieldX, y + 5, 0xAAAAAA)); + widgetId++; + clearId++; + break; + } + case BOOLEAN: { + boolean bVal = def.getValue() instanceof Boolean ? (Boolean) def.getValue() : false; + GuiNpcButtonYesNo btn = new GuiNpcButtonYesNo(widgetId, fieldX, y, fieldW, 20, bVal); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case ENUM: { + Class> enumClass = def.getEnumClass(); + if (enumClass != null) { + Enum[] constants = enumClass.getEnumConstants(); + String[] names = new String[constants.length]; + for (int i = 0; i < constants.length; i++) names[i] = constants[i].toString(); + int selected = def.getValue() instanceof Enum ? ((Enum) def.getValue()).ordinal() : 0; + GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, fieldW, 20, names, selected); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + } + widgetId++; + clearId++; + break; + } + case STRING_ENUM: { + String[] values = def.getStringEnumValues(); + if (values != null && values.length > 0) { + String curVal = def.getStringEnumValue(); + int selected = 0; + for (int i = 0; i < values.length; i++) { + 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); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + } + widgetId++; + clearId++; + break; + } + case SUB_GUI: { + String btnText = def.getButtonLabel(); + int btnW; + if (def.hasClearAction()) { + btnW = fieldW - 22; + GuiNpcButton clearBtn = new GuiNpcButton(clearId, fieldX + fieldW - 20, y, 20, 20, "X"); + sw.addButton(clearBtn); + clearFieldMap.put(clearId, def); + } else { + btnW = fieldW; + } + GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, btnW, 20, btnText); + Integer textColor = def.getButtonTextColor(); + if (textColor != null) btn.setTextColor(textColor); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + widgetId++; + 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++; + clearId++; + break; + } + } + + private void renderFullWidth(FieldDef def, int y) { + int fieldW = getFullFieldWidth(def); + 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 ENUM: + case STRING_ENUM: + return 120; + case SUB_GUI: + return def.hasClearAction() ? 175 : 200; + case STRING_BROWSE: + return 200; + default: + return 80; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // EVENT HANDLING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Handles button events for declarative fields. + * Call from parent GUI's buttonEvent(). Returns true if the event was handled. + *

+ * For SUB_GUI fields, the sub-gui is opened directly via {@code parent.setSubGuiWithResult()}, + * so the result handler survives initGui() rebuilds. After this returns true, check + * {@code parent.hasSubGui()} to determine if initGui() should be called. + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public boolean handleButtonEvent(int buttonId, GuiButton button) { + // Check clear buttons first + if (clearFieldMap.containsKey(buttonId)) { + FieldDef def = clearFieldMap.get(buttonId); + if (def != null && def.hasClearAction()) { + def.getClearAction().run(); + return true; + } + } + + // Check field buttons + FieldDef def = buttonFieldMap.get(buttonId); + if (def == null) return false; + + switch (def.getType()) { + case BOOLEAN: + def.setValue(((GuiNpcButton) button).getValue() == 1); + return true; + case ENUM: { + int idx = ((GuiNpcButton) button).getValue(); + Class> ec = def.getEnumClass(); + if (ec != null) { + Enum[] constants = ec.getEnumConstants(); + if (idx >= 0 && idx < constants.length) def.setValue(constants[idx]); + } + return true; + } + case STRING_ENUM: { + int idx = ((GuiNpcButton) button).getValue(); + String[] values = def.getStringEnumValues(); + if (values != null && idx >= 0 && idx < values.length) def.setStringEnumValue(values[idx]); + return true; + } + case SUB_GUI: + if (def.getSubGuiFactory() != null) { + parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> { + if (def.getSubGuiResultHandler() != null) { + def.getSubGuiResultHandler().accept(sub); + } + }); + } + 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; + } + } + + /** + * Handles text field unfocus events for declarative fields. + * Call from parent GUI's unFocused(). Returns true if the value actually changed. + */ + public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { + FieldDef def = textFieldMap.get(textFieldId); + if (def == null) return false; + + switch (def.getType()) { + case FLOAT: + try { + float newVal = Float.parseFloat(field.getText()); + Object old = def.getValue(); + float oldVal = old instanceof Number ? ((Number) old).floatValue() : 0f; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) { + } + return false; + case INT: + try { + int newVal = Integer.parseInt(field.getText()); + Object old = def.getValue(); + int oldVal = old instanceof Number ? ((Number) old).intValue() : 0; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) { + } + return false; + case STRING: + case STRING_BROWSE: + String newVal = field.getText(); + Object old = def.getValue(); + String oldVal = old != null ? old.toString() : ""; + if (!newVal.equals(oldVal)) { + def.setValue(newVal); + return true; + } + return false; + default: + return false; + } + } + + /** + * Handles sub-gui close events. Call from parent GUI's subGuiClosed(). + *

+ * Note: SUB_GUI fields opened via handleButtonEvent use + * {@code parent.setSubGuiWithResult()}, so their results are handled + * automatically by {@code GuiNPCInterface.closeSubGui()}. This method + * only handles sub-guis opened through other means. + */ + public boolean handleSubGuiClosed(SubGuiInterface subgui) { + return false; + } + + // ═══════════════════════════════════════════════════════════════════ + // 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; + } +} 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..df6cd58b2 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiAnimationDirectory.java @@ -0,0 +1,532 @@ +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.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) { + Animation clone = new Animation(); + clone.readFromNBT(animation.writeToNBT()); + clone.id = -1; + while (itemData.containsKey(clone.name)) clone.name += "_"; + PacketClient.sendClient(new AnimationSavePacket(clone.writeToNBT())); + } + } + + @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 7d1fa84be..c7f1b7ce4 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java @@ -5,6 +5,7 @@ import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket; import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket; 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 net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiYesNo; import net.minecraft.client.gui.GuiYesNoCallback; @@ -37,15 +38,21 @@ import java.util.Vector; public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrollData, ICustomScrollListener, ITextfieldListener, IGuiData, ISubGuiListener, GuiYesNoCallback { private GuiCustomScroll scrollAnimations; - private HashMap data = new HashMap(); + private HashMap customData = new HashMap(); + private HashMap builtInData = new HashMap(); private Animation animation = new Animation(); public boolean playingAnimation = false; private long prevTick; private String selected = null; private String search = ""; - public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save) { - super(npc); + // Toggle between Custom (false) and Built-in (true) animations + private boolean showingBuiltIn = false; + // Track if current animation is built-in + private boolean currentIsBuiltIn = false; + + public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save, boolean hasMenuNpc) { + super(npc, hasMenuNpc); this.setSave(save); this.xOffset = -148 + 70; this.yOffset = -170 + 137; @@ -58,8 +65,23 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol public void initGui() { super.initGui(); - 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")); + // 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"; + 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 + 60, 45, 20, "gui.add")); + this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 84, 45, 20, "gui.remove")); + } if (scrollAnimations == null) { scrollAnimations = new GuiCustomScroll(this, 0, 0); @@ -68,13 +90,23 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol scrollAnimations.guiLeft = guiLeft + 220; scrollAnimations.guiTop = guiTop + 4; addScroll(scrollAnimations); + + // Search field addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search)); - if (animation.id == -1) + // Update scroll list based on current view + scrollAnimations.setList(getSearchList()); + + if (animation.id == -1 && !currentIsBuiltIn) return; - addLabel(new GuiNpcLabel(10, "ID", guiLeft + 368, guiTop + 192)); - addLabel(new GuiNpcLabel(11, animation.id + "", guiLeft + 368, guiTop + 192 + 10)); + // ID label - only for custom animations + if (!currentIsBuiltIn) { + addLabel(new GuiNpcLabel(10, "ID", guiLeft + 368, guiTop + 192)); + addLabel(new GuiNpcLabel(11, animation.id + "", guiLeft + 368, guiTop + 192 + 10)); + } else { + addLabel(new GuiNpcLabel(10, "gui.builtin", guiLeft + 368, guiTop + 192)); + } AnimationData data = npc.display.animationData; if (!playingAnimation) { @@ -90,12 +122,13 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol } } - if (animation != null) { + // Edit button - only for custom animations + if (animation != null && !currentIsBuiltIn) { this.addButton(new GuiNpcButton(100, guiLeft + 10, guiTop + 192, 45, 20, "gui.edit")); } String animTexture = "customnpcs:textures/gui/animation.png"; - int playButtonOffsetX = 140; + int playButtonOffsetX = currentIsBuiltIn ? 80 : 140; if (animation != null && !animation.frames.isEmpty()) { if (!this.playingAnimation || data.animation.paused) {//Play this.addLabel(new GuiNpcLabel(90, data.animation.paused ? "animation.paused" : "animation.stopped", guiLeft + playButtonOffsetX - 15, guiTop + 198)); @@ -151,12 +184,17 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol } } + private HashMap getCurrentData() { + return showingBuiltIn ? builtInData : customData; + } + private List getSearchList() { + HashMap data = getCurrentData(); if (search.isEmpty()) { - return new ArrayList(this.data.keySet()); + return new ArrayList(data.keySet()); } List list = new ArrayList(); - for (String name : this.data.keySet()) { + for (String name : data.keySet()) { if (name.toLowerCase().contains(search)) list.add(name); } @@ -167,16 +205,40 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol protected void actionPerformed(GuiButton guibutton) { GuiNpcButton button = (GuiNpcButton) guibutton; - if (button.id == 0) { + if (button.id == 66) { + mc.displayGuiScreen(new GuiAnimationDirectory(npc)); + return; + } + + // Toggle button + if (button.id == 10) { + showingBuiltIn = !showingBuiltIn; + // Clear selection and search when switching views + selected = null; + search = ""; + animation = new Animation(); + currentIsBuiltIn = false; + playingAnimation = false; + scrollAnimations.clear(); + // Re-request data to ensure both lists are populated + PacketClient.sendClient(new AnimationsGetPacket()); + initGui(); + return; + } + + // Add button - only for custom + if (button.id == 0 && !showingBuiltIn) { save(); String name = "New"; - while (data.containsKey(name)) + while (customData.containsKey(name)) name += "_"; Animation animation = new Animation(-1, name); PacketClient.sendClient(new AnimationSavePacket(animation.writeToNBT())); } - if (button.id == 1) { - if (data.containsKey(scrollAnimations.getSelected())) { + + // Remove button - only for custom + if (button.id == 1 && !showingBuiltIn) { + if (customData.containsKey(scrollAnimations.getSelected())) { GuiYesNo guiyesno = new GuiYesNo(this, scrollAnimations.getSelected(), StatCollector.translateToLocal("gui.delete"), 1); displayGuiScreen(guiyesno); } @@ -204,7 +266,8 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol data.animation.paused = false; } - if (guibutton.id == 100) { + // Edit button - only for custom + if (guibutton.id == 100 && !currentIsBuiltIn) { NoppesUtil.openGUI(player, new GuiNPCEditAnimation(this, this.animation, npc)); } @@ -215,6 +278,10 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol public void setGuiData(NBTTagCompound compound) { this.animation = new Animation(); animation.readFromNBT(compound); + + // Check if this is a built-in animation + currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn"); + setSelected(animation.name); npc.display.animationData.setAnimation(this.animation); this.playingAnimation = false; @@ -225,7 +292,13 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol @Override public void setData(Vector list, HashMap data, EnumScrollData type) { String name = scrollAnimations.getSelected(); - this.data = data; + + if (type == EnumScrollData.ANIMATIONS) { + this.customData = data; + } else if (type == EnumScrollData.BUILTIN_ANIMATIONS) { + this.builtInData = data; + } + scrollAnimations.setList(getSearchList()); if (name != null) @@ -242,28 +315,40 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { if (guiCustomScroll.id == 0) { selected = scrollAnimations.getSelected(); - PacketClient.sendClient(new AnimationGetPacket(data.get(selected))); + HashMap data = getCurrentData(); + + if (showingBuiltIn) { + // Fetch built-in animation by name + PacketClient.sendClient(new BuiltInAnimationGetPacket(selected)); + } else { + // Fetch custom animation by ID + if (data.containsKey(selected)) { + PacketClient.sendClient(new AnimationGetPacket(data.get(selected))); + } + } } } public void save() { - if (selected != null && data.containsKey(selected) && animation != null) { + // Only save custom animations + if (selected != null && customData.containsKey(selected) && animation != null && !currentIsBuiltIn) { PacketClient.sendClient(new AnimationSavePacket(animation.writeToNBT())); } } @Override public void unFocused(GuiNpcTextField guiNpcTextField) { - if (animation.id == -1) + // Don't allow renaming built-in animations + if (animation.id == -1 || currentIsBuiltIn) return; if (guiNpcTextField.id == 0) { String name = guiNpcTextField.getText(); - if (!name.isEmpty() && !data.containsKey(name)) { + if (!name.isEmpty() && !customData.containsKey(name)) { String old = animation.name; - data.remove(animation.name); + customData.remove(animation.name); animation.name = name; - data.put(animation.name, animation.id); + customData.put(animation.name, animation.id); selected = name; scrollAnimations.replace(old, animation.name); } @@ -280,10 +365,12 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol if (!result) return; if (id == 1) { - if (data.containsKey(scrollAnimations.getSelected())) { - PacketClient.sendClient(new AnimationRemovePacket(data.get(selected))); + // Only delete custom animations + if (customData.containsKey(scrollAnimations.getSelected()) && !showingBuiltIn) { + PacketClient.sendClient(new AnimationRemovePacket(customData.get(selected))); scrollAnimations.clear(); animation = new Animation(); + currentIsBuiltIn = false; initGui(); } } 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/GuiNPCManageFactions.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java index 246e528f3..59adbdd91 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java @@ -85,11 +85,13 @@ public class GuiNPCManageFactions extends GuiNPCInterface2 implements IScrollDat addLabel(new GuiNpcLabel(3, "faction.hidden", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(3, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.hideFaction ? 1 : 0)); + getButton(3).setHoverText("faction.hidden.hover"); y += 23; addLabel(new GuiNpcLabel(4, "faction.attacked", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(4, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.getsAttacked ? 1 : 0)); + getButton(4).setHoverText("faction.attacked.hover"); y += 23; diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageLinked.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageLinked.java index e07d2583c..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) { @@ -338,21 +348,21 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, // Health label = StatCollector.translateToLocal("stats.health") + ": "; - value = String.valueOf(npc.stats.maxHealth); + value = "" + npc.stats.maxHealth; fontRendererObj.drawString(label, xLabel, y, 0x29d6b9, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; // Damage (using getAttackStrength) label = StatCollector.translateToLocal("stats.meleestrength") + ": "; - value = String.valueOf(npc.stats.getAttackStrength()); + value = "" + npc.stats.getAttackStrength(); fontRendererObj.drawString(label, xLabel, y, 0xff5714, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; // Attack Speed label = StatCollector.translateToLocal("stats.meleespeed") + ": "; - value = String.valueOf(npc.stats.attackSpeed); + value = "" + npc.stats.attackSpeed; fontRendererObj.drawString(label, xLabel, y, 0xf7ca28, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; @@ -381,7 +391,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, // Walk Speed label = StatCollector.translateToLocal("stats.speed") + ": "; - value = String.valueOf(npc.ais.getWalkingSpeed()); + value = "" + npc.ais.getWalkingSpeed(); fontRendererObj.drawString(label, xLabel, y, 0xffae0d, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; @@ -415,7 +425,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, // Version label = StatCollector.translateToLocal("display.version") + ": "; - value = String.valueOf(linkedItem.version); + value = "" + linkedItem.version; fontRendererObj.drawString(label, xLabel, y, labelColor, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; @@ -423,7 +433,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, // Max Stack Size labelColor = 0xff5714; label = StatCollector.translateToLocal("display.maxStack") + ": "; - value = String.valueOf(linkedItem.stackSize); + value = "" + linkedItem.stackSize; fontRendererObj.drawString(label, xLabel, y, labelColor, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; @@ -431,7 +441,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, // Dig Speed labelColor = 0xf7ca28; label = StatCollector.translateToLocal("display.digSpeed") + ": "; - value = String.valueOf(linkedItem.digSpeed); + value = "" + linkedItem.digSpeed; fontRendererObj.drawString(label, xLabel, y, labelColor, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; @@ -498,14 +508,14 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData, labelColor = 0x7cff54; // isTool label = StatCollector.translateToLocal("display.isTool") + ": "; - value = String.valueOf(linkedItem.isTool).toUpperCase(); + value = ("" + linkedItem.isTool).toUpperCase(); fontRendererObj.drawString(label, xLabel, y, labelColor, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; // isNormalItem label = StatCollector.translateToLocal("display.isNormalItem") + ": "; - value = String.valueOf(linkedItem.isNormalItem).toUpperCase(); + value = ("" + linkedItem.isNormalItem).toUpperCase(); fontRendererObj.drawString(label, xLabel, y, labelColor, false); fontRendererObj.drawString(value, xValue, y, valueColor, false); y += 15; 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 new file mode 100644 index 000000000..b0398d48a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -0,0 +1,701 @@ +package noppes.npcs.client.gui.global; + +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.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; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; +import net.minecraft.client.gui.GuiButton; +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.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 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; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumScrollData; +import noppes.npcs.controllers.data.AnimationData; +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, + 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 customData = new HashMap<>(); + private HashMap builtInData = new HashMap<>(); + private String selected = 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; + + // ==================== PENDING VARIANT ==================== + private String pendingTypeId = null; + + // ==================== PREVIEW ==================== + private AbilityPreviewExecutor previewExecutor; + private long prevTick = 0; + + public GuiNpcManageAbilities(EntityNPCInterface npc, boolean hasMenuNpc) { + super(npc, hasMenuNpc); + + // Layout offset + this.xOffset = -148 + 110; + this.yOffset = -170 + 167; + + // Initialize preview executor + previewExecutor = new AbilityPreviewExecutor(); + previewExecutor.setParentGui(this); + + // Request ability data from server (sends both custom and built-in) + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + + // Enable animation data + AnimationData data = npc.display.animationData; + data.setEnabled(true); + } + + @Override + public void initGui() { + super.initGui(); + + // 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); + + // 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); + + 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 (right side) + if (scroll == null) { + scroll = new GuiCustomScroll(this, SCROLL_MAIN); + scroll.setSize(143, 185); + } + scroll.guiLeft = guiLeft + 220; + scroll.guiTop = guiTop + 4; + addScroll(scroll); + + scroll.setList(getSearchList()); + if (selected != null) { + scroll.setSelected(selected); + } + + // Search bar + addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search)); + + // 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])); + } + + // 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"; + int playButtonOffsetX = 60; + + 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(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 { + 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) { + 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() { + HashMap data = getCurrentData(); + List list = new ArrayList<>(); + 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; + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + // IMPORTANT: Set NPC rotation BEFORE ticking entities + // This ensures anchor point calculations use the correct facing direction + npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; + npc.prevRotationYaw = npc.rotationYaw = NPC_FACING_YAW; + npc.prevRotationYawHead = npc.rotationYawHead = NPC_FACING_YAW; + + // Tick preview executor (entities will use the rotation set above) + tickPreview(); + + // Draw base (includes 3D preview via parent class) + super.drawScreen(mouseX, mouseY, partialTicks); + + // Draw status text + if (previewExecutor.isActive()) { + String status = previewExecutor.getStatusString(); + fontRendererObj.drawString(status, guiLeft + 12, guiTop + 175, 0xFFFFFF); + } + } + + /** + * Tick the preview executor and animations. + */ + private void tickPreview() { + if (previewExecutor.isPlaying() && !previewExecutor.isPaused()) { + long time = mc.theWorld != null ? mc.theWorld.getTotalWorldTime() : System.currentTimeMillis() / 50; + if (time != prevTick) { + // Advance animation + npc.display.animationData.increaseTime(); + + // Tick preview + previewExecutor.tick(); + + // Sync telegraph to GUI for rendering + setPreviewTelegraph(previewExecutor.getTelegraph()); + + prevTick = time; + + // Check if preview finished + if (!previewExecutor.isActive()) { + initGui(); + } + } + } + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + super.actionPerformed(guibutton); + + int id = guibutton.id; + + // 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 == BTN_REMOVE && !showingBuiltIn && selected != null) { + GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), CONFIRM_REMOVE_ABILITY); + displayGuiScreen(guiyesno); + } else if (id == BTN_EDIT && !showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) { + // Edit + previewExecutor.stop(); + setSubGui(selectedAbility.createConfigGui(this)); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + 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()); + } + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == SCROLL_MAIN) { + String newSelection = scroll.getSelected(); + if (newSelection != null && !newSelection.equals(selected)) { + previewExecutor.stop(); + selected = newSelection; + + 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)); + } + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + 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)); + } + } + } + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.CUSTOM_ABILITIES) { + String prevSelected = scroll != null ? scroll.getSelected() : null; + this.customData = data; + if (!showingBuiltIn && !showingChained && scroll != null) { + scroll.setList(getSearchList()); + if (prevSelected != null && customData.containsKey(prevSelected)) { + scroll.setSelected(prevSelected); + } + } + initGui(); + } else if (type == EnumScrollData.BUILTIN_ABILITIES) { + this.builtInData = data; + if (showingBuiltIn && scroll != null) { + scroll.setList(getSearchList()); + if (selected != null && builtInData.containsKey(selected)) { + scroll.setSelected(selected); + } + } + initGui(); + } 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); + } + } + initGui(); + } + } + + @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) { + selected = selectedAbility.getName(); + if (scroll != null) { + scroll.setSelected(selected); + } + } + previewExecutor.stop(); + initGui(); + } + + @Override + public void setSelected(String selected) { + this.selected = selected; + if (scroll != null) { + scroll.setSelected(selected); + } + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiChainedAbilityConfig) { + handleChainConfigClosed(); + initGui(); + return; + } + if (subgui instanceof SubGuiAbilityVariantSelect) { + if (handleVariantSelectClosed((SubGuiAbilityVariantSelect) subgui)) return; + } else if (subgui instanceof SubGuiAbilityTypeSelect) { + if (handleTypeSelectClosed((SubGuiAbilityTypeSelect) subgui)) return; + } else if (subgui instanceof SubGuiDuplicateNameConfirm) { + if (handleDuplicateNameClosed((SubGuiDuplicateNameConfirm) subgui)) return; + } else if (pendingSaveAbility != null) { + if (handlePendingSave()) return; + } + initGui(); + } + + 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(); + previewExecutor.stop(); + setSubGui(ability.createConfigGui(this)); + } + + private boolean hasDuplicateName(Ability ability) { + String name = ability.getName(); + if (name == null || name.isEmpty()) 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 + public void confirmClicked(boolean result, int id) { + NoppesUtil.openGUI(player, this); + if (!result) return; + + if (id == CONFIRM_REMOVE_ABILITY && selected != null) { + PacketClient.sendClient(new CustomAbilityRemovePacket(selected)); + scroll.clear(); + selected = null; + selectedAbility = null; + initGui(); + } else if (id == CONFIRM_REMOVE_CHAIN && selected != null) { + PacketClient.sendClient(new ChainedAbilityRemovePacket(selected)); + scroll.clear(); + selected = null; + selectedChain = null; + initGui(); + } + } + + @Override + public void onAbilitySaved(Ability ability) { + // Defer save until subGuiClosed where we can check for duplicate names + pendingSaveAbility = ability; + } + + @Override + public void onChainedAbilitySaved(ChainedAbility chain) { + pendingSaveChain = chain; + } + + @Override + public void unFocused(GuiNpcTextField textfield) { + // Search field handling is done in keyTyped + } + + @Override + public void save() { + // Nothing to save - abilities are saved individually via packets + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + // Stop preview when GUI closes + previewExecutor.stop(); + } +} 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/GuiNpcManageRecipes.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageRecipes.java index 1b83b0639..40df2d463 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageRecipes.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageRecipes.java @@ -12,7 +12,7 @@ import net.minecraft.util.StatCollector; import noppes.npcs.client.CustomNpcResourceListener; import noppes.npcs.client.NoppesUtil; import noppes.npcs.client.gui.SubGuiNpcAvailability; -import noppes.npcs.client.gui.script.GuiScriptRecipe; +import noppes.npcs.client.gui.script.GuiScriptInterface; import noppes.npcs.client.gui.util.GuiButtonBiDirectional; import noppes.npcs.client.gui.util.GuiContainerNPCInterface2; import noppes.npcs.client.gui.util.GuiCustomScroll; @@ -31,6 +31,7 @@ import noppes.npcs.constants.EnumScrollData; import noppes.npcs.containers.ContainerManageRecipes; import noppes.npcs.controllers.data.RecipeAnvil; import noppes.npcs.controllers.data.RecipeCarpentry; +import noppes.npcs.controllers.data.RecipeScript; import noppes.npcs.entity.EntityNPCInterface; import org.lwjgl.opengl.GL11; @@ -222,15 +223,9 @@ public class GuiNpcManageRecipes extends GuiContainerNPCInterface2 implements IS if (button.id == 16) { save(); if (container.width == 1) { - GuiScriptRecipe gui = new GuiScriptRecipe(this, container.recipeAnvil); - gui.setWorldAndResolution(mc, width, height); - gui.initGui(); - mc.currentScreen = gui; + GuiScriptInterface.open(this, new RecipeScript(container.recipeAnvil.id, true)); } else if (!container.recipe.isGlobal) { - GuiScriptRecipe gui = new GuiScriptRecipe(this, container.recipe); - gui.setWorldAndResolution(mc, width, height); - gui.initGui(); - mc.currentScreen = gui; + GuiScriptInterface.open(this, new RecipeScript(container.recipe.id, false)); } } } 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 41e105a38..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; @@ -90,19 +99,23 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I ArrayList list = new ArrayList<>(); Set keySet = this.spawn.spawnCompounds.keySet(); for (int i : keySet) { - list.add(String.valueOf(i)); + list.add("" + i); } this.spawnEntryScroll.setList(list); 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, "-")); - GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, String.valueOf(selected)); + 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"); } } @@ -215,8 +228,8 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I } if (textfield.id == 25 && this.spawnEntryScroll.hasSelected()) { int selected = Integer.parseInt(spawnEntryScroll.getSelected()); - if (spawnEntryScroll.getList().contains(String.valueOf(textfield.getInteger()))) { - textfield.setText(String.valueOf(selected)); + if (spawnEntryScroll.getList().contains("" + textfield.getInteger())) { + textfield.setText("" + selected); return; } NBTTagCompound compound = spawn.spawnCompounds.get(selected); 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..d36727aad 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java +++ b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java @@ -173,7 +173,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,12 +215,14 @@ 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; @@ -260,8 +263,8 @@ 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 == 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..ee6a6fe51 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java @@ -113,10 +113,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 +218,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); } 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..201abfcd0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java @@ -0,0 +1,712 @@ +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.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; + + if (ability != null && ability.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 227f7cecc..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,9 +10,11 @@ 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.script.GuiScriptLinkedItem; +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; import noppes.npcs.client.gui.util.GuiNpcButton; @@ -25,6 +27,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.controllers.data.LinkedItem; +import noppes.npcs.controllers.data.LinkedItemScript; import org.lwjgl.opengl.GL11; public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListener, GuiYesNoCallback, ISubGuiListener { @@ -35,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; @@ -119,8 +122,8 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe GuiNpcTextField digSpeedField = new GuiNpcTextField(12, this, x + 110, y, 50, 20, "" + linkedItem.digSpeed); digSpeedField.setIntegersOnly().setMinMaxDefault(0, 20, 1); addTextField(digSpeedField); - GuiNpcTextField attackSpeedField = new GuiNpcTextField(14, this, x +165, y, 50, 20, "" +linkedItem.attackSpeed); - attackSpeedField.setIntegersOnly().setMinMaxDefault(0,999999999,20); + GuiNpcTextField attackSpeedField = new GuiNpcTextField(14, this, x + 165, y, 50, 20, "" + linkedItem.attackSpeed); + attackSpeedField.setIntegersOnly().setMinMaxDefault(0, 999999999, 20); addTextField(attackSpeedField); y += spacing; @@ -157,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) @@ -285,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); @@ -307,10 +337,10 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe return; } else if (id == -3) { PacketClient.sendClient(new LinkedItemSavePacket(linkedItem.writeToNBT(false), originalName)); - GuiScriptLinkedItem scriptGUI = new GuiScriptLinkedItem((GuiNPCManageLinked) this.parent, linkedItem); - scriptGUI.setWorldAndResolution(mc, width, height); - scriptGUI.initGui(); - mc.currentScreen = scriptGUI; + 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. @@ -383,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(); } } @@ -431,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()); } } @@ -474,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 8295618dd..36370eb92 100644 --- a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNPCGlobalMainMenu.java +++ b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNPCGlobalMainMenu.java @@ -38,6 +38,8 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 { private GuiNpcSquareButton tagButton; private GuiNpcSquareButton effectsButton; private GuiNpcSquareButton magicsButton; + private GuiNpcSquareButton abilitiesButton; + private GuiNpcSquareButton auctionsButton; public GuiNPCGlobalMainMenu(EntityNPCInterface npc) { super(npc, 5); @@ -94,6 +96,11 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 { registerButton(magicsButton = new GuiNpcSquareButton(20, 0, 0, 20, "global.magic", 0xFF333333)); magicsButton.setIconPos(24, 24, 48, 56).setIconTexture(specialIcons); + registerButton(abilitiesButton = new GuiNpcSquareButton(21, 0, 0, 20, "global.abilities", 0xFF333333)); + abilitiesButton.setIconPos(24, 24, 72, 56).setIconTexture(specialIcons); + + registerButton(auctionsButton = new GuiNpcSquareButton(22, 0, 0, 20, "global.auction", 0xFF333333)); + auctionsButton.setIconPos(24, 24, 96, 56).setIconTexture(specialIcons); // Layout composite buttons optimally. layoutButtons(); @@ -236,6 +243,12 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 { if (id == 19) { NoppesUtil.requestOpenGUI(EnumGuiType.ManageEffects); } + if (id == 21) { + NoppesUtil.requestOpenGUI(EnumGuiType.ManageAbilities); + } + if (id == 22) { + NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction); + } } @Override diff --git a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java index 6452145a6..ff46f9174 100644 --- a/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java +++ b/src/main/java/noppes/npcs/client/gui/mainmenu/GuiNpcAdvanced.java @@ -9,6 +9,7 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.NoppesStringUtils; import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.advanced.GuiNPCAbilities; import noppes.npcs.client.gui.advanced.GuiNPCAdvancedLinkedNpc; import noppes.npcs.client.gui.advanced.GuiNPCDialogNpcOptions; import noppes.npcs.client.gui.advanced.GuiNPCFactionSetup; @@ -24,8 +25,8 @@ import noppes.npcs.client.gui.roles.GuiNpcConversation; import noppes.npcs.client.gui.roles.GuiNpcFollowerJob; import noppes.npcs.client.gui.roles.GuiNpcGuard; import noppes.npcs.client.gui.roles.GuiNpcHealer; -import noppes.npcs.client.gui.roles.GuiNpcSpawner; import noppes.npcs.client.gui.roles.GuiNpcMount; +import noppes.npcs.client.gui.roles.GuiNpcSpawner; import noppes.npcs.client.gui.roles.GuiNpcTransporter; import noppes.npcs.client.gui.util.GuiNPCInterface2; import noppes.npcs.client.gui.util.GuiNpcButton; @@ -48,8 +49,8 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData { super.initGui(); int y = guiTop + 10; this.addButton(new GuiNpcButton(3, guiLeft + 85 + 160, y, 52, 20, "selectServer.edit")); - this.addButton(new GuiNpcButton(8, guiLeft + 85, y, 155, 20, new String[]{"role.none", "role.trader", "role.follower", "role.bank", "role.transporter", "role.mailman", NoppesStringUtils.translate("role.companion", "(WIP)"), "role.mount"}, npc.advanced.role.ordinal())); - getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman); + this.addButton(new GuiNpcButton(8, guiLeft + 85, y, 155, 20, new String[]{"role.none", "role.trader", "role.follower", "role.bank", "role.transporter", "role.mailman", NoppesStringUtils.translate("role.companion", "(WIP)"), "role.mount", "role.auctioneer"}, npc.advanced.role.ordinal())); + getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman && npc.advanced.role != EnumRoleType.Auctioneer); this.addButton(new GuiNpcButton(4, guiLeft + 85 + 160, y += 22, 52, 20, "selectServer.edit")); this.addButton(new GuiNpcButton(5, guiLeft + 85, y, 155, 20, new String[]{"job.none", "job.bard", "job.healer", "job.guard", "job.itemgiver", "role.follower", "job.spawner", "job.conversation", "job.chunkloader"}, npc.advanced.job.ordinal())); @@ -69,6 +70,7 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData { this.addButton(new GuiNpcButton(15, guiLeft + 208, y, 190, 20, "advanced.marks")); this.addButton(new GuiNpcButton(16, guiLeft + 15, y += 22, 190, 20, "menu.magics")); + this.addButton(new GuiNpcButton(17, guiLeft + 208, y, 190, 20, "menu.abilities")); } @Override @@ -82,7 +84,7 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData { hasChanges = true; npc.advanced.setRole(button.getValue()); - getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman); + getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman && npc.advanced.role != EnumRoleType.Auctioneer); } if (button.id == 4) { save(); @@ -130,6 +132,10 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData { save(); NoppesUtil.openGUI(player, new GuiNPCMagic(npc)); } + if (button.id == 17) { + save(); + NoppesUtil.openGUI(player, new GuiNPCAbilities(npc)); + } } @Override diff --git a/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java b/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java new file mode 100644 index 000000000..b61c1e1b7 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java @@ -0,0 +1,383 @@ +package noppes.npcs.client.gui.player; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +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). + */ +@SideOnly(Side.CLIENT) +public class AuctionTooltipHandler { + + /** + * Handle ItemTooltipEvent - append auction info to the end of the tooltip. + */ + public static void onItemTooltip(ItemTooltipEvent event) { + if (event.itemStack == null) return; + + Minecraft mc = Minecraft.getMinecraft(); + if (mc == null || mc.currentScreen == null) return; + + GuiScreen screen = mc.currentScreen; + + if (screen instanceof GuiAuctionListing) { + addListingTooltip((GuiAuctionListing) screen, event.itemStack, event.toolTip); + } else if (screen instanceof GuiAuctionTrades) { + 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); + } + } + + /** + * Find the slot in the container whose getStack() returns the exact same ItemStack reference. + * This avoids the duplicate item bug where ItemStack.areItemStacksEqual matches the wrong listing. + */ + private static Slot findHoveredSlot(GuiContainer gui, ItemStack stack) { + if (stack == null) return null; + for (Object obj : gui.inventorySlots.inventorySlots) { + Slot slot = (Slot) obj; + if (slot.getHasStack() && slot.getStack() == stack) { + return slot; + } + } + return null; + } + + // ========== Listing Page ========== + + private static void addListingTooltip(GuiAuctionListing gui, ItemStack stack, List tooltip) { + Slot slot = findHoveredSlot(gui, stack); + if (slot == null || !(slot instanceof SlotAuctionDisplay)) return; + + ContainerAuctionListing container = gui.getListingContainer(); + if (container == null) return; + + int displayIndex = slot.getSlotIndex(); + AuctionListing listing = container.getListingAt(displayIndex); + if (listing == null) return; + + tooltip.add(""); + + // Seller + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller") + .replace("%s", EnumChatFormatting.WHITE + listing.sellerName)); + + // Current bid or starting price + 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")); + } + + // Buyout price + if (listing.hasBuyout()) { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout") + .replace("%s", EnumChatFormatting.GREEN + AuctionFormatUtil.formatCurrencyWithName(listing.buyoutPrice))); + } + + // Time remaining + 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); + } + + // ========== Trades Page ========== + + private static void addTradesTooltip(GuiAuctionTrades gui, ItemStack stack, List tooltip) { + Slot slot = findHoveredSlot(gui, stack); + if (slot == null || !(slot instanceof SlotAuctionDisplay)) return; + + ContainerAuctionTrades container = gui.getTradesContainer(); + if (container == null) return; + + int displayIndex = slot.getSlotIndex(); + + // Check listings first (selling or bidding) + AuctionListing listing = container.getListingAt(displayIndex); + if (listing != null) { + if (container.isSellingAt(displayIndex)) { + addSellingTooltip(listing, tooltip); + } else if (container.isBiddingAt(displayIndex)) { + addBiddingTooltip(listing, tooltip); + } + return; + } + + // Check claims + AuctionClaim claim = container.getClaimAt(displayIndex); + if (claim != null) { + addClaimTooltip(claim, tooltip); + } + } + + private static void addSellingTooltip(AuctionListing listing, List tooltip) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.selling")); + + 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.GRAY + StatCollector.translateToLocal("auction.noBids")); + } + + 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.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel")); + } + + private static void addBiddingTooltip(AuctionListing listing, List tooltip) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding")); + + 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)); + + 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.GRAY + StatCollector.translateToLocal("auction.trades.clickToRebid")); + } + + private static void addClaimTooltip(AuctionClaim claim, List tooltip) { + tooltip.add(""); + + switch (claim.type) { + case ITEM: + if (claim.isReturned) { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expired")); + } else { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.won")); + } + break; + case CURRENCY: + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.sold")); + 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)); + } + break; + case REFUND: + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.outbid")); + if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy") + .replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName)); + } + break; + } + + // Amount for currency claims + if (claim.type.isCurrency()) { + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount") + .replace("%s", EnumChatFormatting.GOLD + AuctionFormatUtil.formatCurrencyWithName(claim.currency))); + } + + // Expiration + int expirationDays = AuctionClientConfig.getClaimExpirationDays(); + long daysLeft = claim.getDaysUntilExpiration(expirationDays); + if (daysLeft <= 1) { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.claim.expiresSoon")); + } else { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.expires") + .replace("%s", "" + daysLeft)); + } + + tooltip.add(""); + + // Rebid option for REFUND claims with item + if (claim.type == EnumClaimType.REFUND && claim.item != null) { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid")); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund")); + } else { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim")); + } + } + + // ========== Sell Page ========== + + private static void addSellTooltip(GuiAuctionSell gui, ItemStack stack, List tooltip) { + Slot slot = findHoveredSlot(gui, stack); + if (slot == null) return; + + ContainerAuctionSell container = (ContainerAuctionSell) gui.inventorySlots; + if (container == null) return; + + if (container.isSellSlot(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.isPlayerInventorySlot(slot.slotNumber)) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne")); + } + } + + // ========== Global Manage Auction ========== + + 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")); + } + } + } + + 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))); + } + tooltip.add(""); + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim")); + } + +} diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAnvilRecipes.java b/src/main/java/noppes/npcs/client/gui/player/GuiAnvilRecipes.java index 683e21798..00551911a 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAnvilRecipes.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAnvilRecipes.java @@ -237,7 +237,7 @@ public class GuiAnvilRecipes extends GuiNPCInterface { fontRendererObj.drawString(percentText, percentTextX, percentTextY, CustomNpcResourceListener.DefaultTextColor); // Add text overlay for percentage with the full unrounded value. if (func_146978_c(percentTextX - guiLeft, percentTextY - guiTop, percentWidth, fontRendererObj.FONT_HEIGHT, mouseX, mouseY)) { - textOverlays.add(new TextOverlayData(percentTextX, percentTextY, percentWidth, fontRendererObj.FONT_HEIGHT, String.valueOf(recipe.getRepairPercentage()))); + textOverlays.add(new TextOverlayData(percentTextX, percentTextY, percentWidth, fontRendererObj.FONT_HEIGHT, "" + recipe.getRepairPercentage())); } if (!recipe.availability.isDefault()) { @@ -303,7 +303,7 @@ public class GuiAnvilRecipes extends GuiNPCInterface { int xpBoxWidth = scaledTextWidth; int xpBoxHeight = fontRendererObj.FONT_HEIGHT; if (func_146978_c(xpTextX - guiLeft, xpTextY - guiTop, xpBoxWidth, xpBoxHeight, mouseX, mouseY)) { - textOverlays.add(new TextOverlayData(xpTextX, xpTextY, xpBoxWidth, xpBoxHeight, String.valueOf(recipe.getXpCost()))); + textOverlays.add(new TextOverlayData(xpTextX, xpTextY, xpBoxWidth, xpBoxHeight, "" + recipe.getXpCost())); } } @@ -326,7 +326,7 @@ public class GuiAnvilRecipes extends GuiNPCInterface { private String formatXpCost(int xp) { if (xp < 1000) { - return String.valueOf(xp); + return "" + xp; } double xpK = xp / 1000.0; if (xpK == (int) xpK) { diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java new file mode 100644 index 000000000..5b74ad3c3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionBidding.java @@ -0,0 +1,316 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.inventory.Slot; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.AuctionClientConfig; +import noppes.npcs.client.gui.util.GuiAuctionNavButton; +import noppes.npcs.client.gui.util.IGuiData; +import noppes.npcs.client.gui.util.ISubGuiListener; +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; +import java.util.List; + +/** + * GUI for viewing and bidding on a specific auction listing. + * Shows item, auction info, and bid/buyout buttons. + */ +public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiListener, IGuiData { + // Icons + private static final ResourceLocation ICON_BID = new ResourceLocation("customnpcs", "textures/items/npcCoinDiamond.png"); + private static final ResourceLocation ICON_BUYOUT = new ResourceLocation("customnpcs", "textures/items/npcCoinEmerald.png"); + + // Layout + private int itemSlotX = 70; + private int itemSlotY = 75; + private int btnBidX = 58; + private int btnBidY = 110; + private int btnBuyoutX = 82; + private int btnBuyoutY = 110; + private int infoX = 105; + private int infoY = 50; + + // Button IDs + private int btnBidId = 200; + private int btnBuyoutId = 201; + + private final ContainerAuctionBidding biddingContainer; + private AuctionListing listing; + private long playerBalance = 0; + private boolean dataLoaded = false; + private boolean isOwnListing = false; + + // Buttons + private GuiAuctionNavButton btnBid; + private GuiAuctionNavButton btnBuyout; + + public GuiAuctionBidding(EntityNPCInterface npc, ContainerAuctionBidding container) { + super(npc, container); + this.biddingContainer = container; + } + + @Override + public void initGui() { + super.initGui(); + + // Bid button (diamond coin) + btnBid = new GuiAuctionNavButton(btnBidId, guiLeft + btnBidX, guiTop + btnBidY, + "auction.bid.place", ICON_BID); + addButton(btnBid); + + // Buy Now button (emerald coin) - only visible if listing has buyout + btnBuyout = new GuiAuctionNavButton(btnBuyoutId, guiLeft + btnBuyoutX, guiTop + btnBuyoutY, + "auction.bid.buyout", ICON_BUYOUT); + addButton(btnBuyout); + + updateButtonState(); + } + + @Override + protected int getCurrentPage() { + // Not a standard page - return -1 so nav buttons aren't selected + return -1; + } + + /** + * Update button visibility based on listing state + */ + private void updateButtonState() { + if (listing == null) { + if (btnBid != null) btnBid.setVisible(false); + if (btnBuyout != null) btnBuyout.setVisible(false); + return; + } + + // Hide buttons for own listings - can view but not bid/buy + if (isOwnListing) { + if (btnBid != null) btnBid.setVisible(false); + if (btnBuyout != null) btnBuyout.setVisible(false); + return; + } + + // Bid button visible for other players' listings + if (btnBid != null) btnBid.setVisible(true); + + // Buyout button only if listing has buyout + if (btnBuyout != null) { + btnBuyout.setVisible(listing.hasBuyout()); + } + } + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + + if (listing == null) return; + + if (button.id == btnBidId) { + openBidSubGui(); + } else if (button.id == btnBuyoutId) { + if (listing.hasBuyout()) { + openBuyNowSubGui(); + } + } + } + + private void openBidSubGui() { + if (listing == null) return; + long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement()); + setSubGui(new SubGuiAuctionBid(listing.id, minBid, listing.buyoutPrice, playerBalance)); + } + + private void openBuyNowSubGui() { + if (listing == null || !listing.hasBuyout()) return; + setSubGui(new SubGuiAuctionBuyNow(listing.id, listing.buyoutPrice, playerBalance)); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiAuctionBid) { + SubGuiAuctionBid bidGui = (SubGuiAuctionBid) subgui; + if (bidGui.wasSuccessful()) { + // Bid placed - go to listings + AuctionActionPacket.openPage(PAGE_LISTINGS); + } + } else if (subgui instanceof SubGuiAuctionBuyNow) { + SubGuiAuctionBuyNow buyGui = (SubGuiAuctionBuyNow) subgui; + if (buyGui.wasSuccessful()) { + // Bought out - go to my trades + AuctionActionPacket.openPage(PAGE_CLAIMS); + } + } + } + + // ========== Data Handling ========== + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("BiddingData")) { + playerBalance = compound.getLong("Balance"); + isOwnListing = compound.getBoolean("IsOwnListing"); + + if (compound.hasKey("Listing")) { + listing = AuctionListing.fromNBT(compound.getCompoundTag("Listing")); + biddingContainer.setListing(listing); + } + + dataLoaded = true; + updateButtonState(); + } + } + + // ========== Drawing ========== + + @Override + protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) { + // Draw item slot background + drawAuctionSlot(guiLeft + itemSlotX, guiTop + itemSlotY); + + if (!dataLoaded || listing == null) { + // Loading text + String loading = StatCollector.translateToLocal("gui.loading"); + fontRendererObj.drawString(loading, guiLeft + infoX, guiTop + infoY, 0xFFFFFF); + return; + } + + // Draw auction info on the right side + drawAuctionInfo(); + } + + /** + * Draw auction listing information on the right side + */ + private void drawAuctionInfo() { + int x = guiLeft + infoX; + int y = guiTop + infoY; + int xRight = guiLeft + 215; + + int lineHeight = 9; + + // Seller + String sellerLabel = StatCollector.translateToLocal("auction.seller").replace("%s", ""); + fontRendererObj.drawString(EnumChatFormatting.GRAY + sellerLabel, x, y, 0xFFFFFF); + + String label = listing.sellerName; + int length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(EnumChatFormatting.WHITE + listing.sellerName, xRight - length, y, 0xFFFFFF); + y += lineHeight + 4; + + // Current Bid or Starting Price + if (listing.hasBids()) { + String bidLabel = StatCollector.translateToLocal("auction.info.currentBid") + ":"; + fontRendererObj.drawString(EnumChatFormatting.YELLOW + bidLabel, x, y, 0xFFFFFF); + + label = AuctionFormatUtil.formatCurrency(listing.currentBid); + length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF); + y += lineHeight + 4; + + // Current Bidder + String bidderLabel = StatCollector.translateToLocal("auction.info.highBidder"); + fontRendererObj.drawString(EnumChatFormatting.GRAY + bidderLabel, x, y, 0xFFFFFF); + + label = listing.highBidderName != null ? listing.highBidderName : "???"; + length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(EnumChatFormatting.WHITE + label, xRight - length, y, 0xFFFFFF); + y += lineHeight + 4; + } else { + String startLabel = StatCollector.translateToLocal("auction.info.startingPrice"); + fontRendererObj.drawString(EnumChatFormatting.YELLOW + startLabel, x, y, 0xFFFFFF); + + label = AuctionFormatUtil.formatCurrency(listing.startingPrice); + length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF); + y += lineHeight + 4; + } + + // Buyout Price (if available) + if (listing.hasBuyout()) { + String buyoutLabel = StatCollector.translateToLocal("auction.info.buyoutPrice"); + fontRendererObj.drawString(EnumChatFormatting.GREEN + buyoutLabel, x, y, 0xFFFFFF); + + label = AuctionFormatUtil.formatCurrency(listing.buyoutPrice); + length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(EnumChatFormatting.GREEN + label, xRight - length, y, 0xFFFFFF); + y += lineHeight + 4; + } + + // Time Remaining + String timeLabel = StatCollector.translateToLocal("auction.info.timeLeft"); + fontRendererObj.drawString(EnumChatFormatting.GRAY + timeLabel, x, y, 0xFFFFFF); + long timeRemaining = listing.getTimeRemaining(); + EnumChatFormatting timeColor = AuctionFormatUtil.isTimeUrgent(timeRemaining) ? EnumChatFormatting.RED : EnumChatFormatting.WHITE; + + label = timeColor + AuctionFormatUtil.formatTimeRemaining(timeRemaining); + length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(label, xRight - length, y, 0xFFFFFF); + y += lineHeight + 4; + + // Bid Count + String bidCountLabel = StatCollector.translateToLocal("auction.info.bidCount"); + fontRendererObj.drawString(EnumChatFormatting.GRAY + bidCountLabel, x, y, 0xFFFFFF); + + label = "" + listing.bidCount; + length = fontRendererObj.getStringWidth(label); + fontRendererObj.drawString(EnumChatFormatting.WHITE + label, xRight - length, y, 0xFFFFFF); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + if (hasSubGui()) return; + + // Draw button tooltips + drawBiddingPageTooltips(mouseX, mouseY); + } + + private void drawBiddingPageTooltips(int mouseX, int mouseY) { + List tooltip = null; + + if (btnBid != null && btnBid.visible && btnBid.isHovered()) { + tooltip = new ArrayList<>(); + tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.bid.place")); + if (listing != null) { + long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement()); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.bid.minimum") + .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 + AuctionFormatUtil.formatCurrency(listing.buyoutPrice) + " " + AuctionClientConfig.getCurrencyName()); + } + } + + 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(); + } + } + + // ========== Slot Handling ========== + + @Override + protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) { + // Block all slot interactions - view only + } + + 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 new file mode 100644 index 000000000..048260d4c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java @@ -0,0 +1,218 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.gui.util.GuiAuctionNavButton; +import noppes.npcs.client.gui.util.GuiContainerNPCInterface; +import noppes.npcs.containers.ContainerAuction; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import java.util.List; + +/** + * Base GUI for all auction interfaces. + * 256x256 texture with player inventory at bottom. + */ +public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { + // Textures + protected static final ResourceLocation AUCTION_BACKGROUND = new ResourceLocation("customnpcs", "textures/gui/auction/auction.png"); + protected static final ResourceLocation AUCTION_SLOT = new ResourceLocation("customnpcs", "textures/gui/auction/auction_slot.png"); + + // Navigation icons + protected static final ResourceLocation ICON_LISTINGS = new ResourceLocation("customnpcs", "textures/items/npcAncientScroll.png"); + protected static final ResourceLocation ICON_SELL = new ResourceLocation("customnpcs", "textures/gui/auction/sell.png"); + protected static final ResourceLocation ICON_CLAIMS = new ResourceLocation("customnpcs", "textures/gui/auction/my_auctions.png"); + protected static final ResourceLocation ICON_FILTER = new ResourceLocation("customnpcs", "textures/gui/auction/search.png"); + + // Page constants + public static final int PAGE_LISTINGS = 0; + 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; + protected static final int BTN_NAV_CLAIMS = 102; + protected static final int BTN_NAV_FILTER = 103; + + // Navigation positions - non-final for testing/positioning + protected int navX = 35; + protected int navYListings = 46; + protected int navYSell = 67; + protected int navYClaims = 88; + + protected final ContainerAuction auctionContainer; + protected GuiAuctionNavButton btnListings; + protected GuiAuctionNavButton btnSell; + protected GuiAuctionNavButton btnClaims; + + public GuiAuctionInterface(EntityNPCInterface npc, ContainerAuction container) { + super(npc, container); + this.auctionContainer = container; + this.xSize = 256; + this.ySize = 256; + this.closeOnEsc = true; + this.title = ""; + } + + @Override + public void initGui() { + super.initGui(); + initNavigationButtons(); + } + + /** + * Initialize navigation buttons + */ + protected void initNavigationButtons() { + int page = getCurrentPage(); + + btnListings = new GuiAuctionNavButton(BTN_NAV_LISTINGS, guiLeft + navX, guiTop + navYListings, + "auction.nav.listings", ICON_LISTINGS); + btnListings.setSelected(page == PAGE_LISTINGS); + addButton(btnListings); + + btnSell = new GuiAuctionNavButton(BTN_NAV_SELL, guiLeft + navX, guiTop + navYSell, + "auction.nav.sell", ICON_SELL); + btnSell.setSelected(page == PAGE_SELL); + addButton(btnSell); + + btnClaims = new GuiAuctionNavButton(BTN_NAV_CLAIMS, guiLeft + navX, guiTop + navYClaims, + "auction.nav.trades", ICON_CLAIMS); + btnClaims.setSelected(page == PAGE_CLAIMS); + addButton(btnClaims); + } + + /** + * Returns current page constant - implement in subclass + */ + protected abstract int getCurrentPage(); + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + int page = getCurrentPage(); + if (button.id == BTN_NAV_LISTINGS && page != PAGE_LISTINGS) { + AuctionActionPacket.openPage(PAGE_LISTINGS); + } else if (button.id == BTN_NAV_SELL && page != PAGE_SELL) { + AuctionActionPacket.openPage(PAGE_SELL); + } else if (button.id == BTN_NAV_CLAIMS && page != PAGE_CLAIMS) { + AuctionActionPacket.openPage(PAGE_CLAIMS); + } + } + + // ========== Background Drawing ========== + + @Override + protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { + drawWorldBackground(0); + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.renderEngine.bindTexture(AUCTION_BACKGROUND); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + drawAuctionContent(partialTicks, mouseX, mouseY); + + RenderHelper.enableGUIStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + + super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + if (!hasSubGui()) { + drawNavButtonTooltips(mouseX, mouseY); + } + } + + /** + * Draw navigation button tooltips + */ + protected void drawNavButtonTooltips(int mouseX, int mouseY) { + List tooltip = null; + if (btnListings != null && btnListings.isHovered()) tooltip = btnListings.getTooltipLines(); + else if (btnSell != null && btnSell.isHovered()) tooltip = btnSell.getTooltipLines(); + else if (btnClaims != null && btnClaims.isHovered()) tooltip = btnClaims.getTooltipLines(); + + if (tooltip != null) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj); + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + } + + // ========== Slot Drawing Utilities ========== + + /** + * 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) + */ + protected 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(1.0F, 1.0F, 1.0F, 1.0F); + } + + /** + * Draw dark overlay for unavailable slots + */ + protected void drawDarkenedOverlay(int x, int y) { + drawColoredOverlay(x, y, OVERLAY_DARK); + } + + /** + * Draw icon texture on slot (16x16) + */ + protected void drawIconOverlay(int x, int y, ResourceLocation icon) { + 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(1.0F, 1.0F, 1.0F, 1.0F); + mc.renderEngine.bindTexture(icon); + Gui.func_146110_a(x + 1, y + 1, 0, 0, 16, 16, 16, 16); + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + + /** + * Subclasses implement this to draw specific content + */ + protected abstract void drawAuctionContent(float partialTicks, int mouseX, int mouseY); + + @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 new file mode 100644 index 000000000..85312f5ad --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionListing.java @@ -0,0 +1,309 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.inventory.Slot; +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.NoppesUtil; +import noppes.npcs.client.gui.util.GuiAuctionNavButton; +import noppes.npcs.client.gui.util.IGuiData; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.constants.EnumAuctionSort; +import noppes.npcs.containers.ContainerAuctionListing; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +/** + * GUI for browsing auction listings. + * Displays 9x5 grid with pagination and filter controls. + */ +public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiListener, IGuiData { + // Small button textures (10x10) + private static final ResourceLocation SMALL_BUTTON = new ResourceLocation("customnpcs", "textures/gui/auction/small_button.png"); + private static final ResourceLocation SMALL_BUTTON_PRESS = new ResourceLocation("customnpcs", "textures/gui/auction/small_button_press.png"); + + // Arrow icons (8x8) + private static final ResourceLocation ICON_UP = new ResourceLocation("customnpcs", "textures/gui/auction/up.png"); + private static final ResourceLocation ICON_DOWN = new ResourceLocation("customnpcs", "textures/gui/auction/down.png"); + + // Grid layout - non-final for testing/positioning + protected int gridX = 56; + protected int gridY = 46; + protected int cols = 9; + protected int rows = 5; + + // Pagination positions (side by side horizontally) + protected int pageUpX = 33; + protected int pageDownX = 45; + protected int pageBtnY = 128; + + // Filter button position + protected int navYFilter = 109; + + // Button IDs + private static final int BTN_PAGE_UP = 200; + private static final int BTN_PAGE_DOWN = 201; + + private final ContainerAuctionListing listingContainer; + private AuctionFilter filter; + private int currentPage = 0; + private int totalPages = 1; + + // Buttons defined on this page + private GuiAuctionNavButton btnFilter; + private GuiAuctionNavButton btnPageUp; + private GuiAuctionNavButton btnPageDown; + + public GuiAuctionListing(EntityNPCInterface npc, ContainerAuctionListing container) { + super(npc, container); + this.listingContainer = container; + this.filter = new AuctionFilter(); + } + + @Override + public void initGui() { + super.initGui(); + + // Filter button (18x18 with 16x16 icon) + btnFilter = new GuiAuctionNavButton(BTN_NAV_FILTER, guiLeft + navX, guiTop + navYFilter, + "auction.nav.filter", ICON_FILTER); + addButton(btnFilter); + + // Page Up button (10x10 with 8x8 icon) + btnPageUp = new GuiAuctionNavButton(BTN_PAGE_UP, guiLeft + pageUpX, guiTop + pageBtnY, + 10, 8, "auction.page.prev", ICON_UP, SMALL_BUTTON, SMALL_BUTTON_PRESS); + addButton(btnPageUp); + + // Page Down button (10x10 with 8x8 icon) + btnPageDown = new GuiAuctionNavButton(BTN_PAGE_DOWN, guiLeft + pageDownX, guiTop + pageBtnY, + 10, 8, "auction.page.next", ICON_DOWN, SMALL_BUTTON, SMALL_BUTTON_PRESS); + addButton(btnPageDown); + + updateFilterTooltip(); + requestListings(); + } + + @Override + protected int getCurrentPage() { + return PAGE_LISTINGS; + } + + /** + * Request listings from server + */ + private void requestListings() { + AuctionActionPacket.requestListings(filter, currentPage); + } + + /** + * Update pagination button visibility based on current page state + */ + private void updatePaginationVisibility() { + if (btnPageUp != null) { + btnPageUp.setVisible(currentPage > 0); + } + if (btnPageDown != null) { + btnPageDown.setVisible(currentPage < totalPages - 1); + } + } + + // ========== Filter Handling ========== + + private void updateFilterTooltip() { + if (btnFilter == null) return; + + List tooltip = new ArrayList<>(); + tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.nav.filter")); + tooltip.add(""); + + // Sort mode + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.filter.sort") + ":"); + tooltip.add(EnumChatFormatting.WHITE + " " + filter.getSortBy().getDisplayName()); + tooltip.add(""); + + // Search term + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.filter.search") + ":"); + if (filter.hasSearchText()) { + tooltip.add(EnumChatFormatting.GREEN + " \"" + filter.getSearchText() + "\""); + } else { + tooltip.add(EnumChatFormatting.DARK_GRAY + " " + StatCollector.translateToLocal("auction.filter.none")); + } + tooltip.add(""); + + // Instructions + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.filter.leftClick")); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.filter.rightClick")); + + btnFilter.setCustomTooltip(tooltip); + } + + @Override + public void mouseEvent(int mouseX, int mouseY, int mouseButton) { + if (btnFilter != null && btnFilter.isMouseOver(mouseX, mouseY) && mouseButton == 1) { + cycleSortMode(); + } + } + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + + switch (button.id) { + case BTN_NAV_FILTER: + setSubGui(new SubGuiAuctionSearch(filter.getSearchText())); + break; + case BTN_PAGE_UP: + if (currentPage > 0) { + currentPage--; + requestListings(); + NoppesUtil.clickSound(); + } + break; + case BTN_PAGE_DOWN: + if (currentPage < totalPages - 1) { + currentPage++; + requestListings(); + NoppesUtil.clickSound(); + } + break; + } + } + + private void cycleSortMode() { + EnumAuctionSort[] values = EnumAuctionSort.values(); + int next = (filter.getSortBy().ordinal() + 1) % values.length; + filter.setSortBy(values[next]); + updateFilterTooltip(); + currentPage = 0; + requestListings(); + NoppesUtil.clickSound(); + } + + public void onSearchSubmit(String searchText) { + filter.setSearchText(searchText); + updateFilterTooltip(); + currentPage = 0; + requestListings(); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + } + + // ========== Data Handling ========== + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("ListingsData")) { + currentPage = compound.getInteger("Page"); + totalPages = compound.getInteger("TotalPages"); + + // Load listings + listingContainer.displayInventory.clear(); + NBTTagList list = compound.getTagList("Listings", 10); + for (int i = 0; i < list.tagCount() && i < 45; i++) { + AuctionListing listing = AuctionListing.fromNBT(list.getCompoundTagAt(i)); + listingContainer.displayInventory.setListing(i, listing); + } + updatePaginationVisibility(); + } else if (compound.hasKey("ListingsRefresh")) { + requestListings(); + } + } + + // ========== Drawing ========== + + @Override + protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) { + // Draw slot backgrounds + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + int x = guiLeft + gridX + col * 18; + int y = guiTop + gridY + row * 18; + drawAuctionSlot(x, y); + } + } + + // Draw page indicator below pagination buttons + drawPageIndicator(); + } + + private void drawPageIndicator() { + if (totalPages > 1) { + String text = (currentPage + 1) + "/" + totalPages; + // Center between the two buttons (horizontally centered), below buttons + int centerX = guiLeft + pageUpX + 11; + int x = centerX - fontRendererObj.getStringWidth(text) / 2; + fontRendererObj.drawString(text, x, guiTop + pageBtnY + 12, 0xFFFFFF); + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + if (hasSubGui()) return; + + // Draw tooltips for buttons on this page + drawListingPageTooltips(mouseX, mouseY); + } + + private void drawListingPageTooltips(int mouseX, int mouseY) { + List tooltip = null; + + // Filter button tooltip + if (btnFilter != null && btnFilter.isHovered()) { + tooltip = btnFilter.getTooltipLines(); + } + // Page up tooltip + else if (btnPageUp != null && btnPageUp.visible && btnPageUp.isHovered()) { + tooltip = btnPageUp.getTooltipLines(); + } + // Page down tooltip + else if (btnPageDown != null && btnPageDown.visible && btnPageDown.isHovered()) { + tooltip = btnPageDown.getTooltipLines(); + } + + 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(); + } + } + + // ========== Slot Handling ========== + + @Override + protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) { + // Check if clicking on a display slot with a listing + if (slot != null && listingContainer.isDisplaySlot(slot.slotNumber)) { + int listingIndex = slot.slotNumber - listingContainer.getDisplaySlotStart(); + AuctionListing listing = listingContainer.displayInventory.getListing(listingIndex); + if (listing != null) { + // Open bidding page for this listing + AuctionActionPacket.openBidding(listing.id); + NoppesUtil.clickSound(); + } + } + // Block other slot interactions + } + + 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 new file mode 100644 index 000000000..af87ab39b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionSell.java @@ -0,0 +1,346 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.inventory.Slot; +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.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; + +/** + * GUI for creating auction listings. + * Sell slot interactions: left-click=clear, right-click=remove 1. + * Inventory interactions: left-click=add stack, right-click=add 1. + */ +public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldListener { + private static final ResourceLocation ICON_COIN = new ResourceLocation("customnpcs", "textures/items/npcCoinBronze.png"); + private static final ResourceLocation ICON_BAG = new ResourceLocation("customnpcs", "textures/items/npcBag.png"); + + // Layout + private int contentX = 58; + private int contentY = 50; + private int confirmBtnX = 200; + private int confirmBtnY = 118; + private int navYBuyout = 109; + + // Component IDs + private int txtStartingPriceId = 1; + private int txtBuyoutPriceId = 2; + private int btnConfirmId = 10; + private int btnAllowBuyoutId = 11; + + private final ContainerAuctionSell sellContainer; + private long startingPrice = 0; + private long buyoutPrice = 0; + private boolean allowBuyout = true; + private String errorMessage = null; + + // Buttons + private GuiAuctionNavButton btnAllowBuyout; + private GuiNpcLabel lblBuyout; + private GuiNpcTextField txtBuyout; + + public GuiAuctionSell(EntityNPCInterface npc, ContainerAuctionSell container) { + super(npc, container); + this.sellContainer = container; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + contentY; + + // Starting Price label and field + addLabel(new GuiNpcLabel(1, "auction.sell.startingPrice", guiLeft + contentX, y + 5, 0xFFFFFF)); + GuiNpcTextField startingField = new GuiNpcTextField(txtStartingPriceId, this, fontRendererObj, + guiLeft + contentX + 80, y, 80, 18, startingPrice > 0 ? "" + startingPrice : ""); + startingField.setIntegersOnly(); + addTextField(startingField); + + y += 25; + + // Buyout Price label and field (only visible when allowBuyout is true) + lblBuyout = new GuiNpcLabel(2, "auction.sell.buyoutPrice", guiLeft + contentX, y + 5, 0xFFFFFF); + addLabel(lblBuyout); + + txtBuyout = new GuiNpcTextField(txtBuyoutPriceId, this, fontRendererObj, + guiLeft + contentX + 80, y, 80, 18, buyoutPrice > 0 ? "" + buyoutPrice : ""); + txtBuyout.setIntegersOnly(); + addTextField(txtBuyout); + + // Allow Buyout toggle button (18x18 with bag icon) + btnAllowBuyout = new GuiAuctionNavButton(btnAllowBuyoutId, guiLeft + navX, guiTop + navYBuyout, + "auction.sell.allowBuyout", ICON_BAG); + btnAllowBuyout.setToggle(true); // This is a toggle, not a nav button + btnAllowBuyout.setSelected(allowBuyout); + addButton(btnAllowBuyout); + + // Confirm button (custom textured button - using GuiAuctionNavButton) + GuiAuctionNavButton btnConfirm = new GuiAuctionNavButton(btnConfirmId, guiLeft + confirmBtnX - 20, guiTop + confirmBtnY - 10, + "auction.sell.confirm", ICON_COIN); + addButton(btnConfirm); + + updateBuyoutVisibility(); + updateBuyoutTooltip(); + } + + @Override + protected int getCurrentPage() { + return PAGE_SELL; + } + + /** + * Update visibility of buyout price field based on toggle state + */ + private void updateBuyoutVisibility() { + if (lblBuyout != null) { + lblBuyout.enabled = allowBuyout; + } + if (txtBuyout != null) { + txtBuyout.setVisible(allowBuyout); + if (!allowBuyout) { + txtBuyout.setText(""); + buyoutPrice = 0; + } + } + } + + /** + * Update the buyout toggle button tooltip + */ + private void updateBuyoutTooltip() { + if (btnAllowBuyout == null) return; + + List tooltip = new ArrayList<>(); + tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.sell.allowBuyout")); + tooltip.add(""); + if (allowBuyout) { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.sell.buyoutEnabled")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.buyoutEnabledDesc")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.buyoutEnabledDesc2")); + } else { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.sell.buyoutDisabled")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.buyoutDisabledDesc")); + } + tooltip.add(""); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.clickToToggle")); + + btnAllowBuyout.setCustomTooltip(tooltip); + } + + @Override + public void unFocused(GuiNpcTextField textfield) { + if (textfield.id == txtStartingPriceId) { + try { + startingPrice = Long.parseLong(textfield.getText()); + } catch (NumberFormatException e) { + startingPrice = 0; + } + } else if (textfield.id == txtBuyoutPriceId) { + try { + String text = textfield.getText().trim(); + buyoutPrice = text.isEmpty() ? 0 : Long.parseLong(text); + } catch (NumberFormatException e) { + buyoutPrice = 0; + } + } + errorMessage = null; + } + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + + if (button.id == btnConfirmId) { + createListing(); + } else if (button.id == btnAllowBuyoutId) { + allowBuyout = !allowBuyout; + btnAllowBuyout.setSelected(allowBuyout); + updateBuyoutVisibility(); + updateBuyoutTooltip(); + NoppesUtil.clickSound(); + } + } + + private void createListing() { + // Get latest values from text fields + GuiNpcTextField startingField = getTextField(txtStartingPriceId); + GuiNpcTextField buyoutField = getTextField(txtBuyoutPriceId); + + if (startingField != null) { + try { + startingPrice = Long.parseLong(startingField.getText()); + } catch (NumberFormatException e) { + startingPrice = 0; + } + } + + if (buyoutField != null && allowBuyout) { + try { + String text = buyoutField.getText().trim(); + buyoutPrice = text.isEmpty() ? 0 : Long.parseLong(text); + } catch (NumberFormatException e) { + buyoutPrice = 0; + } + } else { + buyoutPrice = 0; + } + + // Validate + ItemStack item = sellContainer.getItemToSell(); + if (item == null) { + errorMessage = StatCollector.translateToLocal("auction.sell.noItem"); + return; + } + + if (startingPrice <= 0) { + errorMessage = StatCollector.translateToLocal("auction.sell.invalidPrice"); + return; + } + + if (allowBuyout && buyoutPrice > 0 && buyoutPrice < startingPrice) { + errorMessage = StatCollector.translateToLocal("auction.sell.buyoutTooLow"); + return; + } + + // Validate player has enough items + int inventoryCount = sellContainer.countItemInInventory(item); + if (item.stackSize > inventoryCount) { + errorMessage = StatCollector.translateToLocal("auction.sell.notEnoughItems"); + return; + } + + // Send create listing packet + AuctionActionPacket.createListing(item, startingPrice, allowBuyout ? buyoutPrice : 0); + + // Clear the sell slot (server will also clear it) + sellContainer.clearSellSlot(); + + // Navigate back to listings page + AuctionActionPacket.openPage(PAGE_LISTINGS); + } + + @Override + protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) { + // Draw sell slot background (centered in content area) + int slotX = guiLeft + contentX; + int slotY = guiTop + contentY + 50; + drawAuctionSlot(slotX, slotY); + + // Draw listing fee info (uses cached config from server) + String feeText = StatCollector.translateToLocal("auction.sell.fee") + .replace("%s", AuctionFormatUtil.formatCurrency(AuctionClientConfig.getListingFee()) + " " + AuctionClientConfig.getCurrencyName()); + fontRendererObj.drawString(EnumChatFormatting.GRAY + feeText, guiLeft + contentX, guiTop + contentY + 77, 0xFFFFFF); + + // Draw error message if any + if (errorMessage != null) { + fontRendererObj.drawString(EnumChatFormatting.RED + errorMessage, guiLeft + contentX, guiTop + contentY + 95, 0xFFFFFF); + } + + drawSellSlotIndicator(slotX, slotY); + } + + /** + * Draw indicator showing staged vs available items + */ + private void drawSellSlotIndicator(int slotX, int slotY) { + ItemStack sellItem = sellContainer.getItemToSell(); + if (sellItem != null) { + int inventoryCount = sellContainer.countItemInInventory(sellItem); + String countText = sellItem.stackSize + "/" + inventoryCount; + + // Color: green if valid, red if over limit + int color = sellItem.stackSize <= inventoryCount ? 0x55FF55 : 0xFF5555; + fontRendererObj.drawStringWithShadow(countText, slotX + 18 + 4, slotY + 5, color); + } else { + // Draw "Place item here" hint + String hint = StatCollector.translateToLocal("auction.sell.placeItem"); + fontRendererObj.drawString(EnumChatFormatting.GRAY + hint, slotX + 20, slotY + 5, 0xFFFFFF); + } + } + + /** + * Handle sell page click behavior. + * Sell slot: left=clear, right=remove 1. + * Inventory: left=add stack, right=add 1. + */ + @Override + protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) { + if (slot == null) return; + + // Sell slot clicks + if (sellContainer.isSellSlot(slotIndex)) { + ItemStack sellItem = sellContainer.getItemToSell(); + if (sellItem != null) { + boolean removeAll = (mouseButton == 0); // Left=clear, Right=remove 1 + sellContainer.removeFromSellSlot(removeAll); + NoppesUtil.clickSound(); + } + return; + } + + // Inventory clicks + if (sellContainer.isPlayerInventorySlot(slotIndex)) { + ItemStack sourceStack = slot.getStack(); + if (sourceStack != null) { + boolean fullStack = (mouseButton == 0); // Left=stack, Right=1 item + sellContainer.addToSellSlot(slotIndex, fullStack); + NoppesUtil.clickSound(); + } + return; + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + if (hasSubGui()) return; + + // Draw tooltips for buttons (icons, not items - item tooltips handled by AuctionTooltipHandler) + drawSellPageTooltips(mouseX, mouseY); + } + + /** + * Draw tooltips for sell page buttons + */ + private void drawSellPageTooltips(int mouseX, int mouseY) { + List tooltip = null; + + // Check all buttons + GuiNpcButton confirmBtn = getButton(btnConfirmId); + if (confirmBtn instanceof GuiAuctionNavButton) { + GuiAuctionNavButton btn = (GuiAuctionNavButton) confirmBtn; + if (btn.isHovered()) { + tooltip = btn.getTooltipLines(); + } + } + + if (btnAllowBuyout != null && btnAllowBuyout.isHovered()) { + tooltip = btnAllowBuyout.getTooltipLines(); + } + + 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 new file mode 100644 index 000000000..05e83c5bc --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java @@ -0,0 +1,391 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.audio.PositionedSoundRecord; +import net.minecraft.inventory.Slot; +import net.minecraft.nbt.NBTTagCompound; +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.IGuiData; +import noppes.npcs.constants.EnumClaimType; +import noppes.npcs.containers.ContainerAuctionTrades; +import noppes.npcs.controllers.data.AuctionClaim; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.entity.EntityNPCInterface; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +/** + * GUI for viewing player's auction trades. + * Shows active listings, bids, and claims with confirmation system. + */ +public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { + // Icon textures + private static final ResourceLocation ICON_X = new ResourceLocation("customnpcs", "textures/gui/auction/x_icon.png"); + private static final ResourceLocation ICON_CHECK = new ResourceLocation("customnpcs", "textures/gui/auction/check_icon.png"); + private static final ResourceLocation ICON_COIN = new ResourceLocation("customnpcs", "textures/items/npcCoinGold.png"); + + // Grid layout + private static final int GRID_X = 56; + private static final int GRID_Y = 46; + private static final int COLS = 9; + private static final int ROWS = 5; + private static final int TOTAL_SLOTS = COLS * ROWS; + + // Slot tint colors (ARGB) + private static final int TINT_BLUE = 0x605080FF; // Active listing/bid (selling) + private static final int TINT_GREEN = 0x6050FF50; // Sold (currency claim) or Won (item claim) + private static final int TINT_YELLOW = 0x60FFFF50; // Outbid (refund claim) + private static final int TINT_RED = 0x60FF5050; // Expired/Returned (item returned to seller) + + private final ContainerAuctionTrades tradesContainer; + private int maxTradeSlots; + + // Pending operation state + private int pendingSlot = -1; + private PendingOp pendingOp = PendingOp.NONE; + + private enum PendingOp {NONE, CANCEL, CLAIM} + + public GuiAuctionTrades(EntityNPCInterface npc, ContainerAuctionTrades container) { + super(npc, container); + this.tradesContainer = container; + // Initial value from client config, updated when server sends trades data + this.maxTradeSlots = AuctionClientConfig.getMaxActiveListings(); + } + + @Override + protected int getCurrentPage() { + return PAGE_CLAIMS; + } + + // ========== Mouse Handling ========== + + @Override + public void mouseEvent(int mouseX, int mouseY, int mouseButton) { + if (hasSubGui()) return; + + int slot = getSlotAt(mouseX, mouseY); + if (slot < 0 || slot >= TOTAL_SLOTS) { + clearPending(); + return; + } + + // Clicking on pending slot - confirm or cancel + if (slot == pendingSlot && pendingOp != PendingOp.NONE) { + handlePendingClick(mouseButton); + return; + } + + // Clear existing pending, start new operation + clearPending(); + + AuctionListing listing = tradesContainer.getListingAt(slot); + AuctionClaim claim = tradesContainer.getClaimAt(slot); + + 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); + NoppesUtil.clickSound(); + } else if (claim != null) { + // Handle claim clicks + if (claim.type == EnumClaimType.REFUND && claim.item != null) { + // REFUND with item = can rebid + if (mouseButton == 0) { + // Left-click = open bidding to rebid + AuctionActionPacket.openBidding(claim.listingId); + NoppesUtil.clickSound(); + } else if (mouseButton == 1) { + // Right-click = show refund claim confirmation + setPending(slot, PendingOp.CLAIM); + NoppesUtil.clickSound(); + } + } else if (mouseButton == 0) { + // Normal claim - left-click shows claim confirmation + setPending(slot, PendingOp.CLAIM); + NoppesUtil.clickSound(); + } + } + } + + /** + * Handle click on pending operation slot + */ + private void handlePendingClick(int mouseButton) { + if (pendingOp == PendingOp.CANCEL && mouseButton == 1) { + // Right-click confirms cancel + AuctionListing listing = tradesContainer.getListingAt(pendingSlot); + if (listing != null) { + AuctionActionPacket.cancelListing(listing.id); + playConfirmSound(); + } + clearPending(); + } else if (pendingOp == PendingOp.CLAIM) { + AuctionClaim claim = tradesContainer.getClaimAt(pendingSlot); + if (claim != null) { + // For REFUND claims with item (rebid option), right-click confirms refund + // For all others, left-click confirms claim + boolean shouldClaim = (claim.type == EnumClaimType.REFUND && claim.item != null) + ? mouseButton == 1 // Right-click for rebiddable refunds + : mouseButton == 0; // Left-click for normal claims + + if (shouldClaim) { + if (claim.type.isItem()) { + AuctionActionPacket.claimItem(claim.id); + } else { + AuctionActionPacket.claimCurrency(claim.id); + } + playConfirmSound(); + clearPending(); + } else { + // Wrong button - cancel operation + clearPending(); + NoppesUtil.clickSound(); + } + } else { + clearPending(); + } + } else { + // Wrong button - cancel operation + clearPending(); + NoppesUtil.clickSound(); + } + } + + /** + * 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 + */ + private void clearPending() { + if (pendingSlot >= 0) { + tradesContainer.clearHiddenSlot(); + } + pendingSlot = -1; + pendingOp = PendingOp.NONE; + } + + /** + * 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 + */ + private int getSlotAt(int mouseX, int mouseY) { + int relX = mouseX - guiLeft - GRID_X; + int relY = mouseY - guiTop - GRID_Y; + if (relX < 0 || relY < 0) return -1; + + int col = relX / 18; + int row = relY / 18; + if (col >= COLS || row >= ROWS) return -1; + + return col + row * COLS; + } + + // ========== Drawing ========== + + @Override + protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) { + for (int row = 0; row < ROWS; row++) { + for (int col = 0; col < COLS; col++) { + int slot = col + row * COLS; + int x = guiLeft + GRID_X + col * 18; + int y = guiTop + GRID_Y + row * 18; + + drawAuctionSlot(x, y); + + // Color tint based on slot contents + int tint = getSlotTint(slot); + if (tint != 0 && slot != pendingSlot) { + drawColoredOverlay(x, y, tint); + } + + // Darken unavailable slots + if (slot >= maxTradeSlots) { + drawDarkenedOverlay(x, y); + } + + // Pending operation icon or currency claim coin + if (slot == pendingSlot) { + if (pendingOp == PendingOp.CANCEL) { + drawIconOverlay(x, y, ICON_X); + } else if (pendingOp == PendingOp.CLAIM) { + drawIconOverlay(x, y, ICON_CHECK); + } + } else { + // Draw coin icon for currency claims or refund claims without item + AuctionClaim claim = tradesContainer.getClaimAt(slot); + if (claim != null) { + // Show coin if: CURRENCY claim OR REFUND claim without item + if (claim.type == EnumClaimType.CURRENCY || + (claim.type == EnumClaimType.REFUND && claim.item == null)) { + drawIconOverlay(x, y, ICON_COIN); + } + } + } + } + } + } + + /** + * Get tint color for slot based on contents + */ + private int getSlotTint(int slot) { + AuctionListing listing = tradesContainer.getListingAt(slot); + AuctionClaim claim = tradesContainer.getClaimAt(slot); + + if (listing != null) { + if (tradesContainer.isSellingAt(slot)) { + // Selling - Blue + return TINT_BLUE; + } else { + // Bidding - Yellow + return TINT_YELLOW; + } + } else if (claim != null) { + switch (claim.type) { + case CURRENCY: + // Sold item - Green + return TINT_GREEN; + case REFUND: + // Outbid - Red (whether rebiddable or not) + return TINT_RED; + case ITEM: + // Won item (green) or Returned/Expired (red) + return claim.isReturned ? TINT_RED : TINT_GREEN; + default: + return TINT_GREEN; + } + } + return 0; + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + if (hasSubGui()) return; + + int slot = getSlotAt(mouseX, mouseY); + if (slot >= 0 && slot < TOTAL_SLOTS) { + drawTradeTooltip(slot, mouseX - guiLeft, mouseY - guiTop); + } + } + + /** + * Draw tooltip for a trade slot + */ + private void drawTradeTooltip(int slot, int x, int y) { + List tooltip = new ArrayList<>(); + + if (slot == pendingSlot) { + // Pending operation tooltip + if (pendingOp == PendingOp.CANCEL) { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.confirmCancel")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.rightClickConfirm")); + tooltip.add(EnumChatFormatting.DARK_GRAY + StatCollector.translateToLocal("auction.trades.otherClickCancel")); + } else if (pendingOp == PendingOp.CLAIM) { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.confirmClaim")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.leftClickConfirm")); + tooltip.add(EnumChatFormatting.DARK_GRAY + StatCollector.translateToLocal("auction.trades.otherClickCancel")); + } + } else { + // Normal slot tooltip + AuctionListing listing = tradesContainer.getListingAt(slot); + AuctionClaim claim = tradesContainer.getClaimAt(slot); + + // 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")); + if (!claim.itemName.isEmpty()) { + tooltip.add(EnumChatFormatting.WHITE + claim.itemName); + } + if (!claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.buyer") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName); + } + tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName()); + break; + case REFUND: + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.outbid")); + if (!claim.otherPlayerName.isEmpty()) { + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.outbidBy") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName); + } + tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName()); + break; + } + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToClaim")); + } else if (slot >= maxTradeSlots) { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.unavailable")); + } + } + + if (!tooltip.isEmpty()) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + drawHoveringText(tooltip, x, y, fontRendererObj); + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + } + + // ========== Slot Handling ========== + + @Override + protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) { + // Block all slot interactions + } + + // ========== Server Updates ========== + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("TradesData")) { + // Full trades data received from server + tradesContainer.setTradesData(compound); + // Update max trade slots from server (permission-aware) + this.maxTradeSlots = tradesContainer.getMaxTradeSlots(); + clearPending(); + } else if (compound.hasKey("TradesUpdate")) { + // Legacy flag - should not happen now but keep for safety + tradesContainer.refreshData(); + } + } + + public ContainerAuctionTrades getTradesContainer() { + return tradesContainer; + } +} 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 d23b15398..49edf72b6 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java @@ -1,136 +1,379 @@ package noppes.npcs.client.gui.player; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.player.GetTraderData; import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import noppes.npcs.NoppesUtilPlayer; import noppes.npcs.client.CustomNpcResourceListener; import noppes.npcs.client.gui.util.GuiContainerNPCInterface; +import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.containers.ContainerNPCTrader; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.roles.RoleTrader; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -public class GuiNPCTrader extends GuiContainerNPCInterface { - private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/trader.png"); +public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData { + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/tradersetup.png"); private final ResourceLocation slot = new ResourceLocation("customnpcs", "textures/gui/slot.png"); private RoleTrader role; private ContainerNPCTrader container; + // Layout constants matching ContainerNPCTrader + private static final int COLUMN_WIDTH = ContainerNPCTrader.COLUMN_WIDTH; + private static final int COLUMN_START_X = ContainerNPCTrader.COLUMN_START_X; + private static final int ROW_HEIGHT = ContainerNPCTrader.ROW_HEIGHT; + private static final int ROW_START_Y = ContainerNPCTrader.ROW_START_Y; + private static final int CURRENCY1_OFFSET = ContainerNPCTrader.CURRENCY1_OFFSET; + private static final int CURRENCY2_OFFSET = ContainerNPCTrader.CURRENCY2_OFFSET; + private static final int OUTPUT_OFFSET = ContainerNPCTrader.OUTPUT_OFFSET; + + // Data received from server via IGuiData + private long playerBalance = 0; + private int[] availableStock = new int[18]; + private long[] currencyCost = new long[18]; + private boolean stockEnabled = false; + + // Client-side countdown: target time when stock resets (System.currentTimeMillis()) + private long resetTargetTime = -1; + + // Current hover status for bottom display + private String statusMessage = ""; + private int statusColor = 0xFFFFFF; + public GuiNPCTrader(EntityNPCInterface npc, ContainerNPCTrader container) { super(npc, container); this.container = container; role = (RoleTrader) npc.roleInterface; closeOnEsc = true; - ySize = 224; - xSize = 223; - this.title = "role.trader"; + ySize = 216; + xSize = 256; + this.title = ""; + + // Initialize stock to unlimited + for (int i = 0; i < 18; i++) { + availableStock[i] = Integer.MAX_VALUE; + currencyCost[i] = 0; + } + + // Request trader data from server (balance, stock, currency costs) + PacketClient.sendClient(new GetTraderData()); } @Override - protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { + public void setGuiData(NBTTagCompound compound) { + playerBalance = compound.getLong("Balance"); + stockEnabled = compound.getBoolean("StockEnabled"); + + // Calculate target time for client-side countdown + long remainingMillis = compound.getLong("ResetTimeMillis"); + if (remainingMillis > 0) { + resetTargetTime = System.currentTimeMillis() + remainingMillis; + } else { + resetTargetTime = -1; + } + + int[] stock = compound.getIntArray("Stock"); + if (stock != null && stock.length == 18) { + availableStock = stock; + } + + for (int i = 0; i < 18; i++) { + currencyCost[i] = compound.getLong("Cost" + i); + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + // Reset status each frame + statusMessage = ""; + statusColor = 0xFFFFFF; + this.drawWorldBackground(0); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); mc.renderEngine.bindTexture(resource); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); + + // Draw "Trader" label in TOP LEFT (above the GUI) + String traderLabel = StatCollector.translateToLocal("role.trader"); + fontRendererObj.drawString(traderLabel, guiLeft + 4, guiTop - 8, 0xFFFFFF); + + // Draw reset timer in TOP RIGHT (above the GUI) + if (stockEnabled && resetTargetTime > 0) { + String timerText = getResetCountdownText(); + int timerWidth = fontRendererObj.getStringWidth(timerText); + int timerColor = timerText.equals(StatCollector.translateToLocal("trader.reopentrader")) ? 0xFFAA00 : 0xFFFFFF; + fontRendererObj.drawString(timerText, guiLeft + xSize - timerWidth - 4, guiTop - 8, timerColor); + } + RenderHelper.enableGUIStandardItemLighting(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); - mc.renderEngine.bindTexture(slot); - for (int slot = 0; slot < 18; slot++) { - int x = guiLeft + slot % 3 * 72 + 10; - int y = guiTop + slot / 3 * 21 + 6; + // Draw trade slots (3 columns x 6 rows, 80px column width) + for (int slotIdx = 0; slotIdx < 18; slotIdx++) { + int col = slotIdx % 3; + int row = slotIdx / 3; + int x = guiLeft + COLUMN_START_X + col * COLUMN_WIDTH; + int y = guiTop + ROW_START_Y + row * ROW_HEIGHT; - ItemStack item = role.inventoryCurrency.items.get(slot); - ItemStack item2 = role.inventoryCurrency.items.get(slot + 18); + // Get item currencies + ItemStack item = role.inventoryCurrency.items.get(slotIdx); + ItemStack item2 = role.inventoryCurrency.items.get(slotIdx + 18); if (item == null) { item = item2; item2 = null; } - if (NoppesUtilPlayer.compareItems(item, item2, false, false)) { + if (item != null && item2 != null && NoppesUtilPlayer.compareItems(item, item2, role.ignoreDamage, role.ignoreNBT)) { item = item.copy(); item.stackSize += item2.stackSize; item2 = null; } - ItemStack sold = role.inventorySold.items.get(slot); + ItemStack sold = role.inventorySold.items.get(slotIdx); + + // Draw slot backgrounds (18x18 each) GL11.glColor4f(1, 1, 1, 1); mc.renderEngine.bindTexture(this.slot); - drawTexturedModalRect(x + 42, y, 0, 0, 18, 18); - if (item != null && sold != null) { + + // Currency slot 1 + drawTexturedModalRect(x + CURRENCY1_OFFSET, y, 0, 0, 18, 18); + // Currency slot 2 + drawTexturedModalRect(x + CURRENCY2_OFFSET, y, 0, 0, 18, 18); + // Output slot + drawTexturedModalRect(x + OUTPUT_OFFSET, y, 0, 0, 18, 18); + + // "=" sign between currency and output + fontRendererObj.drawString("=", x + 40, y + 5, CustomNpcResourceListener.DefaultTextColor); + + // Draw currency items (centered: +1 offset for 16x16 item in 18x18 slot) + if (sold != null) { RenderHelper.enableGUIStandardItemLighting(); + // Draw secondary currency (slot 1) if (item2 != null) { - itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, item2, x, y + 1); - itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, item2, x, y + 1); + itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, item2, x + CURRENCY1_OFFSET + 1, y + 1); + itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, item2, x + CURRENCY1_OFFSET + 1, y + 1); } - GL11.glColor4f(1, 1, 1, 1); - itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, item, x + 18, y + 1); - itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, item, x + 18, y + 1); + + // Draw primary currency (slot 2) + if (item != null) { + GL11.glColor4f(1, 1, 1, 1); + itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, item, x + CURRENCY2_OFFSET + 1, y + 1); + itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, item, x + CURRENCY2_OFFSET + 1, y + 1); + } + RenderHelper.disableStandardItemLighting(); - fontRendererObj.drawString("=", x + 36, y + 5, CustomNpcResourceListener.DefaultTextColor); + // Draw stock count to the RIGHT of the trade (after output slot) + if (stockEnabled && availableStock[slotIdx] < Integer.MAX_VALUE) { + String stockText = "" + availableStock[slotIdx]; + int stockColor = availableStock[slotIdx] > 0 ? 0x00AA00 : 0xAA0000; + fontRendererObj.drawString(stockText, x + OUTPUT_OFFSET + 20, y + 5, stockColor); + } + // Draw dark overlay for out of stock items + if (stockEnabled && availableStock[slotIdx] <= 0) { + drawGradientRect(x + OUTPUT_OFFSET + 1, y + 1, x + OUTPUT_OFFSET + 17, y + 17, 0xC0101010, 0xC0101010); + } } } + GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); RenderHelper.enableStandardItemLighting(); - super.drawGuiContainerBackgroundLayer(f, i, j); + + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + + // Draw player balance (BOTTOM RIGHT, below GUI) + int infoY = guiTop + ySize + 2; + String balanceText = StatCollector.translateToLocal("trader.balance") + ": $" + formatCurrency(playerBalance); + int balanceWidth = fontRendererObj.getStringWidth(balanceText); + fontRendererObj.drawString(balanceText, guiLeft + xSize - balanceWidth - 4, infoY, 0x36e82a); } @Override - protected void drawGuiContainerForegroundLayer(int par1, int par2) { - for (int slot = 0; slot < 18; slot++) { - int x = slot % 3 * 72 + 10; - int y = slot / 3 * 21 + 6; + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + for (int slotIdx = 0; slotIdx < 18; slotIdx++) { + int col = slotIdx % 3; + int row = slotIdx / 3; + int x = COLUMN_START_X + col * COLUMN_WIDTH; + int y = ROW_START_Y + row * ROW_HEIGHT; - ItemStack item = role.inventoryCurrency.items.get(slot); - ItemStack item2 = role.inventoryCurrency.items.get(slot + 18); + ItemStack item = role.inventoryCurrency.items.get(slotIdx); + ItemStack item2 = role.inventoryCurrency.items.get(slotIdx + 18); if (item == null) { item = item2; item2 = null; } - if (NoppesUtilPlayer.compareItems(item, item2, role.ignoreDamage, role.ignoreNBT)) { + if (item != null && item2 != null && NoppesUtilPlayer.compareItems(item, item2, role.ignoreDamage, role.ignoreNBT)) { item = item.copy(); item.stackSize += item2.stackSize; item2 = null; } - ItemStack sold = role.inventorySold.items.get(slot); - if (item == null || sold == null) + + ItemStack sold = role.inventorySold.items.get(slotIdx); + if (sold == null) { continue; - - if (this.func_146978_c(x + 43, y + 1, 16, 16, par1, par2)) { - if (!container.canBuy(slot, player)) { - GL11.glTranslatef(0, 0, 300); - if (item != null && !NoppesUtilPlayer.compareItems(player, item, role.ignoreDamage, role.ignoreNBT)) - this.drawGradientRect(x + 17, y, x + 35, y + 18, 0x70771010, 0x70771010); - if (item2 != null && !NoppesUtilPlayer.compareItems(player, item2, role.ignoreDamage, role.ignoreNBT)) - this.drawGradientRect(x - 1, y, x + 17, y + 18, 0x70771010, 0x70771010); - - String title = StatCollector.translateToLocal("trader.insufficient"); - this.fontRendererObj.drawString(title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 131, 0xDD0000); - GL11.glTranslatef(0, 0, -300); - } else if (!container.isSlotEnabled(slot, player)) { - String title = StatCollector.translateToLocal("trader.slotdisabled"); - this.fontRendererObj.drawString(title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 131, 0xFF4000); - } else { - String title = StatCollector.translateToLocal("trader.sufficient"); - this.fontRendererObj.drawString(title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 131, 0x00DD00); - } } - if (this.func_146978_c(x, y, 16, 16, par1, par2) && item2 != null) { - this.renderToolTip(item2, par1 - guiLeft, par2 - guiTop); + // Check if hovering over output slot (18x18 area) + if (this.func_146978_c(x + OUTPUT_OFFSET, y, 18, 18, mouseX, mouseY)) { + updateSlotStatus(slotIdx, item, item2, x, y); } - if (this.func_146978_c(x + 18, y, 16, 16, par1, par2)) { - this.renderToolTip(item, par1 - guiLeft, par2 - guiTop); + + // Tooltips for currency items + if (this.func_146978_c(x + CURRENCY1_OFFSET, y, 18, 18, mouseX, mouseY) && item2 != null) { + this.renderToolTip(item2, mouseX - guiLeft, mouseY - guiTop); + } + if (this.func_146978_c(x + CURRENCY2_OFFSET, y, 18, 18, mouseX, mouseY) && item != null) { + this.renderToolTip(item, mouseX - guiLeft, mouseY - guiTop); } } + + // Draw status message in BOTTOM LEFT (in foreground coordinates) + if (!statusMessage.isEmpty()) { + fontRendererObj.drawString(statusMessage, 4, ySize + 4, statusColor); + } + } + + /** + * Update status message when hovering over a trade slot + */ + private void updateSlotStatus(int slotIdx, ItemStack item, ItemStack item2, int x, int y) { + long cost = currencyCost[slotIdx]; + String costSuffix = cost > 0 ? " ($" + formatCurrency(cost) + ")" : ""; + + // Check conditions in order of priority + if (stockEnabled && availableStock[slotIdx] <= 0) { + // Out of stock + statusMessage = StatCollector.translateToLocal("trader.outofstock") + costSuffix; + statusColor = 0xDD0000; + } else if (cost > 0 && playerBalance < cost) { + // Can't afford currency cost + statusMessage = StatCollector.translateToLocal("trader.insufficient.currency") + costSuffix; + statusColor = 0xDD0000; + } else if (!container.canBuy(slotIdx, player)) { + // Missing item currency - highlight which ones + GL11.glTranslatef(0, 0, 300); + if (item != null && !NoppesUtilPlayer.compareItems(player, item, role.ignoreDamage, role.ignoreNBT)) { + this.drawGradientRect(x + CURRENCY2_OFFSET, y, x + CURRENCY2_OFFSET + 18, y + 18, 0x70771010, 0x70771010); + } + if (item2 != null && !NoppesUtilPlayer.compareItems(player, item2, role.ignoreDamage, role.ignoreNBT)) { + this.drawGradientRect(x + CURRENCY1_OFFSET, y, x + CURRENCY1_OFFSET + 18, y + 18, 0x70771010, 0x70771010); + } + GL11.glTranslatef(0, 0, -300); + statusMessage = StatCollector.translateToLocal("trader.unavailable") + costSuffix; + statusColor = 0xDD0000; + } else if (!container.isSlotEnabled(slotIdx, player)) { + // Slot disabled + statusMessage = StatCollector.translateToLocal("trader.slotdisabled") + costSuffix; + statusColor = 0xFF4000; + } else { + // Can buy! + statusMessage = StatCollector.translateToLocal("trader.available") + costSuffix; + statusColor = 0x00DD00; + } + } + + /** + * Get the countdown text for stock reset timer. + * Calculated client-side each frame for smooth countdown. + */ + private String getResetCountdownText() { + if (resetTargetTime <= 0) { + return ""; + } + + long remaining = resetTargetTime - System.currentTimeMillis(); + if (remaining <= 0) { + return StatCollector.translateToLocal("trader.reopentrader"); + } + + // Format as HH:MM:SS or D days HH:MM:SS + long seconds = (remaining / 1000) % 60; + long minutes = (remaining / 60000) % 60; + long hours = (remaining / 3600000) % 24; + long days = remaining / 86400000; + + StringBuilder sb = new StringBuilder(); + sb.append(StatCollector.translateToLocal("trader.restock")).append(": "); + + if (days > 0) { + sb.append(days).append("d "); + } + sb.append(String.format("%02d:%02d:%02d", hours, minutes, seconds)); + + return sb.toString(); + } + + /** + * Format currency for display (e.g., 1000 -> "1,000") + */ + 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(); + } + + @Override + 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 + && 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 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 new file mode 100644 index 000000000..2bb766415 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBid.java @@ -0,0 +1,156 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; +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.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. + * Shows minimum bid, player balance, and input field. + */ +public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListener { + private int txtBidId = 1; + private int btnBidId = 10; + private int btnCancelId = 11; + + 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 buyoutPrice, long playerBalance) { + this.listingId = listingId; + this.minimumBid = minimumBid; + this.buyoutPrice = buyoutPrice; + this.playerBalance = playerBalance; + this.bidAmount = minimumBid; + + setBackground("menubg.png"); + xSize = 200; + ySize = 120; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int centerX = guiLeft + xSize / 2; + int y = guiTop + 15; + String currencyName = AuctionClientConfig.getCurrencyName(); + + // Minimum bid info + String minText = StatCollector.translateToLocal("auction.bid.minimum") + .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 + AuctionFormatUtil.formatCurrency(playerBalance) + " " + currencyName); + addLabel(new GuiNpcLabel(2, balanceText, guiLeft + 15, y)); + y += 18; + + // Bid amount field + addLabel(new GuiNpcLabel(3, "auction.bid.yourBid", guiLeft + 15, y + 4)); + GuiNpcTextField bidField = new GuiNpcTextField(txtBidId, this, fontRendererObj, + guiLeft + 80, y, 100, 18, "" + minimumBid); + bidField.setIntegersOnly(); + addTextField(bidField); + y += 28; + + // Error message area (empty initially) + addLabel(new GuiNpcLabel(4, "", guiLeft + 15, y, 0xFF5555)); + y += 16; + + // Buttons + int btnWidth = 70; + int btnSpacing = 20; + int totalBtnWidth = btnWidth * 2 + btnSpacing; + int btnX = centerX - totalBtnWidth / 2; + + addButton(new GuiNpcButton(btnBidId, btnX, y, btnWidth, 20, "auction.bid.place")); + addButton(new GuiNpcButton(btnCancelId, btnX + btnWidth + btnSpacing, y, btnWidth, 20, "gui.cancel")); + } + + @Override + public void unFocused(GuiNpcTextField textfield) { + if (textfield.id == txtBidId) { + try { + bidAmount = Long.parseLong(textfield.getText()); + } catch (NumberFormatException e) { + bidAmount = 0; + } + errorMessage = null; + updateErrorLabel(); + } + } + + @Override + public void buttonEvent(GuiButton button) { + if (button.id == btnBidId) { + placeBid(); + } else if (button.id == btnCancelId) { + close(); + } + } + + private void placeBid() { + // Get latest value from text field + GuiNpcTextField bidField = getTextField(txtBidId); + if (bidField != null) { + try { + bidAmount = Long.parseLong(bidField.getText()); + } catch (NumberFormatException e) { + bidAmount = 0; + } + } + + // Validate + if (bidAmount < minimumBid) { + errorMessage = StatCollector.translateToLocal("auction.error.bidTooLow") + .replace("%s", AuctionFormatUtil.formatCurrency(minimumBid)); + updateErrorLabel(); + return; + } + + if (bidAmount > playerBalance) { + errorMessage = StatCollector.translateToLocal("auction.error.notEnoughCurrency"); + updateErrorLabel(); + return; + } + + if (buyoutPrice > 0 && bidAmount >= buyoutPrice) { + errorMessage = StatCollector.translateToLocal("auction.error.bidExceedsBuyout"); + updateErrorLabel(); + return; + } + + // Send bid packet + AuctionActionPacket.placeBid(listingId, bidAmount); + successful = true; + close(); + } + + private void updateErrorLabel() { + GuiNpcLabel errorLabel = getLabel(4); + if (errorLabel != null) { + errorLabel.label = errorMessage != null ? EnumChatFormatting.RED + errorMessage : ""; + } + } + + public boolean wasSuccessful() { + return successful; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java new file mode 100644 index 000000000..4884c7ae4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionBuyNow.java @@ -0,0 +1,109 @@ +package noppes.npcs.client.gui.player; + +import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; +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. + * Shows buyout price, player balance, and confirmation buttons. + */ +public class SubGuiAuctionBuyNow extends SubGuiInterface { + private int btnConfirmId = 10; + private int btnCancelId = 11; + + private final String listingId; + private final long buyoutPrice; + private final long playerBalance; + private boolean successful = false; + + public SubGuiAuctionBuyNow(String listingId, long buyoutPrice, long playerBalance) { + this.listingId = listingId; + this.buyoutPrice = buyoutPrice; + this.playerBalance = playerBalance; + + setBackground("menubg.png"); + xSize = 220; + ySize = 130; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int centerX = guiLeft + xSize / 2; + int y = guiTop + 15; + String currencyName = AuctionClientConfig.getCurrencyName(); + + // Title + String title = StatCollector.translateToLocal("auction.buyout.title"); + int titleWidth = fontRendererObj.getStringWidth(title); + addLabel(new GuiNpcLabel(0, title, centerX - titleWidth / 2, y)); + y += 20; + + // Confirmation message + String confirmMsg = StatCollector.translateToLocal("auction.buyout.confirm"); + int confirmWidth = fontRendererObj.getStringWidth(confirmMsg); + addLabel(new GuiNpcLabel(1, confirmMsg, centerX - confirmWidth / 2, y)); + y += 16; + + // Buyout price + 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 + AuctionFormatUtil.formatCurrency(playerBalance) + " " + currencyName); + addLabel(new GuiNpcLabel(3, balanceText, guiLeft + 20, y)); + y += 14; + + // Insufficient funds warning + if (playerBalance < buyoutPrice) { + String warning = StatCollector.translateToLocal("auction.error.notEnoughCurrency"); + addLabel(new GuiNpcLabel(4, EnumChatFormatting.RED + warning, guiLeft + 20, y, 0xFFFFFF)); + } + y += 20; + + // Buttons + int btnWidth = 70; + int btnSpacing = 20; + int totalBtnWidth = btnWidth * 2 + btnSpacing; + int btnX = centerX - totalBtnWidth / 2; + + GuiNpcButton confirmBtn = new GuiNpcButton(btnConfirmId, btnX, y, btnWidth, 20, "gui.yes"); + confirmBtn.enabled = playerBalance >= buyoutPrice; + addButton(confirmBtn); + addButton(new GuiNpcButton(btnCancelId, btnX + btnWidth + btnSpacing, y, btnWidth, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton button) { + if (button.id == btnConfirmId) { + if (playerBalance >= buyoutPrice) { + confirmPurchase(); + } + } else if (button.id == btnCancelId) { + close(); + } + } + + private void confirmPurchase() { + // Send buyout packet + AuctionActionPacket.buyout(listingId); + successful = true; + close(); + } + + public boolean wasSuccessful() { + return successful; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionSearch.java b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionSearch.java new file mode 100644 index 000000000..57d52f95d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/SubGuiAuctionSearch.java @@ -0,0 +1,85 @@ +package noppes.npcs.client.gui.player; + +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; + +/** + * Small SubGui for entering auction search text. + */ +public class SubGuiAuctionSearch extends SubGuiInterface implements ITextfieldListener { + private static final int TXT_SEARCH = 0; + private static final int BTN_SUBMIT = 1; + private static final int BTN_CLEAR = 2; + private static final int BTN_CLOSE = 3; + + private String searchText; + + public SubGuiAuctionSearch(String currentSearchText) { + this.searchText = currentSearchText != null ? currentSearchText : ""; + setBackground("menubg.png"); + xSize = 180; + ySize = 80; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + // Close button + addButton(new GuiNpcButton(BTN_CLOSE, guiLeft + xSize - 22, guiTop + 4, 18, 18, "X")); + + // Search label + addLabel(new GuiNpcLabel(0, "auction.filter.search", guiLeft + 10, guiTop + 10, 0xFFFFFF)); + + // Search text field + addTextField(new GuiNpcTextField(TXT_SEARCH, this, fontRendererObj, guiLeft + 10, guiTop + 25, 160, 18, searchText)); + + // Submit and Clear buttons + addButton(new GuiNpcButton(BTN_SUBMIT, guiLeft + 10, guiTop + 50, 70, 20, "gui.apply")); + addButton(new GuiNpcButton(BTN_CLEAR, guiLeft + 85, guiTop + 50, 70, 20, "gui.clear")); + } + + @Override + public void unFocused(GuiNpcTextField textfield) { + if (textfield.id == TXT_SEARCH) { + searchText = textfield.getText(); + } + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == BTN_SUBMIT) { + GuiNpcTextField field = getTextField(TXT_SEARCH); + if (field != null) { + searchText = field.getText(); + } + // Notify parent and close + if (parent instanceof GuiAuctionListing) { + ((GuiAuctionListing) parent).onSearchSubmit(searchText); + } + close(); + } else if (guibutton.id == BTN_CLEAR) { + searchText = ""; + GuiNpcTextField field = getTextField(TXT_SEARCH); + if (field != null) { + field.setText(""); + } + // Notify parent and close + if (parent instanceof GuiAuctionListing) { + ((GuiAuctionListing) parent).onSearchSubmit(""); + } + close(); + } else if (guibutton.id == BTN_CLOSE) { + close(); + } + } + + public String getSearchText() { + return searchText; + } +} 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 7ffb7aff2..f9e627fe7 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 @@ -180,7 +180,7 @@ public class GuiProfiles extends GuiCNPCInventory implements ISubGuiListener, IC if (slot.isTemporary()) { label = StatCollector.translateToLocal("profile.temporary"); - result = (String.valueOf(slot.isTemporary())).toUpperCase(); + result = ("" + slot.isTemporary()).toUpperCase(); labelColor = 0xfc60dd; resultColor = 0x35fc81; fontRendererObj.drawString(label, xLabel, y, labelColor, false); 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 43c259da7..7b54518e3 100644 --- a/src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java +++ b/src/main/java/noppes/npcs/client/gui/roles/GuiNpcTraderSetup.java @@ -8,7 +8,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.CustomNpcResourceListener; import noppes.npcs.client.gui.util.GuiContainerNPCInterface2; -import noppes.npcs.client.gui.util.GuiNpcButtonYesNo; +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; @@ -22,6 +22,9 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex private final ResourceLocation slot = new ResourceLocation("customnpcs", "textures/gui/slot.png"); private RoleTrader role; + // Currency cost textfield IDs start at 100 (100-117 for slots 0-17) + private static final int CURRENCY_FIELD_ID_START = 100; + public GuiNpcTraderSetup(EntityNPCInterface npc, ContainerNPCTraderSetup container) { super(npc, container); ySize = 220; @@ -34,17 +37,30 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex super.initGui(); buttonList.clear(); setBackground("tradersetup.png"); + + // Linked Market name addLabel(new GuiNpcLabel(0, "role.marketname", guiLeft + 214, guiTop + 150)); addTextField(new GuiNpcTextField(0, this, guiLeft + 214, guiTop + 160, 180, 20, role.marketName)); - addLabel(new GuiNpcLabel(1, "gui.ignoreDamage", guiLeft + 260, guiTop + 29)); - addButton(new GuiNpcButtonYesNo(1, guiLeft + 340, guiTop + 24, role.ignoreDamage)); + // Settings button (opens SubGuiNpcTraderSettings) + addButton(new GuiNpcButton(1, guiLeft + 214, guiTop + 184, 88, 20, "gui.settings")); + getButton(1).setHoverText("gui.settings.hover"); - addLabel(new GuiNpcLabel(2, "gui.ignoreNBT", guiLeft + 260, guiTop + 51)); - addButton(new GuiNpcButtonYesNo(2, guiLeft + 340, guiTop + 46, role.ignoreNBT)); + // Stock Options button (opens SubGuiNpcTraderStock) + addButton(new GuiNpcButton(2, guiLeft + 306, guiTop + 184, 88, 20, "stock.options")); + getButton(2).setHoverText("stock.options.hover"); - addLabel(new GuiNpcLabel(3, "gui.recordHistory", guiLeft + 260, guiTop + 73)); - addButton(new GuiNpcButtonYesNo(3, guiLeft + 340, guiTop + 68, role.recordHistory)); + // Currency cost textfields for each slot (FIRST - before item slots) + // Column width: 130px for better spacing + for (int i = 0; i < 18; i++) { + int x = guiLeft + i % 3 * 130 + 15; // First position after "$" label + int y = guiTop + i / 3 * 22 + 14; + long cost = role.getCurrencyCost(i); + GuiNpcTextField field = new GuiNpcTextField(CURRENCY_FIELD_ID_START + i, this, x, y, 36, 16, cost > 0 ? "" + cost : ""); + field.setMaxStringLength(8); + field.setIntegersOnly(); + addTextField(field); + } } @Override @@ -57,13 +73,12 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex @Override public void actionPerformed(GuiButton guibutton) { if (guibutton.id == 1) { - role.ignoreDamage = ((GuiNpcButtonYesNo) guibutton).getBoolean(); + // Open Settings SubGui + setSubGui(new SubGuiNpcTraderSettings(role)); } if (guibutton.id == 2) { - role.ignoreNBT = ((GuiNpcButtonYesNo) guibutton).getBoolean(); - } - if (guibutton.id == 3) { - role.recordHistory = ((GuiNpcButtonYesNo) guibutton).getBoolean(); + // Open Stock Options SubGui + setSubGui(new SubGuiNpcTraderStock(role)); } } @@ -71,19 +86,31 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { super.drawGuiContainerBackgroundLayer(f, i, j); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + // Column width: 130px for better spacing for (int slot = 0; slot < 18; slot++) { - int x = guiLeft + slot % 3 * 94 + 7; + int x = guiLeft + slot % 3 * 130 + 7; int y = guiTop + slot / 3 * 22 + 4; - mc.renderEngine.bindTexture(this.slot); - GL11.glColor4f(1, 1, 1, 1); - drawTexturedModalRect(x - 1, y, 0, 0, 18, 18); - drawTexturedModalRect(x + 17, y, 0, 0, 18, 18); + // "$" label for currency cost + fontRendererObj.drawString("$", x, y + 5, CustomNpcResourceListener.DefaultTextColor); - fontRendererObj.drawString("=", x + 36, y + 5, CustomNpcResourceListener.DefaultTextColor); + // Currency textfield is at x + 8 (drawn by textfield system) + + // Item Cost 1 slot mc.renderEngine.bindTexture(this.slot); GL11.glColor4f(1, 1, 1, 1); - drawTexturedModalRect(x + 42, y, 0, 0, 18, 18); + drawTexturedModalRect(x + 50, y, 0, 0, 18, 18); + + // Item Cost 2 slot + drawTexturedModalRect(x + 68, y, 0, 0, 18, 18); + + // "=" sign + fontRendererObj.drawString("=", x + 88, y + 5, CustomNpcResourceListener.DefaultTextColor); + + // Output slot + mc.renderEngine.bindTexture(this.slot); + GL11.glColor4f(1, 1, 1, 1); + drawTexturedModalRect(x + 104, y, 0, 0, 18, 18); } } @@ -95,10 +122,23 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex @Override public void unFocused(GuiNpcTextField guiNpcTextField) { - String name = guiNpcTextField.getText(); - if (!name.equalsIgnoreCase(role.marketName)) { - role.marketName = name; - PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, true)); + int id = guiNpcTextField.id; + + // Handle market name field + if (id == 0) { + String name = guiNpcTextField.getText(); + if (!name.equalsIgnoreCase(role.marketName)) { + role.marketName = name; + PacketClient.sendClient(new TraderMarketSavePacket(role.marketName, true)); + } + return; + } + + // Handle currency cost fields (IDs 100-117) + if (id >= CURRENCY_FIELD_ID_START && id < CURRENCY_FIELD_ID_START + 18) { + int slot = id - CURRENCY_FIELD_ID_START; + long cost = guiNpcTextField.getInteger(); + role.setCurrencyCost(slot, cost); } } } diff --git a/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderCooldownReset.java b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderCooldownReset.java new file mode 100644 index 000000000..4c72e2059 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderCooldownReset.java @@ -0,0 +1,52 @@ +package noppes.npcs.client.gui.roles; + +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; +import noppes.npcs.roles.RoleTrader; + +/** + * Confirmation dialog for resetting trader stock cooldown. + */ +public class SubGuiNpcTraderCooldownReset extends SubGuiInterface { + + private final RoleTrader role; + public boolean confirmed = false; + + public SubGuiNpcTraderCooldownReset(RoleTrader role) { + this.role = role; + setBackground("menubg.png"); + xSize = 200; + ySize = 100; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 15; + + addLabel(new GuiNpcLabel(0, "stock.cooldown.confirm", guiLeft + 10, y)); + y += 12; + addLabel(new GuiNpcLabel(1, "stock.cooldown.warning", guiLeft + 10, y)); + + y += 35; + + addButton(new GuiNpcButton(0, guiLeft + 30, y, 60, 20, "gui.yes")); + addButton(new GuiNpcButton(1, guiLeft + 110, y, 60, 20, "gui.no")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + // Reset the cooldown + role.resetCooldown(); + confirmed = true; + close(); + } else if (guibutton.id == 1) { + close(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderSettings.java b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderSettings.java new file mode 100644 index 000000000..d9e2a0b40 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderSettings.java @@ -0,0 +1,66 @@ +package noppes.npcs.client.gui.roles; + +import net.minecraft.client.gui.GuiButton; +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.SubGuiInterface; +import noppes.npcs.roles.RoleTrader; + +public class SubGuiNpcTraderSettings extends SubGuiInterface { + + private final RoleTrader role; + + public SubGuiNpcTraderSettings(RoleTrader role) { + this.role = role; + setBackground("menubg.png"); + xSize = 176; + ySize = 136; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 14; + + addLabel(new GuiNpcLabel(1, "gui.ignoreDamage", guiLeft + 10, y + 5)); + addButton(new GuiNpcButtonYesNo(1, guiLeft + 120, y, role.ignoreDamage)); + getButton(1).setHoverText("gui.ignoreDamage.hover"); + + y += 28; + + addLabel(new GuiNpcLabel(2, "gui.ignoreNBT", guiLeft + 10, y + 5)); + addButton(new GuiNpcButtonYesNo(2, guiLeft + 120, y, role.ignoreNBT)); + getButton(2).setHoverText("gui.ignoreNBT.hover"); + + y += 28; + + addLabel(new GuiNpcLabel(3, "gui.recordHistory", guiLeft + 10, y + 5)); + addButton(new GuiNpcButtonYesNo(3, guiLeft + 120, y, role.recordHistory)); + getButton(3).setHoverText("gui.recordHistory.hover"); + + y += 34; + + addButton(new GuiNpcButton(0, guiLeft + (xSize - 60) / 2, y, 60, 20, "gui.done")); + } + + @Override + public void buttonEvent(GuiButton button) { + switch (button.id) { + case 0: + close(); + break; + case 1: + role.ignoreDamage = ((GuiNpcButtonYesNo) button).getBoolean(); + break; + case 2: + role.ignoreNBT = ((GuiNpcButtonYesNo) button).getBoolean(); + break; + case 3: + role.recordHistory = ((GuiNpcButtonYesNo) button).getBoolean(); + break; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStock.java b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStock.java new file mode 100644 index 000000000..4e88c9b21 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStock.java @@ -0,0 +1,159 @@ +package noppes.npcs.client.gui.roles; + +import net.minecraft.client.gui.GuiButton; +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.ISubGuiListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.client.gui.util.SubGuiNpcCooldownPicker; +import noppes.npcs.constants.EnumStockReset; +import noppes.npcs.roles.RoleTrader; + +public class SubGuiNpcTraderStock extends SubGuiInterface implements ISubGuiListener, ITextfieldListener { + + private final RoleTrader role; + + public SubGuiNpcTraderStock(RoleTrader role) { + this.role = role; + setBackground("menubg.png"); + xSize = 220; + ySize = 220; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + + // Enable Stock + addLabel(new GuiNpcLabel(1, "stock.enable", guiLeft + 10, y + 5)); + addButton(new GuiNpcButtonYesNo(1, guiLeft + 140, y, role.stock.enableStock)); + getButton(1).setHoverText("stock.enable.hover"); + + y += 24; + + // Per-Player Stock + addLabel(new GuiNpcLabel(2, "stock.perplayer", guiLeft + 10, y + 5)); + addButton(new GuiNpcButtonYesNo(2, guiLeft + 140, y, role.stock.perPlayer)); + getButton(2).setHoverText("stock.perplayer.hover"); + + y += 24; + + // Reset Type + addLabel(new GuiNpcLabel(3, "stock.resettype", guiLeft + 10, y + 5)); + addButton(new GuiNpcButton(3, guiLeft + 90, y, 120, 20, EnumStockReset.getDisplayNames(), role.stock.resetType.ordinal())); + getButton(3).setHoverText("stock.resettype.hover"); + + y += 24; + + // Custom Time button (only visible for custom types) + EnumStockReset resetType = role.stock.resetType; + if (resetType == EnumStockReset.MCCUSTOM || resetType == EnumStockReset.RLCUSTOM) { + addLabel(new GuiNpcLabel(4, "stock.customtime", guiLeft + 10, y + 5)); + addButton(new GuiNpcButton(4, guiLeft + 90, y, 120, 20, "gui.edit")); + getButton(4).setHoverText("stock.customtime.hover"); + y += 24; + } + + // Default Max Stock (applies to all slots as default) + addLabel(new GuiNpcLabel(5, "stock.defaultmax", guiLeft + 10, y + 5)); + GuiNpcTextField defaultStock = new GuiNpcTextField(5, this, fontRendererObj, guiLeft + 140, y, 60, 20, getDefaultStockString()); + defaultStock.setIntegersOnly(); + defaultStock.setMinMaxDefault(-1, Integer.MAX_VALUE, -1); + addTextField(defaultStock); + + y += 26; + + // Per-Slot Stock button + addButton(new GuiNpcButton(5, guiLeft + 10, y, 95, 20, "stock.perslot")); + getButton(5).setHoverText("stock.perslot.hover"); + + // Reset Stock button + addButton(new GuiNpcButton(6, guiLeft + 115, y, 95, 20, "stock.reset")); + getButton(6).setHoverText("stock.reset.hover"); + + y += 24; + + // Reset Cooldown button + addButton(new GuiNpcButton(7, guiLeft + 10, y, 200, 20, "stock.resetcooldown")); + getButton(7).setHoverText("stock.resetcooldown.hover"); + + // Done button + addButton(new GuiNpcButton(0, guiLeft + (xSize - 60) / 2, guiTop + ySize - 40, 60, 20, "gui.done")); + } + + private String getDefaultStockString() { + // Check if all stocks are the same, if so return that value + int first = role.stock.maxStock[0]; + for (int i = 1; i < 18; i++) { + if (role.stock.maxStock[i] != first) { + return "-1"; // Mixed values, return unlimited + } + } + return "" + first; + } + + @Override + public void buttonEvent(GuiButton button) { + switch (button.id) { + case 0: // Done + close(); + break; + case 1: // Enable Stock + role.stock.enableStock = ((GuiNpcButtonYesNo) button).getBoolean(); + break; + case 2: // Per-Player + role.stock.perPlayer = ((GuiNpcButtonYesNo) button).getBoolean(); + break; + case 3: // Reset Type + int value = ((GuiNpcButton) button).getValue(); + role.stock.resetType = EnumStockReset.values()[value]; + initGui(); // Refresh to show/hide custom time button + break; + case 4: // Custom Time + boolean isMC = role.stock.resetType == EnumStockReset.MCCUSTOM; + setSubGui(new SubGuiNpcCooldownPicker(isMC, role.stock.customResetTime)); + break; + case 5: // Per-Slot Stock + setSubGui(new SubGuiNpcTraderStockSlots(role)); + break; + case 6: // Reset Stock + setSubGui(new SubGuiNpcTraderStockReset(role)); + break; + case 7: // Reset Cooldown + setSubGui(new SubGuiNpcTraderCooldownReset(role)); + break; + } + } + + @Override + public void subGuiClosed(SubGuiInterface subGui) { + if (subGui instanceof SubGuiNpcCooldownPicker) { + long value = ((SubGuiNpcCooldownPicker) subGui).cooldownValue; + // Validate minimum: 1 tick for MC time, 1000ms (1 second) for real time + boolean isMC = role.stock.resetType == EnumStockReset.MCCUSTOM; + long minimum = isMC ? 1 : 1000; + role.stock.customResetTime = Math.max(minimum, value); + } + // Refresh after per-slot editing + if (subGui instanceof SubGuiNpcTraderStockSlots) { + initGui(); + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + if (textField.id == 5) { + int value = textField.getInteger(); + // Apply to all slots + for (int i = 0; i < 18; i++) { + role.stock.setMaxStock(i, value); + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStockReset.java b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStockReset.java new file mode 100644 index 000000000..027108f76 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStockReset.java @@ -0,0 +1,55 @@ +package noppes.npcs.client.gui.roles; + +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; +import noppes.npcs.roles.RoleTrader; + +/** + * Confirmation dialog for resetting trader stock. + */ +public class SubGuiNpcTraderStockReset extends SubGuiInterface { + + private final RoleTrader role; + public boolean confirmed = false; + + public SubGuiNpcTraderStockReset(RoleTrader role) { + this.role = role; + setBackground("menubg.png"); + xSize = 200; + ySize = 100; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 15; + + addLabel(new GuiNpcLabel(0, "stock.reset.confirm", guiLeft + 10, y)); + y += 12; + addLabel(new GuiNpcLabel(1, "stock.reset.warning", guiLeft + 10, y)); + + y += 35; + + addButton(new GuiNpcButton(0, guiLeft + 30, y, 60, 20, "gui.yes")); + addButton(new GuiNpcButton(1, guiLeft + 110, y, 60, 20, "gui.no")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + // Reset the stock + long currentTime = role.stock.resetType.isRealTime() + ? System.currentTimeMillis() + : (role.npc != null && role.npc.worldObj != null ? role.npc.worldObj.getTotalWorldTime() : 0); + role.stock.resetStock(currentTime); + confirmed = true; + close(); + } else if (guibutton.id == 1) { + close(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStockSlots.java b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStockSlots.java new file mode 100644 index 000000000..c9d40c5df --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/roles/SubGuiNpcTraderStockSlots.java @@ -0,0 +1,76 @@ +package noppes.npcs.client.gui.roles; + +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 noppes.npcs.roles.RoleTrader; + +/** + * Per-slot stock management dialog. + * Shows all 18 slots with their max stock values. + */ +public class SubGuiNpcTraderStockSlots extends SubGuiInterface implements ITextfieldListener { + + private final RoleTrader role; + + public SubGuiNpcTraderStockSlots(RoleTrader role) { + this.role = role; + setBackground("menubg.png"); + xSize = 256; + ySize = 216; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + // Title + addLabel(new GuiNpcLabel(0, "stock.perslot.title", guiLeft + 10, guiTop + 6)); + + // 18 slots in 3 columns x 6 rows + int startY = guiTop + 22; + int colWidth = 80; + + for (int i = 0; i < 18; i++) { + int col = i % 3; + int row = i / 3; + + int x = guiLeft + 10 + col * colWidth; + int y = startY + row * 28; + + // Slot label + addLabel(new GuiNpcLabel(i + 1, "Slot " + (i + 1) + ":", x, y + 5)); + + // Max stock textfield + int maxStock = role.stock.maxStock[i]; + String value = maxStock < 0 ? "-1" : "" + maxStock; + GuiNpcTextField field = new GuiNpcTextField(i, this, fontRendererObj, x + 42, y, 32, 18, value); + field.setIntegersOnly(); + field.setMinMaxDefault(-1, Integer.MAX_VALUE, -1); + addTextField(field); + } + + // Done button + addButton(new GuiNpcButton(0, guiLeft + (xSize - 60) / 2, guiTop + ySize - 26, 60, 20, "gui.done")); + } + + @Override + public void buttonEvent(GuiButton button) { + if (button.id == 0) { + close(); + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + int slot = textField.id; + if (slot >= 0 && slot < 18) { + int value = textField.getInteger(); + role.stock.setMaxStock(slot, value); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/script/EventGuiScriptList.java b/src/main/java/noppes/npcs/client/gui/script/EventGuiScriptList.java index 530a3a2be..fe6daff23 100644 --- a/src/main/java/noppes/npcs/client/gui/script/EventGuiScriptList.java +++ b/src/main/java/noppes/npcs/client/gui/script/EventGuiScriptList.java @@ -5,7 +5,7 @@ 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.SubGuiInterface; -import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.controllers.data.IScriptUnit; import java.util.ArrayList; import java.util.Iterator; @@ -14,10 +14,10 @@ import java.util.List; public class EventGuiScriptList extends SubGuiInterface { private GuiCustomScroll scroll1; private GuiCustomScroll scroll2; - private ScriptContainer container; + private IScriptUnit container; private List scripts; - public EventGuiScriptList(List scripts, ScriptContainer container) { + public EventGuiScriptList(List scripts, IScriptUnit container) { this.container = container; this.setBackground("menubg.png"); this.xSize = 346; @@ -50,9 +50,9 @@ public class EventGuiScriptList extends SubGuiInterface { this.addScroll(this.scroll2); this.addLabel(new GuiNpcLabel(2, "script.loadedScripts", this.guiLeft + 200, this.guiTop + 4)); ArrayList temp = new ArrayList(this.scripts); - temp.removeAll(this.container.scripts); + temp.removeAll(getScripts()); this.scroll1.setList(temp); - this.scroll2.setList(this.container.scripts); + this.scroll2.setList(getScripts()); this.addButton(new GuiNpcButton(1, this.guiLeft + 145, this.guiTop + 40, 55, 20, ">")); this.addButton(new GuiNpcButton(2, this.guiLeft + 145, this.guiTop + 62, 55, 20, "<")); this.addButton(new GuiNpcButton(3, this.guiLeft + 145, this.guiTop + 90, 55, 20, ">>")); @@ -63,25 +63,25 @@ public class EventGuiScriptList extends SubGuiInterface { protected void actionPerformed(GuiButton guibutton) { GuiNpcButton button = (GuiNpcButton) guibutton; if (button.id == 1 && this.scroll1.hasSelected()) { - this.container.scripts.add(this.scroll1.getSelected()); + getScripts().add(this.scroll1.getSelected()); this.scroll1.selected = -1; this.scroll2.selected = -1; this.initGui(); } if (button.id == 2 && this.scroll2.hasSelected()) { - this.container.scripts.remove(this.scroll2.getSelected()); + getScripts().remove(this.scroll2.getSelected()); this.scroll2.selected = -1; this.initGui(); } if (button.id == 3) { - this.container.scripts.clear(); + getScripts().clear(); Iterator var3 = this.scripts.iterator(); while (var3.hasNext()) { String script = (String) var3.next(); - this.container.scripts.add(script); + getScripts().add(script); } this.scroll1.selected = -1; @@ -90,7 +90,7 @@ public class EventGuiScriptList extends SubGuiInterface { } if (button.id == 4) { - this.container.scripts.clear(); + getScripts().clear(); this.scroll1.selected = -1; this.scroll2.selected = -1; this.initGui(); @@ -102,6 +102,10 @@ public class EventGuiScriptList extends SubGuiInterface { } + public List getScripts() { + return this.container.getExternalScripts(); + } + public void save() { } } diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiJaninoScript.java b/src/main/java/noppes/npcs/client/gui/script/GuiJaninoScript.java new file mode 100644 index 000000000..9fb601162 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/script/GuiJaninoScript.java @@ -0,0 +1,429 @@ +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/GuiNPCEventScripts.java b/src/main/java/noppes/npcs/client/gui/script/GuiNPCEventScripts.java index 5b4693a10..db1338fff 100644 --- a/src/main/java/noppes/npcs/client/gui/script/GuiNPCEventScripts.java +++ b/src/main/java/noppes/npcs/client/gui/script/GuiNPCEventScripts.java @@ -1,80 +1,13 @@ package noppes.npcs.client.gui.script; -import kamkeel.npcs.network.packets.request.script.EventScriptPacket; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.NBTTags; -import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.data.DataScript; +import noppes.npcs.controllers.data.IScriptHandlerPacket; import noppes.npcs.entity.EntityNPCInterface; -import java.util.ArrayList; -import java.util.List; - public class GuiNPCEventScripts extends GuiScriptInterface { - private final DataScript script; - public GuiNPCEventScripts(EntityNPCInterface npc) { - this.hookList = new ArrayList<>(); - hookList.add("init"); - hookList.add("tick"); - hookList.add("interact"); - hookList.add("dialog"); - hookList.add("damaged"); - hookList.add("killed"); - hookList.add("meleeAttack"); - hookList.add("meleeSwing"); - hookList.add("rangedLaunched"); - hookList.add("target"); - hookList.add("collide"); - hookList.add("kills"); - hookList.add("dialogClose"); - hookList.add("timer"); - hookList.add("targetLost"); - hookList.add("projectileTick"); - hookList.add("projectileImpact"); - - this.script = new DataScript(npc); - this.handler = this.script; - EventScriptPacket.Get(); - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - script.setLanguage(compound.getString("ScriptLanguage")); - script.setEnabled(compound.getBoolean("ScriptEnabled")); - super.setGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(script); - container.readFromNBT(compound.getCompoundTag("Script")); - if (script.getScripts().isEmpty()) { - for (int i = 0; i < compound.getInteger("TotalScripts"); i++) { - script.getScripts().add(new ScriptContainer(script)); - } - } - script.getScripts().set(tab, container); - initGui(); - } - } - - public void save() { - if (loaded) { - super.save(); - List containers = this.script.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - EventScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.script.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.script.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText())); - EventScriptPacket.Save(-1, containers.size(), scriptData); - } + this.handler = new DataScript(npc); + if (this.handler instanceof IScriptHandlerPacket) + ((IScriptHandlerPacket) this.handler).requestData(); } } diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptAllNPCs.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptAllNPCs.java deleted file mode 100644 index 6f0927cbc..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptAllNPCs.java +++ /dev/null @@ -1,76 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.GlobalNPCScriptPacket; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.NBTTags; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.data.GlobalNPCDataScript; - -import java.util.List; - -public class GuiScriptAllNPCs extends GuiScriptInterface { - private final GlobalNPCDataScript script = new GlobalNPCDataScript(null); - - public GuiScriptAllNPCs() { - hookList.add("init"); - hookList.add("tick"); - hookList.add("interact"); - hookList.add("dialog"); - hookList.add("damaged"); - hookList.add("killed"); - hookList.add("meleeAttack"); - hookList.add("meleeSwing"); - hookList.add("rangedLaunched"); - hookList.add("target"); - hookList.add("collide"); - hookList.add("kills"); - hookList.add("dialogClose"); - hookList.add("timer"); - hookList.add("targetLost"); - hookList.add("projectileTick"); - hookList.add("projectileImpact"); - - this.handler = this.script; - GlobalNPCScriptPacket.Get(); - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - script.setLanguage(compound.getString("ScriptLanguage")); - script.setEnabled(compound.getBoolean("ScriptEnabled")); - super.setGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(script); - container.readFromNBT(compound.getCompoundTag("Script")); - if (script.getScripts().isEmpty()) { - for (int i = 0; i < compound.getInteger("TotalScripts"); i++) { - script.getScripts().add(new ScriptContainer(script)); - } - } - script.getScripts().set(tab, container); - initGui(); - } - } - - public void save() { - if (loaded) { - super.save(); - List containers = this.script.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - GlobalNPCScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.script.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.script.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText())); - GlobalNPCScriptPacket.Save(-1, containers.size(), scriptData); - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptBlock.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptBlock.java deleted file mode 100644 index d5a5f3f86..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptBlock.java +++ /dev/null @@ -1,42 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.BlockScriptPacket; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.blocks.tiles.TileScripted; - - -public class GuiScriptBlock extends GuiScriptInterface { - private final TileScripted tileScripted; - - public GuiScriptBlock(int x, int y, int z) { - hookList.add("init"); - hookList.add("tick"); - hookList.add("interact"); - hookList.add("fallenUpon"); - hookList.add("redstone"); - hookList.add("broken"); - hookList.add("exploded"); - hookList.add("rainFilled"); - hookList.add("neighborChanged"); - hookList.add("clicked"); - hookList.add("harvested"); - hookList.add("collide"); - hookList.add("timer"); - - this.handler = this.tileScripted = (TileScripted) player.worldObj.getTileEntity(x, y, z); - BlockScriptPacket.Get(tileScripted.xCoord, tileScripted.yCoord, tileScripted.zCoord); - } - - public void setGuiData(NBTTagCompound compound) { - this.tileScripted.setNBT(compound); - super.setGuiData(compound); - loaded = true; - } - - public void save() { - if (loaded) { - super.save(); - BlockScriptPacket.Save(tileScripted.xCoord, tileScripted.yCoord, tileScripted.zCoord, this.tileScripted.getNBT(new NBTTagCompound())); - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptEffect.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptEffect.java deleted file mode 100644 index 33582ad88..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptEffect.java +++ /dev/null @@ -1,415 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.EffectScriptPacket; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.client.gui.GuiYesNo; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.StatCollector; -import noppes.npcs.NBTTags; -import noppes.npcs.NoppesStringUtils; -import noppes.npcs.client.gui.global.GuiNPCManageEffects; -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.GuiNpcTextField; -import noppes.npcs.client.gui.util.GuiScriptTextArea; -import noppes.npcs.client.gui.util.ICustomScrollListener; -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.controllers.ScriptContainer; -import noppes.npcs.controllers.data.CustomEffect; -import noppes.npcs.controllers.data.EffectScript; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class GuiScriptEffect extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener { - - private int activeTab = 0; - public Map> languages = new HashMap(); - private final int scriptLimit = 1; - public List hookList = new ArrayList(); - public String previousHookClicked = ""; - - public final GuiNPCManageEffects parent; - public final CustomEffect effect; - private final EffectScript scriptHandler; - boolean loaded = false; - - public GuiScriptEffect(GuiNPCManageEffects parent, CustomEffect effect) { - this.drawDefaultBackground = true; - this.closeOnEsc = true; - this.xSize = 420; - this.setBackground("menubg.png"); - - this.parent = parent; - this.effect = effect; - this.scriptHandler = new EffectScript(); - - for (EffectScript.ScriptType type : EffectScript.ScriptType.values()) { - this.hookList.add(type.function); - } - - EffectScriptPacket.Get(effect.id); - } - - 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; - this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings")); - int topXoffset = 0; - int topYoffset = 0; - - - if (this.scriptHandler.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); - ScriptContainer container = this.scriptHandler.container; - GuiScriptTextArea ta = 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); - ta.enableCodeHighlighting(); - ta.setListener(this); - this.addTextField(ta); - 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.scripts); - } - - 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)); - this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex())); - this.getButton(103).enabled = !this.languages.isEmpty(); - 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.scriptHandler.getEnabled() ? 1 : 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 + "function " + hook + "(event) {\n \n}\n"; - this.getTextField(2).setText(this.getTextField(2).getText() + addString); - this.previousHookClicked = ""; - } else { - this.previousHookClicked = hook; - } - - } - - public void unFocused(GuiNpcTextField textfield) { - } - - private String getConsoleText() { - Map map = this.scriptHandler.getConsoleText(); - StringBuilder builder = new StringBuilder(); - Iterator var3 = map.entrySet().iterator(); - - while (var3.hasNext()) { - Map.Entry entry = (Map.Entry) var3.next(); - builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n"); - } - - return builder.toString(); - } - - private int getScriptIndex() { - int i = 0; - - for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) { - String language = (String) var2.next(); - if (language.equalsIgnoreCase(this.scriptHandler.getLanguage())) { - return i; - } - } - - return 0; - } - - public void confirmClicked(boolean flag, int i) { - if (flag) { - if (i == 0) { - 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) { - this.scriptHandler.container = null; - this.activeTab = 0; - } - - if (i == 101) { - this.getTextField(2).setText(NoppesStringUtils.getClipboardContents()); - this.setScript(); - } - - if (i == 102) { - if (this.activeTab == 1) { - ScriptContainer container = this.scriptHandler.container; - container.script = ""; - } else { - this.scriptHandler.clearConsole(); - } - - this.initGui(); - } - } - - this.displayGuiScreen(this); - } - - protected void actionPerformed(GuiButton guibutton) { - if (guibutton.id == 0) { - this.setScript(); - this.activeTab = 0; - this.initGui(); - } - - if (guibutton.id == this.scriptLimit) { - if (scriptHandler.container == null) - this.scriptHandler.container = new ScriptContainer(this.scriptHandler); - 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)); - } - - 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 (guibutton.id == 100) { - NoppesStringUtils.setClipboardContents(this.getTextField(2).getText()); - } - - if (guibutton.id == 101) { - GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101); - this.displayGuiScreen(guiyesno); - } - - GuiYesNo container1; - if (guibutton.id == 102) { - container1 = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102); - this.displayGuiScreen(container1); - } - - if (guibutton.id == 103) { - this.scriptHandler.setLanguage(guibutton.displayString); - } - - if (guibutton.id == 104) { - this.scriptHandler.setEnabled(((GuiNpcButton) guibutton).getValue() == 1); - } - - if (guibutton.id == 105) { - container1 = new GuiYesNo(this, "", ((GuiNpcButton) guibutton).displayString, 10); - this.displayGuiScreen(container1); - } - - if (guibutton.id == 107) { - ScriptContainer container = this.scriptHandler.container; - if (container == null) { - container = new ScriptContainer(this.scriptHandler); - this.scriptHandler.container = container; - } - -// this.setSubGui(new EventGuiScriptList((List)this.languages.get(this.script.getLanguage()), container)); - } - - } - - private void setScript() { - if (this.activeTab == 1) { - ScriptContainer container = this.scriptHandler.container; - if (container == null) { - container = new ScriptContainer(this.scriptHandler); - this.scriptHandler.container = container; - } - - String text = this.getTextField(2).getText(); - text = text.replace("\r\n", "\n"); - text = text.replace("\r", "\n"); - container.script = text; - } - - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - this.scriptHandler.setLanguage(compound.getString("ScriptLanguage")); - this.scriptHandler.setEnabled(compound.getBoolean("ScriptEnabled")); - this.copiedSetGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(this.scriptHandler); - container.readFromNBT(compound.getCompoundTag("Script")); - this.scriptHandler.container = container; - this.initGui(); - } - } - - private void copiedSetGuiData(NBTTagCompound compound) { - NBTTagList data = compound.getTagList("Languages", 10); - HashMap languages = new HashMap(); - - for (int i = 0; i < data.tagCount(); ++i) { - NBTTagCompound comp = data.getCompoundTagAt(i); - ArrayList scripts = new ArrayList(); - NBTTagList list = comp.getTagList("Scripts", 8); - - for (int j = 0; j < list.tagCount(); ++j) { - scripts.add(list.getStringTagAt(j)); - } - - languages.put(comp.getString("Language"), scripts); - } - - this.languages = languages; - this.initGui(); - } - - public void save() { - if (loaded) { - this.setScript(); - - List containers = this.scriptHandler.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - EffectScriptPacket.Save(effect.id, i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.scriptHandler.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.scriptHandler.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.scriptHandler.getConsoleText())); - - EffectScriptPacket.Save(effect.id, -1, containers.size(), scriptData); - } - } - - public void textUpdate(String text) { - ScriptContainer container = this.scriptHandler.container; - if (container != null) { - container.script = text; - } - - } - - public void saveText(String text) { - ScriptContainer container = this.scriptHandler.container; - if (container != null) { - container.script = text; - } - - this.initGui(); - } - - @Override - public void close() { - this.save(); - parent.setWorldAndResolution(mc, width, height); - parent.initGui(); - mc.currentScreen = parent; - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptForge.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptForge.java deleted file mode 100644 index aea39d1a5..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptForge.java +++ /dev/null @@ -1,106 +0,0 @@ -package noppes.npcs.client.gui.script; - -import com.google.common.reflect.ClassPath; -import cpw.mods.fml.common.eventhandler.Event; -import cpw.mods.fml.common.gameevent.TickEvent; -import cpw.mods.fml.common.network.FMLNetworkEvent; -import kamkeel.npcs.network.packets.request.script.ForgeScriptPacket; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.entity.player.ItemTooltipEvent; -import net.minecraftforge.event.world.ChunkDataEvent; -import net.minecraftforge.event.world.ChunkEvent; -import net.minecraftforge.event.world.ChunkWatchEvent; -import net.minecraftforge.event.world.WorldEvent; -import noppes.npcs.NBTTags; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.data.ForgeDataScript; -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.Iterator; -import java.util.List; - -public class GuiScriptForge extends GuiScriptInterface { - private final ForgeDataScript script = new ForgeDataScript(); - - public GuiScriptForge() { - hookList.add("init"); - - ArrayList list = new ArrayList(); - try { - list.addAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("cpw.mods.fml.common.gameevent")); - list.addAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("net.minecraftforge.event")); - list.removeAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("net.minecraftforge.event.terraingen")); - } catch (IOException e) { - e.printStackTrace(); - } - - for (ClassPath.ClassInfo e1 : list) { - ClassPath.ClassInfo classLoader = e1; - Class infoClass = classLoader.load(); - ArrayList c = new ArrayList(Arrays.asList(infoClass.getDeclaredClasses())); - if (c.isEmpty()) { - c.add(infoClass); - } - Iterator var10 = c.iterator(); - while (var10.hasNext()) { - Class c1 = (Class) var10.next(); - if (!EntityEvent.EntityConstructing.class.isAssignableFrom(c1) && !WorldEvent.PotentialSpawns.class.isAssignableFrom(c1) && !TickEvent.RenderTickEvent.class.isAssignableFrom(c1) && !TickEvent.ClientTickEvent.class.isAssignableFrom(c1) && !FMLNetworkEvent.ClientCustomPacketEvent.class.isAssignableFrom(c1) && !ItemTooltipEvent.class.isAssignableFrom(c1) && Event.class.isAssignableFrom(c1) && !Modifier.isAbstract(c1.getModifiers()) && Modifier.isPublic(c1.getModifiers()) && !ChunkEvent.class.isAssignableFrom(c1) && !ChunkWatchEvent.class.isAssignableFrom(c1) && !ChunkDataEvent.class.isAssignableFrom(c1)) { - String eventName = c1.getName(); - int i = eventName.lastIndexOf("."); - eventName = StringUtils.uncapitalize(eventName.substring(i + 1).replace("$", "")); - - hookList.add(eventName); - } - } - } - hookList.add("onCNPCNaturalSpawn"); - - this.handler = this.script; - ForgeScriptPacket.Get(); - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - script.setLanguage(compound.getString("ScriptLanguage")); - script.setEnabled(compound.getBoolean("ScriptEnabled")); - super.setGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(script); - container.readFromNBT(compound.getCompoundTag("Script")); - if (script.getScripts().isEmpty()) { - for (int i = 0; i < compound.getInteger("TotalScripts"); i++) { - script.getScripts().add(new ScriptContainer(script)); - } - } - script.getScripts().set(tab, container); - initGui(); - } - } - - public void save() { - if (loaded) { - super.save(); - List containers = this.script.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - ForgeScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.script.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.script.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText())); - ForgeScriptPacket.Save(-1, containers.size(), scriptData); - } - } -} 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 15aec96dd..88770f1e0 100644 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptGlobal.java +++ b/src/main/java/noppes/npcs/client/gui/script/GuiScriptGlobal.java @@ -8,12 +8,15 @@ import net.minecraft.util.ResourceLocation; import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.IGuiData; +import noppes.npcs.controllers.data.ForgeDataScript; +import noppes.npcs.controllers.data.GlobalNPCDataScript; +import noppes.npcs.controllers.data.PlayerDataScript; 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() { @@ -65,13 +68,13 @@ public class GuiScriptGlobal extends GuiNPCInterface implements IGuiData { protected void actionPerformed(GuiButton guibutton) { if (guibutton.id == 0) { - this.displayGuiScreen(new GuiScriptPlayers()); + GuiScriptInterface.open(this, new PlayerDataScript(null)); } if (guibutton.id == 1) { - this.displayGuiScreen(new GuiScriptForge()); + GuiScriptInterface.open(this, new ForgeDataScript()); } if (guibutton.id == 2) { - this.displayGuiScreen(new GuiScriptAllNPCs()); + GuiScriptInterface.open(this, new GlobalNPCDataScript(null)); } if (guibutton.id > 2) { try { 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 185eb90fd..9607a7b2e 100644 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptInterface.java +++ b/src/main/java/noppes/npcs/client/gui/script/GuiScriptInterface.java @@ -1,7 +1,9 @@ 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.nbt.NBTTagCompound; @@ -17,42 +19,131 @@ import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextArea; import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.GuiScriptTextArea; +import noppes.npcs.client.gui.util.GuiUtil; import noppes.npcs.client.gui.util.ICustomScrollListener; 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; 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 { protected int activeTab = 0; public IScriptHandler handler; public Map> languages = new HashMap(); - private int scriptLimit = 1; + 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; + + + /** + * If true, uses scroll-based tab selection instead of top buttons + */ + protected boolean useScrollTabs = false; + + /** + * If true, shows settings/script toggle instead of numbered tabs + */ + protected boolean useSettingsToggle = false; + + // ==================== FULLSCREEN MODE ==================== + /** + * Whether the editor viewport is currently in fullscreen mode + */ + public static boolean isFullscreen = false; + + /** + * Fullscreen Layout Configuration + * Adjust these values to customize the fullscreen viewport appearance. + * All padding values are in scaled GUI pixels. + */ + public static class FullscreenConfig { + /** + * Padding from the top edge of the screen + */ + public static int paddingTop = 20; + /** + * Padding from the bottom edge of the screen + */ + public static int paddingBottom = 20; + /** + * Padding from the left edge of the screen + */ + public static int paddingLeft = 20; + /** + * Padding from the right edge of the screen + */ + public static int paddingRight = 20; + } + + /** + * Fullscreen toggle button drawn at top-right of viewport + */ + public final FullscreenButton fullscreenButton = new FullscreenButton(); public GuiScriptInterface() { this.drawDefaultBackground = true; this.closeOnEsc = true; this.xSize = 420; + this.isPannableGUI = true; this.setBackground("menubg.png"); } + /** + * Create a GuiScriptInterface for a handler without displaying it. + * Useful when a caller needs to return a GuiScreen (e.g. ClientProxy). + */ + public static GuiScriptInterface create(GuiScreen parent, IScriptHandler handler) { + GuiScriptInterface gui = new GuiScriptInterface(); + gui.handler = handler; + gui.parent = parent; + + // 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(); + + return gui; + } + + /** + * Open a GuiScriptInterface for a handler. + * Wraps the script in a SingleScriptHandler automatically. + */ + public static GuiScriptInterface open(GuiScreen parent, IScriptHandler handler) { + GuiScriptInterface gui = create(parent, handler); + Minecraft.getMinecraft().displayGuiScreen(gui); + return gui; + } + public void initGui() { - //this.xSize = (int)((double)this.width * 0.88D); + // ==================== 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); @@ -63,33 +154,96 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb super.initGui(); this.guiTop += 10; int yoffset = (int) ((double) this.ySize * 0.02D); - GuiMenuTopButton top; - this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings")); - int topXoffset = 0; - int topYoffset = 0; - for (int ta = 0; ta < this.handler.getScripts().size(); ++ta) { - if (ta % 20 == 0 && ta > 0) { - topYoffset -= 20; - topXoffset -= top.width + 20 * 22; + if (hookList.isEmpty()) + hookList = new ArrayList<>(handler.getHooks()); + + // ==================== TAB BUTTONS ==================== + // Skip standard tab creation for GUIs that use custom toggle/scroll tabs + if (!useSettingsToggle) { + GuiMenuTopButton top; + int topButtonsX = isFullscreen && activeTab != 0 ? FullscreenConfig.paddingLeft : this.guiLeft + 4; + int topButtonsY = isFullscreen && activeTab != 0 ? FullscreenConfig.paddingTop - 20 : this.guiTop - 17; + this.addTopButton(top = new GuiMenuTopButton(0, topButtonsX, topButtonsY, "gui.settings")); + + int topXoffset = 0; + int topYoffset = 0; + boolean isSingle = handler.isSingleContainer(); + if (!isSingle) { + for (int ta = 0; ta < this.handler.getScripts().size(); ++ta) { + if (ta % 20 == 0 && ta > 0) { + topYoffset -= 20; + topXoffset -= top.width + 20 * 22; + } + this.addTopButton(top = new GuiMenuTopButton(ta + 1, top.xPosition + top.width + topXoffset, + top.yPosition + topYoffset, ta + 1 + "")); + topXoffset = 0; + topYoffset = 0; + scriptLimit = ta + 2; + } } - this.addTopButton(top = new GuiMenuTopButton(ta + 1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, ta + 1 + "")); - topXoffset = 0; - topYoffset = 0; - scriptLimit = ta + 2; + + if (isSingle && handler.getSingleScript() != null) + this.addTopButton( + top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, + "Script")); + else if (this.handler.getScripts().size() < 100) + this.addTopButton(new GuiMenuTopButton(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.handler.getScripts().size() < 100) - this.addTopButton(new GuiMenuTopButton(scriptLimit, top.xPosition + top.width, top.yPosition, "+")); - - top = this.getTopButton(this.activeTab); - if (top == null) { - this.activeTab = 0; - top = this.getTopButton(0); + // ==================== SCRIPT EDITOR TAB (activeTab > 0) ==================== + // Skip for GUIs that handle their own view initialization (useSettingsToggle) + if (!useSettingsToggle) { + if (this.activeTab > 0) { + initScriptEditorTab(yoffset); + } else { + // ==================== SETTINGS TAB (activeTab == 0) ==================== + initSettingsTab(yoffset); + } } - top.active = true; - if (this.activeTab > 0) { + this.xSize = 420; + this.ySize = 256; + } + + /** + * Initialize the script editor tab layout. + * Handles both normal and fullscreen modes. + */ + private void initScriptEditorTab(int yoffset) { + IScriptUnit container = getCurrentContainer(); + + // ==================== CALCULATE VIEWPORT BOUNDS ==================== + int editorX, editorY, editorWidth, editorHeight; + + FullscreenConfig.paddingTop = 30; + FullscreenConfig.paddingBottom = 20; + FullscreenConfig.paddingLeft = 20; + FullscreenConfig.paddingRight = 20; + if (isFullscreen) { + // Fullscreen: viewport fills screen with configured padding + editorX = FullscreenConfig.paddingLeft; + editorY = FullscreenConfig.paddingTop; + editorWidth = this.width - FullscreenConfig.paddingLeft - FullscreenConfig.paddingRight; + editorHeight = this.height - FullscreenConfig.paddingTop - FullscreenConfig.paddingBottom; + } else { + // Normal: viewport within the GUI panel, leaving space for right panel + editorX = guiLeft + 1 + yoffset; + editorY = guiTop + yoffset; + editorWidth = xSize - 108 - yoffset; + editorHeight = (int) (ySize * 0.96) - yoffset * 2; + } + + // ==================== HOOKS SCROLL (hidden in fullscreen) ==================== + if (!isFullscreen) { GuiCustomScroll hooks = new GuiCustomScroll(this, 1); hooks.allowUserInput = false; hooks.setSize(108, 198); @@ -106,54 +260,178 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, guiTop + 5); hookLabel.color = 0xaaaaaa; addLabel(hookLabel); + } - ScriptContainer container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1); - GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, guiLeft + 1 + yoffset, guiTop + yoffset, xSize - 108 - yoffset, (int) (ySize * 0.96) - yoffset * 2, container == null ? "" : container.script); - ta.enableCodeHighlighting(); - ta.setListener(this); + // ==================== SCRIPT TEXT AREA ==================== + int idx = getActiveScriptIndex(); + GuiScriptTextArea activeArea = getActiveScriptArea(); + if (activeArea == null) { + activeArea = new GuiScriptTextArea(this, 2, editorX, editorY, editorWidth, editorHeight, + container == null ? "" : container.getScript()); + activeArea.setListener(this); + this.closeOnEsc(activeArea::closeOnEsc); + textAreas.put(idx, activeArea); + } else { + activeArea.init(editorX, editorY, editorWidth, editorHeight, + container == null ? "" : container.getScript()); + } - this.addTextField(ta); + // Set the scripting language for proper syntax highlighting + // Use the container's language if available, otherwise fall back to handler's language + String language = (container != null) ? container.getLanguage() : this.handler.getLanguage(); + activeArea.setLanguage(language); + // 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 -> { + if (e.isPress()) { + toggleFullscreen(); + } + }); + + activeArea.enableCodeHighlighting(); + this.addTextField(activeArea); + + // ==================== FULLSCREEN BUTTON ==================== + int scrollbarOffset = activeArea.hasVerticalScrollbar() ? -8 : -2; + fullscreenButton.initGui(editorX + editorWidth, editorY, scrollbarOffset); + + // ==================== RIGHT PANEL BUTTONS (hidden in fullscreen) ==================== + if (!isFullscreen) { 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")); + + // 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; scroll.guiTop = this.guiTop + 88 + yoffset; if (container != null) { - scroll.setList(container.scripts); + scroll.setList(container.getExternalScripts()); } - 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.canEdit = false; - var8.setFocused(true); - 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)); - this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, (String[]) this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex())); - this.getButton(103).enabled = this.languages.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)); - if (this.player.worldObj.isRemote) { - this.addButton(new GuiNpcButton(106, var9, this.guiTop + 55, 150, 20, "script.openfolder")); - } - - 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; + computePanBounds(editorX, editorY, editorWidth, editorHeight); + } + /** + * Initialize the settings tab layout (console view). + */ + private void initSettingsTab(int yoffset) { + 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.canEdit = false; + var8.setFocused(true); + 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.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.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)); + + if (this.player.worldObj.isRemote) { + this.addButton(new GuiNpcButton(106, var9, this.guiTop + 55, 150, 20, "script.openfolder")); + } + + 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")); + + // Disable all buttons until server data arrives + if (!serverDataReceived) { + for (int btnId : new int[]{100, 102, 103, 104, 106, 109, 110, 111, 112}) { + 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) { + this.xSize = x; + this.ySize = y; + return this; + } + + /** + * Get the script context for this GUI. + * Override in subclasses to return a different context. + * + * @return The script context (default: GLOBAL, or handler's context if available) + */ + protected ScriptContext getScriptContext() { + return handler.getContext(); + } + + @Override + 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); + } + + @Override + 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(i, j, k); } public String previousHookClicked = ""; @@ -162,18 +440,54 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { String hook = scroll.getSelected(); if (previousHookClicked.equals(hook)) { + IScriptUnit container = getCurrentContainer(); + if (container == null) + return; + String addString = ""; if (!this.getTextField(2).getText().isEmpty()) addString += "\n"; - addString += "function " + hook + "(event) {\n \n}\n"; + + // Generate the appropriate stub based on language + // hook is already the proper method name from EnumScriptType.function + addString += container.generateHookStub(hook, null); 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) { @@ -192,19 +506,86 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb return builder.toString(); } - private int getScriptIndex() { - int i = 0; - for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) { - String language = (String) var2.next(); - if (language.equalsIgnoreCase(this.handler.getLanguage())) { + /** + * Finds the index of the current handler's language within the available options. + * + * @return The 0-based index, or 0 if not found. + */ + public int getLanguageIndex() { + return getLanguageIndex(getLanguageOptions()); + } + + /** + * Finds the index of the current handler's language within the provided list. + * + * @param languageOptions The list of available languages to search. + * @return The 0-based index, or 0 if not found. + */ + protected int getLanguageIndex(List languageOptions) { + if (languageOptions == null || languageOptions.isEmpty()) + return 0; + + int i = 0; + String current = this.handler != null ? this.handler.getLanguage() : null; + for (String language : languageOptions) { + if (current != null && language.equalsIgnoreCase(current)) return i; - } + i++; } 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. + *

+ * This method prioritizes languages provided by the server through the {@link #languages} map. + * If "Java" is not present but the handler supports Janino, it injects "Java" into the options + * and ensures the client-side Janino script list is synchronized for the {@link EventGuiScriptList}. + * + * @return A list of language names available for selection. + */ + protected List getLanguageOptions() { + List options = new ArrayList<>(); + 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.languages == null) + this.languages = new HashMap(); + if (!this.languages.containsKey("Java")) + this.languages.put("Java", scripts); + options.add("Java"); + } + + return options; + } + public void confirmClicked(boolean flag, int i) { if (flag) { if (i == 0) { @@ -223,7 +604,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html"); } if (i == 10) { - this.handler.getScripts().remove(this.activeTab - 1); + handler.removeScriptUnit(this.activeTab - 1); this.activeTab = 0; } if (i == 101) { @@ -231,10 +612,10 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.setScript(); } if (i == 102) { - ScriptContainer container; + IScriptUnit container; if (this.activeTab > 0) { - container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1); - container.script = ""; + container = this.handler.getScripts().get(this.activeTab - 1); + container.setScript(""); } else { this.handler.clearConsole(); if (this.handler instanceof ScriptCustomItem) { @@ -248,17 +629,67 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb this.displayGuiScreen(this); } + public GuiScriptTextArea getActiveScriptArea() { + int idx = getActiveScriptIndex(); + if (idx >= 0 && textAreas.containsKey(idx)) + return textAreas.get(idx); + return null; + } + + /** + * Get the current script index for text area storage. + * Override in subclasses with different tab logic. + */ + protected int getActiveScriptIndex() { + return this.activeTab - 1; + } + + /** + * Get the current script container. + * Override in subclasses with different container access patterns. + */ + protected IScriptUnit getCurrentContainer() { + int idx = getActiveScriptIndex(); + if (idx >= 0 && idx < this.handler.getScripts().size()) + return this.handler.getScripts().get(idx); + return null; + } + + @Override + public GuiNpcTextField getTextField(int id) { + if (id == 2) { + GuiScriptTextArea area = getActiveScriptArea(); + if (area != null) + return area; + } + return super.getTextField(id); + } + @Override protected void actionPerformed(GuiButton guibutton) { if (guibutton.id >= 0 && guibutton.id < scriptLimit) { this.setScript(); this.activeTab = guibutton.id; this.initGui(); + + // Ensure JaninoScript is compiled after editing + IScriptUnit current = getCurrentContainer(); + if (current != null) + current.ensureCompiled(); } if (guibutton.id == scriptLimit) { - this.handler.getScripts().add(new ScriptContainer(this.handler)); - this.activeTab = this.handler.getScripts().size(); + if (handler.isSingleContainer()) { + if (handler.getSingleScript() == null) { + handler.addScriptUnit(createDefaultScriptUnit()); + } else { + this.setScript(); + } + this.activeTab = 1; + } else { + handler.addScriptUnit(createDefaultScriptUnit()); + this.activeTab = this.handler.getScripts().size(); + } this.initGui(); } @@ -287,7 +718,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb displayGuiScreen(guiyesno); } - ScriptContainer container; if (guibutton.id == 102) { GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102); displayGuiScreen(guiyesno); @@ -313,37 +743,114 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb } if (guibutton.id == 107) { - container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1); + IScriptUnit container = getCurrentContainer(); if (container == null) { - this.handler.getScripts().add(container = new ScriptContainer(this.handler)); + container = createDefaultScriptUnit(); + handler.addScriptUnit(container); } - this.setSubGui(new EventGuiScriptList((List) this.languages.get(this.handler.getLanguage()), container)); + String language = container.getLanguage(); + this.setSubGui(new EventGuiScriptList((List) this.languages.get(language), container)); + } + + // 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); + boolean currentIsJanino = currentUnit.isJanino(); + boolean targetIsJanino = "Java".equals(selectedLanguage); + + 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())); + 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())); + 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); + } + } } } - private void setScript() { - if (this.activeTab > 0) { - ScriptContainer container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1); + protected void setScript() { + if (this.activeTab > 0 || useScrollTabs) { + IScriptUnit container = getCurrentContainer(); + if (container == null) { - this.handler.getScripts().add(container = new ScriptContainer(this.handler)); + container = createDefaultScriptUnit(); + handler.addScriptUnit(container); } - String text = (this.getTextField(2)).getText(); - text = text.replace("\r\n", "\n"); - text = text.replace("\r", "\n"); - container.script = text; + if (container != null) { + String text = (this.getTextField(2)).getText(); + text = text.replace("\r\n", "\n"); + text = text.replace("\r", "\n"); + container.setScript(text); + } } } 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; + } + if (result.kind == IScriptHandlerPacket.GuiDataKind.METADATA) { + loadLanguagesData(compound); + return; + } + if (result.kind == IScriptHandlerPacket.GuiDataKind.TAB) { + initGui(); + return; + } + return; + } + + // For non-IScriptHandlerPacket handlers, ignore unrelated packets + if (!compound.hasKey("ScriptLanguage") && !compound.hasKey("Languages")) { + return; + } + loadLanguagesData(compound); + } + + + // ==================== UNIFIED SCRIPT DATA HANDLING ==================== + + /** + * Load languages data from NBT. + * Separated for potential override in subclasses if needed. + */ + protected void loadLanguagesData(NBTTagCompound compound) { NBTTagList data = compound.getTagList("Languages", 10); HashMap languages = new HashMap(); for (int i = 0; i < data.tagCount(); ++i) { NBTTagCompound comp = data.getCompoundTagAt(i); - ArrayList scripts = new ArrayList(); + java.util.ArrayList scripts = new java.util.ArrayList(); NBTTagList list = comp.getTagList("Scripts", 8); for (int j = 0; j < list.tagCount(); ++j) { @@ -353,28 +860,210 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb languages.put(comp.getString("Language"), scripts); } + if (handler != null && handler.supportsJanino()) { + List javaScripts = (List) languages.get("Java"); + if (javaScripts == null || javaScripts.isEmpty()) { + javaScripts = new ArrayList<>(); + if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) { + javaScripts.addAll(ScriptController.Instance.scripts.keySet()); + } + languages.put("Java", javaScripts); + } + } + this.languages = languages; + this.serverDataReceived = true; this.initGui(); } public void save() { - if (loaded) - this.setScript(); + if (!loaded || !serverDataReceived) + return; + + this.setScript(); + + if (handler instanceof IScriptHandlerPacket) + ((IScriptHandlerPacket) handler).sync(); + + } public void textUpdate(String text) { - ScriptContainer container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1); + IScriptUnit container = getCurrentContainer(); if (container != null) { - container.script = text; + container.setScript(text); } } + @Deprecated @Override + //NEVER USED public void saveText(String text) { - ScriptContainer container = handler.getScripts().get(activeTab); + IScriptUnit container = getCurrentContainer(); if (container != null) - container.script = text; + container.setScript(text); initGui(); } + + @Override + public void close() { + // Ensure JaninoScript is compiled after editing + IScriptUnit current = getCurrentContainer(); + if (current != null) + current.ensureCompiled(); + + if (parent != null) { + this.save(); + parent.setWorldAndResolution(mc, width, height); + parent.initGui(); + mc.currentScreen = parent; + } else + 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 ==================== + + /** + * Toggle fullscreen mode for the editor viewport. + * When entering fullscreen, maximizes the game window if it's not already. + */ + public void toggleFullscreen() { + isFullscreen = !isFullscreen; + + // When entering fullscreen, maximize the game window if not already fullscreen + if (isFullscreen && !Display.isFullscreen()) { + // Note: Display.setFullscreen(true) would make it truly fullscreen, + // but that's usually not desirable for an in-game editor. + // The viewport will expand to fill whatever window size exists. + } + + initGui(); + } + + /** + * Check if editor is currently in fullscreen mode + */ + public boolean isEditorFullscreen() { + return isFullscreen; + } + + // ==================== FULLSCREEN BUTTON ==================== + + /** + * Button to toggle fullscreen mode, displayed at top-right corner of viewport. + * Shows expand icon when minimized, collapse icon when fullscreen. + */ + + public class FullscreenButton { + public int x, y; + public int size = 12; + public boolean hovered = false; + + /** + * Initialize button position relative to viewport bounds + */ + public void initGui(int viewportEndX, int viewportY, int scrollbarOffset) { + // Position at top-right, accounting for scrollbar + this.x = viewportEndX + scrollbarOffset - size - 4; + this.y = viewportY + 4; + } + + /** + * Draw the fullscreen toggle button + */ + public void draw(int mouseX, int mouseY) { + hovered = isMouseOver(mouseX, mouseY); + int y = this.y + getYOffset(); + + // Button background + int bgColor = hovered ? 0x80666666 : 0x60444444; + GuiUtil.drawRectD(x, y, x + size, y + size, bgColor); + + // Draw corner brackets to indicate expand/collapse + int iconColor = hovered ? 0xFFFFFFFF : 0xFFAAAAAA; + int inset = 2; + int cornerLen = 3; + + if (isFullscreen) { + // Draw collapse icon (corners pointing inward) — inward L-shapes + int top = y + inset + 2; + int left = x + inset + 2; + int right = x + size - inset - 3; + int bottom = y + size - inset - 3; + + drawRect(left, top - cornerLen + 1, left + 1, top + 1, iconColor); + drawRect(left - cornerLen + 1, top, left + 1, top + 1, iconColor); + + drawRect(right, top, right + cornerLen, top + 1, iconColor); + drawRect(right, top - cornerLen + 1, right + 1, top + 1, iconColor); + + drawRect(left - cornerLen + 1, bottom, left + 1, bottom + 1, iconColor); + drawRect(left, bottom, left + 1, bottom + cornerLen, iconColor); + + drawRect(right, bottom, right + cornerLen, bottom + 1, iconColor); + drawRect(right, bottom, right + 1, bottom + cornerLen, iconColor); + + } else { + // Draw expand icon (corners pointing outward) ⌐¬⌙⌞ + // Top-left corner pointing outward + drawRect(x + inset, y + inset, x + inset + 1, y + inset + cornerLen, iconColor); + drawRect(x + inset, y + inset, x + inset + cornerLen, y + inset + 1, iconColor); + // Top-right corner pointing outward + drawRect(x + size - inset - 1, y + inset, x + size - inset, y + inset + cornerLen, iconColor); + drawRect(x + size - inset - cornerLen, y + inset, x + size - inset, y + inset + 1, iconColor); + // Bottom-left corner pointing outward + drawRect(x + inset, y + size - inset - cornerLen, x + inset + 1, y + size - inset, iconColor); + drawRect(x + inset, y + size - inset - 1, x + inset + cornerLen, y + size - inset, iconColor); + // Bottom-right corner pointing outward + drawRect(x + size - inset - 1, y + size - inset - cornerLen, x + size - inset, y + size - inset, + iconColor); + drawRect(x + size - inset - cornerLen, y + size - inset - 1, x + size - inset, y + size - inset, + iconColor); + } + } + + public void drawRect(int x1, int y1, int x2, int y2, int color) { + GuiUtil.drawRectD(x1, y1, x2, y2, color); + } + + /** + * Check if mouse is over the button + */ + public boolean isMouseOver(int mouseX, int mouseY) { + int y = this.y + getYOffset(); + return mouseX >= x && mouseX < x + size && mouseY >= y && mouseY < y + size; + } + + /** + * Handle click - returns true if click was consumed + */ + public boolean mouseClicked(int mouseX, int mouseY, int button) { + if (button == 0 && isMouseOver(mouseX, mouseY)) { + toggleFullscreen(); + return true; + } + return false; + } + + public int getYOffset() { + return GuiScriptTextArea.searchBar.getTotalHeight(); + } + } } diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptItem.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptItem.java deleted file mode 100644 index 23a29b90c..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptItem.java +++ /dev/null @@ -1,80 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.item.ItemScriptErrorPacket; -import kamkeel.npcs.network.packets.request.script.item.ItemScriptPacket; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.CustomItems; -import noppes.npcs.NBTTags; -import noppes.npcs.scripted.item.ScriptCustomItem; - -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class GuiScriptItem extends GuiScriptInterface { - private ScriptCustomItem item; - public static Map consoleText = new HashMap<>(); - - public GuiScriptItem() { - hookList.add("init"); - hookList.add("tick"); - hookList.add("tossed"); - hookList.add("pickedUp"); - hookList.add("spawn"); - hookList.add("interact"); - hookList.add("rightClick"); - hookList.add("attack"); - hookList.add("startItem"); - hookList.add("usingItem"); - hookList.add("stopItem"); - hookList.add("finishItem"); - - this.handler = this.item = new ScriptCustomItem(new ItemStack(CustomItems.scripted_item)); - ItemScriptErrorPacket.Get(); - ItemScriptPacket.Get(); - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("ItemScriptConsole")) { - consoleText = NBTTags.GetLongStringMap(compound.getTagList("ItemScriptConsole", 10)); - initGui(); - } else { - this.item.setMCNbt(compound); - this.item.loadScriptData(); - super.setGuiData(compound); - loaded = true; - } - } - - public void save() { - if (loaded) { - super.save(); - ItemScriptPacket.Save(this.item.getMCNbt()); - } - } - - protected String getConsoleText() { - Map map = consoleText; - StringBuilder builder = new StringBuilder(); - Iterator var3 = map.entrySet().iterator(); - - while (var3.hasNext()) { - Map.Entry entry = (Map.Entry) var3.next(); - builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n"); - } - - return builder.toString(); - } - - public void confirmClicked(boolean flag, int i) { - if (i == 102) { - if (activeTab <= 0) { - consoleText = new HashMap<>(); - ItemScriptErrorPacket.Clear(); - } - } - super.confirmClicked(flag, i); - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptLinkedItem.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptLinkedItem.java deleted file mode 100644 index 664c08d1f..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptLinkedItem.java +++ /dev/null @@ -1,428 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.item.LinkedItemScriptPacket; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.client.gui.GuiYesNo; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.StatCollector; -import noppes.npcs.NBTTags; -import noppes.npcs.NoppesStringUtils; -import noppes.npcs.client.gui.global.GuiNPCManageLinked; -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.GuiNpcTextField; -import noppes.npcs.client.gui.util.GuiScriptTextArea; -import noppes.npcs.client.gui.util.ICustomScrollListener; -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.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.data.LinkedItem; -import noppes.npcs.controllers.data.LinkedItemScript; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class GuiScriptLinkedItem extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener { - - private int activeTab = 0; - public Map> languages = new HashMap(); - private final int scriptLimit = 1; - public List hookList = new ArrayList(); - public String previousHookClicked = ""; - - public final GuiNPCManageLinked parent; - public final LinkedItem linkedItem; - private final LinkedItemScript scriptHandler; - boolean loaded = false; - - public GuiScriptLinkedItem(GuiNPCManageLinked parent, LinkedItem linkedItem) { - this.drawDefaultBackground = true; - this.closeOnEsc = true; - this.xSize = 420; - this.setBackground("menubg.png"); - - this.parent = parent; - this.linkedItem = linkedItem; - this.scriptHandler = new LinkedItemScript(); - - hookList.add(EnumScriptType.LINKED_ITEM_BUILD.function); - hookList.add(EnumScriptType.LINKED_ITEM_VERSION.function); - hookList.add(EnumScriptType.INIT.function); - hookList.add(EnumScriptType.TICK.function); - hookList.add(EnumScriptType.TOSSED.function); - hookList.add(EnumScriptType.PICKEDUP.function); - hookList.add(EnumScriptType.SPAWN.function); - hookList.add(EnumScriptType.INTERACT.function); - hookList.add(EnumScriptType.RIGHT_CLICK.function); - hookList.add(EnumScriptType.ATTACK.function); - hookList.add(EnumScriptType.START_USING_ITEM.function); - hookList.add(EnumScriptType.USING_ITEM.function); - hookList.add(EnumScriptType.STOP_USING_ITEM.function); - hookList.add(EnumScriptType.FINISH_USING_ITEM.function); - - LinkedItemScriptPacket.Get(linkedItem.id); - } - - 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; - this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings")); - int topXoffset = 0; - int topYoffset = 0; - - - if (this.scriptHandler.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); - ScriptContainer container = this.scriptHandler.container; - GuiScriptTextArea ta = 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); - ta.enableCodeHighlighting(); - ta.setListener(this); - this.addTextField(ta); - 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.scripts); - } - - 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)); - this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex())); - this.getButton(103).enabled = !this.languages.isEmpty(); - 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.scriptHandler.getEnabled() ? 1 : 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 + "function " + hook + "(event) {\n \n}\n"; - this.getTextField(2).setText(this.getTextField(2).getText() + addString); - this.previousHookClicked = ""; - } else { - this.previousHookClicked = hook; - } - - } - - public void unFocused(GuiNpcTextField textfield) { - } - - private String getConsoleText() { - Map map = this.scriptHandler.getConsoleText(); - StringBuilder builder = new StringBuilder(); - Iterator var3 = map.entrySet().iterator(); - - while (var3.hasNext()) { - Map.Entry entry = (Map.Entry) var3.next(); - builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n"); - } - - return builder.toString(); - } - - private int getScriptIndex() { - int i = 0; - - for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) { - String language = (String) var2.next(); - if (language.equalsIgnoreCase(this.scriptHandler.getLanguage())) { - return i; - } - } - - return 0; - } - - public void confirmClicked(boolean flag, int i) { - if (flag) { - if (i == 0) { - 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) { - this.scriptHandler.container = null; - this.activeTab = 0; - } - - if (i == 101) { - this.getTextField(2).setText(NoppesStringUtils.getClipboardContents()); - this.setScript(); - } - - if (i == 102) { - if (this.activeTab == 1) { - ScriptContainer container = this.scriptHandler.container; - container.script = ""; - } else { - this.scriptHandler.clearConsole(); - } - - this.initGui(); - } - } - - this.displayGuiScreen(this); - } - - protected void actionPerformed(GuiButton guibutton) { - if (guibutton.id == 0) { - this.setScript(); - this.activeTab = 0; - this.initGui(); - } - - if (guibutton.id == this.scriptLimit) { - if (scriptHandler.container == null) - this.scriptHandler.container = new ScriptContainer(this.scriptHandler); - 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)); - } - - 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 (guibutton.id == 100) { - NoppesStringUtils.setClipboardContents(this.getTextField(2).getText()); - } - - if (guibutton.id == 101) { - GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101); - this.displayGuiScreen(guiyesno); - } - - GuiYesNo container1; - if (guibutton.id == 102) { - container1 = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102); - this.displayGuiScreen(container1); - } - - if (guibutton.id == 103) { - this.scriptHandler.setLanguage(guibutton.displayString); - } - - if (guibutton.id == 104) { - this.scriptHandler.setEnabled(((GuiNpcButton) guibutton).getValue() == 1); - } - - if (guibutton.id == 105) { - container1 = new GuiYesNo(this, "", ((GuiNpcButton) guibutton).displayString, 10); - this.displayGuiScreen(container1); - } - - if (guibutton.id == 107) { - ScriptContainer container = this.scriptHandler.container; - if (container == null) { - container = new ScriptContainer(this.scriptHandler); - this.scriptHandler.container = container; - } - -// this.setSubGui(new EventGuiScriptList((List)this.languages.get(this.script.getLanguage()), container)); - } - - } - - private void setScript() { - if (this.activeTab == 1) { - ScriptContainer container = this.scriptHandler.container; - if (container == null) { - container = new ScriptContainer(this.scriptHandler); - this.scriptHandler.container = container; - } - - String text = this.getTextField(2).getText(); - text = text.replace("\r\n", "\n"); - text = text.replace("\r", "\n"); - container.script = text; - } - - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - this.scriptHandler.setLanguage(compound.getString("ScriptLanguage")); - this.scriptHandler.setEnabled(compound.getBoolean("ScriptEnabled")); - this.copiedSetGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(this.scriptHandler); - container.readFromNBT(compound.getCompoundTag("Script")); - this.scriptHandler.container = container; - this.initGui(); - } - - } - - private void copiedSetGuiData(NBTTagCompound compound) { - NBTTagList data = compound.getTagList("Languages", 10); - HashMap languages = new HashMap(); - - for (int i = 0; i < data.tagCount(); ++i) { - NBTTagCompound comp = data.getCompoundTagAt(i); - ArrayList scripts = new ArrayList(); - NBTTagList list = comp.getTagList("Scripts", 8); - - for (int j = 0; j < list.tagCount(); ++j) { - scripts.add(list.getStringTagAt(j)); - } - - languages.put(comp.getString("Language"), scripts); - } - - this.languages = languages; - this.initGui(); - } - - public void save() { - if (loaded) { - this.setScript(); - - List containers = this.scriptHandler.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - LinkedItemScriptPacket.Save(linkedItem.id, i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.scriptHandler.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.scriptHandler.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.scriptHandler.getConsoleText())); - - LinkedItemScriptPacket.Save(linkedItem.id, -1, containers.size(), scriptData); - } - } - - public void textUpdate(String text) { - ScriptContainer container = this.scriptHandler.container; - if (container != null) { - container.script = text; - } - - } - - public void saveText(String text) { - ScriptContainer container = this.scriptHandler.container; - if (container != null) { - container.script = text; - } - - this.initGui(); - } - - @Override - public void close() { - this.save(); - parent.setWorldAndResolution(mc, width, height); - parent.initGui(); - mc.currentScreen = parent; - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptPlayers.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptPlayers.java deleted file mode 100644 index 501e348d1..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptPlayers.java +++ /dev/null @@ -1,132 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.PlayerScriptPacket; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.NBTTags; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.data.EffectScript; -import noppes.npcs.controllers.data.PlayerDataScript; - -import java.util.List; - -public class GuiScriptPlayers extends GuiScriptInterface { - private PlayerDataScript script = new PlayerDataScript((EntityPlayer) null); - - public GuiScriptPlayers() { - hookList.add(EnumScriptType.INIT.function); - hookList.add(EnumScriptType.TICK.function); - hookList.add(EnumScriptType.INTERACT.function); - hookList.add(EnumScriptType.RIGHT_CLICK.function); - hookList.add(EnumScriptType.ATTACK.function); - hookList.add(EnumScriptType.ATTACKED.function); - hookList.add(EnumScriptType.DAMAGED_ENTITY.function); - hookList.add(EnumScriptType.DAMAGED.function); - hookList.add(EnumScriptType.KILLS.function); - hookList.add(EnumScriptType.KILLED.function); - hookList.add(EnumScriptType.DROP.function); - hookList.add(EnumScriptType.RESPAWN.function); - hookList.add(EnumScriptType.BREAK_BLOCK.function); - hookList.add(EnumScriptType.CHAT.function); - hookList.add(EnumScriptType.LOGIN.function); - hookList.add(EnumScriptType.LOGOUT.function); - hookList.add(EnumScriptType.KEY_PRESSED.function); - hookList.add(EnumScriptType.MOUSE_CLICKED.function); - hookList.add(EnumScriptType.TOSS.function); - hookList.add(EnumScriptType.PICKUP.function); - hookList.add(EnumScriptType.PICKUP_XP.function); - hookList.add(EnumScriptType.RANGED_CHARGE.function); - hookList.add(EnumScriptType.RANGED_LAUNCHED.function); - hookList.add(EnumScriptType.TIMER.function); - hookList.add(EnumScriptType.START_USING_ITEM.function); - hookList.add(EnumScriptType.USING_ITEM.function); - hookList.add(EnumScriptType.STOP_USING_ITEM.function); - hookList.add(EnumScriptType.FINISH_USING_ITEM.function); - hookList.add(EnumScriptType.CONTAINER_OPEN.function); - hookList.add(EnumScriptType.USE_HOE.function); - hookList.add(EnumScriptType.BONEMEAL.function); - hookList.add(EnumScriptType.FILL_BUCKET.function); - hookList.add(EnumScriptType.JUMP.function); - hookList.add(EnumScriptType.FALL.function); - hookList.add(EnumScriptType.WAKE_UP.function); - hookList.add(EnumScriptType.SLEEP.function); - hookList.add(EnumScriptType.PLAYSOUND.function); - hookList.add(EnumScriptType.LIGHTNING.function); - hookList.add(EnumScriptType.CHANGED_DIM.function); - hookList.add(EnumScriptType.QUEST_START.function); - hookList.add(EnumScriptType.QUEST_COMPLETED.function); - hookList.add(EnumScriptType.QUEST_TURNIN.function); - hookList.add(EnumScriptType.FACTION_POINTS.function); - hookList.add(EnumScriptType.DIALOG_OPEN.function); - hookList.add(EnumScriptType.DIALOG_OPTION.function); - hookList.add(EnumScriptType.DIALOG_CLOSE.function); - hookList.add(EnumScriptType.SCRIPT_COMMAND.function); - hookList.add(EnumScriptType.CUSTOM_GUI_CLOSED.function); - hookList.add(EnumScriptType.CUSTOM_GUI_BUTTON.function); - hookList.add(EnumScriptType.CUSTOM_GUI_SLOT.function); - hookList.add(EnumScriptType.CUSTOM_GUI_SLOT_CLICKED.function); - hookList.add(EnumScriptType.CUSTOM_GUI_SCROLL.function); - hookList.add(EnumScriptType.CUSTOM_GUI_TEXTFIELD.function); - hookList.add(EnumScriptType.PARTY_QUEST_COMPLETED.function); - hookList.add(EnumScriptType.PARTY_QUEST_SET.function); - hookList.add(EnumScriptType.PARTY_QUEST_TURNED_IN.function); - hookList.add(EnumScriptType.PARTY_INVITE.function); - hookList.add(EnumScriptType.PARTY_KICK.function); - hookList.add(EnumScriptType.PARTY_LEAVE.function); - hookList.add(EnumScriptType.PARTY_DISBAND.function); - hookList.add(EnumScriptType.ANIMATION_START.function); - hookList.add(EnumScriptType.ANIMATION_END.function); - hookList.add(EnumScriptType.ANIMATION_FRAME_ENTER.function); - hookList.add(EnumScriptType.ANIMATION_FRAME_EXIT.function); - hookList.add(EnumScriptType.PROFILE_CHANGE.function); - hookList.add(EnumScriptType.PROFILE_REMOVE.function); - hookList.add(EnumScriptType.PROFILE_CREATE.function); - hookList.add(EffectScript.ScriptType.OnEffectAdd.function); - hookList.add(EffectScript.ScriptType.OnEffectTick.function); - hookList.add(EffectScript.ScriptType.OnEffectRemove.function); - - this.handler = this.script; - PlayerScriptPacket.Get(); - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - script.setLanguage(compound.getString("ScriptLanguage")); - script.setEnabled(compound.getBoolean("ScriptEnabled")); - super.setGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(script); - container.readFromNBT(compound.getCompoundTag("Script")); - if (script.getScripts().isEmpty()) { - for (int i = 0; i < compound.getInteger("TotalScripts"); i++) { - script.getScripts().add(new ScriptContainer(script)); - } - } - script.getScripts().set(tab, container); - initGui(); - } - } - - public void save() { - if (loaded) { - super.save(); - List containers = this.script.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - PlayerScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.script.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.script.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText())); - PlayerScriptPacket.Save(-1, containers.size(), scriptData); - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/GuiScriptRecipe.java b/src/main/java/noppes/npcs/client/gui/script/GuiScriptRecipe.java deleted file mode 100644 index bb93052d7..000000000 --- a/src/main/java/noppes/npcs/client/gui/script/GuiScriptRecipe.java +++ /dev/null @@ -1,435 +0,0 @@ -package noppes.npcs.client.gui.script; - -import kamkeel.npcs.network.packets.request.script.RecipeScriptPacket; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiConfirmOpenLink; -import net.minecraft.client.gui.GuiYesNo; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.StatCollector; -import noppes.npcs.NBTTags; -import noppes.npcs.NoppesStringUtils; -import noppes.npcs.client.gui.global.GuiNpcManageRecipes; -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.GuiNpcTextField; -import noppes.npcs.client.gui.util.GuiScriptTextArea; -import noppes.npcs.client.gui.util.ICustomScrollListener; -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.controllers.ScriptContainer; -import noppes.npcs.controllers.data.RecipeAnvil; -import noppes.npcs.controllers.data.RecipeCarpentry; -import noppes.npcs.controllers.data.RecipeScript; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class GuiScriptRecipe extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener { - private int activeTab = 0; - public Map> languages = new HashMap(); - private final int scriptLimit = 1; - public List hookList = new ArrayList(); - public String previousHookClicked = ""; - - public final GuiNpcManageRecipes parent; - public final int recipeId; - public final boolean anvil; - - private final RecipeScript scriptHandler; - boolean loaded = false; - - public GuiScriptRecipe(GuiNpcManageRecipes parent, RecipeCarpentry recipe) { - this.drawDefaultBackground = true; - this.closeOnEsc = true; - this.xSize = 420; - this.setBackground("menubg.png"); - - this.parent = parent; - - this.scriptHandler = new RecipeScript(); - this.anvil = false; - this.recipeId = recipe.id; - - hookList.add(RecipeScript.ScriptType.PRE.function); - hookList.add(RecipeScript.ScriptType.POST.function); - - RecipeScriptPacket.Get(false, recipeId); - } - - public GuiScriptRecipe(GuiNpcManageRecipes parent, RecipeAnvil recipe) { - this.drawDefaultBackground = true; - this.closeOnEsc = true; - this.xSize = 420; - this.setBackground("menubg.png"); - - this.parent = parent; - - this.scriptHandler = new RecipeScript(); - this.anvil = true; - this.recipeId = recipe.id; - - hookList.add(RecipeScript.ScriptType.PRE.function); - hookList.add(RecipeScript.ScriptType.POST.function); - - RecipeScriptPacket.Get(true, recipeId); - } - - 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; - this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings")); - int topXoffset = 0; - int topYoffset = 0; - - if (this.scriptHandler.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); - ScriptContainer container = this.scriptHandler.container; - GuiScriptTextArea ta = 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); - ta.enableCodeHighlighting(); - ta.setListener(this); - this.addTextField(ta); - 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.scripts); - } - - 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)); - this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex())); - this.getButton(103).enabled = !this.languages.isEmpty(); - 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.scriptHandler.getEnabled() ? 1 : 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 + "function " + hook + "(event) {\n \n}\n"; - this.getTextField(2).setText(this.getTextField(2).getText() + addString); - this.previousHookClicked = ""; - } else { - this.previousHookClicked = hook; - } - - } - - public void unFocused(GuiNpcTextField textfield) { - } - - private String getConsoleText() { - Map map = this.scriptHandler.getConsoleText(); - StringBuilder builder = new StringBuilder(); - Iterator var3 = map.entrySet().iterator(); - - while (var3.hasNext()) { - Map.Entry entry = (Map.Entry) var3.next(); - builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n"); - } - - return builder.toString(); - } - - private int getScriptIndex() { - int i = 0; - - for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) { - String language = (String) var2.next(); - if (language.equalsIgnoreCase(this.scriptHandler.getLanguage())) { - return i; - } - } - - return 0; - } - - public void confirmClicked(boolean flag, int i) { - if (flag) { - if (i == 0) { - 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) { - this.scriptHandler.container = null; - this.activeTab = 0; - } - - if (i == 101) { - this.getTextField(2).setText(NoppesStringUtils.getClipboardContents()); - this.setScript(); - } - - if (i == 102) { - if (this.activeTab == 1) { - ScriptContainer container = this.scriptHandler.container; - container.script = ""; - } else { - this.scriptHandler.clearConsole(); - } - - this.initGui(); - } - } - - this.displayGuiScreen(this); - } - - protected void actionPerformed(GuiButton guibutton) { - if (guibutton.id == 0) { - this.setScript(); - this.activeTab = 0; - this.initGui(); - } - - if (guibutton.id == this.scriptLimit) { - if (scriptHandler.container == null) - this.scriptHandler.container = new ScriptContainer(this.scriptHandler); - 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)); - } - - 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 (guibutton.id == 100) { - NoppesStringUtils.setClipboardContents(this.getTextField(2).getText()); - } - - if (guibutton.id == 101) { - GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101); - this.displayGuiScreen(guiyesno); - } - - GuiYesNo container1; - if (guibutton.id == 102) { - container1 = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102); - this.displayGuiScreen(container1); - } - - if (guibutton.id == 103) { - this.scriptHandler.setLanguage(guibutton.displayString); - } - - if (guibutton.id == 104) { - this.scriptHandler.setEnabled(((GuiNpcButton) guibutton).getValue() == 1); - } - - if (guibutton.id == 105) { - container1 = new GuiYesNo(this, "", ((GuiNpcButton) guibutton).displayString, 10); - this.displayGuiScreen(container1); - } - - if (guibutton.id == 107) { - ScriptContainer container = this.scriptHandler.container; - if (container == null) { - container = new ScriptContainer(this.scriptHandler); - this.scriptHandler.container = container; - } - -// this.setSubGui(new EventGuiScriptList((List)this.languages.get(this.script.getLanguage()), container)); - } - - } - - private void setScript() { - if (this.activeTab == 1) { - ScriptContainer container = this.scriptHandler.container; - if (container == null) { - container = new ScriptContainer(this.scriptHandler); - this.scriptHandler.container = container; - } - - String text = this.getTextField(2).getText(); - text = text.replace("\r\n", "\n"); - text = text.replace("\r", "\n"); - container.script = text; - } - - } - - public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("LoadComplete")) { - loaded = true; - return; - } - - if (!compound.hasKey("Tab")) { - this.scriptHandler.setLanguage(compound.getString("ScriptLanguage")); - this.scriptHandler.setEnabled(compound.getBoolean("ScriptEnabled")); - this.copiedSetGuiData(compound); - } else { - int tab = compound.getInteger("Tab"); - ScriptContainer container = new ScriptContainer(this.scriptHandler); - container.readFromNBT(compound.getCompoundTag("Script")); - this.scriptHandler.container = container; - this.initGui(); - } - } - - private void copiedSetGuiData(NBTTagCompound compound) { - NBTTagList data = compound.getTagList("Languages", 10); - HashMap languages = new HashMap(); - - for (int i = 0; i < data.tagCount(); ++i) { - NBTTagCompound comp = data.getCompoundTagAt(i); - ArrayList scripts = new ArrayList(); - NBTTagList list = comp.getTagList("Scripts", 8); - - for (int j = 0; j < list.tagCount(); ++j) { - scripts.add(list.getStringTagAt(j)); - } - - languages.put(comp.getString("Language"), scripts); - } - - this.languages = languages; - this.initGui(); - } - - public void save() { - if (loaded) { - this.setScript(); - - List containers = this.scriptHandler.getScripts(); - for (int i = 0; i < containers.size(); i++) { - ScriptContainer container = containers.get(i); - RecipeScriptPacket.Save(anvil, recipeId, i, containers.size(), container.writeToNBT(new NBTTagCompound())); - } - NBTTagCompound scriptData = new NBTTagCompound(); - scriptData.setString("ScriptLanguage", this.scriptHandler.getLanguage()); - scriptData.setBoolean("ScriptEnabled", this.scriptHandler.getEnabled()); - scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.scriptHandler.getConsoleText())); - - RecipeScriptPacket.Save(anvil, recipeId, -1, containers.size(), scriptData); - } - } - - public void textUpdate(String text) { - ScriptContainer container = this.scriptHandler.container; - if (container != null) { - container.script = text; - } - - } - - public void saveText(String text) { - ScriptContainer container = this.scriptHandler.container; - if (container != null) { - container.script = text; - } - - this.initGui(); - } - - @Override - public void close() { - this.save(); - parent.setWorldAndResolution(mc, width, height); - parent.initGui(); - mc.currentScreen = parent; - } -} diff --git a/src/main/java/noppes/npcs/client/gui/script/SubGuiSelectList.java b/src/main/java/noppes/npcs/client/gui/script/SubGuiSelectList.java new file mode 100644 index 000000000..2e20a6ed5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/script/SubGuiSelectList.java @@ -0,0 +1,123 @@ +package noppes.npcs.client.gui.script; + +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiCustomScroll; +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.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +public class SubGuiSelectList extends SubGuiInterface { + private GuiCustomScroll scroll1; + private GuiCustomScroll scroll2; + + public String allName, selectedName; + public List all; + public List selected; + + public SubGuiSelectList(List all, List selected, String allName, String selectedName) { + setBackground("menubg.png"); + xSize = 346; + ySize = 216; + this.allName = allName; + this.selectedName = selectedName; + + if (all == null) + all = new ArrayList<>(); + this.all = all; + + if (selected == null) + selected = new ArrayList<>(); + this.selected = selected; + } + + @Override + public void initGui() { + super.initGui(); + if (scroll1 == null) { + scroll1 = new GuiCustomScroll(this, 0); + scroll1.setSize(140, 180); + } + + addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 22, guiTop - 17, "X")); + + scroll1.guiLeft = guiLeft + 4; + scroll1.guiTop = guiTop + 14; + this.addScroll(scroll1); + addLabel(new GuiNpcLabel(1, allName, guiLeft + 4, guiTop + 4)); + + if (scroll2 == null) { + scroll2 = new GuiCustomScroll(this, 1); + scroll2.setSize(140, 180); + } + scroll2.guiLeft = guiLeft + 200; + scroll2.guiTop = guiTop + 14; + this.addScroll(scroll2); + addLabel(new GuiNpcLabel(2, selectedName, guiLeft + 200, guiTop + 4)); + + List tempAll = new ArrayList<>(all); + tempAll.removeAll(selected); + scroll1.setList(tempAll); + scroll2.setList(selected); + + addButton(new GuiNpcButton(1, guiLeft + 145, guiTop + 40, 55, 20, ">")); + addButton(new GuiNpcButton(2, guiLeft + 145, guiTop + 62, 55, 20, "<")); + + addButton(new GuiNpcButton(3, guiLeft + 145, guiTop + 90, 55, 20, ">>")); + addButton(new GuiNpcButton(4, guiLeft + 145, guiTop + 112, 55, 20, "<<")); + + addButton(new GuiNpcButton(66, guiLeft + 260, guiTop + 194, 60, 20, "gui.done")); + } + + protected void actionPerformed(GuiButton guibutton) { + GuiNpcButton button = (GuiNpcButton) guibutton; + + if (button.id == -1) { + close(); + return; + } + + if (button.id == 1) { + if (scroll1.hasSelected()) { + selected.add(scroll1.getSelected()); + + scroll1.selected = -1; + scroll2.selected = -1; + initGui(); + } + } + if (button.id == 2) { + if (scroll2.hasSelected()) { + selected.remove(scroll2.getSelected()); + scroll2.selected = -1; + initGui(); + } + } + if (button.id == 3) { + selected.clear(); + for (String type : all) + selected.add(type); + + scroll1.selected = -1; + scroll2.selected = -1; + initGui(); + } + if (button.id == 4) { + selected.clear(); + scroll1.selected = -1; + scroll2.selected = -1; + initGui(); + } + if (button.id == 66) { + close(); + } + } + + @Override + public void save() { + + } +} diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java new file mode 100644 index 000000000..e6f2ce61c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java @@ -0,0 +1,268 @@ +package noppes.npcs.client.gui.select; + +import kamkeel.npcs.network.PacketClient; +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.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.Vector; + +/** + * Animation selection dialog for choosing global animations. + * Toggle between Built-in animations (by name) and Custom animations (by ID). + */ +public class GuiAnimationSelection extends SubGuiInterface implements ICustomScrollListener, IScrollData { + + private GuiCustomScroll scrollAnimations; + + // Built-in animations (name only, no ID) + private HashMap builtInData = new HashMap<>(); + // Custom/user animations (name -> ID) + private HashMap customData = new HashMap<>(); + + // View mode: true = built-in, false = custom + private boolean showingBuiltIn = true; + + // Initial values passed in + private int initialAnimationId; + private String initialAnimationName; + + // Selected values to return + public int selectedAnimationId = -1; + public String selectedBuiltInName = ""; + + private String selectedCustomName = null; + private String search = ""; + + /** + * Constructor for selecting by ID (user animations). + */ + public GuiAnimationSelection(int animationId) { + this(animationId, ""); + } + + /** + * Constructor for selecting by name (built-in) or ID (user). + */ + public GuiAnimationSelection(int animationId, String animationName) { + title = ""; + setBackground("menubg.png"); + xSize = 220; + ySize = 226; + + this.initialAnimationId = animationId; + this.initialAnimationName = animationName != null ? animationName : ""; + this.selectedAnimationId = animationId; + this.selectedBuiltInName = this.initialAnimationName; + + // Start showing built-in if we have a built-in name, otherwise custom + this.showingBuiltIn = !this.initialAnimationName.isEmpty(); + + // Request animation data from server + PacketClient.sendClient(new AnimationsGetPacket()); + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 4; + + // Toggle button for switching views + String viewLabel = showingBuiltIn ? "gui.builtinAnimations" : "gui.customAnimations"; + this.addButton(new GuiNpcButton(10, guiLeft + 4, y, 212, 20, viewLabel)); + y += 24; + + // Animation scroll list + if (scrollAnimations == null) { + scrollAnimations = new GuiCustomScroll(this, 0, 0); + scrollAnimations.setSize(212, 130); + } + scrollAnimations.setList(getSearchList()); + + // Set selection based on current mode + if (showingBuiltIn && !selectedBuiltInName.isEmpty()) { + scrollAnimations.setSelected(selectedBuiltInName); + } else if (!showingBuiltIn && selectedCustomName != null) { + scrollAnimations.setSelected(selectedCustomName); + } + + scrollAnimations.guiLeft = guiLeft + 4; + scrollAnimations.guiTop = y; + this.addScroll(scrollAnimations); + y += 134; + + // Search textbox + addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, y, 212, 20, search)); + y += 24; + + // Buttons + this.addButton(new GuiNpcButton(1, guiLeft + 4, y, 50, 20, "gui.clear")); + this.addButton(new GuiNpcButton(3, guiLeft + xSize - 108, y, 50, 20, "gui.cancel")); + this.addButton(new GuiNpcButton(2, guiLeft + xSize - 56, y, 50, 20, "gui.done")); + } + + @Override + public void setData(Vector list, HashMap data, EnumScrollData type) { + if (type == EnumScrollData.BUILTIN_ANIMATIONS) { + this.builtInData = data; + + // Check if initial name matches a built-in animation + if (!initialAnimationName.isEmpty()) { + for (String name : builtInData.keySet()) { + if (name.equalsIgnoreCase(initialAnimationName)) { + selectedBuiltInName = name; + selectedAnimationId = -1; + selectedCustomName = null; + showingBuiltIn = true; + break; + } + } + } + } else if (type == EnumScrollData.ANIMATIONS) { + this.customData = data; + + // Find the name for our initial animation ID (if not using built-in) + if (selectedBuiltInName.isEmpty() && initialAnimationId >= 0) { + for (String name : data.keySet()) { + if (data.get(name) == initialAnimationId) { + selectedCustomName = name; + showingBuiltIn = false; + break; + } + } + } + } + + if (scrollAnimations != null) { + scrollAnimations.setList(getSearchList()); + if (showingBuiltIn && !selectedBuiltInName.isEmpty()) { + scrollAnimations.setSelected(selectedBuiltInName); + } else if (!showingBuiltIn && selectedCustomName != null) { + scrollAnimations.setSelected(selectedCustomName); + } + } + } + + @Override + public void setSelected(String selected) { + // Not used in this implementation + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(55) != null) { + if (getTextField(55).isFocused()) { + if (search.equals(getTextField(55).getText())) + return; + search = getTextField(55).getText().toLowerCase(); + if (scrollAnimations != null) { + scrollAnimations.resetScroll(); + scrollAnimations.setList(getSearchList()); + } + } + } + } + + private List getSearchList() { + HashMap sourceData = showingBuiltIn ? builtInData : customData; + + if (search.isEmpty()) { + return new ArrayList<>(sourceData.keySet()); + } + List list = new ArrayList<>(); + for (String name : sourceData.keySet()) { + if (name.toLowerCase().contains(search)) + list.add(name); + } + return list; + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + String selected = scrollAnimations.getSelected(); + if (selected == null) return; + + if (showingBuiltIn) { + if (builtInData.containsKey(selected)) { + selectedBuiltInName = selected; + selectedAnimationId = -1; + selectedCustomName = null; + } + } else { + if (customData.containsKey(selected)) { + selectedCustomName = selected; + selectedAnimationId = customData.get(selected); + selectedBuiltInName = ""; + } + } + initGui(); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + // Double-click to confirm selection + if (!selectedBuiltInName.isEmpty() || selectedAnimationId >= 0) { + close(); + } + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + + // Toggle view button + if (id == 10) { + showingBuiltIn = !showingBuiltIn; + search = ""; + if (scrollAnimations != null) { + scrollAnimations.resetScroll(); + } + initGui(); + } + // Clear + else if (id == 1) { + selectedBuiltInName = ""; + selectedAnimationId = -1; + selectedCustomName = null; + close(); + } + // Done + else if (id == 2) { + close(); + } + // Cancel + else if (id == 3) { + selectedAnimationId = initialAnimationId; + selectedBuiltInName = initialAnimationName; + close(); + } + } + + /** + * Get the name of the selected animation (for display purposes). + */ + public String getSelectedName() { + if (!selectedBuiltInName.isEmpty()) { + return selectedBuiltInName; + } + return selectedCustomName; + } + + /** + * Check if a built-in animation was selected. + */ + public boolean isBuiltInSelected() { + return !selectedBuiltInName.isEmpty(); + } +} 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 341b3cc48..aba735970 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java @@ -39,7 +39,6 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL public static HashMap> cachedDomains = new HashMap<>(); public GuiSoundSelection(String sound) { - drawDefaultBackground = false; title = ""; setBackground("menubg.png"); xSize = 366; @@ -146,11 +145,12 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL scrollSounds.resetScroll(); getTextField(66).setText(""); soundSearch = ""; + initGui(); } 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 4f1bccfaf..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; @@ -371,6 +381,7 @@ public class GuiTextureSelection extends SubGuiInterface implements ICustomScrol selectedDomain = domain; this.location = location; } + static class TextureData { String domain; String absoluteName; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java new file mode 100644 index 000000000..a71c9762f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiAuctionNavButton.java @@ -0,0 +1,197 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import java.util.ArrayList; +import java.util.List; + +/** + * Configurable textured button for auction GUI. + * Supports custom button sizes, icon sizes, and textures. + */ +public class GuiAuctionNavButton extends GuiNpcButton { + // Default auction button textures (18x18) + private static final ResourceLocation DEFAULT_NORMAL = new ResourceLocation("customnpcs", "textures/gui/auction/button.png"); + private static final ResourceLocation DEFAULT_PRESSED = new ResourceLocation("customnpcs", "textures/gui/auction/button_press.png"); + + // Textures + private ResourceLocation textureNormal; + private ResourceLocation texturePressed; + private ResourceLocation iconTexture; + private ItemStack iconItem; + + // Dimensions + private int buttonSize; + private int iconSize; + + // State + private boolean selected; + private boolean isToggle; // Toggle buttons can be clicked when selected, nav buttons cannot + private final String tooltipKey; + private List customTooltip; + + /** + * Create a button with default 18x18 size and 16x16 icon using default textures. + */ + public GuiAuctionNavButton(int id, int x, int y, String tooltipKey, ResourceLocation iconTexture) { + this(id, x, y, 18, 16, tooltipKey, iconTexture, DEFAULT_NORMAL, DEFAULT_PRESSED); + } + + /** + * Create a button with default 18x18 size and 16x16 icon with an item icon. + */ + public GuiAuctionNavButton(int id, int x, int y, String tooltipKey, ItemStack iconItem) { + super(id, x, y, 18, 18, ""); + this.tooltipKey = tooltipKey; + this.iconTexture = null; + this.iconItem = iconItem; + this.buttonSize = 18; + this.iconSize = 16; + this.textureNormal = DEFAULT_NORMAL; + this.texturePressed = DEFAULT_PRESSED; + this.selected = false; + this.customTooltip = null; + } + + /** + * 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 texturePressed Background texture for pressed/hover state + */ + public GuiAuctionNavButton(int id, int x, int y, int buttonSize, int iconSize, String tooltipKey, + ResourceLocation iconTexture, ResourceLocation textureNormal, ResourceLocation texturePressed) { + super(id, x, y, buttonSize, buttonSize, ""); + this.tooltipKey = tooltipKey; + this.iconTexture = iconTexture; + this.iconItem = null; + this.buttonSize = buttonSize; + this.iconSize = iconSize; + this.textureNormal = textureNormal; + this.texturePressed = texturePressed; + this.selected = false; + this.customTooltip = null; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + public boolean isSelected() { + return selected; + } + + /** + * Set whether this is a toggle button. + * Toggle buttons can be clicked when selected (to toggle off). + * Nav buttons cannot be clicked when selected. + */ + public GuiAuctionNavButton setToggle(boolean toggle) { + this.isToggle = toggle; + return this; + } + + public boolean isHovered() { + return field_146123_n; + } + + /** + * Set a custom multi-line tooltip. If null, uses the default tooltipKey translation. + */ + public void setCustomTooltip(List tooltip) { + this.customTooltip = tooltip; + } + + /** + * Get the tooltip lines for display. + */ + public List getTooltipLines() { + if (customTooltip != null && !customTooltip.isEmpty()) { + return customTooltip; + } + List lines = new ArrayList<>(); + if (tooltipKey != null && !tooltipKey.isEmpty()) { + lines.add(StatCollector.translateToLocal(tooltipKey)); + } + return lines; + } + + public String getTooltipText() { + return tooltipKey != null ? StatCollector.translateToLocal(tooltipKey) : ""; + } + + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY) { + if (!this.visible) { + return; + } + + // Check if mouse is hovering + boolean hovered = mouseX >= xPosition && mouseX < xPosition + width + && mouseY >= yPosition && mouseY < yPosition + height; + field_146123_n = hovered; + + // Draw button background + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + if (selected || hovered) { + mc.getTextureManager().bindTexture(texturePressed); + } else { + mc.getTextureManager().bindTexture(textureNormal); + } + Gui.func_146110_a(xPosition, yPosition, 0, 0, buttonSize, buttonSize, buttonSize, buttonSize); + + // Calculate icon offset to center it + int iconOffset = (buttonSize - iconSize) / 2; + int iconX = xPosition + iconOffset; + int iconY = yPosition + iconOffset; + + if (iconItem != null) { + // Render item + RenderHelper.enableGUIStandardItemLighting(); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + RenderItem itemRenderer = RenderItem.getInstance(); + itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, iconItem, iconX, iconY); + GL11.glDisable(GL11.GL_LIGHTING); + RenderHelper.disableStandardItemLighting(); + } else if (iconTexture != null) { + // Render texture icon + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.getTextureManager().bindTexture(iconTexture); + Gui.func_146110_a(iconX, iconY, 0, 0, iconSize, iconSize, iconSize, iconSize); + } + } + + @Override + public boolean mousePressed(Minecraft minecraft, int mouseX, int mouseY) { + // Don't allow clicking if selected (for nav buttons, not toggle buttons) + if (selected && !isToggle) { + return false; + } + return enabled && visible && mouseX >= xPosition && mouseX < xPosition + width + && mouseY >= yPosition && mouseY < yPosition + height; + } + + /** + * Check if this button contains the given mouse coordinates. + */ + public boolean isMouseOver(int mouseX, int mouseY) { + return mouseX >= xPosition && mouseX < xPosition + width + && mouseY >= yPosition && mouseY < yPosition + height; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java index b4049bc8a..cd3e7077c 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java @@ -224,6 +224,15 @@ public abstract class GuiContainerNPCInterface extends GuiContainer { RenderHelper.disableStandardItemLighting(); subgui.drawScreen(i, j, f); } + + // Draw hover text for buttons + boolean subGui = hasSubGui(); + for (GuiCustomScroll scroll : new ArrayList(scrolls.values())) { + scroll.drawHover(i, j); + } + for (GuiNpcButton button : buttons.values()) { + button.drawHover(i, j, subGui); + } } @Override @@ -237,7 +246,10 @@ public abstract class GuiContainerNPCInterface extends GuiContainer { } public void closeSubGui(SubGuiInterface gui) { - subgui = null; + // Only null out subgui if it wasn't replaced by a new one during subGuiClosed + if (subgui == gui) { + subgui = null; + } } public boolean hasSubGui() { diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface2.java b/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface2.java index 3455e4986..5e97ec19a 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface2.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface2.java @@ -61,9 +61,9 @@ public abstract class GuiContainerNPCInterface2 extends GuiContainerNPCInterface GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); mc.renderEngine.bindTexture(defaultBackground2); if (this instanceof GuiNpcTraderSetup) - drawTexturedModalRect(guiLeft + xSize - 210, guiTop, 46, 0, 256, 220); + drawTexturedModalRect(guiLeft + xSize - 210, guiTop, 46, 0, 210, 220); else - drawTexturedModalRect(guiLeft + xSize - 230, guiTop, 26, 0, 256, 220); + drawTexturedModalRect(guiLeft + xSize - 230, guiTop, 26, 0, 230, 220); menu.drawElements(fontRendererObj, i, j, mc, f); 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 0bf481ffb..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; @@ -104,8 +105,10 @@ public class GuiCustomScroll extends GuiScreen { GL11.glTranslatef(guiLeft, guiTop, 0.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - if (selectable) + if (selectable && !hasSubGUI) hover = getMouseOver(i, j); + else if (hasSubGUI) + hover = -1; drawItems(); @@ -198,7 +201,8 @@ public class GuiCustomScroll extends GuiScreen { int k = (14 * i + 4) - scrollY; if (k >= 4 && k + 12 < ySize) { int xOffset = scrollHeight < ySize - 8 ? 0 : 10; - String displayString = StatCollector.translateToLocal(list.get(i)); + String rawEntry = list.get(i); + String displayString = StatCollector.translateToLocal(rawEntry); String text = ""; float maxWidth = (xSize + xOffset - 8) * 0.8f; @@ -213,16 +217,26 @@ public class GuiCustomScroll extends GuiScreen { text += "..."; } else text = displayString; - if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { + + // Non-interactive entries (headers/separators) — colored, no hover/selection + Integer customColor = colors.get(rawEntry); + if (nonInteractive.contains(rawEntry)) { + if (!text.isEmpty()) + 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); + } } } @@ -237,13 +251,17 @@ public class GuiCustomScroll extends GuiScreen { private int getMouseOver(int i, int j) { i -= guiLeft; j -= guiTop; - //fontRenderer.drawString(".", i , j, 0xffffff); if (i >= 4 && i < xSize - 4 && j >= 4 && j < ySize) { for (int j1 = 0; j1 < list.size(); j1++) { if (!mouseInOption(i, j, j1)) { continue; } + // Skip non-interactive entries (headers/separators) + if (nonInteractive.contains(list.get(j1))) { + continue; + } + return j1; } @@ -365,6 +383,13 @@ public class GuiCustomScroll extends GuiScreen { return this; } + public void setSelectable(boolean selectable) { + this.selectable = selectable; + if (!selectable) { + hover = -1; + } + } + public boolean isMouseOver(int x, int y) { return x >= this.guiLeft && x <= this.guiLeft + this.xSize && y >= this.guiTop && y <= this.guiTop + this.ySize; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java index a69d449e7..b147a3af9 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java @@ -1,5 +1,6 @@ package noppes.npcs.client.gui.util; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.StatCollector; import noppes.npcs.client.gui.GuiNpcMobSpawner; import noppes.npcs.controllers.data.Tag; @@ -7,10 +8,10 @@ import noppes.npcs.controllers.data.Tag; import java.util.UUID; public class GuiCustomScrollCloner extends GuiCustomScroll { - private final GuiNpcMobSpawner parent; + private final IClonerGui parent; - public GuiCustomScrollCloner(GuiNpcMobSpawner parent, int id) { - super(parent, id); + public GuiCustomScrollCloner(IClonerGui parent, int id) { + super((GuiScreen) parent, id); this.parent = parent; } @@ -38,24 +39,25 @@ public class GuiCustomScrollCloner extends GuiCustomScroll { text += "..."; } else text = displayString; - if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { + int itemColor = this.colors.getOrDefault(list.get(i), 0xffffff); + if ((multipleSelection && selectedList.contains(list.get(i))) || (!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, this.colors.getOrDefault(text, 0xffffff)); + fontRendererObj.drawString(text, j, k, itemColor); } else if (i == hover) { fontRendererObj.drawString(text, j, k, 0x00ff00); } else { - fontRendererObj.drawString(text, j, k, this.colors.getOrDefault(text, 0xffffff)); + fontRendererObj.drawString(text, j, k, itemColor); } - if ((this.parent.getShowingClones() == 0 || this.parent.getShowingClones() == 2) && this.parent.tagMap != null) { + if ((parent.getShowingClones() == 0 || parent.getShowingClones() == 2) && parent.getTagMap() != null) { int tagStartX = j + fontRendererObj.getStringWidth(displayString) + 3; if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { - if (this.parent.tagMap.hasClone(list.get(i))) { - for (UUID tagUUID : this.parent.tagMap.getUUIDsList(list.get(i))) { - Tag tag = this.parent.tags.get(tagUUID); + if (parent.getTagMap().hasClone(list.get(i))) { + for (UUID tagUUID : parent.getTagMap().getUUIDsList(list.get(i))) { + Tag tag = parent.getTags().get(tagUUID); if (tag != null) { if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { fontRendererObj.drawString("[" + tag.name + "]", tagStartX, k, tag.color); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollIcons.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollIcons.java new file mode 100644 index 000000000..78686dac0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollIcons.java @@ -0,0 +1,108 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +public class GuiCustomScrollIcons extends GuiCustomScroll { + public static final int ICON_NONE = 0; + public static final int ICON_TAB = 1; + public static final int ICON_FOLDER = 2; + + private static final ResourceLocation TAB_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/cloner/tab.png"); + private static final ResourceLocation FOLDER_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/cloner/folder.png"); + + private static final int ICON_RENDER_SIZE = 10; + private static final int ICON_PADDING = 14; + + private List iconTypes = new ArrayList<>(); + + public GuiCustomScrollIcons(GuiScreen parent, int id) { + super(parent, id); + } + + public void setListWithIcons(List names, List icons) { + this.setUnsortedList(names); + this.iconTypes = new ArrayList<>(icons); + } + + @Override + protected void drawItems() { + Minecraft mc = Minecraft.getMinecraft(); + 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; + + int iconType = (i < iconTypes.size()) ? iconTypes.get(i) : ICON_NONE; + int textX = j; + if (iconType != ICON_NONE) { + textX = j + ICON_PADDING; + } + + // Draw icon texture + if (iconType == ICON_FOLDER || iconType == ICON_TAB) { + ResourceLocation tex = (iconType == ICON_FOLDER) ? FOLDER_TEXTURE : TAB_TEXTURE; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.getTextureManager().bindTexture(tex); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + drawFullTexture(j, k - 1, ICON_RENDER_SIZE, ICON_RENDER_SIZE); + GL11.glDisable(GL11.GL_BLEND); + } + + // Draw text + String displayString = StatCollector.translateToLocal(list.get(i)); + String text = ""; + float maxWidth = (xSize + xOffset - 8 - (iconType != ICON_NONE ? ICON_PADDING : 0)) * 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; + } + + int itemColor = this.colors.getOrDefault(list.get(i), 0xffffff); + + if ((multipleSelection && selectedList.contains(list.get(i))) || (!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, textX, k, itemColor); + } else if (i == hover) { + fontRendererObj.drawString(text, textX, k, 0x00ff00); + } else { + fontRendererObj.drawString(text, textX, k, itemColor); + } + } + } + } + + /** + * Draw a full texture (UV 0,0 to 1,1) scaled to the given width/height. + * Works with any texture size (not just 256x256). + */ + private void drawFullTexture(int x, int y, int w, int h) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(x, y + h, 0, 0, 1); + tessellator.addVertexWithUV(x + w, y + h, 0, 1, 1); + tessellator.addVertexWithUV(x + w, y, 0, 1, 0); + tessellator.addVertexWithUV(x, y, 0, 0, 0); + tessellator.draw(); + } +} 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/GuiDiagram.java b/src/main/java/noppes/npcs/client/gui/util/GuiDiagram.java index 07822888c..3624de03c 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiDiagram.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiDiagram.java @@ -9,7 +9,7 @@ import noppes.npcs.constants.EnumDiagramLayout; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.awt.*; +import java.awt.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java b/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java new file mode 100644 index 000000000..957237610 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java @@ -0,0 +1,218 @@ +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 rightPanelPercent = 0.10f; + protected int minLeftPanelW = 80; + protected int minRightPanelW = 40; + protected int minCenterW = 100; + + // ===== LAYOUT CONSTANTS ===== + protected int pad = 10; + protected int topBarH = 24; + protected int gap = 4; + protected int btnH = 20; + + // ===== PANEL COLORS ===== + protected int panelBg = 0xC0101010; + protected int panelBorder = 0xFF333333; + protected int topBarBg = 0xC0181818; + + // ===== COMPUTED LAYOUT (populated by computeLayout) ===== + protected int originX, originY, usableW, usableH; + protected int leftPanelW, rightPanelW; + protected int contentX, contentY, contentW, contentH; + 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; + private int dividerOffset; + private boolean isDragging = false; + private int dragStartX; + + // ===== CONSTRUCTOR ===== + public GuiDirectory() { + super(); + closeOnEsc = true; + drawDefaultBackground = true; + } + + // ===== LAYOUT COMPUTATION ===== + protected void computeLayout() { + originX = pad; + originY = pad; + usableW = width - 2 * pad; + usableH = height - 2 * pad; + + leftPanelW = Math.max(minLeftPanelW, (int) (usableW * leftPanelPercent)); + rightPanelW = Math.max(minRightPanelW, (int) (usableW * rightPanelPercent)); + + if (rightPanelPercent <= 0) { + rightPanelW = 0; + } + + int gapCount = rightPanelW > 0 ? 3 : 2; + contentW = usableW - leftPanelW - rightPanelW - gapCount * gap; + if (contentW < minCenterW) { + contentW = minCenterW; + } + + contentX = originX + leftPanelW + gap; + contentY = originY + topBarH + gap; + contentH = usableH - topBarH - gap; + rightX = contentX + contentW + gap; + + if (enableDivider && dividerOffset == 0) { + dividerOffset = leftPanelW; + } + } + + // ===== INIT GUI ===== + @Override + public void initGui() { + super.initGui(); + computeLayout(); + initTopBar(originY + 2); + initLeftPanel(); + initCenterPanel(); + if (rightPanelW > 0) { + initRightPanel(contentY + 4); + } + } + + // ===== DRAWING ===== + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawTopBar(); + drawPanels(); + if (enableDivider) { + drawDivider(mouseX, mouseY); + } + super.drawScreen(mouseX, mouseY, partialTicks); + drawOverlay(mouseX, mouseY, partialTicks); + } + + protected void drawTopBar() { + GuiUtil.drawRectD(originX, originY, originX + usableW, originY + topBarH, topBarBg); + } + + protected void drawPanels() { + // Left nav panel border + GuiUtil.drawRectD(originX - 1, contentY - 1, originX + leftPanelW + 1, originY + usableH + 1, panelBorder); + + // Right action panel border (if present) + if (rightPanelW > 0) { + GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder); + } + } + + protected void drawDivider(int mouseX, int mouseY) { + if (!enableDivider) return; + int divX = originX + dividerOffset; + int regionTop = contentY; + int regionHeight = contentH; + int handleTop = regionTop + (regionHeight - dividerLineHeight) / 2; + drawRect(divX + 1, handleTop, divX + dividerWidth - 1, handleTop + dividerLineHeight, 0xFF707070); + } + + /** + * Override for extra drawing after super.drawScreen (e.g. status text) + */ + protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { + } + + // ===== DIVIDER MOUSE HANDLING ===== + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (enableDivider && !hasSubGui()) { + int divX = originX + dividerOffset; + int regionTop = contentY; + int handleTop = regionTop + (contentH - dividerLineHeight) / 2; + int handleBottom = handleTop + dividerLineHeight; + if (mouseX >= divX && mouseX <= divX + dividerWidth && + mouseY >= handleTop && mouseY <= handleBottom) { + isDragging = true; + resizingActive = true; + dragStartX = mouseX; + return; + } + } + super.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + if (isDragging) { + int dx = mouseX - dragStartX; + dragStartX = mouseX; + dividerOffset += dx; + + int maxOffset = (usableW - (rightPanelW > 0 ? rightPanelW + gap : 0)) - dividerWidth - minDividerPanelW; + dividerOffset = Math.max(minDividerPanelW, Math.min(dividerOffset, maxOffset)); + + onDividerMoved(dividerOffset); + return; + } + super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + } + + @Override + protected void mouseMovedOrUp(int mouseX, int mouseY, int state) { + if (isDragging) { + isDragging = false; + resizingActive = false; + return; + } + super.mouseMovedOrUp(mouseX, mouseY, state); + } + + /** + * Called when divider is dragged. Override to update scroll sizes. + */ + protected void onDividerMoved(int newOffset) { + } + + // Accessors for divider offset + protected int getDividerOffset() { + return dividerOffset; + } + + protected void setDividerOffset(int offset) { + this.dividerOffset = offset; + } + + // ===== ABSTRACT HOOKS (subclass must implement) ===== + + /** + * 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). + */ + protected abstract void initLeftPanel(); + + /** + * Populate the center content panel (main scroll list). + */ + protected abstract void initCenterPanel(); + + /** + * 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/GuiMenuSideButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java index 0aa6c7d3d..94398bb60 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java @@ -15,6 +15,7 @@ public class GuiMenuSideButton extends GuiNpcButton { public boolean active; public boolean rightSided; + public int textColor = -1; public ItemStack renderStack; public ResourceLocation renderResource; public int renderIconPosX = 0; @@ -96,13 +97,15 @@ public class GuiMenuSideButton extends GuiNpcButton { text += "..."; } else text = displayString; - if (active) { - drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0); - } else if (field_146123_n) { - drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0); + int color; + if (textColor != -1) { + color = textColor; + } else if (active || field_146123_n) { + color = 0xffffa0; } else { - drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xe0e0e0); + color = 0xe0e0e0; } + drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, color); } @Override 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 8a1d015d0..37ce2b789 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java @@ -18,11 +18,11 @@ import org.lwjgl.opengl.GL12; public class GuiModelInterface2 extends GuiNPCInterface2 { public ModelData playerdata; - private static float rotation = 0; + protected static float rotation = 0; private GuiNpcButton left, right, zoom, unzoom; - private static float zoomed = 60; + protected static float zoomed = 60; public int xOffset = 0; public int yOffset = 0; @@ -30,10 +30,18 @@ public class GuiModelInterface2 extends GuiNPCInterface2 { public EntityNPCInterface npc; public GuiModelInterface2(EntityNPCInterface npc) { - super(npc); + this(npc, true); + } + + /** + * @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. + */ + public GuiModelInterface2(EntityNPCInterface npc, boolean hasMenuNpc) { + super(hasMenuNpc ? npc : null); this.npc = npc; playerdata = ((EntityCustomNpc) npc).modelData; - //xSize = 380; drawDefaultBackground = false; } @@ -143,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 1d453a395..08a5dff00 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -27,6 +27,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.Supplier; public abstract class GuiNPCInterface extends GuiScreen { public EntityClientPlayerMP player; @@ -48,13 +50,40 @@ public abstract class GuiNPCInterface extends GuiScreen { public String title; private ResourceLocation background = null; public boolean closeOnEsc = false; + public Supplier closeOnEscSupplier = null; public int guiLeft, guiTop, xSize, ySize; private SubGuiInterface subgui; + private Consumer pendingSubGuiResult; public int mouseX, mouseY, mouseScroll; public float bgScale = 1; public float bgScaleX = 1; public float bgScaleY = 1; 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; @@ -72,6 +101,11 @@ public abstract class GuiNPCInterface extends GuiScreen { background = new ResourceLocation("customnpcs", "textures/gui/" + texture); } + public void setBackground(String texture, int textureHeight) { + background = new ResourceLocation("customnpcs", "textures/gui/" + texture); + bgTextureHeight = textureHeight; + } + public ResourceLocation getResource(String texture) { return new ResourceLocation("customnpcs", "textures/gui/" + texture); } @@ -104,6 +138,10 @@ public abstract class GuiNPCInterface extends GuiScreen { rotateLeft = new GuiNpcButton(0, guiLeft + 44 + xOffsetNpc + xOffsetButton, guiTop + yOffsetNpc + yOffsetButton, 20, 20, "<"); rotateRight = new GuiNpcButton(0, guiLeft + 66 + xOffsetNpc + xOffsetButton, guiTop + yOffsetNpc + yOffsetButton, 20, 20, ">"); } + + //Important for GuiScriptTextArea + for (GuiNpcTextField tf : textfields.values()) + tf.initGui(); } @Override @@ -147,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); + } } @@ -202,13 +251,19 @@ public abstract class GuiNPCInterface extends GuiScreen { } } } + @Override public void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { if (subgui != null) { 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 @@ -217,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) @@ -237,6 +352,29 @@ public abstract class GuiNPCInterface extends GuiScreen { @Override public void keyTyped(char c, int i) { + /* + Fixes closing sub with escape closes all of its parents. + The outermost GUI (root of all subs) closes the deepest open sub on ESC. + */ + boolean isSub = this instanceof SubGuiInterface; + + boolean shouldClose = closeOnEsc; + if (closeOnEscSupplier != null) { + try { + shouldClose = closeOnEscSupplier.get(); + } catch (Exception ignored) { + } + } + + if (shouldClose && !isSub && (i == 1 || (!GuiNpcTextField.isFieldActive() && isInventoryKey(i)))) { + SubGuiInterface sub = getSubGui(); + if (sub != null) + sub.close(); + else + close(); + } + + if (subgui != null) subgui.keyTyped(c, i); for (GuiNpcTextField tf : textfields.values()) @@ -246,27 +384,18 @@ public abstract class GuiNPCInterface extends GuiScreen { guiScrollableComponent.keyTyped(c, i); } - /* - Fixes closing sub with escape closes all of its parents. - The outermost GUI (root of all subs) closes the deepest open sub on ESC. - */ - boolean isSub = this instanceof SubGuiInterface; - - if (closeOnEsc && !isSub && (i == 1 || !GuiNpcTextField.isFieldActive() && isInventoryKey(i))) { - SubGuiInterface sub = getSubGui(); - if (sub != null) - sub.close(); - else - close(); - } } public void onGuiClosed() { GuiNpcTextField.unfocus(); } + public void closeOnEsc(Supplier close) { + this.closeOnEscSupplier = close; + } + public void close() { - if(GuiNpcTextField.activeTextfield != null) + if (GuiNpcTextField.activeTextfield != null) GuiNpcTextField.unfocus(); Keyboard.enableRepeatEvents(false); @@ -346,9 +475,41 @@ 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(); } @@ -357,34 +518,45 @@ public abstract class GuiNPCInterface extends GuiScreen { 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); + scroll.drawScreen(drawX, drawY, f, !subGui && scroll.isMouseOver(drawX, drawY) ? Mouse.getDWheel() : 0); } - // Draw scrollable windows. for (GuiScrollWindow guiScrollableComponent : scrollWindows.values()) { - guiScrollableComponent.drawScreen(i, j, f, !subGui && guiScrollableComponent.isMouseOver(i, j) ? Mouse.getDWheel() : 0); + guiScrollableComponent.drawScreen(drawX, drawY, f, !subGui && guiScrollableComponent.isMouseOver(drawX, drawY) ? Mouse.getDWheel() : 0); } 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 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); @@ -400,11 +572,44 @@ public abstract class GuiNPCInterface extends GuiScreen { GL11.glTranslatef(guiLeft, guiTop, 0); GL11.glScalef(bgScale * bgScaleX, bgScale * bgScaleY, bgScale * bgScaleZ); mc.renderEngine.bindTexture(background); + + // Handle Y dimension: if ySize < texture content height, stitch bottom border + int topHeight = ySize; + int bottomHeight = 0; + int bottomTextureV = 0; + if (ySize < bgTextureHeight) { + bottomHeight = -1; + topHeight = ySize - bottomHeight; + bottomTextureV = bgTextureHeight - bottomHeight; + } + if (xSize > 256) { - drawTexturedModalRect(0, 0, 0, 0, 250, ySize); - drawTexturedModalRect(250, 0, 256 - (xSize - 250), 0, xSize - 250, ySize); - } else - drawTexturedModalRect(0, 0, 0, 0, xSize, ySize); + // GUI wider than texture: draw left portion, then right portion from texture edge + drawTexturedModalRect(0, 0, 0, 0, 250, topHeight); + drawTexturedModalRect(250, 0, 256 - (xSize - 250), 0, xSize - 250, topHeight); + if (bottomHeight > 0) { + drawTexturedModalRect(0, topHeight, 0, bottomTextureV, 250, bottomHeight); + drawTexturedModalRect(250, topHeight, 256 - (xSize - 250), bottomTextureV, xSize - 250, bottomHeight); + } + } else if (xSize < 256) { + // GUI narrower than texture: stitch left and right edges together + int leftWidth = xSize / 2; + int rightWidth = xSize - leftWidth; + // Draw top portion + drawTexturedModalRect(0, 0, 0, 0, leftWidth, topHeight); + drawTexturedModalRect(leftWidth, 0, 256 - rightWidth, 0, rightWidth, topHeight); + // Draw bottom border strip + if (bottomHeight > 0) { + drawTexturedModalRect(0, topHeight, 0, bottomTextureV, leftWidth, bottomHeight); + drawTexturedModalRect(leftWidth, topHeight, 256 - rightWidth, bottomTextureV, rightWidth, bottomHeight); + } + } else { + // GUI exactly 256px wide + drawTexturedModalRect(0, 0, 0, 0, xSize, topHeight); + if (bottomHeight > 0) { + drawTexturedModalRect(0, topHeight, 0, bottomTextureV, xSize, bottomHeight); + } + } GL11.glPopMatrix(); } @@ -453,8 +658,25 @@ public abstract class GuiNPCInterface extends GuiScreen { initGui(); } + /** + * Open a sub-gui with a result handler that will be called when the sub-gui closes. + * The handler survives initGui() rebuilds since it lives on the parent, not the builder. + */ + public void setSubGuiWithResult(SubGuiInterface gui, Consumer resultHandler) { + this.pendingSubGuiResult = resultHandler; + setSubGui(gui); + } + public void closeSubGui(SubGuiInterface gui) { - subgui = null; + if (pendingSubGuiResult != null) { + Consumer handler = pendingSubGuiResult; + pendingSubGuiResult = null; + handler.accept(gui); + } + // Only null out subgui if it wasn't replaced by a new one during subGuiClosed + if (subgui == gui) { + subgui = null; + } initGui(); } @@ -504,6 +726,7 @@ public abstract class GuiNPCInterface extends GuiScreen { public void drawNpcWithExtras(EntityLivingBase entity, int mouseX, int mouseY, float partialTicks) { drawNpc(entity, mouseX, mouseY, partialTicks); } + public void drawNpc(EntityLivingBase entity, int mouseX, int mouseY, float partialTicks) { if (hasSubGui() && !drawNPConSub) return; 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 37ffdb807..489069610 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java @@ -2,7 +2,10 @@ package noppes.npcs.client.gui.util; import kamkeel.npcs.util.TextSplitter; 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; @@ -80,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() { @@ -126,6 +130,7 @@ public class GuiNpcButton extends GuiButton { } public AtomicBoolean rightClicked = new AtomicBoolean(); + @Override public boolean mousePressed(Minecraft minecraft, int i, int j) { boolean bo = super.mousePressed(minecraft, i, j); @@ -149,24 +154,85 @@ public class GuiNpcButton extends GuiButton { public void drawButton(Minecraft mc, int mouseX, int mouseY) { if (!this.visible) return; - // First, draw the button normally using the superclass method. - super.drawButton(mc, mouseX, mouseY); + // Auto-truncate display text if wider than button + String original = this.displayString; + FontRenderer fr = mc.fontRenderer; + if (fr != null) { + int maxTextWidth = this.width - 6; + if (fr.getStringWidth(original) > maxTextWidth) { + String ellipsis = "..."; + int targetWidth = maxTextWidth - fr.getStringWidth(ellipsis); + if (targetWidth > 0) { + this.displayString = fr.trimStringToWidth(original, targetWidth) + ellipsis; + } + } + } + // 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. if (iconTexture != null) { 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; @@ -183,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; @@ -216,17 +299,27 @@ public class GuiNpcButton extends GuiButton { maxHeight += 2 + (textLines.size() - 1) * 10; } - int gameWidth = mc.displayWidth; - int maxTooltipX = gameWidth - maxWidth - 4; + // Get scaled screen dimensions + ScaledResolution scaledRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int screenWidth = scaledRes.getScaledWidth(); + int screenHeight = scaledRes.getScaledHeight(); - if (j2 > maxTooltipX) { - int diff = j2 - maxTooltipX; - j2 -= diff; - GL11.glTranslatef(-300, 0, 0); + // If tooltip would go off right edge, draw on left side of mouse + if (j2 + maxWidth + 6 > screenWidth) { + j2 = x - maxWidth - 16; } - if (k2 + maxHeight + 6 > mc.displayHeight) { - k2 = mc.displayHeight - maxHeight - 6; + // Keep tooltip on screen horizontally + if (j2 < 4) { + j2 = 4; + } + + // Keep tooltip on screen vertically + if (k2 + maxHeight + 6 > screenHeight) { + k2 = screenHeight - maxHeight - 6; + } + if (k2 < 4) { + k2 = 4; } this.zLevel = 300.0F; 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 f620e1e63..4a1ac4b24 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java @@ -1,18 +1,32 @@ package noppes.npcs.client.gui.util; +import kamkeel.npcs.util.TextSplitter; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.StatCollector; import noppes.npcs.client.CustomNpcResourceListener; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; -public class GuiNpcLabel { +import java.util.Iterator; +import java.util.List; + +public class GuiNpcLabel extends Gui { public String label; public int x, y, color; public boolean enabled = true; public int id; public boolean drawShadow = false; + // Hover text support + public String hoverableText = ""; + private boolean wasHovered = false; + private int hoverCount = 0; + public GuiNpcLabel(int id, Object label, int x, int y, int color) { this.id = id; this.label = StatCollector.translateToLocal(label.toString()); @@ -25,6 +39,10 @@ public class GuiNpcLabel { this(id, label, x, y, CustomNpcResourceListener.DefaultTextColor); } + public void setHoverText(String text) { + this.hoverableText = text; + } + public void drawLabel(GuiScreen gui, FontRenderer fontRenderer) { if (enabled) fontRenderer.drawString(label, x, y, color, drawShadow); @@ -34,4 +52,120 @@ public class GuiNpcLabel { int size = Minecraft.getMinecraft().fontRenderer.getStringWidth(label); x += (width - size) / 2; } + + public boolean isMouseOver(int mouseX, int mouseY, FontRenderer fr) { + int width = fr.getStringWidth(label); + return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + 10; + } + + /** + * 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 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 + */ + public void drawHover(int localMouseX, int localMouseY, int screenMouseX, int screenMouseY, boolean hasSubGui, FontRenderer fr) { + if (hasSubGui || hoverableText.isEmpty()) return; + + boolean hovered = isMouseOver(localMouseX, localMouseY, fr); + if (!hovered) { + wasHovered = false; + hoverCount = 0; + return; + } + if (!wasHovered) { + wasHovered = true; + hoverCount = 0; + } + if (hoverCount < 65) hoverCount++; + + if (hoverCount > 60) { + GL11.glPushMatrix(); + Minecraft mc = Minecraft.getMinecraft(); + String displayString = StatCollector.translateToLocal(hoverableText); + GL11.glColor4f(1, 1, 1, 1); + List lines = TextSplitter.splitText(displayString, 30); + drawHoveringText(lines, screenMouseX, screenMouseY, mc); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glPopMatrix(); + } + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) { + if (mc.fontRenderer == null || textLines.isEmpty()) + return; + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + int maxWidth = 0; + Iterator iterator = textLines.iterator(); + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int lineWidth = mc.fontRenderer.getStringWidth(s); + if (lineWidth > maxWidth) { + maxWidth = lineWidth; + } + } + + int j2 = x + 12; + int k2 = y - 12; + int maxHeight = 8; + + if (textLines.size() > 1) { + maxHeight += 2 + (textLines.size() - 1) * 10; + } + + ScaledResolution scaledRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int screenWidth = scaledRes.getScaledWidth(); + int screenHeight = scaledRes.getScaledHeight(); + + if (j2 + maxWidth + 6 > screenWidth) { + j2 = x - maxWidth - 16; + } + if (j2 < 4) { + j2 = 4; + } + if (k2 + maxHeight + 6 > screenHeight) { + k2 = screenHeight - maxHeight - 6; + } + if (k2 < 4) { + k2 = 4; + } + + this.zLevel = 300.0F; + int j1 = -267386864; + this.drawGradientRect(j2 - 3, k2 - 4, j2 + maxWidth + 3, k2 - 3, j1, j1); + this.drawGradientRect(j2 - 3, k2 + maxHeight + 3, j2 + maxWidth + 3, k2 + maxHeight + 4, j1, j1); + this.drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 + maxHeight + 3, j1, j1); + this.drawGradientRect(j2 - 4, k2 - 3, j2 - 3, k2 + maxHeight + 3, j1, j1); + this.drawGradientRect(j2 + maxWidth + 3, k2 - 3, j2 + maxWidth + 4, k2 + maxHeight + 3, j1, j1); + int k1 = 1347420415; + int l1 = (k1 & 16711422) >> 1 | k1 & -16777216; + this.drawGradientRect(j2 - 3, k2 - 3 + 1, j2 - 3 + 1, k2 + maxHeight + 3 - 1, k1, l1); + this.drawGradientRect(j2 + maxWidth + 2, k2 - 3 + 1, j2 + maxWidth + 3, k2 + maxHeight + 3 - 1, k1, l1); + this.drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 - 3 + 1, k1, k1); + this.drawGradientRect(j2 - 3, k2 + maxHeight + 2, j2 + maxWidth + 3, k2 + maxHeight + 3, l1, l1); + + for (int i2 = 0; i2 < textLines.size(); ++i2) { + String s1 = (String) textLines.get(i2); + mc.fontRenderer.drawStringWithShadow(s1, j2, k2, -1); + if (i2 == 0) { + k2 += 2; + } + k2 += 10; + } + + this.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } } 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 0f26d9d36..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,9 +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.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 java.util.ArrayList; +import java.util.List; public class GuiNpcTextField extends GuiTextField { public boolean enabled = true; @@ -18,8 +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); @@ -39,6 +53,9 @@ public class GuiNpcTextField extends GuiTextField { this(id, parent, Minecraft.getMinecraft().fontRenderer, i, j, k, l, s); } + public void initGui() { + } + protected boolean charAllowed(char c, int i) { if (!integersOnly || Character.isDigit(c)) return true; @@ -46,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; @@ -55,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; } @@ -141,6 +200,9 @@ public class GuiNpcTextField extends GuiTextField { else if (getFloat() > maxFloat) setText(maxFloat + ""); } + if (fileNameSafe) { + normalizeFileNameText(); + } setCursorPositionZero(); if (listener != null) listener.unFocused(this); @@ -200,5 +262,218 @@ 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) { + String translated = StatCollector.translateToLocal(text); + this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n"); + } + + public boolean hasHoverText() { + return hoverableText != null && !hoverableText.isEmpty(); + } + + public boolean isMouseOver(int mouseX, int mouseY) { + return mouseX >= xPosition && mouseX < xPosition + width && + 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(hitMouseX, hitMouseY); + if (!isHovered) { + wasHovered = false; + hoverCount = 0; + return; + } + + if (!wasHovered) { + wasHovered = true; + hoverCount = 0; + } else if (hoverCount < 65) { + hoverCount++; + } + + if (hoverCount > 60) { + GL11.glPushMatrix(); + Minecraft mc = Minecraft.getMinecraft(); + GL11.glColor4f(1, 1, 1, 1); + 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; + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + int maxWidth = 0; + for (String s : textLines) { + int lineWidth = mc.fontRenderer.getStringWidth(s); + if (lineWidth > maxWidth) { + maxWidth = lineWidth; + } + } + + int j2 = x + 12; + int k2 = y - 12; + int maxHeight = 8; + + if (textLines.size() > 1) { + maxHeight += 2 + (textLines.size() - 1) * 10; + } + + // Get scaled screen dimensions + ScaledResolution scaledRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int screenWidth = scaledRes.getScaledWidth(); + int screenHeight = scaledRes.getScaledHeight(); + + // If tooltip would go off right edge, draw on left side of mouse + if (j2 + maxWidth + 6 > screenWidth) { + j2 = x - maxWidth - 16; + } + + // Keep tooltip on screen horizontally + if (j2 < 4) { + j2 = 4; + } + + // Keep tooltip on screen vertically + if (k2 + maxHeight + 6 > screenHeight) { + k2 = screenHeight - maxHeight - 6; + } + if (k2 < 4) { + k2 = 4; + } + + int zLevel = 300; + int bgColor = 0xF0100010; + int borderColor1 = 0x505000FF; + int borderColor2 = (borderColor1 & 0xFEFEFE) >> 1 | borderColor1 & 0xFF000000; + + drawGradientRect(j2 - 3, k2 - 4, j2 + maxWidth + 3, k2 - 3, bgColor, bgColor, zLevel); + drawGradientRect(j2 - 3, k2 + maxHeight + 3, j2 + maxWidth + 3, k2 + maxHeight + 4, bgColor, bgColor, zLevel); + drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 + maxHeight + 3, bgColor, bgColor, zLevel); + drawGradientRect(j2 - 4, k2 - 3, j2 - 3, k2 + maxHeight + 3, bgColor, bgColor, zLevel); + drawGradientRect(j2 + maxWidth + 3, k2 - 3, j2 + maxWidth + 4, k2 + maxHeight + 3, bgColor, bgColor, zLevel); + drawGradientRect(j2 - 3, k2 - 3 + 1, j2 - 3 + 1, k2 + maxHeight + 3 - 1, borderColor1, borderColor2, zLevel); + drawGradientRect(j2 + maxWidth + 2, k2 - 3 + 1, j2 + maxWidth + 3, k2 + maxHeight + 3 - 1, borderColor1, borderColor2, zLevel); + drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 - 3 + 1, borderColor1, borderColor1, zLevel); + drawGradientRect(j2 - 3, k2 + maxHeight + 2, j2 + maxWidth + 3, k2 + maxHeight + 3, borderColor2, borderColor2, zLevel); + + for (int l = 0; l < textLines.size(); ++l) { + String s1 = textLines.get(l); + mc.fontRenderer.drawStringWithShadow(s1, j2, k2, -1); + if (l == 0) { + k2 += 2; + } + k2 += 10; + } + + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + + 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; + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glShadeModel(GL11.GL_SMOOTH); + 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.setColorRGBA_F(f5, f6, f7, f4); + 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); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } } 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 9b257f47e..e7798ff5a 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java @@ -2,237 +2,1147 @@ 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.util.TextContainer.LineData; +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; +// 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.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; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; import java.util.ArrayList; -import java.util.Iterator; 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 GuiScriptTextArea extends GuiNpcTextField { - public int id; + + private GuiScriptInterface parent; + + // ==================== DIMENSIONS & POSITION ==================== public int x; public int y; - public int width; - public int height; - private int cursorCounter; - private ITextChangeListener listener; - public String text = null; - private TextContainer container = null; + + // ==================== STATE FLAGS ==================== public boolean active = false; public boolean enabled = true; public boolean visible = true; public boolean clicked = false; public boolean doubleClicked = false; - public boolean clickScrolling = false; - private int startSelection; - private int endSelection; - private int cursorPosition; - private int scrolledLine = 0; - private boolean enableCodeHighlighting = false; - public List undoList = new ArrayList(); - public List redoList = new ArrayList(); - public boolean undoing = false; + public boolean tripleClicked = false; + private int clickCount = 0; private long lastClicked = 0L; - // private static TrueTypeFont font = new TrueTypeFont(new Font("Arial Unicode MS", Font.PLAIN, ConfigClient.FontSize), 1); + + // ==================== 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(); + 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(); + public OverlayKeyPresetViewer KEYS_OVERLAY = new OverlayKeyPresetViewer(KEYS); + + // ==================== 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); - this.id = id; - this.x = x; - this.y = y; + 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) { + 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(); + // 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; + 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); + + // 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 + // 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 GuiScriptTextArea.this.text; + } + + public String getHighlightedWord() { + return GuiScriptTextArea.this.highlightedWord; + } + + @Override + public int getSelectionStart() { + return GuiScriptTextArea.this.selection.getStartSelection(); + } + + @Override + public int getSelectionEnd() { + return GuiScriptTextArea.this.selection.getEndSelection(); + } + + @Override + public void setText(String newText) { + GuiScriptTextArea.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 = GuiScriptTextArea.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 = GuiScriptTextArea.this.y; + searchBaseHeight = GuiScriptTextArea.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); + + GuiScriptTextArea.this.y = newY; + GuiScriptTextArea.this.height = newHeight; + searchAppliedOffset = targetOffset; + + if (container != null) + container.visibleLines = Math.max(GuiScriptTextArea.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 = GuiScriptTextArea.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 GuiScriptTextArea.this.text; + } + + @Override + public void setText(String newText) { + GuiScriptTextArea.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 + } + }); + + // 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); + String lineText = ld.text; + int cursorOffset = selection.getCursorPosition() - ld.start; + cursorCol = ClientProxy.Font.width(lineText.substring(0, Math.min(cursorOffset, lineText.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; + } + + // ==================== RENDERING ==================== public void drawTextBox(int xMouse, int yMouse) { if (!visible) return; clampSelectionBounds(); - drawRect(x - 1, y - 1, x + width + 1, y + height + 1, 0xffa0a0a0); - drawRect(x, y, x + width, y + height, 0xff000000); + + // 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 + 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); - container.visibleLines = height / container.lineHeight; + int searchHeight = searchBar.getTotalHeight(); + + // Draw line number gutter background + int viewportX = x + LINE_NUMBER_GUTTER_WIDTH; + 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 + int wheelDelta = ((GuiNPCInterface) listener).mouseScroll = Mouse.getDWheel(); if (listener instanceof GuiNPCInterface) { - int k2 = ((GuiNPCInterface) listener).mouseScroll = Mouse.getDWheel(); - if (k2 != 0) { - this.scrolledLine -= k2 / 40; - this.scrolledLine = Math.max(Math.min(this.scrolledLine, this.container.linesCount - this.height / this.container.lineHeight), 0); + ((GuiNPCInterface) listener).mouseScroll = wheelDelta; + + // Intercept wheel scroll for tooltip (highest priority) + if (wheelDelta != 0 && hoverState.isTooltipVisible() && hoverState.isMouseOverTooltip(xMouse, yMouse)) { + hoverState.scrollTooltip(wheelDelta); + wheelDelta = 0; + } + + // 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()) { + 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); int i = getSelectionPos(xMouse, yMouse); - if (i != cursorPosition) { - if (doubleClicked) { - startSelection = endSelection = cursorPosition; + if (i != selection.getCursorPosition()) { + if (doubleClicked || tripleClicked) { + selection.reset(selection.getCursorPosition()); doubleClicked = false; + tripleClicked = false; } - setCursor(i, true); + setCursor(i, true); } - } else if (doubleClicked) { + } else if (doubleClicked || tripleClicked) { doubleClicked = false; + tripleClicked = false; } - - if (clickScrolling) { - clickScrolling = Mouse.isButtonDown(0); - int diff = container.linesCount - container.visibleLines; - scrolledLine = Math.min(Math.max((int) (1f * diff * (yMouse - y) / height), 0), diff); - } + // y += searchHeight; + // height -= searchHeight; + // Calculate braces next to cursor to highlight int startBracket = 0, endBracket = 0; - if (startSelection >= 0 && startSelection < text.length() && - (endSelection - startSelection == 1 || startSelection == endSelection)) { - char c = text.charAt(startSelection); - int found = 0; - if (c == '{') { - found = findClosingBracket(text.substring(startSelection), '{', '}'); - } else if (c == '[') { - found = findClosingBracket(text.substring(startSelection), '[', ']'); - } else if (c == '(') { - found = findClosingBracket(text.substring(startSelection), '(', ')'); - } else if (c == '}') { - found = findOpeningBracket(text.substring(0, startSelection + 1), '{', '}'); - } else if (c == ']') { - found = findOpeningBracket(text.substring(0, startSelection + 1), '[', ']'); - } else if (c == ')') { - found = findOpeningBracket(text.substring(0, startSelection + 1), '(', ')'); - } - if (found != 0) { - startBracket = startSelection; - endBracket = startSelection + found; + 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); - - String wordHightLight = null; - if (startSelection != endSelection) { - Matcher m = container.regexWord.matcher(text); - while (m.find()) { - if (m.start() == startSelection && m.end() == endSelection) { - wordHightLight = text.substring(startSelection, endSelection); + 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; } } - } - for (int i = 0; i < list.size(); i++) { - LineData data = list.get(i); - String line = data.text; - int w = line.length(); - 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 posY = y + 1 + (i - scrolledLine) * container.lineHeight; - drawRect(x + 1 + s, posY, x + 1 + e, posY + container.lineHeight + 1, 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 posY = y + 1 + (i - scrolledLine) * container.lineHeight; - drawRect(x + 1 + s, posY, x + 1 + e, posY + container.lineHeight + 1, 0x9900cc00); - } - } - if (i >= scrolledLine && i < scrolledLine + container.visibleLines) { - if (wordHightLight != null) { - Matcher m = container.regexWord.matcher(line); - while (m.find()) { - if (line.substring(m.start(), m.end()).equals(wordHightLight)) { - int s = ClientProxy.Font.width(line.substring(0, m.start())); - int e = ClientProxy.Font.width(line.substring(0, m.end())) + 1; - int posY = y + 1 + (i - scrolledLine) * container.lineHeight; - drawRect(x + 1 + s, posY, x + 1 + e, posY + container.lineHeight + 1, 0x99004c00); + 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; + } } } } - if (startSelection != endSelection && endSelection > data.start && startSelection <= data.end) { - if (startSelection < data.end) { - int s = ClientProxy.Font.width(line.substring(0, Math.max(startSelection - data.start, 0))); - int e = ClientProxy.Font.width(line.substring(0, Math.min(endSelection - data.start, w))) + 1; - int posY = y + 1 + (i - scrolledLine) * container.lineHeight; - drawRect(x + 1 + s, posY, x + 1 + e, posY + container.lineHeight + 1, 0x990000ff); + } + } + + 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 = "" + (i + 1); + int lineNumWidth = ClientProxy.Font.width(lineNum); + 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; + 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().getLine(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); } } - int yPos = y + (i - scrolledLine) * container.lineHeight + 1; - data.drawString(x + 1, yPos, 0xFFe0e0e0); - if (active && isEnabled() && (cursorCounter / 6) % 2 == 0 && cursorPosition >= data.start && cursorPosition < data.end) { - int posX = x + ClientProxy.Font.width(line.substring(0, cursorPosition - data.start)); - drawRect(posX + 1, yPos, posX + 2, yPos + 1 + container.lineHeight, -3092272); + // 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); + 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); } } } + // 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 sbSize = Math.max((int) (1f * container.visibleLines / container.linesCount * height), 2); + int effLines = Math.max(1, getPaddedLineCount()); + int sbSize = Math.max((int) (1f * (container.visibleLines) / effLines * height), 2); int posX = x + width - 6; - int posY = (int) (y + 1f * scrolledLine / container.linesCount * (height - 4)) + 1; + double linesCount = (double) effLines; + int posY = (int) (y + 1f * scroll.getScrollPos() / linesCount * (height - 4)) + 1; - drawRect(posX, posY, posX + 5, posY + sbSize, 0xFFe0e0e0); + drawRect(posX, posY, posX + 5, posY + sbSize + 2, 0xFFe0e0e0); + } + + 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 int findClosingBracket(String str, char s, char e) { - int found = 0; - char[] chars = str.toCharArray(); - - for (int i = 0; i < chars.length; ++i) { - char c = chars[i]; - if (c == s) { - ++found; - } else if (c == e) { - --found; - if (found == 0) { - return i; - } - } - } - - return 0; - } - - private int findOpeningBracket(String str, char s, char e) { - int found = 0; - char[] chars = str.toCharArray(); - - for (int i = chars.length - 1; i >= 0; --i) { - char c = chars[i]; - if (c == e) { - ++found; - } else if (c == s) { - --found; - if (found == 0) { - return i - chars.length + 1; - } - } - } - - return 0; + private void scissorViewport() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + 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 private int getSelectionPos(int xMouse, int yMouse) { - xMouse -= this.x + 1; + 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); - if (i >= this.scrolledLine && i < this.scrolledLine + this.container.visibleLines) { - int yPos = (i - this.scrolledLine) * this.container.lineHeight; - if (yMouse >= yPos && yMouse < yPos + this.container.lineHeight) { + //+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(); @@ -245,7 +1155,13 @@ public class GuiScriptTextArea extends GuiNpcTextField { lineWidth = w; } - return data.end - 1; + // 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()); } } } @@ -253,170 +1169,1576 @@ public class GuiScriptTextArea extends GuiNpcTextField { 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); + } + + /** + * 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 + ClientProxy.Font.width(lineText.substring(0, tokenLocalStart)); + int tokenScreenY = y + (lineIdx - scroll.getScrolledLine()) * container.lineHeight - (int)fracPixels; + int tokenWidth = ClientProxy.Font.width(lineText.substring(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); + 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 (or entire line if no selection) + KEYS.COPY.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + 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 + KEYS.PASTE.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + 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(); + }); + + // 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; + } + } + } + }); + + // 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 + + // 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(); + } + }); + + // AUTOCOMPLETE: Trigger autocomplete (Ctrl+Space) + KEYS.AUTOCOMPLETE.setTask(e -> { + if (!e.isPress() || !isActive.get()) + return; + + autocompleteManager.triggerExplicit(); + }); + } + + public void unfocusAll() { + if (searchBar.hasFocus()) searchBar.unfocus(); + if (goToLineDialog.hasFocus()) goToLineDialog.unfocus(); + if (renameHandler.isActive()) + renameHandler.cancel(); + if (autocompleteManager.isVisible()) + autocompleteManager.dismiss(); + } + // ==================== 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; + + // 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; if (this.isKeyComboCtrlA(i)) { - startSelection = cursorPosition = 0; - endSelection = text.length(); + selection.selectAll(text.length()); return true; } - if (!isEnabled()) - return false; + if (!isEnabled()) return false; - String original = text; + 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; + int j = 1; // default: move one character if (isCtrlKeyDown()) { - Matcher m = container.regexWord.matcher(text.substring(0, cursorPosition)); - while (m.find()) { - if (m.start() == m.end()) - continue; - j = cursorPosition - 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); } - setCursor(cursorPosition - j, GuiScreen.isShiftKeyDown()); + 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; } + + // RIGHT ARROW: move cursor right; with Ctrl -> jump to next word start if (i == Keyboard.KEY_RIGHT) { - int j = 1; + int j = 1; // default: move one character if (isCtrlKeyDown()) { - Matcher m = container.regexWord.matcher(text.substring(cursorPosition)); - if (m.find() && m.start() > 0 || m.find()) { - j = m.start(); + 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 { + while (end < text.length() && !Character.isWhitespace(text.charAt(end)) && !isWordChar.test(text.charAt(end))) end++; + } } + j = Math.max(1, end - pos); } - setCursor(cursorPosition + j, GuiScreen.isShiftKeyDown()); + 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; } + + // 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; } - if (i == Keyboard.KEY_DELETE) { - String s = getSelectionAfterText(); - if (!s.isEmpty() && startSelection == endSelection) - s = s.substring(1); - setText(getSelectionBeforeText() + s); - endSelection = cursorPosition = startSelection; + + 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; } - if (isKeyComboCtrlBackspace(i)) { - String s = getSelectionBeforeText(); - if (startSelection > 0 && startSelection == endSelection) { - int nearestCondition = cursorPosition; - int g; - boolean cursorInWhitespace = Character.isWhitespace(s.charAt(cursorPosition - 1)); - if (cursorInWhitespace) { - // Find the nearest word if we are starting in whitespace - for (g = cursorPosition - 1; g >= 0; g--) { - char currentChar = s.charAt(g); - if (!Character.isWhitespace(currentChar)) { - nearestCondition = g; - break; - } - if (g == 0) { - nearestCondition = 0; - } - } + + // 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 { - // Find the nearest blank space or new line - for (g = cursorPosition - 1; g >= 0; g--) { - char currentChar = s.charAt(g); - if (Character.isWhitespace(currentChar) || currentChar == '\n') { - nearestCondition = g; - break; - } - if (g == 0) { - nearestCondition = 0; + 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; + } - // Remove all text to the left up to the nearest boundary - s = s.substring(0, nearestCondition); - startSelection -= (cursorPosition - nearestCondition); + 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))) { + prevNonWs--; + } + + if (prevNonWs >= 0 && cursorPos <= (text != null ? text.length() : 0) && text.charAt(prevNonWs) == '{') { + String indent = getLogicalLineIndentAt(prevNonWs); + String childIndent = indent + " "; + String after = getSelectionAfterText(); + + // If the next non-whitespace char is '}', don't insert another closer. + int nextNonWs = 0; + while (nextNonWs < after.length() && Character.isWhitespace(after.charAt(nextNonWs))) { + nextNonWs++; + } + if (nextNonWs < after.length() && after.charAt(nextNonWs) == '}') { + addText("\n" + childIndent); + scrollToCursor(); + return true; + } + + 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(); } - setText(s + getSelectionAfterText()); - endSelection = cursorPosition = startSelection; return true; } + + 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. + * 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, true); // Use atomic undo + // 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 before = getSelectionBeforeText(); + if (selection.getStartSelection() > 0 && !selection.hasSelection()) { + 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 { + // 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--; + } + + before = before.substring(0, g); + selection.setStartSelection(selection.getStartSelection() - (pos - g)); + } + setText(before + getSelectionAfterText(), true); // Use atomic undo + 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) { - String s = getSelectionBeforeText(); - if (startSelection > 0 && startSelection == endSelection) { - s = s.substring(0, s.length() - 1); - startSelection--; + // 1) selection deletion + if (selection.hasSelection()) { + String s = getSelectionBeforeText(); + setText(s + getSelectionAfterText(), true); // Use atomic undo + selection.reset(selection.getStartSelection()); + scrollToCursor(); + return true; } - setText(s + getSelectionAfterText()); - endSelection = cursorPosition = startSelection; + + // 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) { + String before = text.substring(0, ValueUtil.clamp(currCheck.start - 1, 0, text.length())); + String after = text.substring(Math.min(currCheck.end, text.length())); + setText(before + after, true); // Use atomic undo + 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, true); // Use atomic undo + // 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, true); // Use atomic undo + 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, true); // Use atomic undo + 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(), true); // Use atomic undo + selection.reset(selection.getStartSelection()); + scrollToCursor(); + // Notify autocomplete of deletion + autocompleteManager.onDeleteKey(text, selection.getCursorPosition()); 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 (startSelection != endSelection) { - NoppesStringUtils.setClipboardContents(text.substring(startSelection, endSelection)); + if (selection.hasSelection()) { + // Copy selected text into clipboard, then remove the selection + NoppesStringUtils.setClipboardContents(selection.getSelectedText(text)); String s = getSelectionBeforeText(); setText(s + getSelectionAfterText()); - endSelection = startSelection = cursorPosition = s.length(); + selection.reset(s.length()); + scrollToCursor(); + } + return true; + } - } - return true; - } + // CTRL+C: Copy if (this.isKeyComboCtrlC(i)) { - if (startSelection != endSelection) { - NoppesStringUtils.setClipboardContents(text.substring(startSelection, endSelection)); + 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; + return false; // nothing to undo undoing = true; - redoList.add(new UndoData(this.text, this.cursorPosition)); + redoList.add(new UndoData(this.text, selection.getCursorPosition())); UndoData data = undoList.remove(undoList.size() - 1); setText(data.text); - endSelection = startSelection = cursorPosition = data.cursorPosition; + 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, this.cursorPosition)); + undoList.add(new UndoData(this.text, selection.getCursorPosition())); UndoData data = redoList.remove(redoList.size() - 1); setText(data.text); - endSelection = startSelection = cursorPosition = data.cursorPosition; + selection.reset(data.cursorPosition); undoing = false; + scrollToCursor(); return true; } - if (i == Keyboard.KEY_TAB) { - addText(" "); - } - if (i == Keyboard.KEY_RETURN) { - addText(Character.toString('\n') + getIndentCurrentLine()); - } - if (ChatAllowedCharacters.isAllowedCharacter(c)) { - addText(Character.toString(c)); + + // CTRL+F: format the text according to IndentHelper rules + if (i == Keyboard.KEY_F && isCtrlKeyDown()) { + formatText(); + return true; } - 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(); + int cursorPos = selection.getCursorPosition(); + + 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. + // 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; + } + } + } + // 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 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 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() && !autocompleteManager.isVisible() + && !(hoverState.isTooltipVisible() && (hoverState.hasOverriddenPosition() || hoverState.hasOverriddenSize())); + } + + // ==================== KEYBOARD MODIFIERS ==================== + private boolean isAltKeyDown() { return Keyboard.isKeyDown(56) || Keyboard.isKeyDown(184); } @@ -442,153 +2764,465 @@ public class GuiScriptTextArea extends GuiNpcTextField { } private String getIndentCurrentLine() { - Iterator var1 = this.container.lines.iterator(); - - LineData data; - do { - if (!var1.hasNext()) { - return ""; + 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); } - - data = (LineData) var1.next(); - } while (this.cursorPosition <= data.start || this.cursorPosition > data.end); - - int i; - for (i = 0; i < data.text.length() && data.text.charAt(i) == 32; ++i) { - ; } - - return data.text.substring(0, i); + return ""; } - private void setCursor(int i, boolean select) { - i = Math.min(Math.max(i, 0), this.text.length()); - if (i != this.cursorPosition) { - if (!select) { - this.endSelection = this.startSelection = this.cursorPosition = i; - } else { - int diff = this.cursorPosition - i; - if (this.cursorPosition == this.startSelection) { - this.startSelection -= diff; - } else if (this.cursorPosition == this.endSelection) { - this.endSelection -= diff; - } + private String getAutoIndentForEnter() { + LineData currentLine = selection.findCurrentLine(container.lines); - if (this.startSelection > this.endSelection) { - int j = this.endSelection; - this.endSelection = this.startSelection; - this.startSelection = j; - } - - this.cursorPosition = i; - } - - clampSelectionBounds(); + 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) { - this.setText(this.getSelectionBeforeText() + s + this.getSelectionAfterText()); - this.endSelection = this.startSelection = this.cursorPosition = this.startSelection + s.length(); + int insertPos = selection.getStartSelection(); + this.setText(this.getSelectionBeforeText() + s + this.getSelectionAfterText(), true); // Use atomic undo for typing + selection.afterTextInsert(insertPos + s.length()); } private int cursorUp() { - for (int i = 0; i < this.container.lines.size(); ++i) { - LineData data = (LineData) this.container.lines.get(i); - if (this.cursorPosition >= data.start && this.cursorPosition < data.end) { - if (i == 0) { - return 0; - } - - int var10000 = this.cursorPosition - data.start; - return this.getSelectionPos(this.x + 1 + ClientProxy.Font.width(data.text.substring(0, this.cursorPosition - data.start)), this.y + 1 + (i - 1 - this.scrolledLine) * this.container.lineHeight); - } - } - - return 0; + return CursorNavigation.cursorUp(selection.getCursorPosition(), container.lines, text); } private int cursorDown() { - for (int i = 0; i < this.container.lines.size(); ++i) { - LineData data = (LineData) this.container.lines.get(i); - if (this.cursorPosition >= data.start && this.cursorPosition < data.end) { - int var10000 = this.cursorPosition - data.start; - return this.getSelectionPos(this.x + 1 + ClientProxy.Font.width(data.text.substring(0, this.cursorPosition - data.start)), this.y + 1 + (i + 1 - this.scrolledLine) * this.container.lineHeight); - } - } - - return this.text.length(); + return CursorNavigation.cursorDown(selection.getCursorPosition(), container.lines, text); } public String getSelectionBeforeText() { - return this.startSelection == 0 ? "" : this.text.substring(0, this.startSelection); + return selection.getTextBefore(text); } public String getSelectionAfterText() { - return this.text.substring(this.endSelection); + 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) { - this.startSelection = this.endSelection = this.cursorPosition = this.getSelectionPos(xMouse, yMouse); + // 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); + + // 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(); - if (this.clicked && this.container.linesCount * this.container.lineHeight > this.height && xMouse > this.x + this.width - 8) { - this.clicked = false; - this.clickScrolling = true; - } else if (time - this.lastClicked < 500L) { - this.doubleClicked = true; - Matcher m = this.container.regexWord.matcher(this.text); - while (m.find()) { - if (this.cursorPosition > m.start() && this.cursorPosition < m.end()) { - this.startSelection = m.start(); - this.endSelection = m.end(); - break; - } + // 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; + + // 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(); + } + } + } } } + // 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) { + 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; } 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 GuiScriptTextArea.UndoData(this.text, this.cursorPosition)); + // 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); - this.container.init(this.width, this.height); - if (this.enableCodeHighlighting) { + //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(); - } - if (this.scrolledLine > this.container.linesCount - this.container.visibleLines) { - this.scrolledLine = Math.max(0, this.container.linesCount - this.container.visibleLines); - } + // Ensure scroll state stays in bounds after text change + int maxScroll = Math.max(0, getPaddedLineCount() - this.container.visibleLines); + scroll.clampToBounds(maxScroll); - clampSelectionBounds(); + selection.clamp(this.text.length()); + + // Consider text changes user activity to pause caret blinking briefly + selection.markActivity(); + searchBar.updateMatches(); + + // Update autocomplete manager with current container + autocompleteManager.setContainer(this.container); } } @@ -602,31 +3236,239 @@ public class GuiScriptTextArea extends GuiNpcTextField { } public boolean hasVerticalScrollbar() { - return this.container.visibleLines < this.container.linesCount; + return this.container != null && this.container.visibleLines < getPaddedLineCount(); } public void enableCodeHighlighting() { 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.). + * This determines which hooks and event types are available for autocomplete. + * + * @param context The script context + */ + public void setScriptContext(ScriptContext context) { + if (this.container != null) { + this.container.setScriptContext(context); + } + } + + /** + * Get the current script context. + * + * @return The script context (NPC, PLAYER, BLOCK, ITEM, etc.) + */ + public ScriptContext getScriptContext() { + 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) { this.listener = listener; } private void clampSelectionBounds() { - if (this.text == null || this.text.isEmpty()) { - this.startSelection = this.endSelection = this.cursorPosition = 0; - return; + 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; } - - int length = this.text.length(); - this.startSelection = Math.max(0, Math.min(this.startSelection, length)); - this.endSelection = Math.max(0, Math.min(this.endSelection, length)); - this.cursorPosition = Math.max(0, Math.min(this.cursorPosition, length)); + + + 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(); } - class UndoData { + 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 { public String text; public int cursorPosition; 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..60e5a38a0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea1.java @@ -0,0 +1,2186 @@ +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 + int wheelDelta = ((GuiNPCInterface) listener).mouseScroll = Mouse.getDWheel(); + if (listener instanceof GuiNPCInterface) { + ((GuiNPCInterface) listener).mouseScroll = wheelDelta; + 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 3555b30fd..8a20a635c 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java @@ -97,6 +97,11 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } public void mouseClicked(int i, int j, int k) { + // Ignore clicks outside the visible scroll window area + if (i < xPos || i > xPos + clipWidth || j < yPos || j > yPos + clipHeight) { + return; + } + i = i - xPos; j = (int) (j - yPos + scrollY); @@ -143,6 +148,7 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } } } + public void mouseEvent(int i, int j, int k) { } @@ -207,6 +213,8 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC return scrolls.get(id); } + public int backgroundColor = 0x66000000; + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { scrollY = (float) lerp(scrollY, nextScrollY, partialTicks); @@ -220,7 +228,7 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC this.drawDefaultBackground = false; if (drawBackground) - this.drawGradientRect(0, 0, this.width, this.height, 0x66000000, 0x88000000); + this.drawGradientRect(0, 0, this.width, this.height, backgroundColor, backgroundColor); if (maxScrollY > 0) @@ -272,8 +280,31 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } for (GuiNpcButton button : buttons.values()) { button.updateSubGUI(subGui); + } + } + + /** + * 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. + */ + public void drawHoverTexts(int mouseX, int mouseY) { + boolean subGui = parent.hasSubGui(); + for (GuiNpcButton button : buttons.values()) { if (!button.hoverableText.isEmpty()) { - button.drawHover(i, j, subGui); + button.drawHover(mouseX, mouseY, subGui); + } + } + 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 new file mode 100644 index 000000000..10f0efc53 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiUtil.java @@ -0,0 +1,236 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.Tessellator; +import org.lwjgl.input.Mouse; +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; + + // Set clip + GL11.glScissor(x * scale, y - height, width * scale, height); + } + + public static void drawHorizontalLine(double y, double startX, double endX, int color) { + if (endX < startX) { + double i1 = startX; + startX = endX; + endX = i1; + } + + drawRectD(startX, y, endX + 1, y + 1, color); + } + + public static void drawVerticalLine(double x, double startY, double endY, int color) { + if (endY < startY) { + double i1 = startY; + startY = endY; + endY = i1; + } + + drawRectD(x, startY + 1, x + 1, endY, color); + } + + public static void drawRectD(double left, double top, double right, double bottom) { + double j1; + + if (left < right) { + j1 = left; + left = right; + right = j1; + } + + if (top < bottom) { + j1 = top; + top = bottom; + bottom = j1; + } + + Tessellator tessellator = Tessellator.instance; + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + tessellator.startDrawingQuads(); + tessellator.addVertex(left, bottom, 0.0D); + tessellator.addVertex(right, bottom, 0.0D); + tessellator.addVertex(right, top, 0.0D); + tessellator.addVertex(left, top, 0.0D); + tessellator.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + } + + + public static void drawRectD(double left, double top, double right, double bottom, int color) { + float f3 = (float) (color >> 24 & 255) / 255.0F; + float f = (float) (color >> 16 & 255) / 255.0F; + float f1 = (float) (color >> 8 & 255) / 255.0F; + float f2 = (float) (color & 255) / 255.0F; + GL11.glColor4f(f, f1, f2, f3); + drawRectD(left, top, right, bottom); + } + + public static void drawGradientRect(int left, int top, int right, int bottom, int startColor, int endColor) { + double zLevel = 0; + + 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); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + GL11.glShadeModel(GL11.GL_SMOOTH); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(f1, f2, f3, f); + tessellator.addVertex(right, top, zLevel); + tessellator.addVertex(left, top, zLevel); + tessellator.setColorRGBA_F(f5, f6, f7, f4); + tessellator.addVertex(left, bottom, zLevel); + tessellator.addVertex(right, bottom, zLevel); + tessellator.draw(); + GL11.glShadeModel(GL11.GL_FLAT); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } + + public static void drawGradientRectHorizontal(int left, int top, int right, int bottom, int startColor, int endColor) { + double zLevel = 0; + + float sA = (float) (startColor >> 24 & 255) / 255.0F; + float sR = (float) (startColor >> 16 & 255) / 255.0F; + float sG = (float) (startColor >> 8 & 255) / 255.0F; + float sB = (float) (startColor & 255) / 255.0F; + + float eA = (float) (endColor >> 24 & 255) / 255.0F; + float eR = (float) (endColor >> 16 & 255) / 255.0F; + float eG = (float) (endColor >> 8 & 255) / 255.0F; + float eB = (float) (endColor & 255) / 255.0F; + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_ALPHA_TEST); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + GL11.glShadeModel(GL11.GL_SMOOTH); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(sR, sG, sB, sA); + tessellator.addVertex(left, top, zLevel); + tessellator.addVertex(left, bottom, zLevel); + tessellator.setColorRGBA_F(eR, eG, eB, eA); + tessellator.addVertex(right, bottom, zLevel); + tessellator.addVertex(right, top, zLevel); + tessellator.draw(); + GL11.glShadeModel(GL11.GL_FLAT); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } + + public static void drawTexturedModalRect(double x, double y, double width, double height, int textureX, int textureY) { + double zLevel = 0; + float f = 1 / 256f; + float f1 = 1 / 256f; + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(x + 0, y + height, zLevel, (float) (textureX) * f, (float) (textureY + height) * f1); + tessellator.addVertexWithUV(x + width, y + height, zLevel, (float) (textureX + width) * f, (float) (textureY + height) * f1); + tessellator.addVertexWithUV(x + width, y + 0, zLevel, (float) (textureX + width) * f, (float) (textureY) * f1); + tessellator.addVertexWithUV(x + 0, y + 0, zLevel, (float) (textureX) * f, (float) (textureY) * f1); + 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); + + int factor = scaledResolution.getScaleFactor(); + + Mouse.setCursorPosition(guiX * factor, mc.displayHeight - (guiY * factor)); + } + + public static void setMouseX(int guiX) { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution scaledResolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + + int factor = scaledResolution.getScaleFactor(); + Mouse.setCursorPosition(guiX * factor, Mouse.getY()); + } + + public static void setMouseY(int guiY) { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution scaledResolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + + int factor = scaledResolution.getScaleFactor(); + Mouse.setCursorPosition(Mouse.getX(), mc.displayHeight - (guiY * factor)); + } + + public static double preciseMouseX() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution scaledResolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + + double width = scaledResolution.getScaledWidth(); + return Mouse.getX() * width / mc.displayWidth; + } + + public static double preciseMouseY() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution scaledResolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + + double height = scaledResolution.getScaledHeight(); + return height - Mouse.getY() * height / mc.displayHeight - 1; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/IAbilityConfigCallback.java b/src/main/java/noppes/npcs/client/gui/util/IAbilityConfigCallback.java new file mode 100644 index 000000000..4012c9f73 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/IAbilityConfigCallback.java @@ -0,0 +1,16 @@ +package noppes.npcs.client.gui.util; + +import kamkeel.npcs.controllers.data.ability.Ability; + +/** + * Callback interface for SubGuiAbilityConfig. + * Implemented by GUIs that open the ability config dialog. + */ +public interface IAbilityConfigCallback { + /** + * Called when an ability has been edited and saved. + * + * @param ability The edited ability + */ + void onAbilitySaved(Ability ability); +} 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 new file mode 100644 index 000000000..60346560a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java @@ -0,0 +1,15 @@ +package noppes.npcs.client.gui.util; + +import noppes.npcs.controllers.data.Tag; +import noppes.npcs.controllers.data.TagMap; + +import java.util.HashMap; +import java.util.UUID; + +public interface IClonerGui { + int getShowingClones(); + + HashMap getTags(); + + TagMap getTagMap(); +} 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/SubGuiInterface.java b/src/main/java/noppes/npcs/client/gui/util/SubGuiInterface.java index 8b35c65dc..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,9 @@ public class SubGuiInterface extends GuiNPCInterface { @Override public void close() { + GuiNpcTextField.unfocus(); + save(); + if (parent instanceof ISubGuiListener) ((ISubGuiListener) parent).subGuiClosed(this); 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/TextContainer.java b/src/main/java/noppes/npcs/client/gui/util/TextContainer.java index dc66332cb..2dc588c0f 100644 --- a/src/main/java/noppes/npcs/client/gui/util/TextContainer.java +++ b/src/main/java/noppes/npcs/client/gui/util/TextContainer.java @@ -8,14 +8,15 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class TextContainer { - private final static char colorChar = '\u00A7'; + protected final static char colorChar = '\u00A7'; //public final Pattern regexString = Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*?(\"|$)|'(?:[^'\\\\]|\\\\.)*?('|$)"); //public final Pattern regexString = Pattern.compile("\"(.*?(? makeup = new ArrayList(); public List lines = new ArrayList(); - public int lineHeight; + public int lineHeight = 13; public int totalHeight; public int visibleLines = 1; public int linesCount; @@ -73,7 +74,7 @@ public class TextContainer { } } - private MarkUp getNextMatching(int start) { + protected MarkUp getNextMatching(int start) { MarkUp markup = null; String s = text.substring(start); Matcher matcher = regexNumber.matcher(s); @@ -128,7 +129,7 @@ public class TextContainer { makeup.add(new MarkUp(start, end, c, level)); } - private boolean removeConflictingMarkUp(int start, int end, int level) { + protected boolean removeConflictingMarkUp(int start, int end, int level) { List conflicting = new ArrayList(); for (MarkUp m : makeup) { if (start >= m.start && start <= m.end || end >= m.start && end <= m.end || start < m.start && end > m.start) { diff --git a/src/main/java/noppes/npcs/client/gui/util/key/OverlayKeyPresetViewer.java b/src/main/java/noppes/npcs/client/gui/util/key/OverlayKeyPresetViewer.java new file mode 100644 index 000000000..5d9cfdaa0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/key/OverlayKeyPresetViewer.java @@ -0,0 +1,499 @@ +package noppes.npcs.client.gui.util.key; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.gui.util.GuiUtil; +import noppes.npcs.client.key.KeyPreset; +import noppes.npcs.client.key.KeyPresetManager; +import noppes.npcs.client.util.Color; +import noppes.npcs.util.ValueUtil; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + +import java.util.LinkedList; +import java.util.List; + +public class OverlayKeyPresetViewer { + public static final ResourceLocation TEXTURE = new ResourceLocation("customnpcs:textures/gui/keypreset_highres.png"); + + public int startX, startY, endX, endY, width, height; + public int mouseX, mouseY; + public boolean showOverlay; + public boolean aboveButton, aboveOverlay; + public int elementSpacing = 5, yStartSpacing = 5; + public float scale = 0.75f; + public Scrollable scroll = new Scrollable(); + + public KeyPresetManager manager; + public OverlayButton viewButton = new OverlayButton(); + public LinkedList list = new LinkedList<>(); + + // from 0-1, where 0.5 is half overlay width; + public float RELATIVE_MAX_DESC_WIDTH = 0.5f; + private final FontRenderer font = Minecraft.getMinecraft().fontRenderer; + + public int bgCol1 = 0xdd101010, bgCol2 = 0xf8303030; + public int borderCol1 = 0x22ffffff, borderCol2 = 0xffffffff; + public boolean hasBorder = true; + public boolean openOnClick; + + public OverlayKeyPresetViewer(KeyPresetManager manager) { + this.manager = manager; + + manager.keys.forEach((key) -> { + PresetElement element = new PresetElement(key); + list.add(element); + }); + } + + public void initGui(int startX, int startY, int width, int height) { + this.startX = startX; + this.startY = startY; + this.width = width; + this.height = height; + this.endX = startX + width; + this.endY = startY + height; + scroll.init(); + } + + public void draw(int mouseX, int mouseY, int wheel) { + this.mouseX = mouseX; + this.mouseY = mouseY; + aboveButton = viewButton.isMouseAbove(mouseX, mouseY); + aboveOverlay = isMouseAbove(mouseX, mouseY); + // If in hover mode, hovering the button opens the overlay. + if (aboveButton && !openOnClick) + showOverlay = true; + + if (showOverlay) { + drawOverlay(wheel); + + // In click-to-open mode we don't auto-close on mouse-out; closure is handled by clicks. + if (!openOnClick && !aboveOverlay && !aboveButton) + showOverlay = false; + } + viewButton.drawButton(); + } + + public void drawOverlay(int wheel) { + scroll.update(wheel); + + if (hasBorder) { + // int borderCol2 = 0xffff00ff,borderCol2 = 0xff00ffff; NEON + + // Top + GuiUtil.drawGradientRectHorizontal(startX - 1, startY - 1, endX + 1, startY, borderCol2, borderCol1); + // Bottom + GuiUtil.drawGradientRectHorizontal(startX - 1, endY, endX + 1, endY + 1, borderCol1, borderCol2); + // Left + GuiUtil.drawGradientRect(startX - 1, startY - 1, startX, endY, borderCol2, borderCol1); + //Right + GuiUtil.drawGradientRect(endX, startY, endX + 1, endY, borderCol1, borderCol2); + } + + GuiUtil.drawGradientRect(startX, startY, endX, endY, bgCol1, bgCol2); + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GuiUtil.setScissorClip(startX, startY, scroll.maxScroll > 0 ? width - scroll.barWidth : width, height); + GL11.glPushMatrix(); + GL11.glTranslatef((startX + 2), startY + yStartSpacing - scroll.scrollY, 0); + + for (int i = 0, height = 0; i < list.size(); i++) { + PresetElement element = list.get(i); + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, 1); + GL11.glTranslatef(0, Math.round(height / scale), 0); + element.drawDescription(); + GL11.glPopMatrix(); + + element.drawBox(height); + height += element.getHeight(); + } + + GL11.glPopMatrix(); + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + if (scroll.maxScroll > 0) + scroll.drawBar(); + } + + public boolean keyTyped(char c, int i) { + if (!showOverlay) + return false; + + for (PresetElement element : list) { + if (element.isEditing) { + element.keyTyped(i); + return true; + } + } + + if (i == Keyboard.KEY_ESCAPE) { + showOverlay = false; + return true; + } + + // If overlay is visible but no element consumed the key, consider it handled + return true; + } + + public boolean mouseClicked(int mouseX, int mouseY, int button) { + // Always allow clicking the view button to toggle when openOnClick is enabled + boolean isAboveButton = viewButton.isMouseAbove(mouseX, mouseY); + if (isAboveButton) { + if (openOnClick) { + showOverlay = !showOverlay; + return true; + } else { + // If not click-to-open mode, clicking the button should still open the overlay + showOverlay = true; + return true; + } + } + + // If overlay is not visible, no other clicks matter + if (!showOverlay) + return false; + + boolean isAboveOverlay = isMouseAbove(mouseX, mouseY); + // In click-to-open mode, clicking outside the overlay (and not the button) should close it + if (openOnClick && !isAboveOverlay && !isAboveButton) { + showOverlay = false; + return true; + } + + boolean consumed = isAboveOverlay; + for (PresetElement element : list) { + if (!element.isMouseAboveBox(mouseX, mouseY)) { + if (element.isEditing) { + element.cancelEdit(); + consumed = true; + } + } else { + element.boxClicked(button); + consumed = true; + } + + if (element.isMouseAboveReset(mouseX, mouseY) && !element.key.isDefault()) { + element.key.defaultState.writeTo(element.key.currentState); + manager.save(); + consumed = true; + } + } + + return consumed; + } + + public boolean isMouseAbove(int mouseX, int mouseY) { + if (scroll.isMouseDragging) + return true; + + return mouseX >= startX && mouseX < endX && mouseY >= startY && mouseY < endY; + } + + public int getWidth() { + return (int) (width / scale); + } + + public boolean isVisible() { + return showOverlay; + } + + + public class Scrollable { + private float scrollY, targetScrollY, maxScroll; + private int totalHeight, scrollbarHeight, barWidth = 2; + private float heightFactor, scrollFactor; + + private boolean isMouseDragging; + private int startDragY; + + public Scrollable() { + } + + public void init() { + totalHeight = 0; + for (PresetElement element : list) + totalHeight += element.getHeight(); + // contentTotal includes top spacing before first element + float contentTotal = totalHeight + yStartSpacing; + + // maxScroll is how much content exceeds the visible area + maxScroll = Math.max(0f, contentTotal - height); + + // compute scrollbar height proportional to visible area vs content + heightFactor = contentTotal > 0f ? (float) height / contentTotal : 1f; + scrollbarHeight = Math.max((int) (height * heightFactor), 20); + + // scrollFactor maps scrollY -> pixel offset for scrollbar + scrollFactor = maxScroll > 0f ? (height - yStartSpacing - scrollbarHeight) / maxScroll : 0f; + } + + public void update(int wheel) { + if (wheel != 0 && isMouseAbove(mouseX, mouseY)) + targetScrollY = ValueUtil.clamp(targetScrollY - wheel / 15, 0, maxScroll); + + + if (Mouse.isButtonDown(0)) { + if (!isMouseDragging && isMouseAboveBar(mouseX, mouseY)) { + isMouseDragging = true; + startDragY = (int) (mouseY - scrollY * scrollFactor); + } + } else + isMouseDragging = false; + + if (isMouseDragging) + scrollY = targetScrollY = ValueUtil.clamp((mouseY - startDragY) / scrollFactor, 0, maxScroll); + + if (scrollY != targetScrollY) { + scrollY = ValueUtil.lerp(scrollY, targetScrollY, 0.1f); + + if (Math.abs(scrollY - targetScrollY) < 0.001) // Snap to exact target value + scrollY = targetScrollY; + } + + scrollY = ValueUtil.clamp(scrollY, 0, maxScroll); + } + + public void drawBar() { + GL11.glPushMatrix(); + GL11.glTranslatef(endX - barWidth - 2, startY + yStartSpacing + scrollY * scrollFactor, 1); + GuiUtil.drawRectD(0, 1, barWidth, scrollbarHeight - 1, (isMouseAboveBar(mouseX, mouseY) || isMouseDragging) ? 0xffbababa : 0xff767676); + GL11.glPopMatrix(); + } + + public boolean isMouseAboveBar(int mouseX, int mouseY) { + int barX = endX - barWidth - 2; + int barY = (int) (startY + yStartSpacing + scrollY * scrollFactor); + + return mouseX >= barX && mouseX < barX + barWidth && mouseY >= barY && mouseY < barY + scrollbarHeight; + } + } + + public class PresetElement { + public KeyPreset key; + public boolean isEditing; + public float boxScreenX, boxScreenY; + + public KeyPreset.KeyState newState = new KeyPreset.KeyState(); + + public PresetElement(KeyPreset key) { + this.key = key; + } + + public void drawDescription() { + boolean hasDescription = key.description != null; + String name = String.format("> %s", key.name); + font.drawString(name, 0, hasDescription ? 0 : 10, 0xffffff); + + if (!key.shouldConflict) + font.drawString("(Conflict-free)", font.getStringWidth(name) + 5, 0, 0xface40); + + if (hasDescription) { + String description = String.format("- %s", key.description); + font.drawSplitString(description, 9, font.FONT_HEIGHT + 3, getMaxStringWidth() - 9, 0x888888); + } + } + + public void drawBox(int offsetY) { + //////////////////////////////////////////// + //////////////////////////////////////////// + //Box texture + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE); + GL11.glPushMatrix(); + GL11.glColor4f(1, 1, 1, 1); + float boxScaleX = 1.75f; + float boxWidth = 32 * boxScaleX; + // compute desired box X based on description width + float desiredBoxX = getMaxStringWidth() * scale + 8; //remove scaling from maxStringWidth + // clamp so the box + reset button always fit inside the content area + float resetWidth = 10f; + float contentAvailable = (scroll.maxScroll > 0 ? width - scroll.barWidth : width) - 4f; // small padding + float maxBoxX = Math.max(0f, contentAvailable - boxWidth - resetWidth - 4f); + boxScreenX = Math.min(desiredBoxX, maxBoxX); + GL11.glScalef(boxScaleX, 1, 0); + + if (isEditing) + new Color(0x4772b3, 1).glColor(); + else if (isMouseAboveBox(mouseX, mouseY)) + new Color(0x656565, 1).glColor(); + else + new Color(0x545454, 1).glColor(); + GuiUtil.drawTexturedModalRect(boxScreenX / boxScaleX, boxScreenY = offsetY - 5, 32, 20, 0, 492); + GL11.glPopMatrix(); + + //Reset box + boolean isDefault = key.isDefault(); + resetWidth = 10; + float resetScreenX = boxScreenX + boxWidth + 2; + + if (isMouseAboveReset(mouseX, mouseY) && !isDefault) + new Color(0x656565, 1).glColor(); + else + new Color(0x545454, 1).glColor(); + GuiUtil.drawTexturedModalRect(resetScreenX, boxScreenY, 10, 20, 33, 492); + + //////////////////////////////////////////// + //////////////////////////////////////////// + //Key name + String name = getBoxKeyName(); + float nameWidth = font.getStringWidth(name); + float nameScale = scale; + float nameBoxRatio = nameWidth * scale / boxWidth; + + GL11.glPushMatrix(); + if (nameBoxRatio > 0.9) { + nameScale /= nameWidth / boxWidth / 1.2f; + GL11.glTranslatef(0, nameBoxRatio * 0.5f, 0); + } + + float nameX = boxScreenX + boxWidth / 2 - (nameWidth / 2 * nameScale); + float nameY = offsetY + 11.5f - (font.FONT_HEIGHT / 2); + GL11.glScalef(nameScale, nameScale, 1); + GL11.glTranslatef(nameX / nameScale, nameY / nameScale, 1); + font.drawStringWithShadow(name, 0, 0, conflicts() ? 0xff5555 : 0xffffffff); + GL11.glPopMatrix(); + + //Reset letter + char letter = 'X'; + float letterX = resetScreenX + (resetWidth / 2) - (font.getCharWidth(letter) / 2 * scale) + 0.25f; + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, 1); + GL11.glTranslatef(letterX / scale, nameY / scale, 1); + font.drawStringWithShadow("" + letter, 0, 0, isDefault ? 0xff8a8a8a : 0xffffffff); + GL11.glPopMatrix(); + + //////////////////////////////////////////// + //////////////////////////////////////////// + } + + public void boxClicked(int button) { + if (isEditing) + setKey(-100 + button); + else if (button == 0) + isEditing = true; + } + + public void keyTyped(int typedKey) { + if (typedKey == 1) { + setKey(0); + return; + } + + newState.setState(newState.keyCode, KeyPreset.isCtrlKeyDown(), KeyPreset.isAltKeyDown(), KeyPreset.isShiftKeyDown()); + if (KeyPreset.isNotCtrlAltShift(typedKey)) + setKey(typedKey); + } + + public void setKey(int keyCode) { + if (keyCode == 0) + newState.clear(); + + newState.keyCode = keyCode; + newState.writeTo(key.currentState); + cancelEdit(); + manager.save(); + } + + public void cancelEdit() { + newState.clear(); + isEditing = false; + } + + public boolean conflicts() { + return list.stream().anyMatch(element -> key.shouldConflict && element.key.shouldConflict && element.key != this.key && element.key.equals(this.key)); + } + + public String getBoxKeyName() { + if (isEditing) { + String modifiers = ""; + if (KeyPreset.isCtrlKeyDown()) + modifiers += "CTRL "; + if (KeyPreset.isAltKeyDown()) + modifiers += "ALT "; + if (KeyPreset.isShiftKeyDown()) + modifiers += "SHIFT "; + + return !modifiers.isEmpty() ? modifiers : "Press a key"; + } + + return key.currentState.getName(); + } + + public boolean isMouseAboveBox(int mouseX, int mouseY) { + mouseX -= startX + 2; + mouseY -= startY + 5 - scroll.scrollY; + + float boxScaleX = 1.75f; + float screenY = boxScreenY + 5; + + return mouseX >= boxScreenX && mouseX < boxScreenX + 32 * boxScaleX && mouseY >= screenY && mouseY < screenY + 10; + } + + public boolean isMouseAboveReset(int mouseX, int mouseY) { + mouseX -= startX + 2; + mouseY -= startY + 5 - scroll.scrollY; + + float boxScaleX = 1.75f; + float resetWidth = 10, boxWidth = 32 * boxScaleX; + float screenX = boxScreenX + boxWidth + 2; + float screenY = boxScreenY + 10; + + return mouseX >= screenX && mouseX < screenX + resetWidth && mouseY >= screenY && mouseY < screenY + 10; + } + + public int getHeight() { + List wrappedDescription = font.listFormattedStringToWidth(String.format("- %s", key.description), getMaxStringWidth()); + + int nameHeight = font.FONT_HEIGHT; + int translations = font.FONT_HEIGHT; + int descriptionHeight = wrappedDescription.size() * (font.FONT_HEIGHT); + + return Math.round((nameHeight + descriptionHeight + translations) * scale) + elementSpacing; + } + + public int getMaxStringWidth() { + return (int) Math.max(getWidth() * RELATIVE_MAX_DESC_WIDTH, 0); + } + } + + public class OverlayButton { + public int startX, startY, endX, width, height; + public int textureWidth = 252, textureHeight = 109; + public float scale = 0.25f; + + public OverlayButton() { + } + + public void initGui(int endX, int startY) { + this.endX = endX; + this.startY = startY; + + startX = (int) (endX - textureWidth * scale / 2); + } + + public void drawButton() { + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE); + + double screenX = startX / scale, screenY = startY / scale; + int oldMinFilter = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GL11.glDisable(GL11.GL_BLEND); + + GL11.glPushMatrix(); + float color = aboveButton ? 1f : 0.4f; + GL11.glColor4f(color, color, color, 1); + GL11.glScalef(scale, scale, 1); + GuiUtil.drawTexturedModalRect(screenX, screenY, textureWidth, textureHeight, 0, 0); + GL11.glPopMatrix(); + + GL11.glEnable(GL11.GL_BLEND); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, oldMinFilter); + } + + public boolean isMouseAbove(int mouseX, int mouseY) { + return mouseX >= startX && mouseX < startX + textureWidth * scale / 2 && mouseY >= startY - 4 && mouseY < startY + textureHeight * scale / 2; + } + } +} 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 new file mode 100644 index 000000000..b7b9ab63a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/BracketMatcher.java @@ -0,0 +1,372 @@ +package noppes.npcs.client.gui.util.script; + +import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; + +import java.util.ArrayList; +import java.util.List; + +/** + * Handles bracket matching, brace span computation, and indent guide generation. + */ +public class BracketMatcher { + + /** + * Find matching bracket at cursor position. + * + * @return int[2] with {startPos, endPos} or null if no bracket found + */ + public static int[] findBracketSpanAt(String text, int pos) { + if (text == null || text.isEmpty()) return null; + + // Try at current position + if (pos >= 0 && pos < text.length()) { + char c = text.charAt(pos); + int found = 0; + if (c == '{') found = findClosingBracket(text.substring(pos), '{', '}'); + else if (c == '[') found = findClosingBracket(text.substring(pos), '[', ']'); + else if (c == '(') found = findClosingBracket(text.substring(pos), '(', ')'); + else if (c == '}') found = findOpeningBracket(text.substring(0, pos + 1), '{', '}'); + else if (c == ']') found = findOpeningBracket(text.substring(0, pos + 1), '[', ']'); + else if (c == ')') found = findOpeningBracket(text.substring(0, pos + 1), '(', ')'); + if (found != 0) return new int[]{pos, pos + found}; + } + + // Scan backwards, skipping whitespace on same line + if (pos > 0) { + int scan = pos - 1; + while (scan >= 0) { + char sc = text.charAt(scan); + if (sc == ' ' || sc == '\t') { + scan--; + continue; + } + if (sc == '\n') break; // Don't cross line boundary + + int found2 = 0; + if (sc == '{') found2 = findClosingBracket(text.substring(scan), '{', '}'); + else if (sc == '[') found2 = findClosingBracket(text.substring(scan), '[', ']'); + else if (sc == '(') found2 = findClosingBracket(text.substring(scan), '(', ')'); + else if (sc == '}') found2 = findOpeningBracket(text.substring(0, scan + 1), '{', '}'); + else if (sc == ']') found2 = findOpeningBracket(text.substring(0, scan + 1), '[', ']'); + else if (sc == ')') found2 = findOpeningBracket(text.substring(0, scan + 1), '(', ')'); + + if (found2 != 0) return new int[]{scan, scan + found2}; + break; // Not a bracket; stop + } + } + return null; + } + + /** + * Find all unmatched brace positions (both opens and closes) in the text. + * Returns a list of character indices into the text for braces that have no matching pair. + */ + public static List findUnmatchedBracePositions(String text) { + List unmatched = new ArrayList<>(); + if (text == null || text.isEmpty()) return unmatched; + + List stack = new ArrayList<>(); // {char, pos} + + boolean inLineComment = false; + boolean inBlockComment = false; + boolean inString = false; + boolean escape = false; + char stringDelimiter = 0; + + for (int pos = 0; pos < text.length(); pos++) { + char c = text.charAt(pos); + char next = pos + 1 < text.length() ? text.charAt(pos + 1) : 0; + + if (inString) { + if (escape) { + escape = false; + } else if (c == '\\') { + escape = true; + } else if (c == stringDelimiter) { + inString = false; + } else if (c == '\n') { + inString = false; + } + continue; + } + + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + pos++; + } + continue; + } + + if (inLineComment) { + if (c == '\n') { + inLineComment = false; + } + continue; + } + + if (c == '/' && next == '/') { + inLineComment = true; + pos++; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + pos++; + continue; + } + + if (c == '"' || c == '\'') { + inString = true; + stringDelimiter = c; + escape = false; + continue; + } + + if (c == '{' || c == '[' || c == '(') { + stack.add(new int[]{c, pos}); + } else if (c == '}' || c == ']' || c == ')') { + if (!stack.isEmpty()) { + int[] top = stack.get(stack.size() - 1); + char topc = (char) top[0]; + char expectOpen = (c == '}') ? '{' : (c == ']') ? '[' : '('; + if (topc == expectOpen) { + stack.remove(stack.size() - 1); + continue; + } else { + // mismatched: mark this close as unmatched + unmatched.add(pos); + continue; + } + } else { + // closing with no opens + unmatched.add(pos); + } + } + } + + // any remaining opens on stack are unmatched + for (int[] open : stack) { + unmatched.add(open[1]); + } + + return unmatched; + } + + /** + * Find closing bracket, returns offset from start or 0 if not found + */ + public static int findClosingBracket(String str, char open, char close) { + int depth = 0; + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (c == open) depth++; + else if (c == close) { + depth--; + if (depth == 0) return i; + } + } + return 0; + } + + /** + * Find opening bracket, returns negative offset from end or 0 if not found + */ + public static int findOpeningBracket(String str, char open, char close) { + int depth = 0; + for (int i = str.length() - 1; i >= 0; i--) { + char c = str.charAt(i); + if (c == close) depth++; + else if (c == open) { + depth--; + if (depth == 0) return i - str.length() + 1; + } + } + return 0; + } + + /** + * Compute brace spans for indent guides. + * Returns list of int[4]: {originalDepth, openLineIdx, closeLineIdx, adjustedDepth} + */ + public static List computeBraceSpans(String text, List lines) { + List spans = new ArrayList<>(); + if (text == null || text.isEmpty() || lines == null || lines.isEmpty()) + return spans; + + int lineIdx = 0; + int lineEnd = lines.get(0).end; + List openStack = new ArrayList<>(); + + boolean inLineComment = false; + boolean inBlockComment = false; + boolean inString = false; + boolean escape = false; + char stringDelimiter = 0; + + for (int pos = 0; pos < text.length(); pos++) { + // Advance line index + while (lineIdx < lines.size() - 1 && pos >= lineEnd) { + lineIdx++; + lineEnd = lines.get(lineIdx).end; + } + + char c = text.charAt(pos); + char next = pos + 1 < text.length() ? text.charAt(pos + 1) : 0; + + // String handling + if (inString) { + if (escape) { + escape = false; + } else if (c == '\\') { + escape = true; + } else if (c == stringDelimiter) { + inString = false; + } else if (c == '\n') { + inString = false; + } // Unterminated string + continue; + } + + // Block comment handling + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + pos++; + } + continue; + } + + // Line comment handling + if (inLineComment) { + if (c == '\n') { + inLineComment = false; + } + continue; + } + + // Start of comments + if (c == '/' && next == '/') { + inLineComment = true; + pos++; + continue; + } + if (c == '/' && next == '*') { + inBlockComment = true; + pos++; + continue; + } + + // Start of string + if (c == '"' || c == '\'') { + inString = true; + stringDelimiter = c; + escape = false; + continue; + } + + // Brace matching + if (c == '{') { + openStack.add(lineIdx); + } else if (c == '}') { + if (!openStack.isEmpty()) { + int openLine = openStack.remove(openStack.size() - 1); + int spanDepth = openStack.size() + 1; + spans.add(new int[]{spanDepth, openLine, lineIdx}); + } + } + } + + // Normalize depths for unmatched braces + if (!openStack.isEmpty()) { + int baseline = openStack.size(); + List adjusted = new ArrayList<>(spans.size()); + for (int[] span : spans) { + int adjustedDepth = Math.max(1, span[0] - baseline); + adjusted.add(new int[]{span[0], span[1], span[2], adjustedDepth}); + } + return adjusted; + } else { + for (int i = 0; i < spans.size(); i++) { + int[] span = spans.get(i); + spans.set(i, new int[]{span[0], span[1], span[2], span[0]}); + } + } + return spans; + } + + /** + * Find which brace span should be highlighted based on bracket at position + * + * @return int[2] {openLine, closeLine} or null + */ + public static int[] findHighlightedSpan(int bracketPos, List lines, List spans) { + if (bracketPos < 0 || lines == null || spans == null) return null; + + // Find line containing bracket + int bracketLineIdx = -1; + for (int i = 0; i < lines.size(); i++) { + LineData ld = lines.get(i); + if (bracketPos >= ld.start && bracketPos < ld.end) { + bracketLineIdx = i; + break; + } + } + + if (bracketLineIdx >= 0) { + for (int[] span : spans) { + int openLine = span[1]; + int closeLine = span[2]; + if (bracketLineIdx >= openLine && bracketLineIdx <= closeLine) { + return new int[]{openLine, closeLine}; + } + } + } + return null; + } + + /** + * Check if a brace at given position has a matching close with same indent + */ + public static boolean hasMatchingCloseWithSameIndent(String text, int bracePos, List lines, int currentIndent) { + if (text == null || lines == null || bracePos < 0) return false; + + // Find line containing the brace + int openLineIdx = -1; + for (int i = 0; i < lines.size(); i++) { + LineData ld = lines.get(i); + if (bracePos >= ld.start && bracePos < ld.end) { + openLineIdx = i; + break; + } + } + + if (openLineIdx < 0) return false; + + List spans = computeBraceSpans(text, lines); + for (int[] span : spans) { + if (span[1] == openLineIdx) { + int closeLineIdx = span[2]; + if (closeLineIdx < lines.size()) { + String closeLine = lines.get(closeLineIdx).text; + int closeIndent = getLineIndent(closeLine); + return closeIndent == currentIndent; + } + } + } + return false; + } + + /** + * Get leading whitespace count of a line + */ + private static int getLineIndent(String line) { + int indent = 0; + for (int i = 0; i < line.length(); i++) { + char c = line.charAt(i); + if (c == ' ' || c == '\t') indent++; + else break; + } + return indent; + } +} 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 new file mode 100644 index 000000000..9b6567b1e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/ClassPathFinder.java @@ -0,0 +1,696 @@ +package noppes.npcs.client.gui.util.script; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Helper class for resolving Java classpath imports and determining class types. + * Handles: + * - Class resolution via Class.forName + * - Inner class notation (Outer.Inner -> Outer$Inner) + * - Package validation + * - Type detection (interface/enum/class) + * - Result caching for performance + */ +public class ClassPathFinder { + + // Cache: fully-qualified class name -> ClassInfo (null if not found) + private final Map classCache = new HashMap<>(); + + // Cache: package prefix -> whether it's a valid package (has classes under it) + private final Set validPackages = new HashSet<>(); + + // Common java.lang classes (auto-imported in Java) + public static final Set JAVA_LANG_CLASSES = 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" + )); + + /** + * Information about a resolved class + */ + public static class ClassInfo { + public final String resolvedName; // Full class name with $ for inner classes + public final ClassType type; // INTERFACE, ENUM, or CLASS + public final int packageEndIndex; // Index in original path where package ends (for "java.util.List" -> 9) + + public ClassInfo(String resolvedName, ClassType type, int packageEndIndex) { + this.resolvedName = resolvedName; + this.type = type; + this.packageEndIndex = packageEndIndex; + } + } + + public enum ClassType { + INTERFACE, + ENUM, + CLASS + } + + /** + * Result of resolving an import path + */ + public static class ResolveResult { + public final boolean found; + public final ClassInfo classInfo; + public final String packagePortion; // The package part (e.g., "java.util") + public final String classPortion; // The class part (e.g., "List" or "IOverlay.ColorType") + public final List classSegments; // Each class/inner-class segment with its type + public final int invalidStartOffset; // Character offset where invalid portion starts (-1 if all valid or all invalid) + public final int packageSegmentCount; // Number of dot-separated identifier tokens that belong to the package portion + + private ResolveResult(boolean found, ClassInfo classInfo, String packagePortion, + String classPortion, List classSegments, int invalidStartOffset, + int packageSegmentCount) { + this.found = found; + this.classInfo = classInfo; + this.packagePortion = packagePortion; + this.classPortion = classPortion; + this.classSegments = classSegments != null ? classSegments : Collections.emptyList(); + this.invalidStartOffset = invalidStartOffset; + this.packageSegmentCount = packageSegmentCount; + } + + public static ResolveResult notFound(String packagePortion, String classPortion, int invalidStartOffset, int packageSegmentCount) { + return new ResolveResult(false, null, packagePortion, classPortion, null, invalidStartOffset, packageSegmentCount); + } + + public static ResolveResult found(ClassInfo info, String packagePortion, + String classPortion, List segments, int packageSegmentCount) { + return new ResolveResult(true, info, packagePortion, classPortion, segments, -1, packageSegmentCount); + } + } + + /** + * Represents a segment of the class portion (e.g., "IOverlay" or "ColorType") + */ + public static class ClassSegment { + public final String name; + public final ClassType type; + + public ClassSegment(String name, ClassType type) { + this.name = name; + this.type = type; + } + } + + /** + * Clear all caches (call when imports change) + */ + public void clearCache() { + classCache.clear(); + validPackages.clear(); + } + + /** + * Resolve an import path to determine if it's a valid class and get its type. + * Handles inner classes like "kamkeel.npcdbc.api.client.overlay.IOverlay.ColorType" + * + * @param importPath The import path (e.g., "java.util.List" or "kamkeel...IOverlay.ColorType") + * @return ResolveResult with resolution details + */ + public ResolveResult resolve(String importPath) { + if (importPath == null || importPath.isEmpty()) { + return ResolveResult.notFound("", "", -1, 0); + } + + // Normalize whitespace/newlines around dots so wrapped imports like + // "kamkeel.npcdbc.api.client.overlay.IOverlay.\n TextureFunction" become + // "kamkeel.npcdbc.api.client.overlay.IOverlay.TextureFunction" before resolving. + String normalizedPath = importPath.replaceAll("\\s*\\.\\s*", ".").trim(); + + // Handle trailing dot (user is still typing a package path like "java.util.") + boolean trailingDot = normalizedPath.endsWith("."); + String pathToResolve = trailingDot ? normalizedPath.substring(0, normalizedPath.length() - 1) : normalizedPath; + + if (pathToResolve.isEmpty()) { + return ResolveResult.notFound("", "", -1, 0); + } + + String[] segments = pathToResolve.split("\\."); + int n = segments.length; + + // Find the first uppercase segment (likely start of class name) + int firstUpperIndex = findFirstUppercaseSegment(segments); + + // No uppercase segments at all: this is a package-like path. + // Validate as far as we can and mark invalid tail red. + if (firstUpperIndex == n) { + int longestValid = findLongestValidPackagePrefixIndex(segments); + if (longestValid == n) { + // Entire path is a valid package (or cached as valid) + return ResolveResult.notFound(pathToResolve, "", -1, n); + } + + if (longestValid > 0) { + String validPrefix = buildPackagePortion(segments, longestValid); + String invalidRemainder = buildClassPortion(segments, longestValid, n); + int invalidOffset = validPrefix.length() + 1; // after the dot + return ResolveResult.notFound(validPrefix, invalidRemainder, invalidOffset, longestValid); + } + + // Nothing validated + return ResolveResult.notFound("", pathToResolve, 0, 0); + } + + // Trailing dot is handled above for lowercase-only paths; for mixed-case paths + // we continue resolving as usual. + + // Try different splits: package vs class boundary + // Start from firstUpperIndex and try treating each uppercase segment as potential class start + for (int classStartIdx = firstUpperIndex; classStartIdx < n; classStartIdx++) { + // Try different inner class depths (deepest first) + for (int classEndIdx = n; classEndIdx > classStartIdx; classEndIdx--) { + String candidate = buildClassName(segments, classStartIdx, classEndIdx); + ClassInfo info = tryResolveClass(candidate); + + if (info != null) { + // Found a valid class! + String packagePortion = buildPackagePortion(segments, classStartIdx); + String validClassPortion = buildClassPortion(segments, classStartIdx, classEndIdx); + + // Register this package as valid for future lookups + if (!packagePortion.isEmpty()) { + registerValidPackage(packagePortion); + } + + // Check if there are MORE segments after what we resolved (invalid inner class) + if (classEndIdx < n) { + // e.g., IOverlay.ColorType resolved but there's more like ".idk" + // Mark the extra parts as invalid + List classSegments = buildClassSegments(segments, classStartIdx, classEndIdx); + String fullClassPortion = buildClassPortion(segments, classStartIdx, n); + // Calculate where the invalid portion starts (after valid class + dot) + int validEndOffset = packagePortion.length() + (packagePortion.isEmpty() ? 0 : 1) + validClassPortion.length() + 1; + return new ResolveResult(false, info, packagePortion, + fullClassPortion, classSegments, validEndOffset, classStartIdx); + } + + // Full resolution successful + List classSegments = buildClassSegments(segments, classStartIdx, n); + return ResolveResult.found( + new ClassInfo(info.resolvedName, info.type, packagePortion.length()), + packagePortion, validClassPortion, classSegments, classStartIdx + ); + } + } + } + + // Class resolution failed completely + // Strategy: Use heuristic - everything before first uppercase = package, rest = class + // This ensures consistent behavior regardless of cache state + + if (firstUpperIndex > 0 && firstUpperIndex < n) { + // There's a package portion (lowercase) and class portion (uppercase start) + String packagePortion = buildPackagePortion(segments, firstUpperIndex); + String classPortion = buildClassPortion(segments, firstUpperIndex, n); + + // Check if we can detect a typo in the package by comparing with cached packages + int typoIndex = findPackageTypoIndex(segments, firstUpperIndex); + if (typoIndex >= 0 && typoIndex < firstUpperIndex) { + // Found a divergence from a known valid package + String validPrefix = buildPackagePortion(segments, typoIndex); + int invalidOffset = validPrefix.isEmpty() ? 0 : validPrefix.length() + 1; + return ResolveResult.notFound(validPrefix, buildClassPortion(segments, typoIndex, n), invalidOffset, typoIndex); + } + + // No typo detected - assume package is valid, only class portion is invalid + int invalidOffset = packagePortion.length() + 1; // After the package dot + return ResolveResult.notFound(packagePortion, classPortion, invalidOffset, firstUpperIndex); + + } else if (firstUpperIndex == 0) { + // Entire path starts with uppercase (e.g., "String" or "MyClass.Inner") + // Treat as class with no package + return ResolveResult.notFound("", pathToResolve, 0, 0); + + } else { + // All lowercase, no uppercase found - entire path is package-like + // If trailing dot was handled above, this is just a package without class + return ResolveResult.notFound(pathToResolve, "", -1, n); + } + } + + /** + * Find index where the typed package diverges from a known cached package. + * Returns -1 if no typo detected, or the segment index where divergence starts. + */ + private int findPackageTypoIndex(String[] segments, int classStartIdx) { + // Build the typed package path segment by segment and compare with cache + StringBuilder sb = new StringBuilder(); + int lastValidIndex = -1; + + for (int i = 0; i < classStartIdx; i++) { + if (i > 0) sb.append("."); + sb.append(segments[i]); + String currentPath = sb.toString(); + + // Check if this exact path is in cache + if (validPackages.contains(currentPath)) { + lastValidIndex = i + 1; // This segment is valid + } else if (i > 0) { + // Not in cache - check if parent is valid but this segment is wrong + String parentPath = buildPackagePortion(segments, i); + if (validPackages.contains(parentPath)) { + // Parent is valid, but current segment isn't in any cached path + // Check if there ARE cached paths extending from parent + boolean hasAlternative = false; + for (String cached : validPackages) { + if (cached.startsWith(parentPath + ".") && cached.length() > parentPath.length() + 1) { + hasAlternative = true; + break; + } + } + if (hasAlternative) { + // There are valid continuations from parent, but this segment doesn't match any + return i; // This segment is likely a typo + } + } + } + } + + // If we found some valid prefix but not all, return where it stopped being valid + if (lastValidIndex > 0 && lastValidIndex < classStartIdx) { + // Check if segment at lastValidIndex diverges from any known path + String validPrefix = buildPackagePortion(segments, lastValidIndex); + for (String cached : validPackages) { + if (cached.startsWith(validPrefix + ".")) { + // There's a known continuation - check if typed segment matches + String nextTyped = segments[lastValidIndex]; + String cachedRemainder = cached.substring(validPrefix.length() + 1); + String nextCached = cachedRemainder.contains(".") ? + cachedRemainder.substring(0, cachedRemainder.indexOf('.')) : cachedRemainder; + if (!nextTyped.equals(nextCached)) { + return lastValidIndex; // Divergence point + } + } + } + } + + return -1; // No typo detected + } + + /** + * Check if a package path is valid (has been seen in successful resolutions or can be validated) + */ + public boolean isValidPackage(String packagePath) { + if (packagePath == null || packagePath.isEmpty()) { + return false; + } + + // Check cache first + if (validPackages.contains(packagePath)) { + return true; + } + + // Try to consult the global PackageFinder index if initialized (fast O(1) lookup) + if (PackageFinder.find(packagePath)) { + registerValidPackage(packagePath); + return true; + } + + // Fallback: try to find any class under this package to validate it + String[] testClasses = getTestClassesForPackage(packagePath); + for (String testClass : testClasses) { + try { + Class.forName(testClass); + registerValidPackage(packagePath); + return true; + } catch (ClassNotFoundException | LinkageError ignored) { + } + } + + return false; + } + + /** + * Get the ClassInfo for a simple class name, using provided imports map + */ + public ClassInfo resolveSimpleName(String simpleName, Map importedClasses) { + return resolveSimpleName(simpleName, importedClasses, Collections.emptySet()); + } + + /** + * Resolve a simple class name using explicit imports, java.lang, or wildcard imports. + * Supports package wildcard imports (e.g., java.util.*) and class-member wildcards + * that have been added to `importedPackages` (e.g., kamkeel..IOverlay.* treated as + * attempting to resolve inner types of IOverlay). + */ + public ClassInfo resolveSimpleName(String simpleName, Map importedClasses, Set importedPackages) { + if (simpleName == null || simpleName.isEmpty()) { + return null; + } + + // Check imported classes first + String fullName = importedClasses.get(simpleName); + if (fullName != null) { + ClassInfo info = tryResolveClass(fullName); + if (info != null) return info; + } + + // Check java.lang classes + if (JAVA_LANG_CLASSES.contains(simpleName)) { + ClassInfo info = tryResolveClass("java.lang." + simpleName); + if (info != null) return info; + } + + // Check wildcard imports: these can be package wildcards (pkg.*) or + // class-member wildcards (Outer.*) where we want to allow resolving + // inner types of the Outer class. Heuristic: if the last segment of + // the imported path starts with uppercase, treat it as a class; otherwise + // treat it as a package. + if (importedPackages != null && !importedPackages.isEmpty()) { + for (String p : importedPackages) { + if (p == null || p.isEmpty()) continue; + String[] segs = p.split("\\."); + String last = segs[segs.length - 1]; + // 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) { + String candidate = p + "." + simpleName; + ClassInfo info = tryResolveClass(candidate); + if (info != null) return info; + } else { + // Try inner type under the class: Outer$Inner + String candidateInner = p + "$" + simpleName; + ClassInfo info = tryResolveClass(candidateInner); + if (info != null) return info; + + // Also try package-like (in case someone imported a class-looking path but it is actually a package) + String candidatePkg = p + "." + simpleName; + info = tryResolveClass(candidatePkg); + if (info != null) return info; + } + } + } + + return null; + } + + /** + * Try to resolve a fully-qualified class name (with $ for inner classes) + */ + private ClassInfo tryResolveClass(String className) { + if (className == null || className.isEmpty()) { + return null; + } + + // Check cache + if (classCache.containsKey(className)) { + return classCache.get(className); + } + + ClassInfo result = null; + + try { + Class clazz = Class.forName(className); + result = createClassInfo(className, clazz); + classCache.put(className, result); + + int lastDot = className.lastIndexOf("."); + if (lastDot > 0) + registerValidPackage(className.substring(0, lastDot)); + } catch (ClassNotFoundException | NoClassDefFoundError e) { + // Not found with given name, will be cached as null + } catch (LinkageError e) { + // Linkage error - treat as not found + } + + return result; + } + + /** + * Public wrapper to attempt resolving a fully-qualified class name. + * Returns null if not found. + */ + public ClassInfo tryResolveClassName(String className) { + return tryResolveClass(className); + } + + private ClassInfo createClassInfo(String resolvedName, Class clazz) { + ClassType type; + if (clazz.isInterface()) { + type = ClassType.INTERFACE; + } else if (clazz.isEnum()) { + type = ClassType.ENUM; + } else { + type = ClassType.CLASS; + } + + // Calculate package end index + int pkgEnd = resolvedName.lastIndexOf('.'); + if (pkgEnd < 0) + pkgEnd = 0; + + return new ClassInfo(resolvedName, type, pkgEnd); + } + + /** + * Build a class name candidate from segments, using $ for inner classes + */ + private String buildClassName(String[] segments, int classStartIdx, int classEndIdx) { + StringBuilder sb = new StringBuilder(); + + // Package portion (dot-separated) + for (int i = 0; i < classStartIdx; i++) { + if (i > 0) + sb.append('.'); + sb.append(segments[i]); + } + + // Class portion ($ for inner classes after the first class) + for (int i = classStartIdx; i < classEndIdx; i++) { + if (i == classStartIdx) { + if (sb.length() > 0) + sb.append('.'); + } else { + sb.append('$'); + } + sb.append(segments[i]); + } + + return sb.toString(); + } + + private String buildPackagePortion(String[] segments, int classStartIdx) { + if (classStartIdx <= 0) + return ""; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < classStartIdx; i++) { + if (i > 0) + sb.append('.'); + sb.append(segments[i]); + } + return sb.toString(); + } + + private String buildClassPortion(String[] segments, int classStartIdx, int endIdx) { + StringBuilder sb = new StringBuilder(); + for (int i = classStartIdx; i < endIdx; i++) { + if (i > classStartIdx) + sb.append('.'); + sb.append(segments[i]); + } + return sb.toString(); + } + + private List buildClassSegments(String[] segments, int classStartIdx, int endIdx) { + List result = new ArrayList<>(); + StringBuilder fullName = new StringBuilder(); + + // Build package portion + for (int i = 0; i < classStartIdx; i++) { + if (i > 0) + fullName.append('.'); + fullName.append(segments[i]); + } + + // Add each class segment + for (int i = classStartIdx; i < endIdx; i++) { + if (i == classStartIdx) { + if (fullName.length() > 0) + fullName.append('.'); + } else { + fullName.append('$'); + } + fullName.append(segments[i]); + + // Try to resolve this partial class name + ClassInfo info = tryResolveClass(fullName.toString()); + ClassType type = (info != null) ? info.type : ClassType.CLASS; + result.add(new ClassSegment(segments[i], type)); + } + + return result; + } + + 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; + } + } + return segments.length; // No uppercase segment + } + + private int findLongestValidPackagePrefixIndex(String[] segments) { + int longestValid = 0; + for (int i = 1; i <= segments.length; i++) { + String pkg = buildPackagePortion(segments, i); + if (isValidPackage(pkg)) { + longestValid = i; + } else { + // If a prefix isn't valid, deeper prefixes can't be valid packages either. + break; + } + } + return longestValid; + } + + private void registerValidPackage(String packagePath) { + validPackages.add(packagePath); + + // Also register all 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) { + // Return common classes for well-known packages + switch (packagePath) { + case "java": + return new String[]{"java.lang.Object"}; + case "java.util": + return new String[]{"java.util.List", "java.util.Map", "java.util.Set"}; + 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: + // For unknown packages, try common class suffixes + return new String[]{ + packagePath + ".package-info", // Won't work but harmless + }; + } + } + + // ==================== GENERIC TYPE PARSING ==================== + + /** + * Parse generic type content and return type names with their positions. + * Handles arbitrary nesting depth like "Map>>" + * + * @param genericContent The content inside <...> (without the outer angle brackets) + * @param importedClasses Map of simple name -> full class name for resolution + * @return List of TypeOccurrence with position and type info + */ + public List parseGenericTypes(String genericContent, Map importedClasses) { + return parseGenericTypes(genericContent, importedClasses, Collections.emptySet()); + } + + public List parseGenericTypes(String genericContent, Map importedClasses, Set importedPackages) { + List results = new ArrayList<>(); + parseGenericTypesRecursive(genericContent, 0, importedClasses, importedPackages, results); + return results; + } + + /** + * Represents a type occurrence within generic content + */ + public static class TypeOccurrence { + public final int startOffset; // Relative to the start of genericContent + public final int endOffset; + public final String typeName; + public final ClassType type; + + public TypeOccurrence(int startOffset, int endOffset, String typeName, ClassType type) { + this.startOffset = startOffset; + this.endOffset = endOffset; + this.typeName = typeName; + this.type = type; + } + } + + private void parseGenericTypesRecursive(String content, int baseOffset, + Map importedClasses, + Set importedPackages, + List results) { + 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); + + // 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)); + } + + // 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); + parseGenericTypesRecursive(nestedContent, baseOffset + nestedStart, importedClasses, importedPackages, results); + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/CommentHandler.java b/src/main/java/noppes/npcs/client/gui/util/script/CommentHandler.java new file mode 100644 index 000000000..ed586e304 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/CommentHandler.java @@ -0,0 +1,218 @@ +package noppes.npcs.client.gui.util.script; + +import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; + +import java.util.List; + +/** + * Handles line comment toggling for the script editor. + */ +public class CommentHandler { + + /** + * Result of comment toggle operation + */ + public static class ToggleResult { + public final String text; + public final int delta; // Change in length (negative if comment removed) + public final int nonWsIndex; // Index of first non-whitespace character + + public ToggleResult(String text, int delta, int nonWsIndex) { + this.text = text; + this.delta = delta; + this.nonWsIndex = nonWsIndex; + } + + public boolean wasCommented() { + return delta < 0; + } + } + + /** + * Toggle line comment on a single line + */ + public static ToggleResult toggleLine(String lineText) { + // Find first non-whitespace + int nonWs = 0; + while (nonWs < lineText.length() && Character.isWhitespace(lineText.charAt(nonWs))) { + nonWs++; + } + + boolean hasContent = nonWs < lineText.length(); + boolean hasComment = hasContent && lineText.startsWith("//", nonWs); + String newText; + + if (hasComment) { + // Remove comment + int cut = Math.min(nonWs + 2, lineText.length()); + newText = lineText.substring(0, nonWs) + lineText.substring(cut); + } else if (hasContent) { + // Add comment + newText = lineText.substring(0, nonWs) + "//" + lineText.substring(nonWs); + } else { + // Empty/whitespace line - no change + newText = lineText; + } + + return new ToggleResult(newText, newText.length() - lineText.length(), nonWs); + } + + /** + * Result of toggling comments on a selection + */ + public static class SelectionToggleResult { + public final String newText; + public final int newStartSelection; + public final int newEndSelection; + + public SelectionToggleResult(String text, int start, int end) { + this.newText = text; + this.newStartSelection = start; + this.newEndSelection = end; + } + } + + /** + * Toggle comments on all lines in a selection + */ + public static SelectionToggleResult toggleCommentSelection( + String text, + List lines, + int startSelection, + int endSelection) { + + StringBuilder newText = new StringBuilder(text.length() + 100); + int prevEnd = 0; + int newStart = -1; + int newEnd = -1; + int newIndex = 0; + + for (LineData line : lines) { + int safeLineStart = Math.max(0, Math.min(line.start, text.length())); + int safeLineEnd = Math.max(0, Math.min(line.end, text.length())); + + // Handle gap between lines (shouldn't happen normally) + if (safeLineStart > prevEnd) { + if (newStart == -1 && startSelection >= prevEnd && startSelection <= safeLineStart) { + newStart = newIndex + (startSelection - prevEnd); + } + if (newEnd == -1 && endSelection >= prevEnd && endSelection <= safeLineStart) { + newEnd = newIndex + (endSelection - prevEnd); + } + newText.append(text, prevEnd, safeLineStart); + newIndex += safeLineStart - prevEnd; + } + + // Check if this line is in selection + if (safeLineEnd > startSelection && safeLineStart < endSelection) { + String lineText = text.substring(safeLineStart, safeLineEnd); + ToggleResult tr = toggleLine(lineText); + String newLineText = tr.text; + int nonWs = tr.nonWsIndex; + int delta = tr.delta; + + // Update start selection position + if (newStart == -1 && startSelection >= safeLineStart && startSelection <= safeLineEnd) { + int offsetInOld = startSelection - safeLineStart; + int newOffset = offsetInOld; + if (offsetInOld >= nonWs) { + newOffset = offsetInOld + delta; + } + newStart = newIndex + Math.max(0, newOffset); + } + + // Update end selection position + if (newEnd == -1 && endSelection >= safeLineStart && endSelection <= safeLineEnd) { + int offsetInOld = endSelection - safeLineStart; + int newOffset = offsetInOld; + if (offsetInOld >= nonWs) { + newOffset = offsetInOld + delta; + } + newEnd = newIndex + Math.max(0, newOffset); + } + + newText.append(newLineText); + newIndex += newLineText.length(); + } else { + // Line not in selection - keep unchanged + if (newStart == -1 && startSelection >= safeLineStart && startSelection <= safeLineEnd) { + newStart = newIndex + (startSelection - safeLineStart); + } + if (newEnd == -1 && endSelection >= safeLineStart && endSelection <= safeLineEnd) { + newEnd = newIndex + (endSelection - safeLineStart); + } + newText.append(text, safeLineStart, safeLineEnd); + newIndex += safeLineEnd - safeLineStart; + } + prevEnd = safeLineEnd; + } + + // Handle remaining text after last line + if (prevEnd < text.length()) { + if (newStart == -1 && startSelection >= prevEnd && startSelection <= text.length()) { + newStart = newIndex + (startSelection - prevEnd); + } + if (newEnd == -1 && endSelection >= prevEnd && endSelection <= text.length()) { + newEnd = newIndex + (endSelection - prevEnd); + } + newText.append(text, prevEnd, text.length()); + newIndex += text.length() - prevEnd; + } + + // Fallback for positions not found + if (newStart == -1) newStart = Math.max(0, Math.min(startSelection, newText.length())); + if (newEnd == -1) newEnd = Math.max(0, Math.min(endSelection, newText.length())); + + return new SelectionToggleResult(newText.toString(), newStart, newEnd); + } + + /** + * Toggle comment on a single line at cursor position + */ + public static SingleLineToggleResult toggleCommentAtCursor( + String text, + List lines, + int cursorPosition) { + + for (LineData line : lines) { + int lineStart = Math.max(0, Math.min(line.start, text.length())); + int lineEnd = Math.max(0, Math.min(line.end, text.length())); + + if (cursorPosition >= lineStart && cursorPosition <= lineEnd) { + String lineText = text.substring(lineStart, lineEnd); + ToggleResult tr = toggleLine(lineText); + boolean hadComment = tr.delta < 0; + + String before = text.substring(0, lineStart); + String after = lineEnd <= text.length() ? text.substring(lineEnd) : ""; + String newText = before + tr.text + after; + + // Calculate new cursor position + int cursorDelta = hadComment ? -2 : 2; + int newCursor = cursorPosition + cursorDelta; + if (cursorPosition < lineStart + tr.nonWsIndex + (hadComment ? 2 : 0)) { + newCursor = cursorPosition; + } + newCursor = Math.max(lineStart, newCursor); + + return new SingleLineToggleResult(newText, newCursor); + } + } + + // No line found at cursor - return unchanged + return new SingleLineToggleResult(text, cursorPosition); + } + + /** + * Result of toggling comment on single line + */ + public static class SingleLineToggleResult { + public final String newText; + public final int newCursorPosition; + + public SingleLineToggleResult(String text, int cursor) { + this.newText = text; + this.newCursorPosition = cursor; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/CursorNavigation.java b/src/main/java/noppes/npcs/client/gui/util/script/CursorNavigation.java new file mode 100644 index 000000000..52faebe0c --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/CursorNavigation.java @@ -0,0 +1,218 @@ +package noppes.npcs.client.gui.util.script; + +import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Handles cursor navigation logic (up, down, left, right, word movement). + */ +public class CursorNavigation { + + /** + * Move cursor up one line, maintaining column position + */ + public static int cursorUp(int cursorPosition, List lines, String text) { + if (lines == null || lines.isEmpty()) return 0; + + for (int i = 0; i < lines.size(); i++) { + LineData data = lines.get(i); + boolean isLastLine = (i == lines.size() - 1); + boolean isOnLine = isLastLine + ? (cursorPosition >= data.start && cursorPosition <= data.end) + : (cursorPosition >= data.start && cursorPosition < data.end); + + if (isOnLine) { + if (i == 0) { + return 0; // Already on first line + } + + int column = Math.min(cursorPosition - data.start, data.text.length()); + LineData target = lines.get(i - 1); + int targetColumn = Math.min(column, target.text.length()); + int targetIndent = getLineIndent(target.text); + int minPos = target.start + Math.min(targetIndent, target.text.length()); + int targetPos = target.start + targetColumn; + return Math.max(minPos, targetPos); + } + } + return 0; + } + + /** + * Move cursor down one line, maintaining column position + */ + public static int cursorDown(int cursorPosition, List lines, String text) { + if (lines == null || lines.isEmpty()) return text != null ? text.length() : 0; + if (text != null && cursorPosition == text.length()) return cursorPosition; + + for (int i = 0; i < lines.size(); i++) { + LineData data = lines.get(i); + boolean isLastLine = (i == lines.size() - 1); + boolean isOnLine = isLastLine + ? (cursorPosition >= data.start && cursorPosition <= data.end) + : (cursorPosition >= data.start && cursorPosition < data.end); + + if (isOnLine) { + if (i >= lines.size() - 1) { + return cursorPosition; // Already on last line + } + + int column = Math.min(cursorPosition - data.start, data.text.length()); + LineData target = lines.get(i + 1); + int targetColumn = Math.min(column, target.text.length()); + int targetIndent = getLineIndent(target.text); + int minPos = target.start + Math.min(targetIndent, target.text.length()); + int targetPos = target.start + targetColumn; + return Math.max(minPos, targetPos); + } + } + return text != null ? text.length() : 0; + } + + /** + * Move cursor left, optionally by word + */ + public static int cursorLeft(int cursorPosition, String text, Pattern wordPattern, boolean byWord) { + if (text == null || cursorPosition <= 0) return 0; + + int moveAmount = 1; + if (byWord && wordPattern != null) { + Matcher m = wordPattern.matcher(text.substring(0, cursorPosition)); + while (m.find()) { + if (m.start() != m.end()) { + moveAmount = cursorPosition - m.start(); + } + } + } + return Math.max(cursorPosition - moveAmount, 0); + } + + /** + * Move cursor right, optionally by word + */ + public static int cursorRight(int cursorPosition, String text, Pattern wordPattern, boolean byWord) { + if (text == null) return 0; + int textLen = text.length(); + if (cursorPosition >= textLen) return textLen; + + int moveAmount = 1; + if (byWord && wordPattern != null) { + Matcher m = wordPattern.matcher(text.substring(cursorPosition)); + if (m.find() && m.start() > 0) { + moveAmount = m.start(); + } else if (m.find()) { + moveAmount = m.start(); + } + } + return Math.min(cursorPosition + moveAmount, textLen); + } + + /** + * Get cursor position from mouse click coordinates + */ + public static int getPositionFromMouse( + int mouseX, int mouseY, + int areaX, int areaY, + int gutterWidth, + int lineHeight, + int scrolledLine, + double scrollFracOffset, + List lines, + String text, + FontWidthProvider fontWidth) { + + int xMouse = mouseX - (areaX + gutterWidth + 1); + int yMouse = mouseY - areaY - 1; + + // Account for fractional scroll offset + double fracPixels = scrollFracOffset * lineHeight; + yMouse = (int) Math.round(yMouse + fracPixels); + + if (lines == null || lines.isEmpty()) { + return text != null ? text.length() : 0; + } + + int visibleLines = Math.min(lines.size(), scrolledLine + 50); // Reasonable limit + + for (int i = 0; i < lines.size(); i++) { + LineData data = lines.get(i); + + if (i >= scrolledLine && i <= visibleLines) { + int yPos = (i - scrolledLine) * lineHeight; + + if (yMouse >= yPos && yMouse < yPos + lineHeight) { + // Found the line, now find character position + int lineWidth = 0; + char[] chars = data.text.toCharArray(); + + for (int j = 1; j <= chars.length; j++) { + int w = fontWidth.getWidth(data.text.substring(0, j)); + if (xMouse < lineWidth + (w - lineWidth) / 2) { + return data.start + j - 1; + } + lineWidth = w; + } + + // Click past end of line - place cursor at end of text (not on newline) + int posAfterChars = data.start + chars.length; + return Math.min(posAfterChars, text.length()); + } + } + } + + return text != null ? text.length() : 0; + } + + /** + * Interface for font width measurement + */ + public interface FontWidthProvider { + int getWidth(String text); + } + + /** + * Get leading whitespace count of a line + */ + private static int getLineIndent(String lineText) { + int indent = 0; + for (int i = 0; i < lineText.length(); i++) { + char c = lineText.charAt(i); + if (c == ' ' || c == '\t') indent++; + else break; + } + return indent; + } + + /** + * Find line index containing given position + */ + public static int findLineIndex(int position, List lines) { + if (lines == null || lines.isEmpty()) return 0; + + for (int i = 0; i < lines.size(); i++) { + LineData line = lines.get(i); + boolean isLastLine = (i == lines.size() - 1); + boolean isOnLine = isLastLine + ? (position >= line.start && position <= line.end) + : (position >= line.start && position < line.end); + if (isOnLine) { + return i; + } + } + return lines.size() - 1; + } + + /** + * Find line data containing given position + */ + public static LineData findLineAt(int position, List lines) { + int idx = findLineIndex(position, lines); + if (idx >= 0 && idx < lines.size()) { + return lines.get(idx); + } + return null; + } +} 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 new file mode 100644 index 000000000..a52bf2576 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/FormatHelper.java @@ -0,0 +1,2046 @@ +package noppes.npcs.client.gui.util.script; + +import java.util.ArrayList; +import java.util.List; + +/** + * 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
  • + *
+ */ +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. + */ + public static class FormatSettings { + // Spaces around operators + public boolean spaceAroundAssignment = true; // a = b + public boolean spaceAroundArithmetic = true; // a + b - c * d / e + public boolean spaceAroundComparison = true; // a == b, a != b, a <= b + public boolean spaceAroundLogical = true; // a && b || c + public boolean spaceAroundBitwise = true; // a & b | c ^ d + + // Spaces within brackets + public boolean spaceWithinParens = false; // (a) vs ( a ) + public boolean spaceWithinBrackets = false; // [a] vs [ a ] + public boolean spaceWithinBraces = true; // {a} vs { a } (for initializers) + + // Spaces before/after + public boolean spaceAfterComma = true; // a, b vs a,b + public boolean spaceBeforeComma = false; // a, b vs a , b + public boolean spaceAfterSemicolon = true; // for (a; b; c) vs for (a;b;c) + public boolean spaceBeforeSemicolon = false; + public boolean spaceAfterColon = true; // case a: b vs case a:b + public boolean spaceBeforeColon = false; + + // Method calls + public boolean spaceBeforeMethodParens = false; // foo() vs foo () + public boolean spaceAfterTypeCast = true; // (int) x vs (int)x + + // Control statements + public boolean spaceBeforeIfParens = true; // if (...) vs if(...) + public boolean spaceBeforeWhileParens = true; + public boolean spaceBeforeForParens = true; + public boolean spaceBeforeSwitchParens = true; + public boolean spaceBeforeCatchParens = true; + + // Braces + public boolean spaceBeforeOpenBrace = true; // if () { vs if (){ + + // Line length + public int maxLineLength = 120; + public boolean wrapLongLines = false; // Auto-wrap lines longer than maxLineLength + public int wrapIndentSpaces = 4; // Extra indent for wrapped lines + public boolean wrapComments = true; // Also wrap long comments + + // Wrap break preferences (where to break long lines) + public boolean wrapAfterComma = true; // Prefer breaking after commas + public boolean wrapAfterOperator = true; // Prefer breaking after operators + public boolean wrapBeforeDot = true; // Break before . for chained calls + public boolean wrapMethodArguments = true; // Each arg on new line when wrapping method calls + + // Whitespace normalization + public boolean normalizeWhitespace = true; // Multiple spaces → single space + public boolean trimTrailingWhitespace = true; + + // Unary operators + public boolean spaceAroundUnaryNot = false; // !a vs ! a + public boolean spaceAroundUnaryIncDec = false; // ++i vs ++ i + + /** + * Create default settings (similar to IntelliJ defaults) + */ + public static FormatSettings defaults() { + return new FormatSettings(); + } + + /** + * Create compact settings (minimal spacing) + */ + public static FormatSettings compact() { + FormatSettings s = new FormatSettings(); + s.spaceWithinParens = false; + s.spaceWithinBrackets = false; + s.spaceWithinBraces = false; + s.wrapLongLines = false; + return s; + } + } + + private FormatSettings settings; + + public FormatHelper() { + this.settings = FormatSettings.defaults(); + } + + public FormatHelper(FormatSettings settings) { + this.settings = settings != null ? settings : FormatSettings.defaults(); + } + + public void setSettings(FormatSettings settings) { + this.settings = settings; + } + + public FormatSettings getSettings() { + return settings; + } + + // ==================== MAIN FORMAT METHOD ==================== + + /** + * 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(); + + for (int i = 0; i < lines.length; i++) { + String line = formatLine(lines[i]); + + if (settings.trimTrailingWhitespace) { + line = trimTrailing(line); + } + + result.append(line); + if (i < lines.length - 1) { + result.append("\n"); + } + } + + return result.toString(); + } + + /** + * Split multiple statements on one line into separate lines with proper indentation. + * E.g., " this.a = 1; this.b = 2;" becomes two lines + * Also handles scope: "if(x){ int y = 20; }" becomes proper multi-line structure + */ + private String splitStatementsOntoSeparateLines(String text) { + String[] lines = text.split("\n", -1); + StringBuilder result = new StringBuilder(); + + for (int lineIdx = 0; lineIdx < lines.length; lineIdx++) { + String line = lines[lineIdx]; + + // Skip empty lines or comment-only lines + String trimmed = line.trim(); + if (trimmed.isEmpty() || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) { + result.append(line); + if (lineIdx < lines.length - 1) result.append("\n"); + continue; + } + + // Extract leading indentation + int indent = 0; + while (indent < line.length() && (line.charAt(indent) == ' ' || line.charAt(indent) == '\t')) { + indent++; + } + String indentation = line.substring(0, indent); + String content = line.substring(indent); + + // Split by semicolons (but preserve those in strings, for loops, etc.) + List statements = splitBySemicolons(content); + + for (int si = 0; si < statements.size(); si++) { + String stmt = statements.get(si).trim(); + if (stmt.isEmpty()) continue; + + // Check if statement opens a scope { and has code after it + int braceIdx = stmt.indexOf('{'); + if (braceIdx >= 0 && braceIdx < stmt.length() - 1) { + String afterBrace = stmt.substring(braceIdx + 1).trim(); + if (!afterBrace.isEmpty() && !afterBrace.equals("}")) { + // Split: keep up to and including {, put rest on new line with extra indent + result.append(indentation).append(stmt, 0, braceIdx + 1).append("\n"); + // Calculate new indent (add 4 spaces) + String newIndent = indentation + " "; + result.append(newIndent).append(afterBrace); + if (si < statements.size() - 1) result.append("\n"); + continue; + } + } + + result.append(indentation).append(stmt); + // Add semicolon back if it was removed + if (si < statements.size() - 1) { + result.append("\n"); + } + } + + if (lineIdx < lines.length - 1) result.append("\n"); + } + + return result.toString(); + } + + /** + * Split content by semicolons, preserving those in strings and for-loops. + */ + private List splitBySemicolons(String content) { + List statements = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + int parenDepth = 0; + boolean inString = false; + boolean inChar = false; + boolean escaped = false; + int forLoopDepth = 0; + + for (int i = 0; i < content.length(); i++) { + char c = content.charAt(i); + + // Track strings + if (c == '\"' && !escaped && !inChar) { + inString = !inString; + } else if (c == '\'' && !escaped && !inString) { + inChar = !inChar; + } + + escaped = (c == '\\' && !escaped); + + if (inString || inChar) { + current.append(c); + continue; + } + + // Track for loops + if (c == '(' && i >= 3 && content.substring(Math.max(0, i - 3), i + 1).matches(".*\\bfor\\s*\\(")) { + forLoopDepth++; + parenDepth++; + } else if (c == '(') { + parenDepth++; + } else if (c == ')') { + parenDepth--; + if (forLoopDepth > 0 && parenDepth < forLoopDepth) { + forLoopDepth = 0; + } + } + + // Semicolon: split if not in for-loop header + if (c == ';' && forLoopDepth == 0) { + current.append(c); + statements.add(current.toString()); + current = new StringBuilder(); + continue; + } + + current.append(c); + } + + // Add remaining content + if (current.length() > 0) { + statements.add(current.toString()); + } + + return statements; + } + + /** + * Format a single line of code. + */ + private String formatLine(String line) { + if (line.trim().isEmpty()) return line; + + // Preserve leading indentation + int indent = 0; + while (indent < line.length() && (line.charAt(indent) == ' ' || line.charAt(indent) == '\t')) { + indent++; + } + String indentation = line.substring(0, indent); + String content = line.substring(indent); + + if (content.isEmpty()) return line; + + // Skip formatting for lines that are entirely comments + String trimmed = content.trim(); + if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*")) { + return line; + } + + // Skip formatting for continuation lines (lines that start with operators, dots, etc.) + // These are wrapped lines from a previous format and should be preserved as-is + if (isContinuationLine(trimmed)) { + return line; + } + + // Format the content + 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). + */ + private boolean isContinuationLine(String trimmedContent) { + if (trimmedContent.isEmpty()) return false; + char firstChar = trimmedContent.charAt(0); + // Lines starting with these are likely continuations + if (firstChar == '.' || firstChar == '+' || firstChar == '-' || + firstChar == '*' || firstChar == '/' || firstChar == '%' || + firstChar == '&' || firstChar == '|' || firstChar == '^' || + firstChar == '?' || firstChar == ':' || firstChar == ',') { + return true; + } + // Also check for && and || + if (trimmedContent.startsWith("&&") || trimmedContent.startsWith("||")) { + return true; + } + return false; + } + + /** + * 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) { + List preserveRegions = findPreserveRegions(content); + + if (preserveRegions.isEmpty()) { + return formatCodeSegment(content); + } + + StringBuilder result = new StringBuilder(); + int lastEnd = 0; + + for (int[] region : preserveRegions) { + if (region[0] > lastEnd) { + String codeSegment = content.substring(lastEnd, region[0]); + 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(' '); + } + } + } + + // 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]; + } + + if (lastEnd < content.length()) { + 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. + */ + private List findPreserveRegions(String content) { + List regions = new ArrayList<>(); + + int i = 0; + while (i < content.length()) { + char c = content.charAt(i); + + // String literal + if (c == '"') { + int end = findStringEnd(content, i, '"'); + regions.add(new int[]{i, end}); + i = end; + continue; + } + + // Char literal + if (c == '\'') { + int end = findStringEnd(content, i, '\''); + regions.add(new int[]{i, end}); + i = end; + continue; + } + + // Line comment + if (c == '/' && i + 1 < content.length() && content.charAt(i + 1) == '/') { + regions.add(new int[]{i, content.length()}); + break; + } + + // Block comment (could span multiple lines but we process line-by-line) + if (c == '/' && i + 1 < content.length() && content.charAt(i + 1) == '*') { + int end = content.indexOf("*/", i + 2); + if (end >= 0) { + regions.add(new int[]{i, end + 2}); + i = end + 2; + } else { + regions.add(new int[]{i, content.length()}); + break; + } + continue; + } + + i++; + } + + return regions; + } + + /** + * Find end of string/char literal. + */ + private int findStringEnd(String content, int start, char quote) { + int i = start + 1; + while (i < content.length()) { + char c = content.charAt(i); + if (c == '\\' && i + 1 < content.length()) { + i += 2; // Skip escape sequence + continue; + } + if (c == quote) { + return i + 1; + } + i++; + } + return content.length(); + } + + // ==================== TOKEN-BASED CODE SEGMENT FORMATTING ==================== + + /** + * Format a code segment (no strings/comments) using the token pipeline: + * tokenize → format → reconstruct. + */ + private String formatCodeSegment(String code) { + if (code.isEmpty()) return code; + + // Phase 1: Tokenize + List tokens = tokenize(code); + + // Phase 1.5: Merge split operators (e.g. = = → ==, > = → >=) + if (settings.normalizeWhitespace) { + tokens = mergeSplitOperators(tokens); + } + + // 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); + + // Phase 2: Format (apply spacing rules) + List formatted = formatTokens(tokens); + + // Phase 3: Reconstruct + return reconstruct(formatted); + } + + // ==================== 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; + } + + 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 ==================== + + /** + * 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 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; + + while (i < tokens.size()) { + Token t = tokens.get(i); + + 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; + } + } + + // 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; + } + } + + result.add(t); + i++; + } + + return result; + } + + /** + * 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 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; + } + + /** + * Skip past the tokens that were consumed by the merge. + * Returns the index of the first token AFTER the merged sequence. + */ + private int skipMergedTokens(List tokens, int startIdx, String merged) { + int charsConsumed = 0; + int i = startIdx; + + 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 i; + } + + // ==================== PHASE 2: TOKEN FORMATTER ==================== + + /** + * 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 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); + } + } + + 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; + } + + /** + * 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 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, label : uses settings) ---- + if (prev.type == TokenType.COLON) { + if (isTernaryColon(allTokens, currIdx - 1)) return " "; + return settings.spaceAfterColon ? " " : ""; + } + if (curr.type == TokenType.COLON) { + if (isTernaryColon(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 ""; + } + 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; + } + + 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 > ahead + int depth = 1; + 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 if (op.equals(">")) { + // Check if there's a matching < before + int depth = 1; + 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; + } + + /** + * Find the previous non-whitespace token before the given index. + */ + 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); + } + } + return null; + } + + // ==================== PHASE 3: RECONSTRUCTOR ==================== + + /** + * Reconstruct formatted code from a list of tokens. + */ + private String reconstruct(List tokens) { + StringBuilder sb = new StringBuilder(); + for (Token t : tokens) { + sb.append(t.value); + } + return sb.toString(); + } + + /** + * Trim trailing whitespace from a line. + */ + private String trimTrailing(String line) { + int end = line.length(); + while (end > 0 && (line.charAt(end - 1) == ' ' || line.charAt(end - 1) == '\t')) { + end--; + } + return line.substring(0, end); + } + + // ==================== STATIC UTILITIES ==================== + + /** + * Format code with default settings. + */ + public static String formatCode(String code) { + return new FormatHelper().format(code); + } + + /** + * 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 ==================== + + /** + * Wrap long lines according to settings. + * Call this after format() if wrapLongLines is enabled. + * + * @param text The text to wrap + * @param maxWidth Maximum line width (use settings.maxLineLength if 0) + * @return Text with wrapped lines + */ + public String wrapLines(String text, int maxWidth) { + if (text == null || text.isEmpty()) return text; + + int width = maxWidth > 0 ? maxWidth : settings.maxLineLength; + String[] lines = text.split("\n", -1); + StringBuilder result = new StringBuilder(); + + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + + if (getVisualLength(line) <= width) { + result.append(line); + } else { + // Determine if this is a comment line + String trimmed = line.trim(); + if (trimmed.startsWith("//")) { + result.append(wrapCommentLine(line, width)); + } else if (trimmed.startsWith("/*") || trimmed.startsWith("*")) { + result.append(wrapBlockCommentLine(line, width)); + } else { + result.append(wrapCodeLine(line, width)); + } + } + + if (i < lines.length - 1) { + result.append("\n"); + } + } + + return result.toString(); + } + + /** + * Get visual length of a line (tabs count as 4 spaces). + */ + private int getVisualLength(String line) { + int len = 0; + for (char c : line.toCharArray()) { + if (c == '\t') { + len += 4; + } else { + len++; + } + } + return len; + } + + /** + * Extract leading indentation from a line. + */ + private String extractIndent(String line) { + int i = 0; + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) { + i++; + } + return line.substring(0, i); + } + + /** + * Wrap a single-line comment (// style). + */ + private String wrapCommentLine(String line, int maxWidth) { + if (!settings.wrapComments) return line; + + String indent = extractIndent(line); + String content = line.substring(indent.length()); + + // Must start with // + if (!content.startsWith("//")) return line; + + String commentContent = content.substring(2).trim(); + String prefix = indent + "// "; + int prefixLen = getVisualLength(prefix); + int contentWidth = maxWidth - prefixLen; + + if (contentWidth <= 10) return line; // Too narrow to wrap + + StringBuilder result = new StringBuilder(); + result.append(indent).append("// "); + + String[] words = commentContent.split("\\s+"); + int lineLen = prefixLen; + + for (int i = 0; i < words.length; i++) { + String word = words[i]; + int wordLen = word.length(); + + if (lineLen + wordLen > maxWidth && lineLen > prefixLen) { + // Start new line + result.append("\n").append(prefix); + lineLen = prefixLen; + } + + if (lineLen > prefixLen) { + result.append(" "); + lineLen++; + } + + result.append(word); + lineLen += wordLen; + } + + return result.toString(); + } + + /** + * Wrap a block comment line (* style). + */ + private String wrapBlockCommentLine(String line, int maxWidth) { + if (!settings.wrapComments) return line; + + String indent = extractIndent(line); + String content = line.substring(indent.length()).trim(); + + // Determine prefix for wrapped lines + String prefix; + String textContent; + + if (content.startsWith("/**")) { + prefix = indent + " * "; + textContent = content.substring(3).trim(); + } else if (content.startsWith("/*")) { + prefix = indent + " * "; + textContent = content.substring(2).trim(); + } else if (content.startsWith("*")) { + prefix = indent + " * "; + textContent = content.substring(1).trim(); + } else { + return line; + } + + // Handle closing */ + boolean hasClose = textContent.endsWith("*/"); + if (hasClose) { + textContent = textContent.substring(0, textContent.length() - 2).trim(); + } + + int prefixLen = getVisualLength(prefix); + int contentWidth = maxWidth - prefixLen; + + if (contentWidth <= 10) return line; + + StringBuilder result = new StringBuilder(); + + // First line keeps original prefix + if (content.startsWith("/**")) { + result.append(indent).append("/** "); + } else if (content.startsWith("/*")) { + result.append(indent).append("/* "); + } else { + result.append(indent).append(" * "); + } + + String[] words = textContent.split("\\s+"); + int lineLen = prefixLen; + + for (int i = 0; i < words.length; i++) { + String word = words[i]; + int wordLen = word.length(); + + if (lineLen + wordLen > maxWidth && lineLen > prefixLen) { + result.append("\n").append(prefix); + lineLen = prefixLen; + } + + if (lineLen > prefixLen) { + result.append(" "); + lineLen++; + } + + result.append(word); + lineLen += wordLen; + } + + if (hasClose) { + result.append(" */"); + } + + return result.toString(); + } + + /** + * 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()); + + // --- 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) { + String wrapIndent = indent + spaces(settings.wrapIndentSpaces); + String fullLine = indent + content; + + if (getVisualLength(fullLine) <= maxWidth) { + return fullLine; + } + + List breakPoints = findBreakPoints(content); + + if (breakPoints.isEmpty()) { + return fullLine; + } + + StringBuilder result = new StringBuilder(); + result.append(indent); + + 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); + + if (currentLen + segmentLen > maxWidth && !isFirstLine) { + result.append("\n").append(wrapIndent); + currentLen = getVisualLength(wrapIndent); + isFirstLine = false; + + segment = trimLeading(segment); + } else if (currentLen + segmentLen > maxWidth && isFirstLine && lastBreak > 0) { + result.append("\n").append(wrapIndent); + currentLen = getVisualLength(wrapIndent); + isFirstLine = false; + } + + result.append(segment); + currentLen += getVisualLength(segment); + lastBreak = segmentEnd; + isFirstLine = false; + } + + if (lastBreak < content.length()) { + String remaining = content.substring(lastBreak); + int remLen = getVisualLength(remaining); + + if (currentLen + remLen > maxWidth && !isFirstLine) { + result.append("\n").append(wrapIndent); + remaining = trimLeading(remaining); + } + + result.append(remaining); + } + + return result.toString(); + } + + /** + * Trim leading whitespace (Java 8 compatible). + */ + private String trimLeading(String s) { + int start = 0; + while (start < s.length() && Character.isWhitespace(s.charAt(start))) { + start++; + } + return s.substring(start); + } + + /** + * A potential line break point. + */ + private static class BreakPoint { + int position; // Position in string (after this char) + @SuppressWarnings("unused") + int priority; // Lower = better place to break (for future sorting) + + BreakPoint(int pos, int prio) { + this.position = pos; + this.priority = prio; + } + } + + /** + * Find good positions to break a line. + */ + private List findBreakPoints(String content) { + List points = new ArrayList<>(); + + int parenDepth = 0; + int bracketDepth = 0; + int braceDepth = 0; + 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) : ' '; + + // Track string state + if ((c == '"' || c == '\'') && prev != '\\') { + if (!inString) { + inString = true; + stringChar = c; + } else if (c == stringChar) { + inString = false; + } + } + + if (inString) continue; + + // Track bracket depth + if (c == '(') parenDepth++; + else if (c == ')') parenDepth--; + else if (c == '[') bracketDepth++; + else if (c == ']') bracketDepth--; + else if (c == '{') braceDepth++; + else if (c == '}') braceDepth--; + + // Calculate total nesting depth (prefer breaking at lower depth) + int depth = parenDepth + bracketDepth + braceDepth; + + // Find break points + if (settings.wrapAfterComma && c == ',') { + // After comma is a good break point (better at lower depth) + points.add(new BreakPoint(i + 1, 1 + depth)); + } + + 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 != '=') { + 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)); + } + if (c == '|' && i + 1 < content.length() && content.charAt(i + 1) == '|') { + points.add(new BreakPoint(i + 2, 2 + depth)); + } + } + + if (settings.wrapBeforeDot && c == '.') { + // Before dot (for method chaining) + points.add(new BreakPoint(i, 2 + depth)); + } + + // After opening brace + if (c == '{' && i + 1 < content.length()) { + points.add(new BreakPoint(i + 1, 1)); + } + } + + // Sort by position + points.sort((a, b) -> Integer.compare(a.position, b.position)); + + return points; + } + + /** + * Create a string of n spaces. + */ + private String spaces(int n) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + sb.append(' '); + } + return sb.toString(); + } + + /** + * Format and wrap code in one step. + */ + public String formatAndWrap(String text, int maxWidth) { + String formatted = format(text); + if (settings.wrapLongLines) { + return wrapLines(formatted, maxWidth); + } + return formatted; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/GoToLineDialog.java b/src/main/java/noppes/npcs/client/gui/util/script/GoToLineDialog.java new file mode 100644 index 000000000..e3e023dee --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/GoToLineDialog.java @@ -0,0 +1,628 @@ +package noppes.npcs.client.gui.util.script; + +import net.minecraft.client.Minecraft; +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.key.OverlayKeyPresetViewer; +import org.lwjgl.input.Keyboard; +import org.lwjgl.opengl.GL11; + +/** + * Go To Line:Column dialog for the script editor. + * Provides IntelliJ-like "Go to Line" functionality (Ctrl+G). + *

+ * Input format: "line" or "line:column" + * Example: "42" goes to line 42, column 1 + * Example: "42:15" goes to line 42, column 15 + */ +public class GoToLineDialog { + + // ==================== TEXTURE ==================== + public static final ResourceLocation TEXTURE = OverlayKeyPresetViewer.TEXTURE; + + // ==================== DIMENSIONS ==================== + private int x, y, width; + private int dialogWidth = 200; + private int dialogHeight = 51; + private int textFieldWidth = 180; + private int textFieldHeight = 16; + private int padding = 8; + + // ==================== STATE ==================== + private boolean visible = false; + private boolean focused = true; + + // ==================== TEXT FIELD ==================== + private String inputText = ""; + private int cursor = 0; + private int selectionStart = 0; + private int selectionEnd = 0; + private int scrollOffset = 0; + + // ==================== CURSOR BLINK ==================== + private int cursorCounter = 0; + private long lastInputTime = 0; + + // ==================== CALLBACK ==================== + private GoToLineCallback callback; + + private final FontRenderer font = Minecraft.getMinecraft().fontRenderer; + + /** + * Callback interface for go-to-line operations + */ + public interface GoToLineCallback { + /** + * Get total line count + */ + int getLineCount(); + + /** + * Get the column count for a specific line (0-indexed) + */ + int getColumnCount(int lineIndex); + + /** + * Navigate to specific line and column (both 1-indexed for user display) + */ + void goToLineColumn(int line, int column); + + /** + * Called when dialog closes - should restore focus to editor + */ + void onDialogClose(); + + void unfocusMainEditor(); + + void focusMainEditor(); + } + + public void setCallback(GoToLineCallback callback) { + this.callback = callback; + } + + /** + * Initialize/update position for the dialog + */ + public void initGui(int guiX, int guiY, int guiWidth) { + this.width = guiWidth; + // Center the dialog horizontally + this.x = guiX + (guiWidth - dialogWidth) / 2; + // Position near top of editor + this.y = guiY + 40; + } + + // ==================== VISIBILITY ==================== + + public boolean isVisible() { + return visible; + } + + public void show() { + visible = true; + focused = true; + inputText = ""; + cursor = 0; + selectionStart = 0; + selectionEnd = 0; + scrollOffset = 0; + markActivity(); + if (callback != null) callback.unfocusMainEditor(); + } + + public void close() { + visible = false; + focused = false; + if (callback != null) { + callback.onDialogClose(); + callback.focusMainEditor(); + } + } + + public void toggle() { + if (visible && focused) { + close(); + } else { + show(); + } + } + + public boolean hasFocus() { + return visible && focused; + } + + public void unfocus() { + focused = false; + } + // ==================== RENDERING ==================== + + public void draw(int mouseX, int mouseY) { + if (!visible) + return; + + ParseResult result = null; + if (!inputText.isEmpty()) + result = parseInput(inputText); + + GL11.glPushMatrix(); + 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); + + // Draw dialog background with shadow + drawDialogBackground(result != null && !result.valid); + + // Draw title + String title = "Go to Line"; + font.drawString(title, x + padding + 1, y + padding + 4, 0xFFe0e0e0); + + // Draw hint text showing valid range + int lineCount = callback != null ? callback.getLineCount() : 0; + String hint = "[" + lineCount + " lines]"; + int hintWidth = font.getStringWidth(hint); + dialogWidth = 200; + font.drawString(hint, x + dialogWidth - padding - hintWidth, y + padding + 4, 0xFF888888); + + + // Draw text field + int fieldX = x + padding + 0; + int fieldY = y + padding + 14 + 5; + textFieldWidth = dialogWidth - padding * 2; + drawTextField(fieldX, fieldY, textFieldWidth, textFieldHeight, inputText, cursor, + selectionStart, selectionEnd, scrollOffset, focused); + + if (inputText.isEmpty()) + font.drawString("[Line][:Column]", x + padding + 6, y + padding + 23, 0xFF888888); + + // Draw error/validation hint if input is invalid + if (result != null && !result.valid) + font.drawString(result.error, x + padding + 2, y + dialogHeight - 3, 0xFFff6666); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + } + + private void drawDialogBackground(boolean resultInvalid) { + int dialogHeight = this.dialogHeight; + if (resultInvalid) + dialogHeight += 5; // Pad by 6 + + int y = this.y + 5; + // Draw shadow + Gui.drawRect(x + 2, y + 2, x + dialogWidth + 2, y + dialogHeight + 2, 0x80000000); + + // Draw main background + Gui.drawRect(x, y, x + dialogWidth, y + dialogHeight, 0xFF2d2d30); + + // Draw border + Gui.drawRect(x, y, x + dialogWidth, y + 1, 0xFF3c3c3c); + Gui.drawRect(x, y + dialogHeight - 1, x + dialogWidth, y + dialogHeight, 0xFF3c3c3c); + Gui.drawRect(x, y, x + 1, y + dialogHeight, 0xFF3c3c3c); + Gui.drawRect(x + dialogWidth - 1, y, x + dialogWidth, y + dialogHeight, 0xFF3c3c3c); + } + + private void drawTextField(int fx, int fy, int fw, int fh, String text, int cursor, + int selStart, int selEnd, int scrollOff, boolean isFocused) { + // Draw text field background + Gui.drawRect(fx, fy, fx + fw, fy + fh, 0xFF1e1e1e); + Gui.drawRect(fx, fy, fx + fw, fy + 1, isFocused ? 0xFF007acc : 0xFF3c3c3c); + Gui.drawRect(fx, fy + fh - 1, fx + fw, fy + fh, isFocused ? 0xFF007acc : 0xFF3c3c3c); + Gui.drawRect(fx, fy, fx + 1, fy + fh, isFocused ? 0xFF007acc : 0xFF3c3c3c); + Gui.drawRect(fx + fw - 1, fy, fx + fw, fy + fh, isFocused ? 0xFF007acc : 0xFF3c3c3c); + + // Calculate visible area + int textX = fx + 4; + int textY = fy + (fh - 8) / 2; + int visibleWidth = fw - 8; + + // Apply scroll offset + String visibleText = text; + int adjustedCursor = cursor; + int adjustedSelStart = selStart; + int adjustedSelEnd = selEnd; + + if (scrollOff > 0 && scrollOff < text.length()) { + visibleText = text.substring(scrollOff); + adjustedCursor = cursor - scrollOff; + adjustedSelStart = Math.max(0, selStart - scrollOff); + adjustedSelEnd = Math.max(0, selEnd - scrollOff); + } + + // Draw selection highlight + if (adjustedSelStart != adjustedSelEnd) { + int minSel = Math.min(adjustedSelStart, adjustedSelEnd); + int maxSel = Math.max(adjustedSelStart, adjustedSelEnd); + String beforeSel = visibleText.substring(0, Math.min(minSel, visibleText.length())); + String inSel = visibleText.substring(Math.min(minSel, visibleText.length()), + Math.min(maxSel, visibleText.length())); + int selX = textX + font.getStringWidth(beforeSel); + int selW = font.getStringWidth(inSel); + Gui.drawRect(selX, textY - 1, selX + selW, textY + 9, 0xFF264f78); + } + + // Draw text + font.drawString(visibleText, textX, textY, 0xFFe0e0e0); + + // Draw cursor + if (isFocused && shouldShowCursor()) { + String beforeCursor = adjustedCursor > 0 && adjustedCursor <= visibleText.length() + ? visibleText.substring(0, adjustedCursor) : ""; + int cursorX = textX + font.getStringWidth(beforeCursor); + Gui.drawRect(cursorX, textY - 1, cursorX + 1, textY + 9, 0xFFe0e0e0); + } + } + + // ==================== INPUT HANDLING ==================== + + public boolean mouseClicked(int mouseX, int mouseY, int button) { + if (!visible) + return false; + + // Check if click is inside dialog + if (mouseX >= x && mouseX < x + dialogWidth && mouseY >= y && mouseY < y + dialogHeight) { + // Check if click is in text field + int fieldX = x + padding; + int fieldY = y + padding + 14; + if (mouseX >= fieldX && mouseX < fieldX + textFieldWidth && + mouseY >= fieldY && mouseY < fieldY + textFieldHeight) { + focused = true; + if (callback != null) callback.unfocusMainEditor(); + // Position cursor based on click + int clickX = mouseX - fieldX - 4; + String visibleText = scrollOffset > 0 && scrollOffset < inputText.length() + ? inputText.substring(scrollOffset) : inputText; + int newCursor = getCharIndexAtX(visibleText, clickX) + scrollOffset; + cursor = Math.max(0, Math.min(newCursor, inputText.length())); + selectionStart = cursor; + selectionEnd = cursor; + markActivity(); + } + return true; + } + + // Click outside dialog - close it + close(); + return false; + } + + private int getCharIndexAtX(String text, int targetX) { + int x = 0; + for (int i = 0; i < text.length(); i++) { + int charWidth = font.getCharWidth(text.charAt(i)); + if (x + charWidth / 2 > targetX) { + return i; + } + x += charWidth; + } + return text.length(); + } + + public boolean keyTyped(char c, int keyCode) { + // Escape - close dialog + if (keyCode == Keyboard.KEY_ESCAPE && visible) { + close(); + return true; + } + + if (!visible || !focused) + return false; + + boolean ctrl = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); + boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + // Enter - execute go to line + if (keyCode == Keyboard.KEY_RETURN || keyCode == Keyboard.KEY_NUMPADENTER) { + executeGoToLine(); + return true; + } + + // Select all (Ctrl+A) + if (ctrl && keyCode == Keyboard.KEY_A) { + selectionStart = 0; + selectionEnd = inputText.length(); + cursor = inputText.length(); + markActivity(); + return true; + } + + // Copy (Ctrl+C) + if (ctrl && keyCode == Keyboard.KEY_C) { + if (selectionStart != selectionEnd) { + int minSel = Math.min(selectionStart, selectionEnd); + int maxSel = Math.max(selectionStart, selectionEnd); + noppes.npcs.NoppesStringUtils.setClipboardContents(inputText.substring(minSel, maxSel)); + } + return true; + } + + // Cut (Ctrl+X) + if (ctrl && keyCode == Keyboard.KEY_X) { + if (selectionStart != selectionEnd) { + int minSel = Math.min(selectionStart, selectionEnd); + int maxSel = Math.max(selectionStart, selectionEnd); + noppes.npcs.NoppesStringUtils.setClipboardContents(inputText.substring(minSel, maxSel)); + inputText = inputText.substring(0, minSel) + inputText.substring(maxSel); + cursor = minSel; + selectionStart = cursor; + selectionEnd = cursor; + updateScrollOffset(); + markActivity(); + } + return true; + } + + // Paste (Ctrl+V) + if (ctrl && keyCode == Keyboard.KEY_V) { + String clipboard = noppes.npcs.NoppesStringUtils.getClipboardContents(); + if (clipboard != null) { + // Only allow digits and colon + StringBuilder filtered = new StringBuilder(); + for (char ch : clipboard.toCharArray()) { + if (Character.isDigit(ch) || ch == ':') { + filtered.append(ch); + } + } + insertText(filtered.toString()); + } + return true; + } + + // Backspace + if (keyCode == Keyboard.KEY_BACK) { + if (selectionStart != selectionEnd) { + deleteSelection(); + } else if (cursor > 0) { + inputText = inputText.substring(0, cursor - 1) + inputText.substring(cursor); + cursor--; + selectionStart = cursor; + selectionEnd = cursor; + updateScrollOffset(); + } + markActivity(); + return true; + } + + // Delete + if (keyCode == Keyboard.KEY_DELETE) { + if (selectionStart != selectionEnd) { + deleteSelection(); + } else if (cursor < inputText.length()) { + inputText = inputText.substring(0, cursor) + inputText.substring(cursor + 1); + } + markActivity(); + return true; + } + + // Left arrow + if (keyCode == Keyboard.KEY_LEFT) { + if (shift) { + if (cursor > 0) { + cursor--; + selectionEnd = cursor; + } + } else { + if (selectionStart != selectionEnd) { + cursor = Math.min(selectionStart, selectionEnd); + } else if (cursor > 0) { + cursor--; + } + selectionStart = cursor; + selectionEnd = cursor; + } + updateScrollOffset(); + markActivity(); + return true; + } + + // Right arrow + if (keyCode == Keyboard.KEY_RIGHT) { + if (shift) { + if (cursor < inputText.length()) { + cursor++; + selectionEnd = cursor; + } + } else { + if (selectionStart != selectionEnd) { + cursor = Math.max(selectionStart, selectionEnd); + } else if (cursor < inputText.length()) { + cursor++; + } + selectionStart = cursor; + selectionEnd = cursor; + } + updateScrollOffset(); + markActivity(); + return true; + } + + // Home + if (keyCode == Keyboard.KEY_HOME) { + if (shift) { + selectionEnd = 0; + cursor = 0; + } else { + cursor = 0; + selectionStart = cursor; + selectionEnd = cursor; + } + updateScrollOffset(); + markActivity(); + return true; + } + + // End + if (keyCode == Keyboard.KEY_END) { + if (shift) { + selectionEnd = inputText.length(); + cursor = inputText.length(); + } else { + cursor = inputText.length(); + selectionStart = cursor; + selectionEnd = cursor; + } + updateScrollOffset(); + markActivity(); + return true; + } + + // Type character - only allow digits and colon + if (ChatAllowedCharacters.isAllowedCharacter(c)) { + if (Character.isDigit(c) || c == ':') { + insertText("" + c); + markActivity(); + return true; + } + } + + return true; // Consume all other keys when dialog is focused + } + + private void insertText(String text) { + if (selectionStart != selectionEnd) { + deleteSelection(); + } + inputText = inputText.substring(0, cursor) + text + inputText.substring(cursor); + cursor += text.length(); + selectionStart = cursor; + selectionEnd = cursor; + updateScrollOffset(); + } + + private void deleteSelection() { + int minSel = Math.min(selectionStart, selectionEnd); + int maxSel = Math.max(selectionStart, selectionEnd); + inputText = inputText.substring(0, minSel) + inputText.substring(maxSel); + cursor = minSel; + selectionStart = cursor; + selectionEnd = cursor; + updateScrollOffset(); + } + + private void updateScrollOffset() { + int fieldWidth = textFieldWidth - 8; + String beforeCursor = cursor > 0 ? inputText.substring(0, cursor) : ""; + int cursorX = font.getStringWidth(beforeCursor); + + // Scroll to keep cursor visible + if (cursorX - scrollOffset * 6 > fieldWidth) { + scrollOffset = Math.max(0, cursor - fieldWidth / 6); + } else if (cursor < scrollOffset) { + scrollOffset = cursor; + } + } + + private void executeGoToLine() { + ParseResult result = parseInput(inputText); + if (result.valid && callback != null) { + callback.goToLineColumn(result.line, result.column); + close(); + } + } + + // ==================== PARSING ==================== + + private static class ParseResult { + boolean valid; + int line; + int column; + String error; + + static ParseResult invalid(String error) { + ParseResult r = new ParseResult(); + r.valid = false; + r.error = error; + return r; + } + + static ParseResult of(int line, int column) { + ParseResult r = new ParseResult(); + r.valid = true; + r.line = line; + r.column = column; + return r; + } + } + + private ParseResult parseInput(String input) { + if (input == null || input.trim().isEmpty()) { + return ParseResult.invalid("Enter line number"); + } + + input = input.trim(); + int line, column = 1; + + int colonIndex = input.indexOf(':'); + if (colonIndex >= 0) { + // Format: line:column + String linePart = input.substring(0, colonIndex); + String colPart = input.substring(colonIndex + 1); + + if (linePart.isEmpty()) { + return ParseResult.invalid("Invalid line number"); + } + + try { + line = Integer.parseInt(linePart); + } catch (NumberFormatException e) { + return ParseResult.invalid("Invalid line number"); + } + + if (!colPart.isEmpty()) { + try { + column = Integer.parseInt(colPart); + } catch (NumberFormatException e) { + return ParseResult.invalid("Invalid column number"); + } + } + } else { + // Format: just line + try { + line = Integer.parseInt(input); + } catch (NumberFormatException e) { + return ParseResult.invalid("Invalid line number"); + } + } + + // Validate ranges + int lineCount = callback != null ? callback.getLineCount() : 0; + if (line < 1) { + return ParseResult.invalid("Line must be >= 1"); + } + if (line > lineCount) { + return ParseResult.invalid("Line must be <= " + lineCount); + } + if (column < 1) { + return ParseResult.invalid("Column must be >= 1"); + } + // Column validation happens at callback - depends on actual line length + + return ParseResult.of(line, column); + } + + // ==================== CURSOR BLINK ==================== + + public void updateCursor() { + cursorCounter++; + } + + private void markActivity() { + lastInputTime = System.currentTimeMillis(); + } + + private boolean shouldShowCursor() { + // Keep cursor visible for 500ms after any input + if (System.currentTimeMillis() - lastInputTime < 500) { + return true; + } + // Then blink every 500ms + return (cursorCounter / 10) % 2 == 0; + } + + // ==================== GETTERS ==================== + + public int getTotalHeight() { + return visible ? dialogHeight + 10 : 0; + } +} 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 new file mode 100644 index 000000000..12a5567ad --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/IndentHelper.java @@ -0,0 +1,376 @@ +package noppes.npcs.client.gui.util.script; + +import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; + +import java.util.Arrays; +import java.util.List; + +/** + * Helper class for indentation-related operations. + */ +public class IndentHelper { + + public static final int TAB_SIZE = 4; + + /** + * Get leading whitespace count of a line + */ + public static int getLineIndent(String lineText) { + int leading = 0; + for (int i = 0; i < lineText.length(); i++) { + char c = lineText.charAt(i); + if (c == ' ' || c == '\t') leading++; + else break; + } + return leading; + } + + /** + * Extract leading whitespace as string + */ + public static String getIndentString(String lineText) { + int indent = getLineIndent(lineText); + return lineText.substring(0, indent); + } + + /** + * Create a string of n spaces + */ + public static String spaces(int n) { + if (n <= 0) return ""; + char[] arr = new char[n]; + Arrays.fill(arr, ' '); + return new String(arr); + } + + /** + * Calculate expected indent for a line based on context + */ + public static int getExpectedIndent(LineData currentLine, List allLines) { + if (currentLine == null || allLines == null) return 0; + + int idx = allLines.indexOf(currentLine); + if (idx <= 0) return 0; + + // Find previous non-empty line + LineData prevLine = null; + for (int i = idx - 1; i >= 0; i--) { + LineData line = allLines.get(i); + if (line.text.trim().length() > 0) { + prevLine = line; + break; + } + } + + if (prevLine == null) return 0; + + int prevIndent = getLineIndent(prevLine.text); + String prevTrimmed = prevLine.text.trim(); + String currTrimmed = currentLine.text.trim(); + + // If current line starts with }, expected is one level back + if (currTrimmed.startsWith("}")) { + return Math.max(0, prevIndent - TAB_SIZE); + } + + // If previous line ends with {, expected is one level forward + if (prevTrimmed.endsWith("{")) { + return prevIndent + TAB_SIZE; + } + + return prevIndent; + } + + /** + * Calculate auto-indent for Enter key + */ + public static String getAutoIndentForEnter(String lineText, int cursorInLine) { + int leading = 0; + while (leading < lineText.length() && + (lineText.charAt(leading) == ' ' || lineText.charAt(leading) == '\t')) { + leading++; + } + + String baseIndent = lineText.substring(0, leading); + int relativeCursor = Math.max(0, Math.min(cursorInLine, lineText.length())); + String beforeCursor = lineText.substring(0, relativeCursor); + + // Find last non-whitespace before cursor + int lastNonWs = -1; + for (int i = beforeCursor.length() - 1; i >= 0; i--) { + if (!Character.isWhitespace(beforeCursor.charAt(i))) { + lastNonWs = i; + break; + } + } + + // Add extra indent if last char is { + // Only add extra indent if cursor is actually after the opening brace (not just in trailing whitespace) + // Check that the last non-whitespace is at or after the line's indent position + boolean opensBlock = lastNonWs >= 0 && lastNonWs >= leading && beforeCursor.charAt(lastNonWs) == '{'; + if (opensBlock) { + return baseIndent + spaces(TAB_SIZE); + } + + return baseIndent; + } + + /** + * Calculate target indent for Tab key + */ + public static int calculateTabTargetIndent(int currentIndent, int cursorColumn, boolean atTextStart) { + if (atTextStart) { + // At text start, move to next tab stop + return ((currentIndent / TAB_SIZE) + 1) * TAB_SIZE; + } else { + // Inside indent, snap to nearest tab stop + int remainder = currentIndent % TAB_SIZE; + if (remainder == 0) { + return currentIndent + TAB_SIZE; + } else { + int down = currentIndent - remainder; + int up = currentIndent + (TAB_SIZE - remainder); + int distDown = remainder; + int distUp = TAB_SIZE - remainder; + if (distUp <= distDown) return up; + else return down; + } + } + } + + /** + * Calculate target indent for Shift+Tab + */ + public static int calculateShiftTabTargetIndent(int currentIndent) { + return Math.max(0, ((currentIndent - 1) / TAB_SIZE) * TAB_SIZE); + } + + /** + * Format entire text with proper indentation and operator spacing + */ + public static FormatResult formatText(String text, int cursorPosition) { + return formatText(text, cursorPosition, 0); + } + + /** + * Format entire text with proper indentation, operator spacing, and optional line wrapping + * + * @param text The text to format + * @param cursorPosition Current cursor position + * @param viewportWidth Viewport width for line wrapping (0 = no wrapping) + */ + public static FormatResult formatText(String text, int cursorPosition, int viewportWidth) { + // First pass: fix indentation + String indented = formatIndentation(text, cursorPosition); + + // Second pass: apply operator spacing and whitespace normalization + FormatHelper helper = new FormatHelper(); + FormatHelper.FormatSettings settings = helper.getSettings(); + + // Enable wrapping if viewport width is provided + if (viewportWidth > 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)); + } + + String formatted = helper.format(indented); + + // Apply wrapping if enabled + if (viewportWidth > 0 && settings.wrapLongLines) { + formatted = helper.wrapLines(formatted, settings.maxLineLength); + } + + // Recalculate cursor position (try to maintain relative position) + int newCursorPos = Math.min(cursorPosition, formatted.length()); + + // Try to find cursor on same line with same content context + String[] origLines = text.split("\n", -1); + String[] newLines = formatted.split("\n", -1); + + int lineStartPos = 0; + int cursorLine = -1; + int cursorColInLine = 0; + + for (int li = 0; li < origLines.length; li++) { + int lineEndPos = lineStartPos + origLines[li].length(); + if (cursorPosition >= lineStartPos && cursorPosition <= lineEndPos) { + cursorLine = li; + cursorColInLine = cursorPosition - lineStartPos; + break; + } + lineStartPos = lineEndPos + 1; + } + + if (cursorLine >= 0 && cursorLine < newLines.length) { + int newLineStart = 0; + for (int li = 0; li < cursorLine; li++) { + newLineStart += newLines[li].length() + 1; + } + // Clamp cursor to new line length + newCursorPos = newLineStart + Math.min(cursorColInLine, newLines[cursorLine].length()); + } + + return new FormatResult(formatted, newCursorPos); + } + + /** + * Format indentation only (first pass) + */ + private static String formatIndentation(String text, int cursorPosition) { + String[] linesArr = text.split("\n", -1); + StringBuilder out = new StringBuilder(text.length() + 32); + + boolean inString = false; + boolean escape = false; + boolean inBlockComment = false; + int depth = 0; + + for (int li = 0; li < linesArr.length; li++) { + String line = linesArr[li]; + String trimmedLeading = line.replaceAll("^[ \\t]+", ""); + int originalIndent = getLineIndent(line); + + int opens = 0, closes = 0; + boolean startsWithClose = false; + + // Parse line for braces + for (int idx = 0; idx < line.length(); idx++) { + char c = line.charAt(idx); + char next = idx + 1 < line.length() ? line.charAt(idx + 1) : 0; + + if (inString) { + if (escape) { + escape = false; + } else if (c == '\\') { + escape = true; + } else if (c == '"') { + inString = false; + } + continue; + } + + if (inBlockComment) { + if (c == '*' && next == '/') { + inBlockComment = false; + idx++; + } + continue; + } + + if (c == '/' && next == '/') break; + if (c == '/' && next == '*') { + inBlockComment = true; + idx++; + continue; + } + if (c == '"') { + inString = true; + escape = false; + continue; + } + + if (c == '{') { + opens++; + } else if (c == '}') { + closes++; + if (!startsWithClose && line.substring(0, idx).trim().isEmpty()) { + startsWithClose = true; + } + } + } + + int indentLevel = depth; + if (startsWithClose) indentLevel = Math.max(0, indentLevel - 1); + int targetIndent = indentLevel * TAB_SIZE; + + // Check if this is a continuation line: + // 1. Line starts with operator/dot (explicit continuation) + // 2. Previous line ends with operator (implicit continuation - this line continues it) + // If so, preserve extra indentation beyond the base level + boolean isContinuation = isContinuationLine(trimmedLeading); + if (!isContinuation && li > 0) { + // Check if previous line ends with an operator (indicating this line continues it) + String prevLine = linesArr[li - 1].trim(); + isContinuation = lineEndsWithContinuationOperator(prevLine); + } + + if (isContinuation && originalIndent > targetIndent) { + // This is a continuation line - preserve its extra indent + out.append(spaces(originalIndent)).append(trimmedLeading); + } else { + out.append(spaces(targetIndent)).append(trimmedLeading); + } + if (li < linesArr.length - 1) out.append('\n'); + + depth = Math.max(0, depth + opens - closes); + } + + return out.toString(); + } + + /** + * Check if a line appears to be a continuation of a previous line + * (i.e., starts with an operator, dot, or other continuation character) + */ + private static boolean isContinuationLine(String trimmedContent) { + if (trimmedContent.isEmpty()) return false; + char firstChar = trimmedContent.charAt(0); + // Lines starting with these are likely continuations + if (firstChar == '.' || firstChar == '+' || firstChar == '-' || + firstChar == '*' || firstChar == '/' || firstChar == '%' || + firstChar == '&' || firstChar == '|' || firstChar == '^' || + firstChar == '?' || firstChar == ':' || firstChar == ',') { + return true; + } + // Also check for && and || + if (trimmedContent.startsWith("&&") || trimmedContent.startsWith("||")) { + return true; + } + return false; + } + + /** + * Check if a line ends with an operator that indicates the next line is a continuation + */ + private static boolean lineEndsWithContinuationOperator(String trimmedLine) { + if (trimmedLine.isEmpty()) return false; + // Remove trailing comments + int commentIdx = trimmedLine.indexOf("//"); + if (commentIdx >= 0) { + trimmedLine = trimmedLine.substring(0, commentIdx).trim(); + } + if (trimmedLine.isEmpty()) return false; + + // Check if ends with operator + char lastChar = trimmedLine.charAt(trimmedLine.length() - 1); + if (lastChar == '+' || lastChar == '-' || lastChar == '*' || + lastChar == '/' || lastChar == '%' || lastChar == '=' || + lastChar == '&' || lastChar == '|' || lastChar == '^' || + lastChar == '?' || lastChar == ':' || lastChar == ',' || + lastChar == '(' || lastChar == '[') { + // But not if it's ; or } which end statements + return true; + } + // Check for && and || + if (trimmedLine.endsWith("&&") || trimmedLine.endsWith("||")) { + return true; + } + return false; + } + + /** + * Result of text formatting + */ + public static class FormatResult { + public final String text; + public final int cursorPosition; + + public FormatResult(String text, int cursorPosition) { + this.text = text; + this.cursorPosition = cursorPosition; + } + } +} 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 new file mode 100644 index 000000000..b54b1cf1d --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/JavaTextContainer.java @@ -0,0 +1,1317 @@ +package noppes.npcs.client.gui.util.script; + +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.TextContainer; + +import java.util.ArrayList; +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( + "\\b(public|protected|private|static|final|abstract|synchronized|native|default)\\b"); + public static final Pattern KEYWORD = 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|new|typeof|instanceof|import)\\b"); + + public static final Pattern CLASS_DECL = Pattern.compile("\\b(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)"); + + public static final Pattern NEW_TYPE = Pattern.compile("\\bnew\\s+([A-Za-z_][a-zA-Z0-9_]*)"); + ; + + public static final Pattern METHOD_DECL = Pattern.compile("\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type + "([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name + ); + public static final Pattern METHOD_CALL = Pattern.compile("([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\("); + + // Class-level global fields + public static final Pattern GLOBAL_FIELD_DECL = Pattern.compile( + "\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)"); + + // Local fields inside methods (simplified) + public static final Pattern LOCAL_FIELD_DECL = Pattern.compile( + "\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)"); + + public static final Pattern STRING = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1"); + public static final Pattern COMMENT = Pattern.compile("/\\*[\\s\\S]*?(?:\\*/|$)|//.*|#.*"); + public static final Pattern NUMBER = 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"); + + // Import statement: import [static] package.path.ClassName [.*]; (semicolon optional for live typing) + // Allows optional whitespace (including newlines) around the dots so wrapped imports match. + // Match imports while allowing optional whitespace/newlines around dots. + public static final Pattern IMPORT = 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*(?:;|$)"); + + // ClassPathFinder for resolving imports and determining class types + private final ClassPathFinder classPathFinder = new ClassPathFinder(); + + public List lines = new ArrayList<>(); + public List methodBlocks = new ArrayList<>(); + + public JavaTextContainer(String text) { + super(text); + } + + // Map an offset into the normalized path (tokens joined with '.') back to + // an absolute index in the original substring `orig` (absolute positions start at pathStart). + // The normalization removes whitespace/newlines around dots; this function + // advances a normalized counter when it encounters identifier chars or dots + // and returns the corresponding original index (absolute). + private int mapNormalizedOffsetToOriginal(String orig, int normalizedOffset, int pathStart) { + if (orig == null || orig.isEmpty()) return pathStart; + int norm = 0; + for (int i = 0; i < orig.length(); i++) { + char c = orig.charAt(i); + if (Character.isLetterOrDigit(c) || c == '_' || c == '.') { + norm++; + } + if (norm >= normalizedOffset) { + return pathStart + i; + } + } + return pathStart + orig.length(); + } + + public void init(String text, int width, int height) { + this.text = text == null ? "" : text.replaceAll("\\r?\\n|\\r", "\n"); + lines.clear(); + String[] split = text.split("\n", -1); + + int totalChars = 0; + for (String l : split) { + StringBuilder line = new StringBuilder(); + // Break the source line `l` into layout-friendly segments using `regexWord`. + // `regexWord` finds word tokens (letters/numbers/underscore/hyphen), newlines + // or the end-of-line. The loop takes substrings from the previous match + // index `i` up to the current `m.start()` so each `word` contains the + // next token plus any following delimiters (spaces, punctuation). + // This lets us measure and wrap at token boundaries rather than mid-word. + Matcher m = regexWord.matcher(l); + int i = 0; + while (m.find()) { + String word = l.substring(i, m.start()); + if (ClientProxy.Font.width(line + word) > width - 10) { + // Note: `end` is an exclusive offset into the full text (start..end). + // For wrapped lines we record the current `totalChars` as the start + // and compute the exclusive end as `start + line.length()`. + lines.add(new LineData(line.toString(), totalChars, totalChars += line.length())); + line = new StringBuilder(); + } + line.append(word); + i = m.start(); + } + lines.add(new LineData(line.toString(), totalChars, totalChars += line.length() + 1)); + } + linesCount = lines.size(); + totalHeight = linesCount * lineHeight; + // Number of fully-visible lines that fit in the given viewport height. + // Use floor division and ensure at least 1 line is visible. + // Don't forget -1, fixes enter auto-scrolling properly + visibleLines = Math.max(height / lineHeight - 1, 1); + } + + private List globalFields = new ArrayList<>(); + private List localFields = new ArrayList<>(); + private java.util.Map importedClasses = new java.util.HashMap<>(); // simpleName -> fullName + private java.util.Set importedPackages = new java.util.HashSet<>(); // wildcard imports + private java.util.Set unresolvedClasses = new java.util.HashSet<>(); // classes that failed to resolve + private java.util.List importEntries = new java.util.ArrayList<>(); + + private static class ImportEntry { + public final String fullPath; // normalized path (no trailing . or *) + public final String matchText; // full matched import text + public final int pathStart; // start of the path group + public final int pathEnd; // end of the path group + public final int importKwStart; // start of the 'import' keyword + public final int importKwEnd; // end of the 'import' keyword + public final int starPos; // absolute pos of '*' in matchText, or -1 + public final boolean isWildcard; + // Cached resolve result (may be null for wildcard imports or if not resolved yet) + public ClassPathFinder.ResolveResult resolveResult; + + public ImportEntry(String fullPath, String matchText, int pathStart, int pathEnd, int importKwStart, int importKwEnd, int starPos, boolean isWildcard) { + this.fullPath = fullPath; + this.matchText = matchText; + this.pathStart = pathStart; + this.pathEnd = pathEnd; + this.importKwStart = importKwStart; + this.importKwEnd = importKwEnd; + this.starPos = starPos; + this.isWildcard = isWildcard; + } + } + + private void collectImports() { + importedClasses.clear(); + importedPackages.clear(); + importEntries.clear(); + unresolvedClasses.clear(); + classPathFinder.clearCache(); + + List excluded = MethodBlock.getExcludedRanges(text); + Matcher m = IMPORT.matcher(text); + while (m.find()) { + if (isInExcludedRange(m.start(), excluded)) + continue; + String fullPath = m.group(1).trim(); + String matchText = m.group(0); + int pathStart = m.start(1); + int pathEnd = m.end(1); + int importKwStart = m.start(); + int importKwEnd = Math.min(importKwStart + 6, text.length()); + + boolean isWildcard = matchText.contains("*"); + int starIndex = matchText.indexOf('*'); + int absStar = starIndex != -1 ? m.start() + starIndex : -1; + + // Record entry for finalization later + importEntries.add(new ImportEntry(fullPath, matchText, pathStart, pathEnd, importKwStart, importKwEnd, absStar, isWildcard)); + + // For wildcard imports we register the package for resolution; final marking deferred + if (isWildcard) { + importedPackages.add(fullPath); + } else { + // Resolve the import to get the proper class name (so simple-name lookups can work now) + ClassPathFinder.ResolveResult result = classPathFinder.resolve(fullPath); + + // Extract simple name (last segment) + int lastDot = fullPath.lastIndexOf('.'); + String simpleName = lastDot >= 0 ? fullPath.substring(lastDot + 1) : fullPath; + + if (!simpleName.isEmpty()) { + if (result.found && result.classInfo != null) { + // Store with resolved name (has $ for inner classes) + importedClasses.put(simpleName, result.classInfo.resolvedName); + } else { + // Store original path for unresolved imports + importedClasses.put(simpleName, fullPath); + // Track this as an unresolved class + unresolvedClasses.add(simpleName); + } + } + // Cache the full ResolveResult on the ImportEntry for reuse in finalizeImports + ImportEntry last = importEntries.get(importEntries.size() - 1); + last.resolveResult = result; + } + } + } + + /** + * Parse and highlight generic type parameters using ClassPathFinder. + * Handles arbitrarily nested generics like "Map>>". + */ + private void highlightGenericTypes(String genericContent, int contentStart, List marks, List excluded) { + if (genericContent == null || genericContent.isEmpty()) return; + + List occurrences = classPathFinder.parseGenericTypes(genericContent, importedClasses, importedPackages); + + for (ClassPathFinder.TypeOccurrence occ : occurrences) { + int absStart = contentStart + occ.startOffset; + int absEnd = contentStart + occ.endOffset; + + if (!isInExcludedRange(absStart, excluded)) { + TokenType tokenType; + switch (occ.type) { + case INTERFACE: + tokenType = TokenType.INTERFACE_DECL; + break; + case ENUM: + tokenType = TokenType.ENUM_DECL; + break; + default: + tokenType = TokenType.IMPORTED_CLASS; + break; + } + marks.add(new Mark(absStart, absEnd, tokenType)); + } + } + } + + private void collectFields() { + globalFields.clear(); + localFields.clear(); + methodBlocks.clear(); + + // Extract method blocks first + methodBlocks = MethodBlock.collectMethodBlocks(text); + + // Get excluded ranges (strings and comments) for the entire text + List excludedRanges = MethodBlock.getExcludedRanges(text); + + // Global fields (excluding those inside methods, strings, and comments) + Matcher mGlobal = GLOBAL_FIELD_DECL.matcher(text); + while (mGlobal.find()) { + String varName = mGlobal.group(2); + int varPosition = mGlobal.start(2); + + // Skip if inside a string or comment + if (isInExcludedRange(varPosition, excludedRanges)) { + continue; + } + + // Check if this variable is inside a method + boolean isInsideMethod = false; + for (MethodBlock block : methodBlocks) { + if (block.containsPosition(varPosition)) { + isInsideMethod = true; + break; + } + } + + // Only add as global if it's not inside any method + if (!isInsideMethod) { + globalFields.add(varName); + } + } + + // Extract local variables from each method block + for (MethodBlock block : methodBlocks) { + // localVariables are already extracted in MethodBlock constructor + for (String var : block.localVariables) { + if (!globalFields.contains(var) && !localFields.contains(var)) { + localFields.add(var); + } + } + } + } + + // Find which method block contains a given position + private MethodBlock findMethodBlockAtPosition(int position) { + for (MethodBlock block : methodBlocks) { + if (block.containsPosition(position)) { + return block; + } + } + return null; + } + + private void highlightVariableReferences(List marks) { + // Known Java keywords and types that shouldn't be flagged as undefined + java.util.Set knownIdentifiers = new java.util.HashSet<>(java.util.Arrays.asList( + // Primitive types + "boolean", "int", "float", "double", "long", "char", "byte", "short", "void", + // Keywords + "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", "strictfp", "goto", + // Common JS/scripting keywords + "undefined", "NaN", "Infinity", "arguments", "prototype", "constructor", + // Common types (first letter uppercase pattern handles most) + "String", "Object", "Array", "Math", "System", "Integer", "Double", "Float", + "Boolean", "Long", "Byte", "Short", "Character", "List", "Map", "Set" + )); + + // First pass: handle field accesses (this.field and obj.field patterns) + Pattern thisFieldPattern = Pattern.compile("\\bthis\\s*\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)"); + Matcher thisFieldMatcher = thisFieldPattern.matcher(text); + while (thisFieldMatcher.find()) { + String fieldName = thisFieldMatcher.group(1); + int fieldPos = thisFieldMatcher.start(1); + // Highlight as GLOBAL_FIELD if it exists, UNDEFINED_VAR otherwise + if (globalFields.contains(fieldName)) { + marks.add(new Mark(fieldPos, thisFieldMatcher.end(1), TokenType.GLOBAL_FIELD)); + } else { + marks.add(new Mark(fieldPos, thisFieldMatcher.end(1), TokenType.UNDEFINED_VAR)); + } + } + + // Handle identifier.field patterns (e.g., obj.field, global.field) + // The field part should be highlighted as GLOBAL_FIELD (light blue) + // Also, detect chained accesses like `a.b.c` and treat subsequent segments + // as fields when the root `a` is a known variable (parameter/local/global/this). + // Collect function parameters from JS-style `function name(a, b)` declarations + // so script parameters (e.g., `function tick(e)`) are recognized as known roots. + java.util.Set scriptFunctionParams = new java.util.HashSet<>(); + Pattern funcPattern = Pattern.compile("\\bfunction\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s*\\(([^)]*)\\)"); + Matcher funcM = funcPattern.matcher(text); + while (funcM.find()) { + String inside = funcM.group(1); + if (inside != null && !inside.trim().isEmpty()) { + for (String p : inside.split(",")) { + String pn = p.trim(); + if (!pn.isEmpty()) scriptFunctionParams.add(pn); + } + } + } + + Pattern chainPattern = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*(?:\\s*\\.\\s*[a-zA-Z_][a-zA-Z0-9_]*)+)\\b"); + Matcher chainMatcher = chainPattern.matcher(text); + while (chainMatcher.find()) { + if (isInExcludedRange(chainMatcher.start(), MethodBlock.getExcludedRanges(text))) continue; + String chain = chainMatcher.group(1); + int absStart = chainMatcher.start(1); + + java.util.List segs = new java.util.ArrayList<>(); + java.util.List segPos = new java.util.ArrayList<>(); + Matcher segM = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*").matcher(chain); + while (segM.find()) { + segs.add(segM.group()); + segPos.add(absStart + segM.start()); + } + if (segs.size() < 2) continue; + + String root = segs.get(0); + if (Character.isUpperCase(root.charAt(0))) continue; + + boolean rootIsKnown = false; + if (globalFields.contains(root) || localFields.contains(root)) rootIsKnown = true; + MethodBlock mbForRoot = findMethodBlockAtPosition(segPos.get(0)); + if (mbForRoot != null && mbForRoot.parameters.contains(root)) rootIsKnown = true; + if (scriptFunctionParams.contains(root)) rootIsKnown = true; + if ("this".equals(root)) rootIsKnown = true; + + if (rootIsKnown) { + for (int si = 1; si < segs.size(); si++) { + int sAbs = segPos.get(si); + int sEnd = sAbs + segs.get(si).length(); + marks.add(new Mark(sAbs, sEnd, TokenType.GLOBAL_FIELD)); + } + } + } + + // Fallback: simple two-part identifier.field patterns + Pattern objFieldPattern = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)"); + Matcher objFieldMatcher = objFieldPattern.matcher(text); + while (objFieldMatcher.find()) { + String fieldName = objFieldMatcher.group(2); + int fieldPos = objFieldMatcher.start(2); + String objName = objFieldMatcher.group(1); + if (!objName.equals("this")) { + marks.add(new Mark(fieldPos, objFieldMatcher.end(2), TokenType.GLOBAL_FIELD)); + } + } + + Pattern identifier = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b"); + Matcher m = identifier.matcher(text); + while (m.find()) { + String name = m.group(1); + int position = m.start(1); + + // Skip known keywords + if (knownIdentifiers.contains(name)) continue; + + // Skip field access (identifier preceded by a dot) - these should be gray/default + if (isFieldAccess(position)) continue; + + // Never treat parts of import/package statements as undefined variables + if (isInImportOrPackageStatement(position)) continue; + + // Check if inside a method + MethodBlock methodBlock = findMethodBlockAtPosition(position); + + if (methodBlock != null) { + // Inside a method - first check parameters, locals, and globals (respecting registrations) + if (methodBlock.parameters.contains(name)) { + marks.add(new Mark(m.start(1), m.end(1), TokenType.PARAMETER)); + continue; + } + + if (methodBlock.isLocalDeclaredAtPosition(name, position) || localFields.contains(name)) { + marks.add(new Mark(m.start(1), m.end(1), TokenType.LOCAL_FIELD)); + continue; + } + + if (globalFields.contains(name)) { + marks.add(new Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD)); + continue; + } + + // If it's an uppercase identifier that hasn't been registered as a local/param/global, + // treat it as a type reference (skip) rather than an undefined variable. + if (Character.isUpperCase(name.charAt(0))) continue; + + // Unknown variable - mark as undefined but only if it's not a method call or type reference + if (!isMethodCall(position) && !isTypeReference(name, position)) { + marks.add(new Mark(m.start(1), m.end(1), TokenType.UNDEFINED_VAR)); + } + } else { + // Outside any method - check global fields first + if (globalFields.contains(name) || localFields.contains(name)) { + marks.add(new Mark(m.start(1), m.end(1), TokenType.GLOBAL_FIELD)); + continue; + } + + // Uppercase unregistered identifiers are likely type names; skip them + if (Character.isUpperCase(name.charAt(0))) continue; + + if (!isMethodCall(position) && !isTypeReference(name, position)) { + marks.add(new Mark(m.start(1), m.end(1), TokenType.UNDEFINED_VAR)); + } + } + } + } + + private boolean isInImportOrPackageStatement(int position) { + if (position < 0 || position >= text.length()) return false; + + int lineStart = text.lastIndexOf('\n', position); + lineStart = (lineStart < 0) ? 0 : lineStart + 1; + int lineEnd = text.indexOf('\n', position); + lineEnd = (lineEnd < 0) ? text.length() : lineEnd; + + // Quick scan of the line start for "import" or "package" + int i = lineStart; + while (i < lineEnd && Character.isWhitespace(text.charAt(i))) i++; + + if (i + 6 <= lineEnd && text.startsWith("import", i)) { + // Ensure word boundary + int after = i + 6; + return after == lineEnd || Character.isWhitespace(text.charAt(after)); + } + if (i + 7 <= lineEnd && text.startsWith("package", i)) { + int after = i + 7; + return after == lineEnd || Character.isWhitespace(text.charAt(after)); + } + return false; + } + + /** + * Check if the identifier at this position is a field access (preceded by a dot) + * e.g., in "obj.field", the "field" part is a field access + */ + private boolean isFieldAccess(int position) { + if (position <= 0) return false; + + // Look backwards from position, skipping any whitespace + int i = position - 1; + while (i >= 0 && Character.isWhitespace(text.charAt(i))) { + i--; + } + + // Check if preceded by a dot + return i >= 0 && text.charAt(i) == '.'; + } + + /** + * Check if the identifier at this position is a method call (followed by parenthesis) + */ + private boolean isMethodCall(int position) { + // Skip whitespace after identifier + int i = position; + // Note: parentheses needed to avoid evaluating text.charAt(i) when i >= text.length() + while (i < text.length() && (Character.isLetterOrDigit(text.charAt(i)) || text.charAt(i) == '_')) { + i++; + } + // Skip whitespace + while (i < text.length() && Character.isWhitespace(text.charAt(i))) { + i++; + } + // Check for opening paren + return i < text.length() && text.charAt(i) == '('; + } + + /** + * Check if this looks like a type reference (e.g., part of a declaration or generic) + * But NOT a comparison like "i < container" which uses < as less-than operator + */ + private boolean isTypeReference(String name, int position) { + // Check if preceded by 'new ' + if (position > 4) { + String before = text.substring(Math.max(0, position - 5), position); + if (before.endsWith("new ")) { + return true; + } + } + + // Check if preceded by < but make sure it's a generic, not a comparison + // Generic: Type 1) { + int checkPos = position - 1; + // Skip whitespace + while (checkPos > 0 && Character.isWhitespace(text.charAt(checkPos))) { + checkPos--; + } + if (checkPos >= 0 && text.charAt(checkPos) == '<') { + // Check what's before the < + int beforeLt = checkPos - 1; + while (beforeLt >= 0 && Character.isWhitespace(text.charAt(beforeLt))) { + beforeLt--; + } + if (beforeLt >= 0) { + char beforeChar = text.charAt(beforeLt); + // If it's a letter/digit/underscore (identifier) or ) followed by space + <, it's a comparison + // If it's a type name directly followed by <, it's a generic + // Check if there was whitespace between the identifier and < + boolean hasSpaceBeforeLt = (checkPos > 0 && Character.isWhitespace(text.charAt(checkPos - 1))); + if (hasSpaceBeforeLt && (Character.isLetterOrDigit(beforeChar) || beforeChar == '_' || beforeChar == ')')) { + // This is a comparison like "i < container" or "(x + 1) < y" + return false; + } + // Otherwise it's likely a generic like List + if (Character.isLetter(beforeChar) || beforeChar == '>') { + return true; + } + } + } + // Check for comma in generics like Map + if (checkPos >= 0 && text.charAt(checkPos) == ',') { + return true; + } + } + return false; + } + + /** + * Check if position is in an excluded range (string or comment) + */ + private boolean isInExcludedRange(int pos, List ranges) { + for (int[] range : ranges) { + if (pos >= range[0] && pos < range[1]) { + return true; + } + } + return false; + } + + private void finalizeImports(List marks) { + if (importEntries.isEmpty()) return; + + for (ImportEntry ie : importEntries) { + // Highlight the 'import' keyword + marks.add(new Mark(ie.importKwStart, ie.importKwEnd, TokenType.IMPORT_KEYWORD)); + + String fullPath = ie.fullPath; + int pathStart = ie.pathStart; + int pathEnd = ie.pathEnd; + String matchText = ie.matchText; + + if (!ie.isWildcard) { + // Non-wildcard: reuse cached resolve result if available, otherwise resolve now + ClassPathFinder.ResolveResult result = classPathFinder.resolve(fullPath); + + String orig = text.substring(pathStart, pathEnd); + List tokens = new ArrayList<>(); + List tokenStarts = new ArrayList<>(); + List tokenEnds = new ArrayList<>(); + Matcher idm = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*").matcher(orig); + while (idm.find()) { + tokens.add(idm.group()); + tokenStarts.add(idm.start()); + tokenEnds.add(idm.end()); + } + + int pkgSegments = result.packageSegmentCount; + boolean hasPackage = pkgSegments > 0; + + if (result.found && result.invalidStartOffset < 0) { + if (hasPackage && pkgSegments <= tokenEnds.size()) { + int pkgEnd = pathStart + tokenEnds.get(pkgSegments - 1); + marks.add(new Mark(pathStart, pkgEnd, TokenType.TYPE_DECL)); + } + + if (result.classSegments != null && !result.classSegments.isEmpty()) { + int classTokenStart = hasPackage ? pkgSegments : 0; + for (int si = 0; si < result.classSegments.size(); si++) { + int tokIdx = classTokenStart + si; + if (tokIdx >= 0 && tokIdx < tokenStarts.size()) { + int s = pathStart + tokenStarts.get(tokIdx); + int e = pathStart + tokenEnds.get(tokIdx); + ClassPathFinder.ClassSegment seg = result.classSegments.get(si); + TokenType segType; + switch (seg.type) { + case INTERFACE: + segType = TokenType.INTERFACE_DECL; + break; + case ENUM: + segType = TokenType.ENUM_DECL; + break; + default: + segType = TokenType.IMPORTED_CLASS; + break; + } + marks.add(new Mark(s, e, segType)); + } + } + } + } else if (result.classSegments != null && !result.classSegments.isEmpty()) { + if (hasPackage && pkgSegments <= tokenEnds.size()) { + int pkgEnd = pathStart + tokenEnds.get(pkgSegments - 1); + marks.add(new Mark(pathStart, pkgEnd, TokenType.TYPE_DECL)); + } + + int classTokenStart = hasPackage ? pkgSegments : 0; + for (int si = 0; si < result.classSegments.size(); si++) { + int tokIdx = classTokenStart + si; + if (tokIdx >= 0 && tokIdx < tokenStarts.size()) { + int s = pathStart + tokenStarts.get(tokIdx); + int e = pathStart + tokenEnds.get(tokIdx); + ClassPathFinder.ClassSegment seg = result.classSegments.get(si); + TokenType segType; + switch (seg.type) { + case INTERFACE: + segType = TokenType.INTERFACE_DECL; + break; + case ENUM: + segType = TokenType.ENUM_DECL; + break; + default: + segType = TokenType.IMPORTED_CLASS; + break; + } + marks.add(new Mark(s, e, segType)); + } + } + + if (result.invalidStartOffset >= 0) { + int invalidAbs = mapNormalizedOffsetToOriginal(orig, result.invalidStartOffset, pathStart); + if (invalidAbs < pathEnd) { + marks.add(new Mark(invalidAbs, pathEnd, TokenType.UNDEFINED_VAR)); + } + } + } else { + if (result.invalidStartOffset >= 0 && hasPackage) { + if (pkgSegments <= tokenEnds.size()) { + int pkgEnd = pathStart + tokenEnds.get(pkgSegments - 1); + marks.add(new Mark(pathStart, pkgEnd, TokenType.TYPE_DECL)); + } + + int invalidAbs = mapNormalizedOffsetToOriginal(orig, result.invalidStartOffset, pathStart); + if (invalidAbs < pathEnd) { + marks.add(new Mark(invalidAbs, pathEnd, TokenType.UNDEFINED_VAR)); + } + } else if (fullPath.endsWith(".") && hasPackage && result.invalidStartOffset < 0) { + marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL)); + } else if (result.invalidStartOffset < 0 && hasPackage) { + marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL)); + } else { + marks.add(new Mark(pathStart, pathEnd, TokenType.UNDEFINED_VAR)); + } + } + + // Highlight .* if present (shouldn't for non-wildcard, but keep behavior) + int starIndex = matchText.indexOf('*'); + if (starIndex != -1) { + int absStar = ie.importKwStart + (starIndex - 0); + marks.add(new Mark(absStar, absStar + 1, TokenType.DEFAULT)); + } + } else { + // Wildcard import: try to determine whether this is a valid package or + // a class whose inner types are being imported (Outer.*) + boolean marked = false; + + // If package is known valid, mark as package + if (classPathFinder.isValidPackage(fullPath)) { + marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL)); + marked = true; + } else { + // Probe uppercase identifiers in file to see if any inner types resolve + java.util.Set uppercaseIds = new java.util.HashSet<>(); + Matcher idm = Pattern.compile("\\b([A-Z][a-zA-Z0-9_]*)\\b").matcher(text); + while (idm.find()) uppercaseIds.add(idm.group(1)); + + for (String ident : uppercaseIds) { + String candInner = fullPath + "$" + ident; + ClassPathFinder.ClassInfo infoInner = classPathFinder.tryResolveClassName(candInner); + if (infoInner != null) { + // outer may be a class - try to get its info + ClassPathFinder.ClassInfo outerInfo = classPathFinder.tryResolveClassName(fullPath); + // mark package tokens (all but last) as TYPE_DECL and last as outer type + String orig = text.substring(pathStart, pathEnd); + List tokens = new ArrayList<>(); + List tokenStarts = new ArrayList<>(); + List tokenEnds = new ArrayList<>(); + Matcher tokm = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*").matcher(orig); + while (tokm.find()) { + tokens.add(tokm.group()); + tokenStarts.add(tokm.start()); + tokenEnds.add(tokm.end()); + } + + int tokenCount = tokenStarts.size(); + if (tokenCount > 0) { + int pkgEnd = pathStart + (tokenEnds.get(Math.max(0, tokenCount - 2))); + if (tokenCount >= 2) { + // mark package (all except last) + marks.add(new Mark(pathStart, pathStart + tokenEnds.get(tokenCount - 2), TokenType.TYPE_DECL)); + } + // mark outer class token (last) + int s = pathStart + tokenStarts.get(tokenCount - 1); + int e = pathStart + tokenEnds.get(tokenCount - 1); + TokenType segType = TokenType.IMPORTED_CLASS; + if (outerInfo != null) { + switch (outerInfo.type) { + case INTERFACE: + segType = TokenType.INTERFACE_DECL; + break; + case ENUM: + segType = TokenType.ENUM_DECL; + break; + default: + segType = TokenType.IMPORTED_CLASS; + break; + } + } + marks.add(new Mark(s, e, segType)); + } + marked = true; + // ensure package listed in importedPackages + importedPackages.add(fullPath); + break; + } + + // Try package-like resolution: fullPath + "." + ident + String candDot = fullPath + "." + ident; + if (classPathFinder.tryResolveClassName(candDot) != null) { + marks.add(new Mark(pathStart, pathEnd, TokenType.TYPE_DECL)); + marked = true; + importedPackages.add(fullPath); + break; + } + } + } + + if (!marked) { + // Unknown wildcard import - mark as undefined + marks.add(new Mark(pathStart, pathEnd, TokenType.UNDEFINED_VAR)); + } + + // highlight star + if (ie.starPos >= 0) marks.add(new Mark(ie.starPos, ie.starPos + 1, TokenType.DEFAULT)); + } + } + } + + + private void collectImportedClassUsages(List marks) { + List excluded = MethodBlock.getExcludedRanges(text); + // Find identifiers followed by dot (e.g., Math.min, ArrayList.class) + Pattern classUsage = Pattern.compile("\\b([A-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 (isInExcludedRange(start, excluded)) + continue; + + // Check if this class was imported but failed to resolve + if (unresolvedClasses.contains(className)) { + marks.add(new Mark(start, end, TokenType.UNDEFINED_VAR)); + continue; + } + + // Check if this is an imported class, wildcard match, or java.lang class + boolean isImported = importedClasses.containsKey(className) || ClassPathFinder.JAVA_LANG_CLASSES.contains(className); + if (!isImported && !importedPackages.isEmpty()) { + isImported = true; // Wildcard import present + } + + // Also skip if it's a local/global field or parameter (avoid false positives) + MethodBlock block = findMethodBlockAtPosition(start); + boolean isShadowed = globalFields.contains(className) || localFields.contains(className); + if (block != null) { + isShadowed = isShadowed || block.parameters.contains(className) || block.isLocalDeclaredAtPosition( + className, start); + } + + if (isImported && !isShadowed) { + // Resolve the class to determine its type + ClassPathFinder.ClassInfo info = classPathFinder.resolveSimpleName(className, importedClasses, importedPackages); + TokenType tokenType = TokenType.IMPORTED_CLASS; + if (info != null) { + switch (info.type) { + case INTERFACE: + tokenType = TokenType.INTERFACE_DECL; + break; + case ENUM: + tokenType = TokenType.ENUM_DECL; + break; + } + } + marks.add(new Mark(start, end, tokenType)); + } else if (!isImported && !isShadowed) { + marks.add(new Mark(start, end, TokenType.UNDEFINED_VAR)); + } + } + } + + private void collectClassDeclarations(List marks) { + 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)); + + int nameStart = m.start(2); + int nameEnd = m.end(2); + if (isInExcludedRange(nameStart, excluded)) + continue; + String kind = m.group(1); + if ("interface".equals(kind)) { + marks.add(new Mark(nameStart, nameEnd, TokenType.INTERFACE_DECL)); + } else if ("enum".equals(kind)) { + marks.add(new Mark(nameStart, nameEnd, TokenType.ENUM_DECL)); + } else { + marks.add(new Mark(nameStart, nameEnd, TokenType.CLASS_DECL)); + } + } + } + + public void formatCodeText() { + // Step 1: Tokenize the full text + List marks = new ArrayList<>(); + + collectImports(); // Parse import statements first + collectFields(); // Extract global and local fields with method scoping + collectPatternMatches(marks, COMMENT, TokenType.COMMENT); + collectPatternMatches(marks, STRING, TokenType.STRING); + + // Import marking is deferred until after type/usages are discovered. + // finalizeImports(marks) will create import marks later. + collectClassDeclarations(marks); // Highlight class/interface/enum declarations + + // Highlight general keywords + collectPatternMatches(marks, KEYWORD, TokenType.KEYWORD); + collectPatternMatches(marks, MODIFIER, TokenType.MODIFIER); + + collectTypeDeclarations(marks); + collectPatternMatches(marks, NEW_TYPE, TokenType.NEW_TYPE, 1); + + collectMethodDeclarations(marks); + collectPatternMatches(marks, METHOD_CALL, TokenType.METHOD_CALL, 1); + + collectPatternMatches(marks, NUMBER, TokenType.NUMBER); + + highlightVariableReferences(marks); + collectImportedClassUsages(marks); // Highlight imported class usages (e.g., Math.min) + + // Finalize import markings after usages/types have been discovered + finalizeImports(marks); + + marks = resolveConflicts(marks); + + // Compute indent guides based on matched braces, ignoring strings/comments + computeIndentGuides(marks); + + // Step 2: Clear existing tokens + for (LineData line : lines) { + line.tokens.clear(); + } + + // Step 3: Assign tokens to the correct lines + for (LineData line : lines) { + int cursor = line.start; + // collectImportStatements used to create marks here; we now defer marking until types/usages are discovered + // so finalizeImports will create the visual marks from recorded import entries. + for (Mark mark : marks) { + if (mark.end <= line.start || mark.start >= line.end) + continue; + + int tokenStart = Math.max(mark.start, line.start); + int tokenEnd = Math.min(mark.end, line.end); + + tokenStart = Math.max(0, Math.min(tokenStart, text.length())); + tokenEnd = Math.max(0, Math.min(tokenEnd, text.length())); + + // plain text before token + if (cursor < tokenStart) { + int end = Math.min(tokenStart, text.length()); + line.tokens.add( + new Token(text.substring(cursor, end), TokenType.DEFAULT, cursor, end)); + } + + // token text + if (tokenStart < tokenEnd) { + line.tokens.add(new Token(text.substring(tokenStart, Math.min(tokenEnd, text.length())), mark.type, tokenStart, Math.min(tokenEnd, text.length()))); + } + + cursor = tokenEnd; + } + + // trailing plain text + if (cursor < line.end) { + int end = Math.min(line.end, text.length()); + line.tokens.add(new Token(text.substring(cursor, end), TokenType.DEFAULT, cursor, end)); + } + } + } + + private void collectMethodDeclarations(List marks) { + Matcher m = METHOD_DECL.matcher(text); + while (m.find()) { // method name + marks.add(new Mark(m.start(2), m.end(2), TokenType.METHOD_DECARE)); + // return type + marks.add(new Mark(m.start(1), m.end(1), TokenType.TYPE_DECL)); + } + } + + private void collectTypeDeclarations(List marks) { + List excluded = MethodBlock.getExcludedRanges(text); + + // Pattern to find type declarations: Type<...> variableName or Type variableName + // We'll manually parse the generic portion to handle arbitrary nesting + Pattern typeStart = Pattern.compile( + "(?:(?:public|private|protected|static|final|transient|volatile)\\s+)*" + + "([A-Z][a-zA-Z0-9_]*)\\s*" // Group 1 → type name (must start with uppercase) + ); + + for (LineData ld : lines) { + int lineStart = ld.start; + int lineEnd = ld.end; + if (lineStart >= lineEnd) continue; + String s = ld.text; + + Matcher m = typeStart.matcher(s); + int searchFrom = 0; + + while (m.find(searchFrom)) { + int typeNameStart = lineStart + m.start(1); + int typeNameEnd = lineStart + m.end(1); + + // Skip if in excluded range + boolean skip = false; + for (int[] r : excluded) { + if (typeNameStart < r[1] && typeNameEnd > r[0]) { + skip = true; + break; + } + } + if (skip) { + searchFrom = m.end(); + continue; + } + + String typeName = m.group(1); + int posAfterType = m.end(1); + + // Skip whitespace after type name + while (posAfterType < s.length() && Character.isWhitespace(s.charAt(posAfterType))) { + posAfterType++; + } + + // Check for generic parameters + String genericContent = null; + int genericStart = -1; + int genericEnd = -1; + + if (posAfterType < s.length() && s.charAt(posAfterType) == '<') { + genericStart = posAfterType; + int depth = 1; + int i = posAfterType + 1; + while (i < s.length() && depth > 0) { + char c = s.charAt(i); + if (c == '<') depth++; + else if (c == '>') depth--; + i++; + } + if (depth == 0) { + genericEnd = i; + genericContent = s.substring(genericStart + 1, genericEnd - 1); + posAfterType = genericEnd; + } + } + + // Skip whitespace after generics + while (posAfterType < s.length() && Character.isWhitespace(s.charAt(posAfterType))) { + posAfterType++; + } + + // Check if this looks like a type declaration: + // 1. Has generic content (e.g., List) - always a type + // 2. Followed by a variable name (lowercase start or underscore) + // 3. At end of line with generic content (line might be wrapped) + boolean hasGeneric = genericContent != null && !genericContent.isEmpty(); + boolean atEndOfLine = posAfterType >= s.length(); + boolean followedByVarName = false; + + if (!atEndOfLine) { + char nextChar = s.charAt(posAfterType); + followedByVarName = Character.isLetter(nextChar) || nextChar == '_'; + } + + // Accept as type if: has generics OR followed by variable name + // This handles both `List myList` and wrapped lines like `List` + if (hasGeneric || followedByVarName) { + // This looks like a type declaration + + // Resolve the main type + ClassPathFinder.ClassInfo info = classPathFinder.resolveSimpleName(typeName, importedClasses, importedPackages); + TokenType tokenType = TokenType.UNDEFINED_VAR; + if (info != null) { + switch (info.type) { + case INTERFACE: + tokenType = TokenType.INTERFACE_DECL; + break; + case ENUM: + tokenType = TokenType.ENUM_DECL; + break; + default: + tokenType = TokenType.TYPE_DECL; + } + } + marks.add(new Mark(typeNameStart, typeNameEnd, tokenType)); + + // Handle generic content + if (hasGeneric && genericStart >= 0) { + int absGenericStart = lineStart + genericStart; + int absGenericEnd = lineStart + genericEnd; + + // Mark < and > as default + marks.add(new Mark(absGenericStart, absGenericStart + 1, TokenType.DEFAULT)); + marks.add(new Mark(absGenericEnd - 1, absGenericEnd, TokenType.DEFAULT)); + + // Parse and highlight all types in generic content + int contentStart = lineStart + genericStart + 1; + highlightGenericTypes(genericContent, contentStart, marks, excluded); + } + + // If followed by a variable name, detect it and register uppercase-starting + // variable names as locals so subsequent identifier scanning treats them + // as variables (not types). This handles declarations like: + // MyType Capital = new MyType(); + if (followedByVarName) { + int v = posAfterType; + // skip whitespace + while (v < s.length() && Character.isWhitespace(s.charAt(v))) v++; + int varStart = v; + while (v < s.length() && (Character.isLetterOrDigit(s.charAt(v)) || s.charAt(v) == '_')) v++; + int varEnd = v; + if (varEnd > varStart) { + String varName = s.substring(varStart, varEnd); + int absVarStart = lineStart + varStart; + int absVarEnd = lineStart + varEnd; + if (Character.isUpperCase(varName.charAt(0))) { + MethodBlock mb = findMethodBlockAtPosition(absVarStart); + if (mb != null) { + if (!mb.localVariables.contains(varName)) mb.localVariables.add(varName); + if (!localFields.contains(varName)) localFields.add(varName); + marks.add(new Mark(absVarStart, absVarEnd, TokenType.LOCAL_FIELD)); + } + } + } + } + } + + searchFrom = m.end(); + } + } + } + + private void collectPatternMatches(List marks, Pattern pattern, TokenType type, int group) { + Matcher m = pattern.matcher(text); + while (m.find()) { + marks.add(new Mark(m.start(group), m.end(group), type)); + } + } + + private void collectPatternMatches(List marks, Pattern pattern, TokenType type) { + collectPatternMatches(marks, pattern, type, 0); + } + + private List resolveConflicts(List marks) { + // Sort by start index first, then by descending priority so higher-priority marks + // at the same start are considered first. + marks.sort((a, b) -> { + if (a.start != b.start) + return Integer.compare(a.start, b.start); + return Integer.compare(b.type.priority, a.type.priority); + }); + + List result = new ArrayList<>(); + for (Mark m : marks) { + boolean skip = false; + // Remove any existing lower-priority marks that overlap with this higher-priority mark + for (int i = result.size() - 1; i >= 0; i--) { + Mark r = result.get(i); + if (m.start < r.end && m.end > r.start) { + if (r.type.priority < m.type.priority) { + // remove lower-priority overlapping mark + result.remove(i); + } else { + // an existing mark has equal or higher priority and overlaps -> skip adding m + skip = true; + break; + } + } + } + if (!skip) { + result.add(m); + } + } + // Optionally sort the result by start before returning + result.sort((a, b) -> Integer.compare(a.start, b.start)); + return result; + } + + public static class LineData { + public String text; + public int start, end; + public List tokens = new ArrayList<>(); + public List indentCols = new ArrayList<>(); + + public LineData(String text, int startIndex, int end) { + this.text = text; + this.start = startIndex; + this.end = end; + } + + public void drawString(int x, int y, int color) { + StringBuilder builder = new StringBuilder(); + int lastIndex = 0; + + for (Token t : tokens) { + int tokenStart = t.start - this.start; // relative position in line + if (tokenStart > lastIndex) { + // append the text before the token (spaces, punctuation) + builder.append(text, lastIndex, tokenStart); + } + builder.append(colorChar).append(t.type.color).append(t.text).append(colorChar).append('f'); + lastIndex = tokenStart + t.text.length(); + } + + // append any remaining text after the last token + if (lastIndex < text.length()) { + builder.append(text.substring(lastIndex)); + } + + ClientProxy.Font.drawString(builder.toString(), x, y, color); + } + } + + public static class Token { + public String text; + public TokenType type; + public int start, end; // start/end relative to the line + + public Token(String text, TokenType type, int start, int end) { + this.text = text; + this.type = type; + this.start = start; + this.end = end; + } + + @Override + public String toString() { + return "Token{'" + text + '\'' + ", " + type + ", (color=" + type.color + ", priority=" + type.priority + ")" + '}'; + } + } + + private static class Mark { + public int start, end; + public TokenType type; + + public Mark(int start, int end, TokenType type) { + this.start = start; + this.end = end; + this.type = type; + } + + @Override + public String toString() { + return "Mark{" + type + ", (start=" + start + ", end=" + end + ")" + '}'; + } + } + + 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), + ENUM_DECL('d', 85), + CLASS_DECL('3', 85), + TYPE_DECL('3', 70), + METHOD_DECARE('2', 60), + METHOD_CALL('a', 50), + NUMBER('7', 40), + VARIABLE('f', 30), + GLOBAL_FIELD('b', 35), // aqua - class-level fields + LOCAL_FIELD('e', 25), // yellow - local variables + PARAMETER('9', 36), // blue - method parameters (Bug 10) + UNDEFINED_VAR('4', 105), // dark red - undefined variables (higher priority so it isn't overridden) + DEFAULT('f', 0); + + public final char color; + public final int priority; + + TokenType(char color, int priority) { + this.color = color; + this.priority = priority; + } + } + + // Compute indent guide columns per line based on brace matching. + private void computeIndentGuides(List marks) { + // Clear existing guides + for (LineData ld : lines) { + ld.indentCols.clear(); + } + + // Build ignored ranges from STRING and COMMENT tokens + List ignored = new ArrayList<>(); + for (Mark m : marks) { + if (m.type == TokenType.STRING || m.type == TokenType.COMMENT) { + ignored.add(new int[]{m.start, m.end}); + } + } + + java.util.function.Predicate isIgnored = (pos) -> { + for (int[] r : ignored) { + if (pos >= r[0] && pos < r[1]) + return true; + } + return false; + }; + + class OpenBrace { + int line, col; + + OpenBrace(int l, int c) { + line = l; + col = c; + } + } + java.util.Deque stack = new java.util.ArrayDeque<>(); + + final int tabSize = 4; + + for (int li = 0; li < lines.size(); li++) { + LineData ld = lines.get(li); + String s = ld.text; + for (int i = 0; i < s.length(); i++) { + int absPos = ld.start + i; + if (isIgnored.test(absPos)) + continue; + char c = s.charAt(i); + if (c == '{') { + // compute leading indentation (expanded) up to this char + int leading = 0; + for (int k = 0; k < i; k++) { + char ch = s.charAt(k); + if (ch == '\t') + leading += tabSize; + else + leading += 1; + } + stack.push(new OpenBrace(li, leading)); + } else if (c == '}') { + if (!stack.isEmpty()) { + OpenBrace open = stack.pop(); + int startLine = open.line; + int col = open.col; + if (startLine == li) + continue; // same-line block, skip + // add guide column to lines inside the block + int from = Math.max(0, startLine + 1); + int to = Math.min(lines.size() - 1, li); + for (int l = from; l <= to; l++) { + List list = lines.get(l).indentCols; + if (!list.contains(col)) + list.add(col); + } + } + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/MethodBlock.java b/src/main/java/noppes/npcs/client/gui/util/script/MethodBlock.java new file mode 100644 index 000000000..6158c85ed --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/MethodBlock.java @@ -0,0 +1,230 @@ +package noppes.npcs.client.gui.util.script; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MethodBlock { + + // pattern matches returnType + methodName + parentheses + public static final Pattern METHOD_PATTERN = Pattern.compile( + "\\b([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type + "([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name + ); + + // Pattern for variable declarations (same as in JavaTextContainer) + public static final Pattern LOCAL_VAR_DECL = Pattern.compile( + "\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)"); + + // Pattern for method parameters: Type name (with optional ... for varargs) + public static final Pattern PARAMETER_PATTERN = Pattern.compile( + "([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*(?:\\.{3})?)\\s+([a-zA-Z_][a-zA-Z0-9_]*)"); + + public int startOffset; + public int endOffset; + public String text; + public List localVariables = new ArrayList<>(); + public List parameters = new ArrayList<>(); // Method parameters + public Map localVarPositions = new HashMap<>(); // Track declaration positions + + public MethodBlock(int start, int end, String text) { + this.startOffset = start; + this.endOffset = end; + this.text = text; + extractParameters(); + extractLocalVariables(); + } + + // Extract method parameters from the method signature + private void extractParameters() { + parameters.clear(); + + // Find the parameter list between ( and ) + int parenStart = text.indexOf('('); + int parenEnd = text.indexOf(')'); + + if (parenStart < 0 || parenEnd <= parenStart) return; + + String paramList = text.substring(parenStart + 1, parenEnd); + + // Skip if empty + if (paramList.trim().isEmpty()) return; + + // Split by comma (but be careful of generic types like List) + Matcher m = PARAMETER_PATTERN.matcher(paramList); + while (m.find()) { + String paramName = m.group(2); + if (!parameters.contains(paramName)) { + parameters.add(paramName); + } + } + } + + // Extract local variables declared within this method + private void extractLocalVariables() { + localVariables.clear(); + localVarPositions.clear(); + + // Get excluded ranges (strings and comments) for this method's text + List excludedRanges = getExcludedRanges(text); + + Matcher m = LOCAL_VAR_DECL.matcher(text); + while (m.find()) { + String varName = m.group(2); + int declPosition = m.start(); + + // Skip if inside a string or comment + if (isInExcludedRange(declPosition, excludedRanges)) { + continue; + } + + // Check if this is a "this.field" assignment - if so, skip it + // Look backwards from the declaration position to see if preceded by "this." + boolean isThisFieldAssignment = false; + if (declPosition >= 5) { + int checkStart = Math.max(0, declPosition - 10); + String before = text.substring(checkStart, declPosition); + if (before.matches(".*\\bthis\\s*\\.\\s*$")) { + isThisFieldAssignment = true; + } + } + + if (!isThisFieldAssignment && !localVariables.contains(varName)) { + localVariables.add(varName); + // Store the absolute position in the full text (startOffset + relative position) + localVarPositions.put(varName, startOffset + declPosition); + } + } + } + + // Check if a reference position comes before the local variable declaration + // This handles cases like: global.field on line 7, then var global = "x" on line 9 + // At line 7, the local 'global' doesn't exist yet, so it should refer to the global 'global' + public boolean isLocalDeclaredAtPosition(String varName, int absolutePosition) { + if (!localVariables.contains(varName)) { + return false; + } + Integer declPos = localVarPositions.get(varName); + if (declPos == null) { + return false; + } + // The local variable is only "in scope" at or after its declaration position + return absolutePosition >= declPos; + } + + // Check if a position (in the full text) falls within this method + public boolean containsPosition(int position) { + return position >= startOffset && position < endOffset; + } + + public String toString() { + return text; + } + + public static List collectMethodBlocks(String text) { + List methods = new ArrayList<>(); + + // Matches: returnType methodName(...) { (non-greedy capture until first { ) + Pattern methodPattern = Pattern.compile( + "\\b([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type + "([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\([^)]*\\)\\s*" + // method name + parameters + "\\{", // opening brace + Pattern.MULTILINE); + + Matcher m = methodPattern.matcher(text); + while (m.find()) { + int start = m.start(); // start of method declaration + int braceStart = text.indexOf("{", m.end() - 1); // first { after declaration + if (braceStart == -1) + continue; + + int braceEnd = findMatchingBrace(text, braceStart); + if (braceEnd == -1) + continue; + + String methodText = text.substring(start, braceEnd + 1); + methods.add(new MethodBlock(start, braceEnd + 1, methodText)); + } + + return methods; + } + + // Find ranges of text to skip (strings and comments). Returns merged, sorted ranges. + public static List getExcludedRanges(String text) { + List ranges = new ArrayList<>(); + + // Find all strings and char literals (simple heuristic) + Pattern stringPattern = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1"); + Matcher stringMatcher = stringPattern.matcher(text); + while (stringMatcher.find()) { + ranges.add(new int[]{stringMatcher.start(), stringMatcher.end()}); + } + + // Find all comments (block and line comments) + Pattern commentPattern = Pattern.compile("/\\*[\\s\\S]*?(?:\\*/|$)|//.*"); + Matcher commentMatcher = commentPattern.matcher(text); + while (commentMatcher.find()) { + ranges.add(new int[]{commentMatcher.start(), commentMatcher.end()}); + } + + if (ranges.isEmpty()) + return ranges; + + // Sort ranges by start position + ranges.sort((a, b) -> Integer.compare(a[0], b[0])); + + // Merge overlapping/adjacent ranges for faster scanning + List merged = new ArrayList<>(); + int[] current = ranges.get(0); + for (int i = 1; i < ranges.size(); i++) { + int[] next = ranges.get(i); + if (next[0] <= current[1]) { + // overlap or adjacent + current[1] = Math.max(current[1], next[1]); + } else { + merged.add(current); + current = next; + } + } + merged.add(current); + return merged; + } + + // Check if a position is within an excluded range + private static boolean isInExcludedRange(int pos, List ranges) { + for (int[] range : ranges) { + if (pos >= range[0] && pos < range[1]) { + return true; + } + } + return false; + } + + // Utility to find the matching closing brace, ignoring braces in strings and + // comments + public static int findMatchingBrace(String text, int openBraceIndex) { + List excludedRanges = getExcludedRanges(text); + + int depth = 0; + for (int i = openBraceIndex; i < text.length(); i++) { + // Skip characters inside strings or comments + if (isInExcludedRange(i, excludedRanges)) { + continue; + } + + char c = text.charAt(i); + if (c == '{') { + depth++; + } else if (c == '}') { + depth--; + if (depth == 0) { + return i; + } + } + } + return -1; // no match + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/PackageFinder.java b/src/main/java/noppes/npcs/client/gui/util/script/PackageFinder.java new file mode 100644 index 000000000..5dd70e7ce --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/PackageFinder.java @@ -0,0 +1,199 @@ +package noppes.npcs.client.gui.util.script; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * PackageFinder builds an index of package names found on the provided ClassLoader + * (scanning jar files and directories). After construction queries via {@link #contains} + * are O(1) HashSet lookups. + */ +public class PackageFinder { + private static volatile PackageFinder INSTANCE = null; + private final Set packages = new HashSet<>(); + private final ClassLoader classLoader; + + private PackageFinder(ClassLoader cl) throws IOException { + this.classLoader = cl == null ? Thread.currentThread().getContextClassLoader() : cl; + buildIndex(); + } + + private void buildIndex() throws IOException { + packages.clear(); + + ClassLoader cl = this.classLoader; + + // Try URLClassLoader first (common on most JVM versions used here) + if (cl instanceof URLClassLoader) { + URL[] urls = ((URLClassLoader) cl).getURLs(); + for (URL url : urls) { + try { + String protocol = url.getProtocol(); + if ("file".equals(protocol)) { + File f; + try { + URI u = url.toURI(); + f = new File(u); + } catch (Exception ex) { + f = new File(url.getPath()); + } + if (f.exists()) { + if (f.isDirectory()) + scanDirectory(f); + else if (f.isFile() && f.getName().endsWith(".jar")) + scanJar(f); + } + } else if ("jar".equals(protocol)) { + // jar:file:/path/to/jar.jar!/... + String s = url.getPath(); + int excl = s.indexOf('!'); + String jarPath = (excl >= 0) ? s.substring(0, excl) : s; + if (jarPath.startsWith("file:")) + jarPath = jarPath.substring(5); + File jf = new File(jarPath); + if (jf.exists()) + scanJar(jf); + } + } catch (IOException ignored) { + // ignore individual entries + } + } + } else { + // Fallback: scan system classpath as a best-effort + String cp = System.getProperty("java.class.path", ""); + String[] entries = cp.split(File.pathSeparator); + for (String e : entries) { + if (e == null || e.isEmpty()) + continue; + File f = new File(e); + if (!f.exists()) + continue; + if (f.isDirectory()) + scanDirectory(f); + else if (f.isFile() && f.getName().endsWith(".jar")) + scanJar(f); + } + } + } + + private void scanJar(File jarFile) throws IOException { + try (JarFile jf = new JarFile(jarFile)) { + Enumeration en = jf.entries(); + while (en.hasMoreElements()) { + JarEntry je = en.nextElement(); + String name = je.getName(); + if (name.endsWith(".class")) { + int idx = name.lastIndexOf('/'); + if (idx > 0) { + String pkg = name.substring(0, idx).replace('/', '.'); + addPackageHierarchy(pkg); + } + } + } + } + } + + private void scanDirectory(File dir) throws IOException { + final Path root = dir.toPath(); + if (!Files.exists(root)) + return; + Files.walk(root).forEach(p -> { + try { + if (Files.isRegularFile(p) && p.toString().endsWith(".class")) { + Path parent = p.getParent(); + if (parent == null) + return; + Path rel = root.relativize(parent); + String rp = rel.toString(); + if (rp.isEmpty()) + return; + // Normalize separators to dot + String pkg = rp.replace(File.separatorChar, '.'); + addPackageHierarchy(pkg); + } + } catch (Exception ignored) { + } + }); + } + + private void addPackageHierarchy(String pkg) { + if (pkg == null || pkg.isEmpty()) + return; + String cur = pkg; + while (true) { + if (!cur.isEmpty()) + packages.add(cur); + int idx = cur.lastIndexOf('.'); + if (idx < 0) + break; + cur = cur.substring(0, idx); + } + } + + public boolean contains(String pkg) { + if (pkg == null || pkg.isEmpty()) + return false; + return packages.contains(pkg); + } + + public static boolean find(String pkg) { + PackageFinder pf = getInstance(); + if (pf != null) + return pf.contains(pkg); + return false; + } + + /** + * Initialize the global singleton with the provided ClassLoader (or context CL if null). + * This is idempotent; calling again will re-create the index. + */ + public static synchronized void init(ClassLoader cl) throws IOException { + if (INSTANCE == null) { + INSTANCE = new PackageFinder(cl); + } else { + // rebuild index with new classloader if provided + if (cl != null) { + INSTANCE = new PackageFinder(cl); + } else { + INSTANCE.buildIndex(); + } + } + } + + /** + * Get the initialized singleton. Call {@link #init(ClassLoader)} first. + */ + public static PackageFinder getInstance() { + if (INSTANCE == null) { + try { + INSTANCE = fromContext(); + } catch (IOException e) { + } + } + return INSTANCE; + } + + /** + * Convenience factory using the context classloader and building a standalone finder (not touching singleton). + */ + public static PackageFinder fromContext() throws IOException { + return new PackageFinder(Thread.currentThread().getContextClassLoader()); + } + + /** + * Reload the index using the configured ClassLoader. + */ + public synchronized void reload() throws IOException { + buildIndex(); + } +} 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 new file mode 100644 index 000000000..15a71a900 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/RenameRefactorHandler.java @@ -0,0 +1,1058 @@ +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; +import java.util.List; +import java.util.regex.Matcher; +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 + * - ESC cancels, Enter confirms + * - Live preview as you type the new name + * - Full word selection by default when starting rename + * - Allows empty word during editing (shows empty box) + * - Click support within rename box + */ +public class RenameRefactorHandler { + + // ==================== STATE ==================== + private boolean active = false; + private String initialWord = ""; // The word when rename started (for undo grouping) + private String originalWord = ""; // Current baseline for live rename + private String currentWord = ""; // Current word being typed + private int primaryOccurrenceStart = -1; + 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<>(); + + // For restoring original text on cancel + private String originalText = ""; + private int originalCursorPos = 0; + + // Callback interface + private RenameCallback callback; + + // Pattern for identifiers + private static final Pattern IDENTIFIER = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*"); + // Placeholder to show when the rename box is empty + private static final String EMPTY_PLACEHOLDER = "|"; + + /** + * Callback interface for rename operations + */ + public interface RenameCallback { + String getText(); + + void setText(String text); + + void setTextWithoutUndo(String text); // Set text without creating undo entry + + void pushUndoState(String text, int cursor); // Push an undo state + + List getLines(); + + int getCursorPosition(); + + SelectionState getSelectionState(); + + void setCursorPosition(int pos); + + void unfocusMainEditor(); + + void focusMainEditor(); + + int getGutterWidth(); + + int getLineHeight(); + + int getScrolledLine(); + + double getFractionalOffset(); + + void scrollToPosition(int pos); + + ScriptTextContainer getContainer(); + + int getViewportWidth(); // For determining if clicks are in rename box + } + + public void setCallback(RenameCallback callback) { + this.callback = callback; + } + + /** + * Start rename refactoring at the current cursor position. + * Selects the word under cursor and finds all occurrences within scope. + * + * @return true if rename mode was successfully started + */ + public boolean startRename() { + if (callback == null) + return false; + + String text = callback.getText(); + int cursor = callback.getCursorPosition(); + + if (text == null || text.isEmpty()) + return false; + + // Find word under cursor + int[] wordBounds = findWordAtPosition(text, cursor); + if (wordBounds == null) + return false; + + // Store original state for cancel AND for undo grouping + originalText = text; + originalCursorPos = cursor; + + 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 (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.getSelectionState().markActivity(); + + return true; + } + + /** + * Cancel rename operation and restore original state + */ + public void cancel() { + if (!active) + return; + + // Restore original text + if (callback != null && !originalText.isEmpty()) { + callback.setText(originalText); + callback.setCursorPosition(originalCursorPos); + } + + resetState(); + + if (callback != null) { + callback.focusMainEditor(); + } + } + + /** + * Confirm rename operation and apply changes + */ + public void confirm() { + if (!active || callback == null) + return; + + // If word is empty, restore original + if (currentWord.isEmpty()) { + cancel(); + return; + } + + // Push the original text (pre-rename) so the first undo will restore the + // document to its state before the refactor. + // 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()) + callback.pushUndoState(originalText, originalCursorPos); + + // Calculate cursor position relative to primary occurrence + int cursorInWord = callback.getCursorPosition() - primaryOccurrenceStart; + cursorInWord = Math.max(0, Math.min(cursorInWord, currentWord.length())); + int newCursorPos = primaryOccurrenceStart + cursorInWord; + + resetState(); + + callback.focusMainEditor(); + callback.setCursorPosition(Math.max(0, newCursorPos)); + } + + private void resetState() { + active = false; + initialWord = ""; + originalWord = ""; + currentWord = ""; + primaryOccurrenceStart = -1; + primaryOccurrenceEnd = -1; + 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) { + if (!active || callback == null) + return false; + + // ESC - cancel + if (keyCode == Keyboard.KEY_ESCAPE) { + cancel(); + return true; + } + + // Enter - confirm + if (keyCode == Keyboard.KEY_RETURN) { + confirm(); + return true; + } + + // Tab - confirm and move on + if (keyCode == Keyboard.KEY_TAB) { + confirm(); + return true; + } + + // 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())); + + // Backspace + if (keyCode == Keyboard.KEY_BACK) { + if (hasSelection || GuiScreen.isCtrlKeyDown()) { + // Delete selected text (entire word if fully selected) + currentWord = ""; + applyLiveRename(); + sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart); + callback.setCursorPosition(primaryOccurrenceStart); + } else if (cursorInWord > 0) { + String before = currentWord.substring(0, cursorInWord - 1); + String after = currentWord.substring(cursorInWord); + currentWord = before + after; + applyLiveRename(); + // Update cursor after the text change + callback.setCursorPosition(primaryOccurrenceStart + cursorInWord - 1); + } + sel.markActivity(); + return true; + } + + // Delete + if (keyCode == Keyboard.KEY_DELETE) { + if (hasSelection) { + // Delete selected text (entire word if fully selected) + currentWord = ""; + applyLiveRename(); + sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart); + callback.setCursorPosition(primaryOccurrenceStart); + } else if (cursorInWord < currentWord.length()) { + String before = currentWord.substring(0, cursorInWord); + String after = currentWord.substring(cursorInWord + 1); + currentWord = before + after; + applyLiveRename(); + } + sel.markActivity(); + return true; + } + + // Backspace + if (keyCode == Keyboard.KEY_SPACE && hasSelection) { + // Delete selected text (entire word if fully selected) + currentWord = ""; + applyLiveRename(); + sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart); + callback.setCursorPosition(primaryOccurrenceStart); + } + + // Left arrow + if (keyCode == Keyboard.KEY_LEFT) { + if (cursorInWord > 0) { + callback.setCursorPosition(primaryOccurrenceStart + cursorInWord - 1); + sel.setSelection(0, 0); // Clear selection + } + sel.markActivity(); + return true; + } + + // Right arrow + if (keyCode == Keyboard.KEY_RIGHT) { + if (cursorInWord < currentWord.length()) { + callback.setCursorPosition(primaryOccurrenceStart + cursorInWord + 1); + sel.setSelection(0, 0); // Clear selection + } + sel.markActivity(); + return true; + } + + // Home + if (keyCode == Keyboard.KEY_HOME) { + callback.setCursorPosition(primaryOccurrenceStart); + sel.setSelection(0, 0); // Clear selection + sel.markActivity(); + return true; + } + + // End + if (keyCode == Keyboard.KEY_END) { + callback.setCursorPosition(primaryOccurrenceStart + currentWord.length()); + sel.setSelection(0, 0); // Clear selection + sel.markActivity(); + return true; + } + + // Ctrl+A - select all (select the whole word) + if (keyCode == Keyboard.KEY_A && + Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) { + sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart + currentWord.length()); + callback.setCursorPosition(primaryOccurrenceStart + currentWord.length()); + sel.markActivity(); + return true; + } + + // Character input - only valid identifier characters + boolean isFirstChar = hasSelection || (currentWord.isEmpty() && cursorInWord == 0); + if (isValidIdentifierChar(c, isFirstChar)) { + if (hasSelection) { + // Replace entire selection with this character + currentWord = "" + c; + applyLiveRename(); + callback.setCursorPosition(primaryOccurrenceStart + 1); + sel.setSelection(0, 0); // Clear selection + } else { + String before = currentWord.substring(0, cursorInWord); + String after = currentWord.substring(cursorInWord); + currentWord = before + c + after; + applyLiveRename(); + callback.setCursorPosition(primaryOccurrenceStart + cursorInWord + 1); + } + sel.markActivity(); + return true; + } + + // Block other input while in rename mode + return true; + } + + /** + * Check if string is a valid identifier + */ + private boolean isValidIdentifier(String s) { + if (s == null || s.isEmpty()) + return false; + return IDENTIFIER.matcher(s).matches(); + } + + /** + * Check if character is valid for an identifier + */ + private boolean isValidIdentifierChar(char c, boolean isFirst) { + if (isFirst) { + return Character.isLetter(c) || c == '_'; + } + return Character.isLetterOrDigit(c) || c == '_'; + } + + /** + * Apply rename changes live as user types (without creating undo entries) + */ + private void applyLiveRename() { + if (callback == null) + return; + + String text = callback.getText(); + + // Calculate new primary position after rename + int occurrencesBefore = 0; + for (int[] occ : allOccurrences) { + if (occ[0] < primaryOccurrenceStart) { + occurrencesBefore++; + } + } + int lengthDiff = currentWord.length() - originalWord.length(); + int newPrimaryStart = primaryOccurrenceStart + (occurrencesBefore * lengthDiff); + + // If the current typed word is empty, do NOT modify the document's other occurrences. + // We treat empty as a temporary state: preserve the editor text and the previously + // discovered occurrences so they will re-appear when the user types again. + if (currentWord.isEmpty()) { + // Keep the text unchanged and preserve allOccurrences (do not clear). + callback.setTextWithoutUndo(text); + // Keep originalWord as the last non-empty word so length calculations remain correct + // and place the caret at the primary position for editing. + setSelection(newPrimaryStart, newPrimaryStart); + return; + } + + // Apply rename for non-empty currentWord + String newText = applyRename(text, currentWord); + callback.setTextWithoutUndo(newText); // Don't create undo entry for each keystroke + + // Update tracking for current word (only when non-empty) + originalWord = currentWord; + + // Recalculate occurrences based on the new word + findOccurrences(newText, currentWord); + + // Update primary occurrence tracking + if (!allOccurrences.isEmpty()) { + for (int[] occ : allOccurrences) { + if (Math.abs(occ[0] - newPrimaryStart) < 2) { + setSelection(occ[0], occ[1]); + break; + } + } + } else if (currentWord.isEmpty()) { + // Keep tracking the position even when empty + setSelection(newPrimaryStart, newPrimaryStart); + } + } + + private void setSelection(int start, int end) { + primaryOccurrenceStart = start; + primaryOccurrenceEnd = end; + if (callback != null) + callback.getSelectionState().setSelection(start, end); + } + + /** + * Update occurrence positions when word is empty (for visual tracking) + */ + private void updateOccurrencePositionsForEmpty(int newPrimaryStart) { + // No-op: we preserve the previously discovered occurrences while the user + // temporarily clears the rename box. Clearing occurrences here caused them + // to be removed from the document during live-editing. Rendering will use + // primary occurrence position set by setSelection(). + // Intentionally left blank. + } + + /** + * Apply rename to all occurrences in text + */ + private String applyRename(String text, String newName) { + if (allOccurrences.isEmpty()) + return text; + + StringBuilder result = new StringBuilder(); + int lastEnd = 0; + + // Sort occurrences by position + List sorted = new ArrayList<>(allOccurrences); + sorted.sort((a, b) -> Integer.compare(a[0], b[0])); + + for (int[] occ : sorted) { + if (occ[0] >= lastEnd && occ[1] <= text.length()) { + result.append(text, lastEnd, occ[0]); + result.append(newName); // Append newName, even if empty (which deletes the occurrence) + lastEnd = occ[1]; + } + } + result.append(text.substring(lastEnd)); + + return result.toString(); + } + + /** + * Find all occurrences of the identifier within scope + */ + private void findOccurrences(String text, String word) { + allOccurrences.clear(); + + if (word.isEmpty() || scope == null) + return; + + // Get excluded ranges (strings and comments) + List excluded = MethodBlock.getExcludedRanges(text); + + Pattern pattern = Pattern.compile("\\b" + Pattern.quote(word) + "\\b"); + Matcher m = pattern.matcher(text); + + while (m.find()) { + int start = m.start(); + int end = m.end(); + + // Skip if in string or comment + if (isInExcludedRange(start, excluded)) + continue; + + // Check if within scope + if (scope.isGlobal) { + // For global scope, skip positions where local variables shadow the global + if (!isInLocalShadowedRange(start)) { + allOccurrences.add(new int[]{start, end}); + } + } else if (scope.containsPosition(start)) { + 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; + if (hasParamDecl) { + // Parameter scope starts at method start + scopeStart = method.startOffset; + } else { + // Local variable scope starts at declaration + 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()}); + } + } + } + } + } + + /** + * Check if a position is within a locally shadowed range + */ + private boolean isInLocalShadowedRange(int pos) { + for (int[] range : localShadowedPositions) { + if (pos >= range[0] && pos < range[1]) + return true; + } + 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)); + int parenStart = methodHeader.indexOf('('); + int parenEnd = methodHeader.indexOf(')'); + if (parenStart >= 0 && parenEnd > parenStart) { + String params = methodHeader.substring(parenStart + 1, parenEnd); + Pattern paramPattern = Pattern.compile("\\b" + Pattern.quote(varName) + "\\b"); + return paramPattern.matcher(params).find(); + } + return false; + } + + /** + * Check if position is in an excluded range + */ + private boolean isInExcludedRange(int pos, List ranges) { + for (int[] range : ranges) { + if (pos >= range[0] && pos < range[1]) + return true; + } + return false; + } + + /** + * Find word boundaries at a given position + */ + private int[] findWordAtPosition(String text, int pos) { + if (pos < 0 || pos > text.length()) + return null; + + // Find start of word + int start = pos; + while (start > 0 && isIdentifierChar(text.charAt(start - 1))) { + start--; + } + + // Find end of word + int end = pos; + while (end < text.length() && isIdentifierChar(text.charAt(end))) { + end++; + } + + if (start == end) + return null; + + // Validate it's a proper identifier + String word = text.substring(start, end); + if (!IDENTIFIER.matcher(word).matches()) + return null; + + return new int[]{start, end}; + } + + private boolean isIdentifierChar(char c) { + return Character.isLetterOrDigit(c) || c == '_'; + } + + /** + * Determine the scope for a variable at the given position. + * Key insight: Local variables shadow global variables within their scope. + * We need to check if the cursor is within the scope of a local declaration. + */ + private ScopeInfo determineScope(String text, int position, String varName, JavaTextContainer container) { + List methods = MethodBlock.collectMethodBlocks(text); + + // First, check if this is a global field declaration (outside any method) + boolean isGlobalField = isGlobalFieldDeclaration(text, varName, methods); + + // Check if cursor is outside all methods - definitely global scope + boolean insideMethod = false; + MethodBlock containingMethod = null; + for (MethodBlock method : methods) { + if (method.containsPosition(position)) { + insideMethod = true; + containingMethod = method; + break; + } + } + + if (!insideMethod || containingMethod == null) { + // Cursor is outside methods - must be global scope + return new ScopeInfo(0, text.length(), true, "global"); + } + + // 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)); + int parenStart = methodHeader.indexOf('('); + int parenEnd = methodHeader.indexOf(')'); + if (parenStart >= 0 && parenEnd > parenStart) { + String params = methodHeader.substring(parenStart + 1, parenEnd); + Pattern paramPattern = Pattern.compile("\\b" + Pattern.quote(varName) + "\\b"); + if (paramPattern.matcher(params).find()) { + // It's a parameter - scope to method + return new ScopeInfo(containingMethod.startOffset, containingMethod.endOffset, false, "parameter"); + } + } + + // Check if there's a local variable with this name in the method + if (containingMethod.localVariables.contains(varName)) { + // Find where the local variable is declared + int localDeclPosition = findLocalDeclarationPosition(text, varName, containingMethod); + + if (localDeclPosition >= 0 && position >= localDeclPosition) { + // Cursor is at or after the local declaration - this is the local variable + int[] blockBounds = findInnermostBlockWithDeclaration(text, position, varName, containingMethod); + if (blockBounds != null) { + return new ScopeInfo(blockBounds[0], blockBounds[1], false, "block"); + } + return new ScopeInfo(containingMethod.startOffset, containingMethod.endOffset, false, "local"); + } else if (isGlobalField) { + // Cursor is BEFORE the local declaration - must be referring to global + // This is the shadowing case + return new ScopeInfo(0, text.length(), true, "global"); + } + } + + // No local variable with this name - check if it's a global field + if (isGlobalField) { + return new ScopeInfo(0, text.length(), true, "global"); + } + + // Unknown variable - default to method scope as fallback + return new ScopeInfo(containingMethod.startOffset, containingMethod.endOffset, false, "method"); + } + + /** + * Check if a variable is declared as a global field (outside any method) + */ + private boolean isGlobalFieldDeclaration(String text, String varName, List methods) { + Matcher m = JavaTextContainer.GLOBAL_FIELD_DECL.matcher(text); + while (m.find()) { + if (m.group(2).equals(varName)) { + int pos = m.start(2); + // Verify it's not inside a method + boolean insideMethod = false; + for (MethodBlock method : methods) { + if (method.containsPosition(pos)) { + insideMethod = true; + break; + } + } + if (!insideMethod) { + return true; + } + } + } + return false; + } + + /** + * Find the position of the first local variable declaration with the given name + */ + private int findLocalDeclarationPosition(String text, String varName, MethodBlock method) { + // Pattern for local variable declaration: Type varName = or Type varName; + Pattern localDecl = Pattern.compile("\\b\\w+\\s+" + Pattern.quote(varName) + "\\s*[=;,)]"); + String methodText = text.substring(method.startOffset, Math.min(method.endOffset, text.length())); + Matcher m = localDecl.matcher(methodText); + + // Skip past the method header (parameters) to find true local declarations + int bodyStart = methodText.indexOf('{'); + if (bodyStart < 0) + bodyStart = 0; + + while (m.find()) { + if (m.start() >= bodyStart) { + return method.startOffset + m.start(); + } + } + return -1; + } + + /** + * Find the innermost brace block that contains both the position and a declaration of varName + */ + private int[] findInnermostBlockWithDeclaration(String text, int position, String varName, MethodBlock method) { + List excluded = MethodBlock.getExcludedRanges(text); + + // Find all brace blocks within the method + List blocks = new ArrayList<>(); + List braceStack = new ArrayList<>(); + + for (int i = method.startOffset; i < method.endOffset && i < text.length(); i++) { + if (isInExcludedRange(i, excluded)) + continue; + + char c = text.charAt(i); + if (c == '{') { + braceStack.add(i); + } else if (c == '}') { + if (!braceStack.isEmpty()) { + int openPos = braceStack.remove(braceStack.size() - 1); + blocks.add(new int[]{openPos, i + 1}); + } + } + } + + // Find smallest block containing position that has a declaration of varName + int[] best = null; + int bestSize = Integer.MAX_VALUE; + + Pattern declPattern = Pattern.compile("\\b\\w+\\s+" + Pattern.quote(varName) + "\\s*[=;,)]"); + + for (int[] block : blocks) { + if (block[0] <= position && block[1] >= position) { + int size = block[1] - block[0]; + if (size < bestSize) { + // Check if this block contains a declaration of varName + String blockText = text.substring(block[0], Math.min(block[1], text.length())); + if (declPattern.matcher(blockText).find()) { + best = block; + bestSize = size; + } + } + } + } + + return best; + } + + // ==================== RENDERING ==================== + + /** + * Get all occurrences for rendering highlights + */ + public List getOccurrences() { + return allOccurrences; + } + + /** + * Get primary occurrence (the one under cursor when rename started) + */ + public int[] getPrimaryOccurrence() { + if (!active) + return null; + return new int[]{primaryOccurrenceStart, primaryOccurrenceEnd}; + } + + /** + * Check if a given occurrence is the primary one + */ + public boolean isPrimaryOccurrence(int start) { + return start == primaryOccurrenceStart; + } + + /** + * Get cursor position within the rename word for rendering + */ + public int getCursorInWord() { + if (callback == null) return 0; + int cursorPos = callback.getCursorPosition(); + return Math.max(0, Math.min(cursorPos - primaryOccurrenceStart, currentWord.length())); + } + + /** + * Check if word is fully selected (for visual rendering) + */ + public boolean isWordFullySelected() { + if (callback == null) return false; + SelectionState selection = callback.getSelectionState(); + return selection.hasSelection() && + selection.getStartSelection() == primaryOccurrenceStart && + selection.getEndSelection() == primaryOccurrenceEnd; + } + + /** + * Get the current word being renamed + */ + public String getCurrentWord() { + return currentWord; + } + + // ==================== MOUSE HANDLING ==================== + + /** + * Handle mouse click within the rename box area. + * + * @param clickPosInText The text position where the click occurred + * @return true if the click was within the primary occurrence box, false otherwise + */ + public boolean handleClick(int clickPosInText) { + if (!active || callback == null) + return false; + + return false; + } + + /** + * Check if a text position is within the primary rename occurrence + */ + public boolean isPositionInPrimaryOccurrence(int pos) { + if (!active) + return false; + return pos >= primaryOccurrenceStart && pos <= primaryOccurrenceEnd; + } + + // ==================== STATUS ==================== + + public boolean isActive() { + return active; + } + + /** + * @deprecated Use GuiScriptTextArea's cursor rendering instead + */ + public void updateCursor() { + // No-op - cursor is now handled by GuiScriptTextArea + } + + /** + * Check if cursor should be visible based on blink timing. + * Uses SelectionState's recent input check. + */ + public boolean shouldShowCursor() { + if (callback != null) { + return callback.getSelectionState().hadRecentInput(); + } + return true; + } + + /** + * Get scope type description for status display + */ + public String getScopeDescription() { + if (scope == null) + return ""; + switch (scope.scopeType) { + case "global": + return "Renaming in file (" + allOccurrences.size() + " occurrences)"; + case "parameter": + return "Renaming parameter (" + allOccurrences.size() + " occurrences)"; + case "local": + return "Renaming local variable (" + allOccurrences.size() + " occurrences)"; + case "method": + return "Renaming in method (" + allOccurrences.size() + " occurrences)"; + case "block": + return "Renaming in block (" + allOccurrences.size() + " occurrences)"; + default: + return "Renaming (" + allOccurrences.size() + " occurrences)"; + } + } + + /** + * Get number of occurrences that will be renamed + */ + public int getOccurrenceCount() { + return allOccurrences.size(); + } + + public void drawStatusBox() { + // String status = renameHandler.getScopeDescription(); + // String hint = "Enter \u2713 | Esc \u2715"; // Enter to confirm, Esc to cancel + // int statusWidth = Math.max(ClientProxy.Font.width(status), ClientProxy.Font.width(hint)) + 8; + // int statusX = x + width - statusWidth - 8; + // int statusY = y + height - 30; + // // Semi-transparent background + // drawRect(statusX - 2, statusY - 2, statusX + statusWidth + 2, statusY + 24, 0xDD1a1a2e); + // // Border (purple/blue for rename mode) + // int borderColor = 0xFF6677dd; + // drawRect(statusX - 2, statusY - 2, statusX + statusWidth + 2, statusY - 1, borderColor); + // drawRect(statusX - 2, statusY + 23, statusX + statusWidth + 2, statusY + 24, borderColor); + // drawRect(statusX - 2, statusY - 2, statusX - 1, statusY + 24, borderColor); + // drawRect(statusX + statusWidth + 1, statusY - 2, statusX + statusWidth + 2, statusY + 24, borderColor); + // // Status text (top line) + // ClientProxy.Font.drawString(status, statusX + 4, statusY + 2, 0xFFccddff); + // // Hint text (bottom line - dimmer) + // ClientProxy.Font.drawString(hint, statusX + 4, statusY + 13, 0xAA88aacc); + } +} 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 new file mode 100644 index 000000000..f8c92d64a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/ScrollState.java @@ -0,0 +1,213 @@ +package noppes.npcs.client.gui.util.script; + +import org.lwjgl.input.Mouse; + +/** + * Manages smooth scrolling state and animation for the script text area. + * Uses exponential smoothing for fluid scroll animations. + */ +public class ScrollState { + // Current fractional scroll position (in lines) + private double scrollPos = -1.0; + // Target scroll position to animate towards + private double targetScroll = 0.0; + // Current scroll velocity for momentum calculations + private double scrollVelocity = 0.0; + // Last timestamp for delta time calculation + private long lastScrollTime = 0L; + // First visible line + private int scrolledLine = 0; + // Scrollbar drag offset when dragging thumb + private int scrollbarDragOffset = 0; + // Whether currently dragging the scrollbar + private boolean clickScrolling = false; + + // Animation parameters + private static final double TAU = 0.15; // Time constant (~55ms feels snappy) + private static final double SNAP_THRESHOLD = 0.1; // Snap to target when this close (increased to avoid microstutters) + private static final double MAX_DT = 0.1; // Max delta time for stability + + /** + * Reset scroll state to initial values + */ + public void reset() { + scrollPos = 0.0; + targetScroll = 0.0; + scrollVelocity = 0.0; + scrolledLine = 0; + lastScrollTime = System.currentTimeMillis(); + } + + /** + * Initialize scroll position if not already initialized + */ + public void initializeIfNeeded(int currentLine) { + if (scrollPos < 0) { + scrollPos = currentLine; + 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; + scrollVelocity = 0.0; + } else { + // Exponential smoothing + double alpha = 1.0 - Math.exp(-dt / Math.max(1e-6, TAU)); + 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 + */ + public void clampToBounds(int maxScroll) { + if (scrollPos < 0) scrollPos = 0; + if (scrollPos > maxScroll) scrollPos = maxScroll; + if (targetScroll < 0) targetScroll = 0; + 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 + */ + 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 visibleLines Number of visible lines in viewport + * @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; + } else if (lineIdx > lastFullyVisible) { + // Line is below viewport - scroll down + targetScroll = Math.min(lineIdx - visibleLines, maxScroll); + } + // If line is visible, don't change scroll + } + + // Getters + public double getScrollPos() { return scrollPos; } + public double getTargetScroll() { return targetScroll; } + + /** @return First visible line **/ + public int getScrolledLine() { + return scrolledLine; + } + 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; } + + /** + * 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 visibleLines number of visible lines in viewport + * @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 + setClickScrolling(Mouse.isButtonDown(0)); + int diff = Math.max(0, linesCount - visibleLines); + if (diff > 0) { + int sbSize = Math.max((int) (1f * visibleLines / Math.max(1, linesCount) * areaHeight), 2); + int trackTop = areaY + 1; + int trackHeight = Math.max(1, areaHeight - 4); + int thumbRange = Math.max(1, trackHeight - sbSize); + double linesCountD = Math.max(1, (double) linesCount); + int thumbTop = (int) (areaY + 1f * getScrollPos() / linesCountD * (areaHeight - 4)) + 1; + + if (yMouse < thumbTop || yMouse > thumbTop + sbSize) { + double centerRatio = (double) (yMouse - trackTop) / (double) trackHeight; + centerRatio = Math.max(0.0, Math.min(1.0, centerRatio)); + setTargetScroll(centerRatio * diff, maxScroll); + setScrollbarDragOffset(sbSize / 2); + } else { + int desiredTop = yMouse - getScrollbarDragOffset(); + desiredTop = Math.max(trackTop, Math.min(trackTop + thumbRange, desiredTop)); + double ratio = (double) (desiredTop - trackTop) / (double) thumbRange; + ratio = Math.max(0.0, Math.min(1.0, ratio)); + setTargetScroll(ratio * diff, maxScroll); + } + } + if (!isClickScrolling()) { + setScrollbarDragOffset(0); + } + } + + /** + * Attempt to start a scrollbar drag if the mouse down occurred on the scrollbar thumb area. + * Returns true if drag was initiated (caller should cancel normal text-click drag behavior). + */ + public void startScrollbarDrag(int yMouse, int areaY, int areaHeight, int linesCount) { + // Thumb width in GuiScriptTextArea is 6px (posX..posX+5), so check clicks near the right edge + // Start click-scrolling mode and set initial drag offset relative to thumb top. + setClickScrolling(true); + double linesCountD = Math.max(1, (double) linesCount); + 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 new file mode 100644 index 000000000..5e783d227 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/SearchReplaceBar.java @@ -0,0 +1,1382 @@ +package noppes.npcs.client.gui.util.script; + +import net.minecraft.client.Minecraft; +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; +import noppes.npcs.util.ValueUtil; +import org.lwjgl.input.Keyboard; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Search and Replace bar component for the script editor. + * Provides IntelliJ-like search functionality with: + * - Search text field with rounded edges + * - Match case (Cc) toggle + * - Whole word (W) toggle + * - Previous/Next match navigation + * - Replace functionality with Replace/Replace All/Exclude buttons + * - Auto-scroll to matches + * - All matches highlighting + */ +public class SearchReplaceBar { + + // ==================== TEXTURE ==================== + public static final ResourceLocation TEXTURE = OverlayKeyPresetViewer.TEXTURE; + + // ==================== DIMENSIONS ==================== + private int x, y, width; + public GuiNPCInterface ownerGui; + private int barHeight = 24; + private int replaceBarHeight = 22; + private int textFieldWidth = 150; + private int textFieldHeight = 16; + private int buttonSize = 16; + private int buttonSpacing = 2; + private int padding = 4; + + // ==================== STATE ==================== + private boolean visible = false; + private boolean showReplace = false; + private boolean searchFieldFocused = true; + private boolean replaceFieldFocused = false; + + // ==================== SEARCH OPTIONS ==================== + private boolean matchCase = false; + private boolean wholeWord = false; + + // ==================== TEXT FIELDS ==================== + private String searchText = ""; + private String replaceText = ""; + private int searchCursor = 0; + private int replaceCursor = 0; + private int searchSelectionStart = 0; + private int searchSelectionEnd = 0; + private int replaceSelectionStart = 0; + private int replaceSelectionEnd = 0; + // Text scroll offsets for when text exceeds field width + private int searchScrollOffset = 0; + private int replaceScrollOffset = 0; + + // ==================== UNDO/REDO ==================== + private List searchUndoList = new ArrayList<>(); + private List searchRedoList = new ArrayList<>(); + private List replaceUndoList = new ArrayList<>(); + private List replaceRedoList = new ArrayList<>(); + + // ==================== MATCHES ==================== + private List matches = new ArrayList<>(); + private int currentMatchIndex = -1; + private List excludedMatches = new ArrayList<>(); + + // ==================== HOVER STATE ==================== + private boolean hoverClose = false; + private boolean hoverSearchUnwind = false; + private boolean hoverMatchCase = false; + private boolean hoverWholeWord = false; + private boolean hoverPrev = false; + private boolean hoverNext = false; + private boolean hoverReplace = false; + private boolean hoverReplaceAll = false; + private boolean hoverExclude = false; + + // ==================== CURSOR BLINK ==================== + private int cursorCounter = 0; + private long lastInputTime = 0; // For cursor blink pause on activity + + // ==================== DOUBLE/TRIPLE CLICK ==================== + private long lastClickTime = 0; + private int clickCount = 0; + private boolean lastClickWasSearch = true; + + // ==================== CALLBACK ==================== + public SearchCallback callback; + + private final FontRenderer font = Minecraft.getMinecraft().fontRenderer; + + /** + * Callback interface for search/replace operations + */ + public interface SearchCallback { + String getText(); + + String getHighlightedWord(); + + // Return current selection bounds in the main editor (start inclusive, end exclusive) + int getSelectionStart(); + + int getSelectionEnd(); + + void setText(String text); + + void scrollToPosition(int position); + + void setSelection(int start, int end); + + int getGutterWidth(); + + void unfocusMainEditor(); + + void focusMainEditor(); + + void onMatchesUpdated(); // Called when matches change (for undo/redo sync) + + void resizeEditor(boolean open, int barHeight); + } + + public SearchReplaceBar() { + } + + public void setCallback(SearchCallback callback) { + this.callback = callback; + } + + /** + * Initialize bar position based on text area bounds. + * Preserves existing state (search text, matches, etc.) across initGui calls. + */ + public void initGui(int textAreaX, int textAreaY, int textAreaWidth) { + this.x = textAreaX; + this.y = textAreaY; + this.width = textAreaWidth; + // State is preserved - don't reset searchText, matches, visible, etc. + } + + public void open() { + boolean oldVisible = this.visible; + boolean matchHighlight = false; + visible = true; + if (callback != null) { + // Always notify callback that the search UI is open and provide its current height. + callback.resizeEditor(true, getTotalHeight()); + callback.unfocusMainEditor(); + + String highlight = callback.getHighlightedWord(); + if (highlight != null) { + searchText = highlight; + matchHighlight = true; + } + } + + searchSelectionStart = 0; + searchSelectionEnd = searchText.length(); + searchCursor = searchText.length(); + markActivity(); + updateMatches(); + if (matchHighlight) { + setCurrentMatchToHighlight(); + navigateToCurrentMatch(); + } + } + + /** + * Open search bar (Ctrl+R) + */ + public void openSearch() { + showReplace = false; + searchFieldFocused = true; + replaceFieldFocused = false; + open(); + + } + + /** + * Open search+replace bar (Ctrl+Shift+R) + */ + public void openSearchReplace() { + showReplace = true; //both for window resize properly + searchFieldFocused = false; + replaceFieldFocused = true; + open(); + } + + /** + * Close the search bar and restore focus to main editor + */ + public void close() { + if (callback != null) { + // When closing, signal closed and height 0 + callback.resizeEditor(false, 0); + callback.focusMainEditor(); + } + visible = false; + searchFieldFocused = false; + replaceFieldFocused = false; + } + + public void focus(boolean replace) { + if (replace) + replaceFieldFocused = true; + else + searchFieldFocused = true; + } + + /** + * Unfocus the search bar (when clicking main editor) + */ + public void unfocus() { + searchFieldFocused = false; + replaceFieldFocused = false; + } + + /** + * Save current state to undo list before making changes + */ + private void saveState(boolean isSearchField) { + if (isSearchField) { + searchUndoList.add(new UndoData(searchText, searchCursor)); + searchRedoList.clear(); // Clear redo on new change + } else { + replaceUndoList.add(new UndoData(replaceText, replaceCursor)); + replaceRedoList.clear(); + } + } + + /** + * Undo last change in focused field + */ + public void undo() { + if (searchFieldFocused && !searchUndoList.isEmpty()) { + UndoData data = searchUndoList.remove(searchUndoList.size() - 1); + searchRedoList.add(new UndoData(searchText, searchCursor)); + searchText = data.text; + searchCursor = data.cursorPosition; + searchSelectionStart = searchCursor; + searchSelectionEnd = searchCursor; + updateScrollOffset(true); + updateMatches(); + } else if (replaceFieldFocused && !replaceUndoList.isEmpty()) { + UndoData data = replaceUndoList.remove(replaceUndoList.size() - 1); + replaceRedoList.add(new UndoData(replaceText, replaceCursor)); + replaceText = data.text; + replaceCursor = data.cursorPosition; + replaceSelectionStart = replaceCursor; + replaceSelectionEnd = replaceCursor; + updateScrollOffset(false); + } + } + + /** + * Redo last undone change in focused field + */ + public void redo() { + if (searchFieldFocused && !searchRedoList.isEmpty()) { + UndoData data = searchRedoList.remove(searchRedoList.size() - 1); + searchUndoList.add(new UndoData(searchText, searchCursor)); + searchText = data.text; + searchCursor = data.cursorPosition; + searchSelectionStart = searchCursor; + searchSelectionEnd = searchCursor; + updateScrollOffset(true); + updateMatches(); + } else if (replaceFieldFocused && !replaceRedoList.isEmpty()) { + UndoData data = replaceRedoList.remove(replaceRedoList.size() - 1); + replaceUndoList.add(new UndoData(replaceText, replaceCursor)); + replaceText = data.text; + replaceCursor = data.cursorPosition; + replaceSelectionStart = replaceCursor; + replaceSelectionEnd = replaceCursor; + updateScrollOffset(false); + } + } + + /** + * Update scroll offset for text field to keep cursor visible + */ + private void updateScrollOffset(boolean isSearchField) { + int fieldWidth = textFieldWidth - 8; + String text = isSearchField ? searchText : replaceText; + int cursor = isSearchField ? searchCursor : replaceCursor; + String beforeCursor = cursor > 0 ? text.substring(0, cursor) : ""; + int cursorX = font.getStringWidth(beforeCursor); + int scrollOffset = isSearchField ? searchScrollOffset : replaceScrollOffset; + + // Scroll to keep cursor visible + if (cursorX - scrollOffset * 6 > fieldWidth) { + scrollOffset = Math.max(0, cursor - fieldWidth / 6); + } else if (cursor < scrollOffset) { + scrollOffset = cursor; + } + + if (isSearchField) { + searchScrollOffset = scrollOffset; + } else { + replaceScrollOffset = scrollOffset; + } + } + + /** + * Toggle visibility + */ + public void toggle() { + if (visible && !showReplace) { + close(); + } else { + openSearch(); + } + } + + /** + * Toggle replace mode + */ + public void toggleReplace() { + if (visible && showReplace) { + close(); + } else { + openSearchReplace(); + } + } + + public boolean isVisible() { + return visible; + } + + public boolean isSearchFocused() { + return visible && searchFieldFocused; + } + + public boolean isReplaceFocused() { + return visible && replaceFieldFocused; + } + + public boolean hasFocus() { + return visible && (searchFieldFocused || replaceFieldFocused); + } + + /** + * Get total height of the bar (for viewport offset) + */ + public int getTotalHeight() { + if (!visible) return 0; + return showReplace ? barHeight + replaceBarHeight : barHeight; + } + + /** + * Get all current matches for highlighting + */ + public List getMatches() { + return matches; + } + + /** + * Get current match index + */ + public int getCurrentMatchIndex() { + return currentMatchIndex; + } + + /** + * Check if a match is excluded + */ + public boolean isMatchExcluded(int index) { + return excludedMatches.contains(index); + } + + /** + * Update cursor blink counter + */ + public void updateCursor() { + cursorCounter++; + } + + /** + * Mark activity to pause cursor blinking + */ + private void markActivity() { + lastInputTime = System.currentTimeMillis(); + } + + /** + * Check if there was recent input (cursor stays visible during typing) + */ + private boolean hadRecentInput() { + return System.currentTimeMillis() - lastInputTime < 500; + } + + /** + * Check if cursor should be visible (solid during typing, blinking otherwise) + */ + private boolean shouldShowCursor() { + return hadRecentInput() || (cursorCounter / 10) % 2 == 0; + } + + // ==================== DRAWING ==================== + + /** + * Draw the search/replace bar + */ + public void draw(int mouseX, int mouseY) { + if (!visible) return; + + updateHoverStates(mouseX, mouseY); + + int totalHeight = getTotalHeight(); + Gui.drawRect(x, y, x + width, y + totalHeight, 0xFF2d2d30); + Gui.drawRect(x, y + totalHeight - 1, x + width, y + totalHeight, 0xFF414141); + + drawSearchRow(mouseX, mouseY); + + if (showReplace) { + drawReplaceRow(mouseX, mouseY); + } + } + + private void drawSearchRow(int mouseX, int mouseY) { + int rowY = y + padding; + int currentX = x + padding; + textFieldWidth = 100; + drawTextField(currentX, rowY, textFieldWidth, textFieldHeight, + searchText, searchCursor, searchSelectionStart, searchSelectionEnd, + searchFieldFocused, "Search...", searchScrollOffset, true); + currentX += textFieldWidth + buttonSpacing + 4; + + // "0 results" in red, otherwise "X/Y" in normal color + String matchInfo = matches.isEmpty() ? "0 results" : + (currentMatchIndex + 1) + "/" + matches.size(); + int matchInfoWidth = font.getStringWidth(matchInfo); + font.drawString(matchInfo, currentX, rowY + 4, + matches.isEmpty() && !searchText.isEmpty() ? 0xFFff6666 : 0xFFcccccc); + currentX += matchInfoWidth + 8; + drawToggleButton(currentX, rowY, "Cc", matchCase, hoverMatchCase, "Match Case"); + currentX += buttonSize + buttonSpacing; + + drawToggleButton(currentX, rowY, "W", wholeWord, hoverWholeWord, "Whole Word"); + currentX += buttonSize + buttonSpacing + 4; + + boolean prevEnabled = !matches.isEmpty(); + drawNavButton(currentX, rowY, "▲", prevEnabled, hoverPrev); + currentX += buttonSize + buttonSpacing; + + boolean nextEnabled = !matches.isEmpty(); + drawNavButton(currentX, rowY, "▼", nextEnabled, hoverNext); + currentX += buttonSize + buttonSpacing; + + int closeX = x + width - buttonSize - padding; + drawCloseButton(closeX, rowY, hoverClose); + + int replaceUnwindButton = closeX - buttonSize - buttonSpacing; + drawActionButton(replaceUnwindButton, rowY, showReplace ? "▼" : "◀", hoverSearchUnwind, true); + } + + private void drawReplaceRow(int mouseX, int mouseY) { + int rowY = y + barHeight + 2; + int currentX = x + padding; + + drawTextField(currentX, rowY, textFieldWidth, textFieldHeight, + replaceText, replaceCursor, replaceSelectionStart, replaceSelectionEnd, + replaceFieldFocused, "Replace...", replaceScrollOffset, false); + currentX += textFieldWidth + buttonSpacing + 4; + + drawActionButton(currentX, rowY, "Replace", hoverReplace, !matches.isEmpty()); + currentX += font.getStringWidth("Replace") + 12 + buttonSpacing; + + drawActionButton(currentX, rowY, "Replace All", hoverReplaceAll, !matches.isEmpty()); + currentX += font.getStringWidth("Replace All") + 12 + buttonSpacing; + + drawActionButton(currentX, rowY, "Exclude", hoverExclude, currentMatchIndex >= 0); + } + + private void drawTextField(int fieldX, int fieldY, int fieldWidth, int fieldHeight, + String text, int cursor, int selStart, int selEnd, + boolean focused, String placeholder, int scrollOffset, boolean isSearchField) { + // Draw text field background + Gui.drawRect(fieldX, fieldY, fieldX + fieldWidth, fieldY + fieldHeight, 0xFF1e1e1e); + Gui.drawRect(fieldX, fieldY, fieldX + fieldWidth, fieldY + 1, focused ? 0xFF007acc : 0xFF3c3c3c); + Gui.drawRect(fieldX, fieldY + fieldHeight - 1, fieldX + fieldWidth, fieldY + fieldHeight, + focused ? 0xFF007acc : 0xFF3c3c3c); + Gui.drawRect(fieldX, fieldY, fieldX + 1, fieldY + fieldHeight, focused ? 0xFF007acc : 0xFF3c3c3c); + Gui.drawRect(fieldX + fieldWidth - 1, fieldY, fieldX + fieldWidth, fieldY + fieldHeight, + focused ? 0xFF007acc : 0xFF3c3c3c); + + // Calculate visible area + int textX = fieldX + 4; + int textY = fieldY + (fieldHeight - 8) / 2; + int visibleWidth = fieldWidth - 8; + + // Apply scroll offset + String visibleText = text; + int adjustedSelStart = selStart; + int adjustedSelEnd = selEnd; + + if (scrollOffset > 0 && scrollOffset < text.length()) { + visibleText = text.substring(scrollOffset); + adjustedSelStart = Math.max(0, selStart - scrollOffset); + adjustedSelEnd = Math.max(0, selEnd - scrollOffset); + } + + // Draw selection highlight + if (adjustedSelStart != adjustedSelEnd) { + int minSel = Math.min(adjustedSelStart, adjustedSelEnd); + int maxSel = Math.max(adjustedSelStart, adjustedSelEnd); + String beforeSel = visibleText.substring(0, Math.min(minSel, visibleText.length())); + String inSel = visibleText.substring(Math.min(minSel, visibleText.length()), + Math.min(maxSel, visibleText.length())); + int selX = textX + font.getStringWidth(beforeSel); + int selW = font.getStringWidth(inSel); + Gui.drawRect(selX, textY - 1, selX + selW, textY + 9, 0xFF264f78); + } + + int cursorPosX = font.getStringWidth(text.substring(0, Math.min(cursor, text.length()))); + if (cursorPosX - scrollOffset > visibleWidth - 2) { + scrollOffset = cursorPosX - visibleWidth + 2; + } else if (cursorPosX - scrollOffset < 0) { + scrollOffset = Math.max(0, cursorPosX); + } + // Update stored scroll offset + if (isSearchField) { + searchScrollOffset = scrollOffset; + } else { + replaceScrollOffset = scrollOffset; + } + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GuiUtil.setScissorClip(fieldX + 2, fieldY, fieldWidth - 4, fieldHeight, ownerGui); + + + // Draw selection highlight + if (selStart != selEnd && focused) { + int startX = textX + font.getStringWidth( + text.substring(0, Math.min(selStart, text.length()))) - scrollOffset; + int endX = textX + font.getStringWidth(text.substring(0, Math.min(selEnd, text.length()))) - scrollOffset; + Gui.drawRect(startX, textY - 1, endX, textY + font.FONT_HEIGHT, 0xFF2d5ca6); + } + + // Draw text with scroll offset + boolean noMatches = !text.isEmpty() && matches.isEmpty(); + int col = text.isEmpty() ? 0xFFa0a0a0 : 0xFFe0e0e0; + if (isSearchField && noMatches) + col = 0xFFff6666; // Red + + font.drawString(text.isEmpty() ? placeholder : text, textX - scrollOffset, textY, col); + + // Draw cursor (stays visible during typing) + if (focused && shouldShowCursor()) { + int cursorDrawX = textX + cursorPosX - scrollOffset; + Gui.drawRect(cursorDrawX, textY - 1, cursorDrawX + 1, textY + font.FONT_HEIGHT, 0xFFffffff); + } + + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + } + + private void oldDrawTextField(int fieldX, int fieldY, int fieldWidth, int fieldHeight, + String text, int cursor, int selStart, int selEnd, + boolean focused, String placeholder, int scrollOffset, boolean isSearchField) { + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE); + GL11.glPushMatrix(); + GL11.glColor4f(1, 1, 1, 1); + + float boxScaleX = fieldWidth / 32f, boxScaleY = 1.5f; + GL11.glScalef(boxScaleX, boxScaleY, 1); + + if (focused) { + GL11.glColor4f(0.28f, 0.45f, 0.7f, 1f); + } else { + GL11.glColor4f(0.33f, 0.33f, 0.33f, 1f); + } + GuiUtil.drawTexturedModalRect(fieldX / boxScaleX, (fieldY - 16) / boxScaleY, 32, 20, 0, 492); + GL11.glPopMatrix(); + + int textX = fieldX + 4; + int textY = fieldY + (fieldHeight - font.FONT_HEIGHT) / 2; + int visibleWidth = fieldWidth - 8; + + // Calculate scroll offset to keep cursor visible + int cursorPosX = font.getStringWidth(text.substring(0, Math.min(cursor, text.length()))); + if (cursorPosX - scrollOffset > visibleWidth - 2) { + scrollOffset = cursorPosX - visibleWidth + 2; + } else if (cursorPosX - scrollOffset < 0) { + scrollOffset = Math.max(0, cursorPosX); + } + // Update stored scroll offset + if (isSearchField) { + searchScrollOffset = scrollOffset; + } else { + replaceScrollOffset = scrollOffset; + } + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GuiUtil.setScissorClip(fieldX + 2, fieldY, fieldWidth - 4, fieldHeight, ownerGui); + + { + // Draw selection highlight + if (selStart != selEnd && focused) { + int startX = textX + font.getStringWidth(text.substring(0, Math.min(selStart, text.length()))) - scrollOffset; + int endX = textX + font.getStringWidth(text.substring(0, Math.min(selEnd, text.length()))) - scrollOffset; + Gui.drawRect(startX, textY - 1, endX, textY + font.FONT_HEIGHT, 0xFF2d5ca6); + } + + // Draw text with scroll offset + boolean noMatches = !text.isEmpty() && matches.isEmpty(); + int col = text.isEmpty() ? 0xFFa0a0a0 : 0xFFe0e0e0; + if (isSearchField && noMatches) + col = 0xFFff6666; // Red + + font.drawString(text.isEmpty() ? placeholder : text, textX - scrollOffset, textY, col); + + // Draw cursor (stays visible during typing) + if (focused && shouldShowCursor()) { + int cursorDrawX = textX + cursorPosX - scrollOffset; + Gui.drawRect(cursorDrawX, textY - 1, cursorDrawX + 1, textY + font.FONT_HEIGHT, 0xFFffffff); + } + } + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + } + + private void drawToggleButton(int btnX, int btnY, String label, boolean active, boolean hovered, String tooltip) { + int bgColor = active ? 0xFF4a6da7 : (hovered ? 0xFF505050 : 0xFF3c3c3c); + Gui.drawRect(btnX, btnY, btnX + buttonSize, btnY + buttonSize, bgColor); + Gui.drawRect(btnX, btnY, btnX + buttonSize, btnY + 1, 0xFF606060); + Gui.drawRect(btnX, btnY + buttonSize - 1, btnX + buttonSize, btnY + buttonSize, 0xFF2a2a2a); + + int textColor = active ? 0xFFffffff : (hovered ? 0xFFcccccc : 0xFF999999); + int labelWidth = font.getStringWidth(label); + font.drawString(label, btnX + (buttonSize - labelWidth) / 2, btnY + (buttonSize - font.FONT_HEIGHT) / 2 + 1, textColor); + } + + private void drawNavButton(int btnX, int btnY, String arrow, boolean enabled, boolean hovered) { + int bgColor = !enabled ? 0xFF393939 : (hovered ? 0xFF505050 : 0xFF3c3c3c); + Gui.drawRect(btnX, btnY, btnX + buttonSize, btnY + buttonSize, bgColor); + Gui.drawRect(btnX, btnY, btnX + buttonSize, btnY + 1, 0xFF606060); + + + int textColor = !enabled ? 0xFF555555 : (hovered ? 0xFFffffff : 0xFFaaaaaa); + int arrowWidth = font.getStringWidth(arrow); + font.drawString(arrow, btnX + (buttonSize - arrowWidth) / 2, btnY + (buttonSize - font.FONT_HEIGHT) / 2, textColor); + } + + private void drawCloseButton(int btnX, int btnY, boolean hovered) { + int bgColor = hovered ? 0xFFc75050 : 0xFF3c3c3c; + Gui.drawRect(btnX, btnY, btnX + buttonSize, btnY + buttonSize, bgColor); + + int textColor = hovered ? 0xFFffffff : 0xFFaaaaaa; + String xChar = "X"; + int xWidth = font.getStringWidth(xChar); + font.drawString(xChar, btnX + (buttonSize - xWidth) / 2, btnY + (buttonSize - font.FONT_HEIGHT) / 2 + 1, textColor); + } + + private void drawActionButton(int btnX, int btnY, String label, boolean hovered, boolean enabled) { + int btnWidth = font.getStringWidth(label) + 10; + int btnHeight = 14; + + int bgColor = !enabled ? 0xFF393939 : (hovered ? 0xFF505050 : 0xFF3c3c3c); + Gui.drawRect(btnX, btnY + 1, btnX + btnWidth, btnY + btnHeight + 1, bgColor); + Gui.drawRect(btnX, btnY + 1, btnX + btnWidth, btnY + 2, 0xFF555555); + Gui.drawRect(btnX, btnY + btnHeight, btnX + btnWidth, btnY + btnHeight + 1, 0xFF2a2a2a); + + int textColor = !enabled ? 0xFF555555 : (hovered ? 0xFFffffff : 0xFFaaaaaa); + font.drawString(label, btnX + 5, btnY + (btnHeight - font.FONT_HEIGHT) / 2 + 2, textColor); + } + + // ==================== HOVER DETECTION ==================== + + private void updateHoverStates(int mouseX, int mouseY) { + int rowY = y + padding; + int currentX = x + padding; + + int searchFieldEndX = currentX + textFieldWidth; + currentX = searchFieldEndX + buttonSpacing + 4; + + String matchInfo = matches.isEmpty() ? "0 results" : (currentMatchIndex + 1) + "/" + matches.size(); + currentX += font.getStringWidth(matchInfo) + 8; + + int matchCaseX = currentX; + hoverMatchCase = isMouseOver(mouseX, mouseY, matchCaseX, rowY, buttonSize, buttonSize); + currentX += buttonSize + buttonSpacing; + + int wholeWordX = currentX; + hoverWholeWord = isMouseOver(mouseX, mouseY, wholeWordX, rowY, buttonSize, buttonSize); + currentX += buttonSize + buttonSpacing + 4; + + int prevX = currentX; + hoverPrev = isMouseOver(mouseX, mouseY, prevX, rowY, buttonSize, buttonSize); + currentX += buttonSize + buttonSpacing; + + int nextX = currentX; + hoverNext = isMouseOver(mouseX, mouseY, nextX, rowY, buttonSize, buttonSize); + + int closeX = x + width - buttonSize - padding; + hoverClose = isMouseOver(mouseX, mouseY, closeX, rowY, buttonSize, buttonSize); + + int replaceUnwindButton = closeX - buttonSize - buttonSpacing; + hoverSearchUnwind = isMouseOver(mouseX, mouseY, replaceUnwindButton, rowY, buttonSize, buttonSize); + + if (showReplace) { + int replaceRowY = y + barHeight + 2; + currentX = x + padding + textFieldWidth + buttonSpacing + 4; + + int replaceWidth = font.getStringWidth("Replace") + 12; + hoverReplace = isMouseOver(mouseX, mouseY, currentX, replaceRowY + 1, replaceWidth, 14); + currentX += replaceWidth + buttonSpacing; + + int replaceAllWidth = font.getStringWidth("Replace All") + 12; + hoverReplaceAll = isMouseOver(mouseX, mouseY, currentX, replaceRowY + 1, replaceAllWidth, 14); + currentX += replaceAllWidth + buttonSpacing; + + int excludeWidth = font.getStringWidth("Exclude") + 12; + hoverExclude = isMouseOver(mouseX, mouseY, currentX, replaceRowY + 1, excludeWidth, 14); + } else { + hoverReplace = hoverReplaceAll = hoverExclude = false; + } + } + + private boolean isMouseOver(int mouseX, int mouseY, int bx, int by, int bw, int bh) { + return mouseX >= bx && mouseX < bx + bw && mouseY >= by && mouseY < by + bh; + } + + public void resetSelection() { + searchSelectionStart = searchSelectionEnd = searchCursor; + replaceSelectionStart = replaceSelectionEnd = replaceCursor; + } + // ==================== MOUSE INPUT ==================== + + /** + * Handle mouse click - supports double-click for word selection, triple-click for all + * + * @return true if click was consumed + */ + public boolean mouseClicked(int mouseX, int mouseY, int button) { + if (!visible) return false; + if (button != 0) return false; // Only handle left clicks + + int totalHeight = getTotalHeight(); + // If click is outside the bar, don't consume it (let main editor handle) + if (mouseX < x || mouseX > x + width || mouseY < y || mouseY > y + totalHeight) { + resetSelection(); + return false; + } + + int rowY = y + padding; + int currentX = x + padding; + + // Handle click timing for double/triple click + long now = System.currentTimeMillis(); + boolean isSearchFieldClick = isMouseOver(mouseX, mouseY, currentX, rowY - 2, textFieldWidth, textFieldHeight + 4); + boolean isReplaceFieldClick = showReplace && isMouseOver(mouseX, mouseY, x + padding, y + barHeight, textFieldWidth, textFieldHeight + 4); + + if ((isSearchFieldClick || isReplaceFieldClick) && callback != null) callback.unfocusMainEditor(); + + if (isSearchFieldClick) { + boolean sameField = lastClickWasSearch; + if (sameField && now - lastClickTime < 300) { + clickCount++; + } else { + clickCount = 1; + } + lastClickTime = now; + lastClickWasSearch = true; + + searchFieldFocused = true; + replaceFieldFocused = false; + markActivity(); + + if (clickCount == 1) { + // Single click - position cursor + int clickX = mouseX - currentX - 4 + searchScrollOffset; + searchCursor = getTextCursorPosition(searchText, clickX); + searchSelectionStart = searchSelectionEnd = searchCursor; + } else if (clickCount == 2) { + // Double click - select word + selectWordAt(searchText, getTextCursorPosition(searchText, mouseX - currentX - 4 + searchScrollOffset), true); + } else if (clickCount >= 3) { + // Triple click - select all + searchSelectionStart = 0; + searchSelectionEnd = searchText.length(); + searchCursor = searchText.length(); + clickCount = 0; + } + return true; + } + currentX += textFieldWidth + buttonSpacing + 4; + + String matchInfo = matches.isEmpty() ? "0 results" : (currentMatchIndex + 1) + "/" + matches.size(); + currentX += font.getStringWidth(matchInfo) + 8; + + if (hoverMatchCase) { + matchCase = !matchCase; + updateMatches(); + return true; + } + currentX += buttonSize + buttonSpacing; + + if (hoverWholeWord) { + wholeWord = !wholeWord; + updateMatches(); + return true; + } + currentX += buttonSize + buttonSpacing + 4; + + if (hoverPrev && !matches.isEmpty()) { + goToPreviousMatch(); + return true; + } + currentX += buttonSize + buttonSpacing; + + if (hoverNext && !matches.isEmpty()) { + goToNextMatch(); + return true; + } + + if (hoverClose) { + close(); + return true; + } + + if (hoverSearchUnwind) { + showReplace = !showReplace; + return true; + } + + if (showReplace) { + int replaceRowY = y + barHeight + 2; + + if (isReplaceFieldClick || isMouseOver(mouseX, mouseY, x + padding, replaceRowY - 2, textFieldWidth, textFieldHeight + 4)) { + // Handle click timing for replace field + boolean sameField = !lastClickWasSearch; + if (sameField && now - lastClickTime < 300) { + clickCount++; + } else { + clickCount = 1; + } + lastClickTime = now; + lastClickWasSearch = false; + + searchFieldFocused = false; + replaceFieldFocused = true; + markActivity(); + + if (clickCount == 1) { + int clickX = mouseX - x - padding - 4 + replaceScrollOffset; + replaceCursor = getTextCursorPosition(replaceText, clickX); + replaceSelectionStart = replaceSelectionEnd = replaceCursor; + } else if (clickCount == 2) { + selectWordAt(replaceText, getTextCursorPosition(replaceText, mouseX - x - padding - 4 + replaceScrollOffset), false); + } else if (clickCount >= 3) { + replaceSelectionStart = 0; + replaceSelectionEnd = replaceText.length(); + replaceCursor = replaceText.length(); + clickCount = 0; + } + return true; + } + + if (hoverReplace && !matches.isEmpty()) { + replaceCurrent(); + return true; + } + + if (hoverReplaceAll && !matches.isEmpty()) { + replaceAll(); + return true; + } + + if (hoverExclude && currentMatchIndex >= 0) { + excludeCurrentMatch(); + return true; + } + } + + // Click was within bar bounds but not on any control - consume it to prevent MTA from getting focus + return true; + } + + private int getTextCursorPosition(String text, int clickX) { + if (text.isEmpty() || clickX <= 0) return 0; + + for (int i = 1; i <= text.length(); i++) { + int w = font.getStringWidth(text.substring(0, i)); + if (clickX < w) { + int prevW = font.getStringWidth(text.substring(0, i - 1)); + return clickX < (prevW + w) / 2 ? i - 1 : i; + } + } + return text.length(); + } + + /** + * Select word at cursor position (for double-click) + */ + private void selectWordAt(String text, int pos, boolean isSearchField) { + if (text.isEmpty()) return; + + // Find word boundaries + int start = pos; + int end = pos; + + // Expand left + while (start > 0 && isWordChar(text.charAt(start - 1))) { + start--; + } + // Expand right + while (end < text.length() && isWordChar(text.charAt(end))) { + end++; + } + + if (isSearchField) { + searchSelectionStart = start; + searchSelectionEnd = end; + searchCursor = end; + } else { + replaceSelectionStart = start; + replaceSelectionEnd = end; + replaceCursor = end; + } + } + + private boolean isWordChar(char c) { + return Character.isLetterOrDigit(c) || c == '_'; + } + + // ==================== KEYBOARD INPUT ==================== + + /** + * Handle keyboard input + * + * @return true if input was consumed + */ + public boolean keyTyped(char c, int keyCode) { + if (keyCode == Keyboard.KEY_ESCAPE && visible) { + close(); + return true; + } + + if (!visible || (!searchFieldFocused && !replaceFieldFocused)) return false; + + // Check modifier keys - don't let them trigger first-match issue + boolean ctrl = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); + boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + boolean alt = Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU); + + // Ignore lone modifier key presses + if (keyCode == Keyboard.KEY_LCONTROL || keyCode == Keyboard.KEY_RCONTROL || + keyCode == Keyboard.KEY_LSHIFT || keyCode == Keyboard.KEY_RSHIFT || + keyCode == Keyboard.KEY_LMENU || keyCode == Keyboard.KEY_RMENU) { + return true; // Consume but don't process + } + + if (keyCode == Keyboard.KEY_TAB) { + if (showReplace) { + searchFieldFocused = !searchFieldFocused; + replaceFieldFocused = !replaceFieldFocused; + } else if (searchFieldFocused && callback != null) { + searchFieldFocused = false; + callback.focusMainEditor(); + } + markActivity(); + return true; + } + + // Enter/Shift+Enter for next/previous match + if (keyCode == Keyboard.KEY_RETURN) { + if (shift) { + // Shift+Enter = previous match + if (!matches.isEmpty()) { + goToPreviousMatch(); + } + } else if (replaceFieldFocused && !matches.isEmpty()) { + replaceCurrent(); + } else if (!matches.isEmpty()) { + goToNextMatch(); + } + return true; + } + + // Up/Down arrows cycle through matches when SRB is focused + if (keyCode == Keyboard.KEY_UP && !matches.isEmpty()) { + goToPreviousMatch(); + return true; + } + if (keyCode == Keyboard.KEY_DOWN && !matches.isEmpty()) { + goToNextMatch(); + return true; + } + + if (searchFieldFocused) { + handleTextFieldInput(c, keyCode, true); + } else if (replaceFieldFocused) { + handleTextFieldInput(c, keyCode, false); + } + + return true; + } + + private void handleTextFieldInput(char c, int keyCode, boolean isSearchField) { + String text = isSearchField ? searchText : replaceText; + int cursor = isSearchField ? searchCursor : replaceCursor; + int selStart = isSearchField ? searchSelectionStart : replaceSelectionStart; + int selEnd = isSearchField ? searchSelectionEnd : replaceSelectionEnd; + + boolean hasSelection = selStart != selEnd; + boolean ctrl = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); + boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + if (ctrl && keyCode == Keyboard.KEY_A) { + selStart = 0; + selEnd = text.length(); + cursor = text.length(); + } else if (ctrl && keyCode == Keyboard.KEY_C) { + if (hasSelection) { + String selected = text.substring(Math.min(selStart, selEnd), Math.max(selStart, selEnd)); + setClipboard(selected); + } + } else if (ctrl && keyCode == Keyboard.KEY_X) { + if (hasSelection) { + String selected = text.substring(Math.min(selStart, selEnd), Math.max(selStart, selEnd)); + setClipboard(selected); + saveState(isSearchField); + text = text.substring(0, Math.min(selStart, selEnd)) + text.substring(Math.max(selStart, selEnd)); + cursor = Math.min(selStart, selEnd); + selStart = selEnd = cursor; + } + } else if (ctrl && keyCode == Keyboard.KEY_V) { + String clipboard = getClipboard(); + if (clipboard != null) { + clipboard = clipboard.replace("\n", "").replace("\r", ""); + saveState(isSearchField); + if (hasSelection) { + text = text.substring(0, Math.min(selStart, selEnd)) + clipboard + text.substring(Math.max(selStart, selEnd)); + cursor = Math.min(selStart, selEnd) + clipboard.length(); + } else { + text = text.substring(0, cursor) + clipboard + text.substring(cursor); + cursor += clipboard.length(); + } + selStart = selEnd = cursor; + } + } else if (keyCode == Keyboard.KEY_BACK) { + saveState(isSearchField); + if (hasSelection) { + text = text.substring(0, Math.min(selStart, selEnd)) + text.substring(Math.max(selStart, selEnd)); + cursor = Math.min(selStart, selEnd); + } else if (cursor > 0) { + text = text.substring(0, cursor - 1) + text.substring(cursor); + cursor--; + } + selStart = selEnd = cursor; + } else if (keyCode == Keyboard.KEY_DELETE) { + saveState(isSearchField); + if (hasSelection) { + text = text.substring(0, Math.min(selStart, selEnd)) + text.substring(Math.max(selStart, selEnd)); + cursor = Math.min(selStart, selEnd); + } else if (cursor < text.length()) { + text = text.substring(0, cursor) + text.substring(cursor + 1); + } + selStart = selEnd = cursor; + } else if (keyCode == Keyboard.KEY_LEFT) { + if (shift) { + if (cursor > 0) { + cursor--; + if (selStart == selEnd) { + selEnd = cursor + 1; + selStart = cursor; + } else if (cursor < selStart) { + selStart = cursor; + } else { + selEnd = cursor; + } + } + } else { + if (hasSelection) { + cursor = Math.min(selStart, selEnd); + } else if (cursor > 0) { + cursor--; + } + selStart = selEnd = cursor; + } + } else if (keyCode == Keyboard.KEY_RIGHT) { + if (shift) { + if (cursor < text.length()) { + cursor++; + if (selStart == selEnd) { + selStart = cursor - 1; + selEnd = cursor; + } else if (cursor > selEnd) { + selEnd = cursor; + } else { + selStart = cursor; + } + } + } else { + if (hasSelection) { + cursor = Math.max(selStart, selEnd); + } else if (cursor < text.length()) { + cursor++; + } + selStart = selEnd = cursor; + } + } else if (keyCode == Keyboard.KEY_HOME) { + if (shift) { + selEnd = selStart == selEnd ? cursor : selEnd; + selStart = 0; + } else { + selStart = selEnd = 0; + } + cursor = 0; + } else if (keyCode == Keyboard.KEY_END) { + if (shift) { + selStart = selStart == selEnd ? cursor : selStart; + selEnd = text.length(); + } else { + selStart = selEnd = text.length(); + } + cursor = text.length(); + } else if (ChatAllowedCharacters.isAllowedCharacter(c)) { + saveState(isSearchField); + if (hasSelection) { + text = text.substring(0, Math.min(selStart, selEnd)) + c + text.substring(Math.max(selStart, selEnd)); + cursor = Math.min(selStart, selEnd) + 1; + } else { + text = text.substring(0, cursor) + c + text.substring(cursor); + cursor++; + } + selStart = selEnd = cursor; + } + + if (selStart > selEnd) { + int temp = selStart; + selStart = selEnd; + selEnd = temp; + } + + // Mark activity on any input to keep cursor visible + markActivity(); + + if (isSearchField) { + searchText = text; + searchCursor = cursor; + searchSelectionStart = selStart; + searchSelectionEnd = selEnd; + updateMatches(); + } else { + replaceText = text; + replaceCursor = cursor; + replaceSelectionStart = selStart; + replaceSelectionEnd = selEnd; + } + } + + private void setClipboard(String text) { + try { + java.awt.datatransfer.StringSelection selection = new java.awt.datatransfer.StringSelection(text); + java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null); + } catch (Exception ignored) { + } + } + + private String getClipboard() { + try { + return (String) java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().getData(java.awt.datatransfer.DataFlavor.stringFlavor); + } catch (Exception e) { + return null; + } + } + + // ==================== SEARCH LOGIC ==================== + + /** + * Update matches based on current search text and options + */ + public void updateMatches() { + matches.clear(); + excludedMatches.clear(); + + if (callback == null || searchText.isEmpty()) { + if (callback != null) callback.onMatchesUpdated(); + return; + } + + String sourceText = callback.getText(); + if (sourceText == null || sourceText.isEmpty()) { + callback.onMatchesUpdated(); + return; + } + + String searchPattern = searchText; + + if (wholeWord) { + searchPattern = "\\b" + Pattern.quote(searchPattern) + "\\b"; + } else { + searchPattern = Pattern.quote(searchPattern); + } + + int flags = matchCase ? 0 : Pattern.CASE_INSENSITIVE; + + try { + Pattern pattern = Pattern.compile(searchPattern, flags); + Matcher matcher = pattern.matcher(sourceText); + + while (matcher.find()) { + matches.add(new int[]{matcher.start(), matcher.end()}); + } + } catch (Exception ignored) { + } + + // No need to navigate right now + if (!matches.isEmpty()) { + // currentMatchIndex = 0; + // navigateToCurrentMatch(); + } + + currentMatchIndex = ValueUtil.clamp(currentMatchIndex, 0, matches.size() - 1); + callback.onMatchesUpdated(); + } + + /** + * If the editor currently has a selection, prefer the match that contains that selection + * and navigate to it. + */ + private void setCurrentMatchToHighlight() { + if (callback == null || matches.isEmpty()) + return; + try { + int selStart = callback.getSelectionStart(); + int selEnd = callback.getSelectionEnd(); + if (selStart >= 0 && selEnd > selStart) { + for (int i = 0; i < matches.size(); i++) { + int[] m = matches.get(i); + if (m[0] <= selStart && m[1] >= selEnd) { + currentMatchIndex = i; + return; + } + } + } + } catch (Exception ignored) { + } + } + + /** + * Navigate to next match + */ + public void goToNextMatch() { + if (matches.isEmpty()) return; + + if (currentMatchIndex < 0) currentMatchIndex = 0; + else currentMatchIndex = (currentMatchIndex + 1) % matches.size(); + + navigateToCurrentMatch(); + } + + /** + * Navigate to previous match + */ + public void goToPreviousMatch() { + if (matches.isEmpty()) return; + + if (currentMatchIndex < 0) currentMatchIndex = matches.size() - 1; + else currentMatchIndex = (currentMatchIndex - 1 + matches.size()) % matches.size(); + + navigateToCurrentMatch(); + } + + /** + * Navigate viewport to current match and select it + */ + private void navigateToCurrentMatch() { + if (callback == null || currentMatchIndex < 0 || currentMatchIndex >= matches.size()) return; + + int[] match = matches.get(currentMatchIndex); + callback.scrollToPosition(match[0]); + callback.setSelection(match[0], match[1]); + } + + // ==================== REPLACE LOGIC ==================== + + /** + * Replace current match + */ + public void replaceCurrent() { + if (callback == null || currentMatchIndex < 0 || matches.isEmpty()) return; + if (excludedMatches.contains(currentMatchIndex)) { + goToNextMatch(); + return; + } + + String sourceText = callback.getText(); + int[] match = matches.get(currentMatchIndex); + + String newText = sourceText.substring(0, match[0]) + replaceText + sourceText.substring(match[1]); + callback.setText(newText); + + updateMatches(); + + if (!matches.isEmpty()) { + int replacementEnd = match[0] + replaceText.length(); + for (int i = 0; i < matches.size(); i++) { + if (matches.get(i)[0] >= replacementEnd) { + currentMatchIndex = i; + break; + } + } + navigateToCurrentMatch(); + } + } + + /** + * Replace all matches + */ + public void replaceAll() { + if (callback == null || matches.isEmpty()) return; + + String sourceText = callback.getText(); + StringBuilder result = new StringBuilder(); + int lastEnd = 0; + + for (int i = 0; i < matches.size(); i++) { + if (excludedMatches.contains(i)) { + continue; + } + int[] match = matches.get(i); + result.append(sourceText, lastEnd, match[0]); + result.append(replaceText); + lastEnd = match[1]; + } + result.append(sourceText.substring(lastEnd)); + + callback.setText(result.toString()); + updateMatches(); + } + + /** + * Exclude current match from replacement + */ + public void excludeCurrentMatch() { + if (currentMatchIndex < 0) return; + + if (excludedMatches.contains(currentMatchIndex)) { + // If already excluded, remove the exclusion and keep selection on this match + excludedMatches.remove(Integer.valueOf(currentMatchIndex)); + } else { + // Otherwise exclude and move to the next match + excludedMatches.add(currentMatchIndex); + goToNextMatch(); + } + } + + // ==================== UTILITY ==================== + + /** + * Get search text for external highlighting + */ + public String getSearchText() { + return searchText; + } + + /** + * Check if bar consumes click at position + */ + public boolean isMouseOverBar(int mouseX, int mouseY) { + if (!visible) return false; + int totalHeight = getTotalHeight(); + return mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + totalHeight; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/SelectionState.java b/src/main/java/noppes/npcs/client/gui/util/script/SelectionState.java new file mode 100644 index 000000000..89efa34cd --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/SelectionState.java @@ -0,0 +1,242 @@ +package noppes.npcs.client.gui.util.script; + +import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; + +import java.util.List; +import java.util.regex.Pattern; + +/** + * Manages cursor position, text selection, and related operations. + */ +public class SelectionState { + private int startSelection = 0; + private int endSelection = 0; + private int cursorPosition = 0; + private long lastInputTime = 0L; + + /** + * Reset all cursor selections to a single position + */ + public void reset(int position) { + startSelection = endSelection = cursorPosition = position; + } + + /** + * Clamp all selection bounds to valid text range + */ + public void clamp(int textLength) { + if (textLength <= 0) { + startSelection = endSelection = cursorPosition = 0; + return; + } + startSelection = Math.max(0, Math.min(startSelection, textLength)); + endSelection = Math.max(0, Math.min(endSelection, textLength)); + cursorPosition = Math.max(0, Math.min(cursorPosition, textLength)); + } + + /** + * Set cursor position, optionally extending selection + */ + public void setCursor(int position, int textLength, boolean extendSelection) { + position = Math.max(0, Math.min(position, textLength)); + + if (position != cursorPosition) { + if (!extendSelection) { + endSelection = startSelection = cursorPosition = position; + } else { + int diff = cursorPosition - position; + if (cursorPosition == startSelection) { + startSelection -= diff; + } else if (cursorPosition == endSelection) { + endSelection -= diff; + } + + // Ensure start <= end + if (startSelection > endSelection) { + int temp = endSelection; + endSelection = startSelection; + startSelection = temp; + } + cursorPosition = position; + } + clamp(textLength); + markActivity(); + } + } + + /** + * Select a range of text + */ + public void setSelection(int start, int end) { + startSelection = Math.min(start, end); + endSelection = Math.max(start, end); + } + + /** + * Select all text + */ + public void selectAll(int textLength) { + startSelection = cursorPosition = 0; + endSelection = textLength; + } + + /** + * Check if there's an active selection (not just cursor) + */ + public boolean hasSelection() { + return startSelection != endSelection; + } + + /** + * Get selected text + */ + public String getSelectedText(String text) { + if (!hasSelection() || text == null) return ""; + int start = Math.max(0, Math.min(startSelection, text.length())); + int end = Math.max(0, Math.min(endSelection, text.length())); + return text.substring(start, end); + } + + /** + * Get text before selection/cursor + */ + public String getTextBefore(String text) { + if (text == null || startSelection <= 0) return ""; + return text.substring(0, Math.min(startSelection, text.length())); + } + + /** + * Get text after selection/cursor + */ + public String getTextAfter(String text) { + if (text == null) return ""; + int pos = Math.min(endSelection, text.length()); + return text.substring(pos); + } + + /** + * Find which line the cursor is on (0-indexed) + */ + public int getCursorLineIndex(List lines, int textLength) { + if (lines == null || lines.isEmpty()) return 0; + + for (int i = 0; i < lines.size(); i++) { + LineData ld = lines.get(i); + boolean isLastLine = (i == lines.size() - 1); + boolean isOnLine = isLastLine + ? (cursorPosition >= ld.start && cursorPosition <= ld.end) + : (cursorPosition >= ld.start && cursorPosition < ld.end); + if (isOnLine) { + return i; + } + } + return lines.size() - 1; + } + + /** + * Check if cursor is on a specific line, handling the last line specially + * (last line doesn't have trailing newline, so use <= for end boundary) + */ + public boolean isCursorOnLine(int lineIndex, LineData line, int totalLines) { + boolean isLastLine = (lineIndex == totalLines - 1); + return isLastLine + ? (cursorPosition >= line.start && cursorPosition <= line.end) + : (cursorPosition >= line.start && cursorPosition < line.end); + } + + /** + * Find line containing the cursor + */ + public LineData findCurrentLine(List lines) { + if (lines == null) return null; + for (int i = 0; i < lines.size(); i++) { + LineData line = lines.get(i); + if (isCursorOnLine(i, line, lines.size())) { + return line; + } + } + return null; + } + + /** + * Mark user activity (for cursor blink timing) + */ + public void markActivity() { + lastInputTime = System.currentTimeMillis(); + } + + /** + * Check if there was recent input (for cursor blink pause) + */ + public boolean hadRecentInput() { + return System.currentTimeMillis() - lastInputTime < 500; + } + + // Getters + public int getStartSelection() { + return startSelection; + } + + public int getEndSelection() { + return endSelection; + } + + public int getCursorPosition() { + return cursorPosition; + } + + public long getLastInputTime() { + return lastInputTime; + } + + // Direct setters (use with caution, prefer higher-level methods) + public void setStartSelection(int pos) { + this.startSelection = pos; + } + + public void setEndSelection(int pos) { + this.endSelection = pos; + } + + public void setCursorPositionDirect(int pos) { + this.cursorPosition = pos; + } + + /** + * After text modification, update selection to new position + */ + public void afterTextInsert(int newPosition) { + endSelection = startSelection = cursorPosition = newPosition; + markActivity(); + } + + /** + * Select the word surrounding the current cursor position using the provided regex. + * The regex should match word tokens; the implementation finds the token which + * contains the cursor and selects its start..end. + */ + public void selectWordAtCursor(String text, Pattern wordPattern) { + if (text == null || wordPattern == null) return; + java.util.regex.Matcher m = wordPattern.matcher(text); + while (m.find()) { + if (cursorPosition >= m.start() && cursorPosition <= m.end()) { + setSelection(m.start(), m.end()); + return; + } + } + } + + /** + * Select the entire line containing the cursor. `lines` is the parsed + * line data from `JavaTextContainer` where each LineData has start/end indices. + */ + public void selectLineAtCursor(List lines) { + if (lines == null) return; + for (LineData line : lines) { + if (isCursorOnLine(lines.indexOf(line), line, lines.size())) { + setSelection(line.start, line.end); + return; + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/UndoManager.java b/src/main/java/noppes/npcs/client/gui/util/script/UndoManager.java new file mode 100644 index 000000000..c5cfd9f77 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/UndoManager.java @@ -0,0 +1,126 @@ +package noppes.npcs.client.gui.util.script; + +import java.util.ArrayList; +import java.util.List; + +/** + * Manages undo/redo stacks for the text editor. + */ +public class UndoManager { + + /** + * Stores a snapshot of text state for undo/redo + */ + public static class UndoState { + public final String text; + public final int cursorPosition; + + public UndoState(String text, int cursorPosition) { + this.text = text; + this.cursorPosition = cursorPosition; + } + } + + private final List undoStack = new ArrayList<>(); + private final List redoStack = new ArrayList<>(); + private boolean isUndoing = false; + + // Optional: limit stack size to prevent memory issues + private static final int MAX_STACK_SIZE = 100; + + /** + * Record current state before making a change + */ + public void recordState(String text, int cursorPosition) { + if (isUndoing) return; + + undoStack.add(new UndoState(text, cursorPosition)); + redoStack.clear(); + + // Trim stack if too large + while (undoStack.size() > MAX_STACK_SIZE) { + undoStack.remove(0); + } + } + + /** + * Undo to previous state + * + * @param currentText Current text before undo + * @param currentCursor Current cursor position + * @return Previous state, or null if nothing to undo + */ + public UndoState undo(String currentText, int currentCursor) { + if (undoStack.isEmpty()) return null; + + isUndoing = true; + redoStack.add(new UndoState(currentText, currentCursor)); + UndoState state = undoStack.remove(undoStack.size() - 1); + isUndoing = false; + + return state; + } + + /** + * Redo to next state + * + * @param currentText Current text before redo + * @param currentCursor Current cursor position + * @return Next state, or null if nothing to redo + */ + public UndoState redo(String currentText, int currentCursor) { + if (redoStack.isEmpty()) return null; + + isUndoing = true; + undoStack.add(new UndoState(currentText, currentCursor)); + UndoState state = redoStack.remove(redoStack.size() - 1); + isUndoing = false; + + return state; + } + + /** + * Check if undo is available + */ + public boolean canUndo() { + return !undoStack.isEmpty(); + } + + /** + * Check if redo is available + */ + public boolean canRedo() { + return !redoStack.isEmpty(); + } + + /** + * Clear all history + */ + public void clear() { + undoStack.clear(); + redoStack.clear(); + } + + /** + * Check if currently performing an undo/redo operation + */ + public boolean isUndoing() { + return isUndoing; + } + + /** + * Set undoing flag (for external control during setText) + */ + public void setUndoing(boolean undoing) { + this.isUndoing = undoing; + } + + // For backward compatibility with existing code + public List getUndoList() { + return undoStack; + } + + public List getRedoList() { + return redoStack; + } +} 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..413c72667 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteItem.java @@ -0,0 +1,830 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +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(1), // Field or property + VARIABLE(2), // Local variable or parameter + CLASS(3), // Class or interface type + ENUM(4), // Enum type + KEYWORD(6), // Language keyword + SNIPPET(7); // 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 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, + false, // TODO: Check for @Deprecated annotation + 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.VARIABLE; + 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); + } + + /** + * Add a boost to the match score (e.g., from usage tracking). + */ + 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; } + + /** + * 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 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 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; + } + } + + @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 String signature; + private String documentation; + private Object sourceData; + private boolean deprecated = false; + private boolean requiresImport = false; + private String importPath = null; + + 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 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 AutocompleteItem build() { + if (insertText == null) { + insertText = name; + } + return new AutocompleteItem(name, searchName, insertText, kind, typeLabel, + null, signature, documentation, sourceData, deprecated, requiresImport, importPath, -1); + } + } +} 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..1ef9d3034 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteManager.java @@ -0,0 +1,1117 @@ +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) { + 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) { + 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 + int checkPos = pos; + while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) { + checkPos--; + } + 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) == '.') { + return pos; + } else { + while (pos >= 0 && Character.isJavaIdentifierPart(text.charAt(pos))) + pos--; + + if (pos >= 0 && text.charAt(pos) == '.') + 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..58263494e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/AutocompleteMenu.java @@ -0,0 +1,1000 @@ +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.MODIFIER.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(typeLabel, typeLabelX, textY, col, type); + } + } + + public int getColor(AutocompleteItem item) { + 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 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(String typeLabel, int x, int y, int typeColor, TypeInfo typeInfo) { + if (typeInfo == null) { + 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/JSAutocompleteProvider.java b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JSAutocompleteProvider.java new file mode 100644 index 000000000..b342a5384 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JSAutocompleteProvider.java @@ -0,0 +1,354 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +import noppes.npcs.client.gui.util.script.interpreter.js_parser.*; +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.TypeChecker; +import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo; +import noppes.npcs.config.ConfigScript; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +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. + */ + protected void addMemberSuggestions(Context context, List items) { + String receiverExpr = context.receiverExpression; + if (receiverExpr == null || receiverExpr.isEmpty()) { + return; + } + + // Use ScriptDocument's resolveExpressionType - handles both Java and JS + TypeInfo receiverType = document.resolveExpressionType(receiverExpr, getMemberAccessResolvePosition(context)); + if (receiverType == null || !receiverType.isResolved()) { + return; + } + + // Check for synthetic types first (e.g., Nashorn Java object, custom types) + SyntheticType syntheticType = + document.getTypeResolver().getSyntheticType(receiverType.getSimpleName()); + if (syntheticType != null) { + addSyntheticTypeSuggestions(syntheticType, items, context.methodsOnly); + return; + } + + boolean isStaticContext = isStaticAccess(receiverExpr, getMemberAccessResolvePosition(context)); + + Class javaClass = receiverType.getJavaClass(); + if (javaClass != null) { + Set addedMethods = new HashSet<>(); + for (Method method : javaClass.getMethods()) { + if (!Modifier.isPublic(method.getModifiers())) continue; + if (isStaticContext && !Modifier.isStatic(method.getModifiers())) continue; + String sig = method.getName() + "(" + method.getParameterCount() + ")"; + if (addedMethods.add(sig)) { + items.add(AutocompleteItem.fromMethod(MethodInfo.fromReflection(method, receiverType), context.methodsOnly)); + } + } + List effectiveSyntheticMethods = receiverType.getSyntheticMethods(); + if (!effectiveSyntheticMethods.isEmpty()) { + for (MethodInfo method : effectiveSyntheticMethods) { + if (isStaticContext && !method.isStatic()) continue; + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + } else { + JSTypeInfo jsType = getMergeRegistryType(javaClass); + if (jsType != null) { + addMethodsFromType(jsType, receiverType, items, new HashSet<>(), context.methodsOnly, isStaticContext); + } + } + if (!context.methodsOnly) { + for (Field field : javaClass.getFields()) { + if (!Modifier.isPublic(field.getModifiers())) continue; + if (isStaticContext && !Modifier.isStatic(field.getModifiers())) continue; + items.add(AutocompleteItem.fromField(FieldInfo.fromReflection(field, receiverType))); + } + if (!receiverType.getSyntheticFields().isEmpty()) { + for (FieldInfo field : receiverType.getSyntheticFields()) { + if (isStaticContext && !field.isStatic()) continue; + items.add(AutocompleteItem.fromField(field)); + } + } else { + JSTypeInfo jsType = getMergeRegistryType(javaClass); + if (jsType != null) { + addFieldsFromType(jsType, receiverType, items, new HashSet<>(), isStaticContext); + } + } + } + if (!isStaticContext && javaClass != Object.class) { + JSTypeInfo objJSType = registry.getType("Object"); + if (objJSType != null) { + for (JSMethodInfo m : objJSType.getMethods().values()) { + if (!m.isStatic()) { + items.add(AutocompleteItem.fromJSMethod(m, receiverType, 1, context.methodsOnly)); + } + } + } + } + return; + } + + Set syntheticMethodNames = new HashSet<>(); + for (MethodInfo method : receiverType.getSyntheticMethods()) { + syntheticMethodNames.add(method.getName()); + if (isStaticContext && !method.isStatic()) continue; + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + for (FieldInfo field : receiverType.getSyntheticFields()) { + if (!context.methodsOnly) { + if (isStaticContext && !field.isStatic()) continue; + if (syntheticMethodNames.contains(field.getName())) continue; + items.add(AutocompleteItem.fromField(field)); + } + } + + JSTypeInfo jsTypeInfo = receiverType.getJSTypeInfo(); + if (jsTypeInfo != null) { + addMethodsFromType(jsTypeInfo, receiverType, items, new HashSet<>(), context.methodsOnly, isStaticContext); + if (!context.methodsOnly && ConfigScript.ShowImplementationFieldsInAutocomplete) { + addFieldsFromType(jsTypeInfo, receiverType, items, new HashSet<>(), isStaticContext); + } + } + + if (!isStaticContext) { + Set addedObjMethods = new HashSet<>(); + for (Method m : Object.class.getMethods()) { + if (!Modifier.isPublic(m.getModifiers()) || Modifier.isStatic(m.getModifiers())) continue; + String sig = m.getName() + "(" + m.getParameterCount() + ")"; + if (addedObjMethods.add(sig)) { + items.add(AutocompleteItem.fromMethod(MethodInfo.fromReflection(m, receiverType), context.methodsOnly)); + } + } + JSTypeInfo objJSType = registry.getType("Object"); + if (objJSType != null) { + for (JSMethodInfo m : objJSType.getMethods().values()) { + if (!m.isStatic()) { + items.add(AutocompleteItem.fromJSMethod(m, receiverType, 1, context.methodsOnly)); + } + } + } + } + } + + 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(); + } + + 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..067bccaca --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/autocomplete/JavaAutocompleteProvider.java @@ -0,0 +1,605 @@ +package noppes.npcs.client.gui.util.script.autocomplete; + +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.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.Field; +import java.lang.reflect.Method; +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 and score by prefix, then apply usage boosts and static penalties + filterAndScore(items, context.prefix, context.isMemberAccess, isStaticContext, ownerFullName); + + // Sort by score + Collections.sort(items); + + 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 the type of the receiver expression + TypeInfo receiverType = document.resolveExpressionType(receiverExpr, getMemberAccessResolvePosition(context)); + + if (receiverType == null || !receiverType.isResolved()) { + return; + } + + // Determine if this is a static context (accessing a class type) + boolean isStaticContext = isStaticAccess(receiverExpr, getMemberAccessResolvePosition(context)); + + Class clazz = receiverType.getJavaClass(); + if (clazz == null) { + // Try ScriptTypeInfo + if (receiverType instanceof ScriptTypeInfo) { + addScriptTypeMembers((ScriptTypeInfo) receiverType, items, isStaticContext, context.methodsOnly); + } + return; + } + + // Add methods + Set addedMethods = new HashSet<>(); + for (Method method : clazz.getMethods()) { + if (Modifier.isPublic(method.getModifiers())) { + // Filter by static context + if (isStaticContext && !Modifier.isStatic(method.getModifiers())) { + continue; + } + + String sig = method.getName() + "(" + method.getParameterCount() + ")"; + if (!addedMethods.contains(sig)) { + addedMethods.add(sig); + MethodInfo methodInfo = MethodInfo.fromReflection(method, receiverType); + items.add(AutocompleteItem.fromMethod(methodInfo, context.methodsOnly)); + } + } + } + + for (MethodInfo method : receiverType.getSyntheticMethods()) { + if (isStaticContext && !Modifier.isStatic(method.getModifiers())) + continue; + + items.add(AutocompleteItem.fromMethod(method, context.methodsOnly)); + } + + // Add fields (skip if methodsOnly is true - but the filtering will be done in getSuggestions) + if (!context.methodsOnly) { + for (Field field : clazz.getFields()) { + if (Modifier.isPublic(field.getModifiers())) { + // Filter by static context + if (isStaticContext && !Modifier.isStatic(field.getModifiers())) { + continue; + } + + FieldInfo fieldInfo = FieldInfo.fromReflection(field, receiverType); + items.add(AutocompleteItem.fromField(fieldInfo)); + } + } + + for (FieldInfo field : receiverType.getSyntheticFields()) { + if (isStaticContext && !Modifier.isStatic(field.getModifiers())) + continue; + + items.add(AutocompleteItem.fromField(field)); + } + } + + // Add nested types (inner classes/interfaces) in static context + if (isStaticContext && !context.methodsOnly) { + try { + for (Class nested : clazz.getDeclaredClasses()) { + if (!Modifier.isPublic(nested.getModifiers())) { + continue; + } + // Convert $ notation to dot notation for resolution + String nestedFullName = nested.getName().replace('$', '.'); + TypeInfo nestedType = TypeResolver.getInstance().resolveFullName(nestedFullName); + if (nestedType != null && nestedType.isResolved()) { + items.add(AutocompleteItem.fromType(nestedType)); + } + } + } catch (SecurityException ignored) { + // Some runtimes may restrict getDeclaredClasses() + } + } + + } + + /** + * 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 members from a script-defined type. + */ + protected void addScriptTypeMembers(ScriptTypeInfo scriptType, List items, boolean isStaticContext) { + addScriptTypeMembers(scriptType, items, isStaticContext, false); + } + + /** + * Add members from a script-defined type. + * @param scriptType The script type to get members from + * @param items The list to add items to + * @param isStaticContext Whether we're in a static context + * @param forMethodReference If true, only add methods with no parentheses in insert text + */ + protected void addScriptTypeMembers(ScriptTypeInfo scriptType, List items, boolean isStaticContext, boolean forMethodReference) { + // Add methods (getMethods returns Map>) + for (List overloads : scriptType.getMethods().values()) { + for (MethodInfo method : overloads) { + // Filter by static context + if (isStaticContext && !method.isStatic()) { + continue; + } + items.add(AutocompleteItem.fromMethod(method, forMethodReference)); + } + } + + // Add fields (skip if methodsOnly/forMethodReference is true) + if (!forMethodReference) { + // Add fields (getFields returns Map) + for (FieldInfo field : scriptType.getFields().values()) { + // Filter by static context + if (isStaticContext && !field.isStatic()) { + continue; + } + items.add(AutocompleteItem.fromField(field)); + } + + // Add enum constants (getEnumConstants returns Map) + for (EnumConstantInfo enumConstant : scriptType.getEnumConstants().values()) { + items.add(AutocompleteItem.fromField(enumConstant.getFieldInfo())); + } + + // Add nested types (inner classes/interfaces) in static context + if (isStaticContext) { + for (ScriptTypeInfo inner : scriptType.getInnerClasses()) { + items.add(AutocompleteItem.fromType(inner)); + } + } + } + + // Add parent class members + if (scriptType.hasSuperClass()) { + TypeInfo superType = scriptType.getSuperClass(); + if (superType != null && superType.getJavaClass() != null) { + Class superClazz = superType.getJavaClass(); + Set addedMethods = new HashSet<>(); + for (Method method : superClazz.getMethods()) { + if (Modifier.isPublic(method.getModifiers())) { + String sig = method.getName() + "(" + method.getParameterCount() + ")"; + if (!addedMethods.contains(sig)) { + addedMethods.add(sig); + MethodInfo methodInfo = MethodInfo.fromReflection(method, superType); + items.add(AutocompleteItem.fromMethod(methodInfo, forMethodReference)); + } + } + } + } + } + } + + /** + * 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; + } + + // Create an item that requires import + 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()) + .signature(type.getFullName()) + .sourceData(type) + .requiresImport(true) + .importPath(fullName) + .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(); + } + + /** + * Filter items by prefix, calculate match scores, apply usage boosts, and penalize static members in instance contexts. + */ + protected void filterAndScore(List items, String prefix, + boolean isMemberAccess, boolean isStaticContext, String ownerFullName) { + UsageTracker tracker = getUsageTracker(); + + if (prefix == null || prefix.isEmpty()) { + // No filtering needed, all items get a base score + usage boost + for (AutocompleteItem item : items) { + item.calculateMatchScore("", false); + applyUsageBoost(item, tracker, ownerFullName); + applyStaticPenalty(item, isMemberAccess, isStaticContext); + applyObjectMethodPenalty(item); + applyKeywordPenalty(item, prefix); + } + return; + } + + // For non-member access (first word), require strict prefix matching + // For member access (after dot), allow fuzzy/contains matching + boolean requirePrefix = !isMemberAccess; + + // Filter, score, apply usage boosts, and apply penalties + Iterator iter = items.iterator(); + while (iter.hasNext()) { + AutocompleteItem item = iter.next(); + int score = item.calculateMatchScore(prefix, requirePrefix); + if (score < 0) { + iter.remove(); + } else { + applyUsageBoost(item, tracker, ownerFullName); + applyStaticPenalty(item, isMemberAccess, isStaticContext); + applyObjectMethodPenalty(item); + applyKeywordPenalty(item, prefix); + } + } + } + + /** + * Apply usage-based score boost to an item. + */ + protected void applyUsageBoost(AutocompleteItem item, UsageTracker tracker, String ownerFullName) { + int usageCount = tracker.getUsageCount(item, ownerFullName); + int boost = UsageTracker.calculateUsageBoost(usageCount); + item.addScoreBoost(boost); + } + + /** + * Apply penalty to static members when accessed in a non-static (instance) context. + * This matches IntelliJ's behavior where static members are deprioritized when + * accessing through an instance (e.g., Minecraft.getMinecraft().getMinecraft()). + * However, if the item is a very strong match (exact prefix), don't penalize as much. + */ + protected void applyStaticPenalty(AutocompleteItem item, boolean isMemberAccess, boolean isStaticContext) { + // Only apply penalty in member access contexts (after dot) + if (!isMemberAccess) { + return; + } + + // Only penalize when we're in an instance context (not static) + if (isStaticContext) { + return; + } + + boolean isStatic = item.isStatic(); + + // Apply penalty to static members in instance context + if (isStatic) { + int matchScore = item.getMatchScore(); + // Strong prefix matches (score >= 800) get a lighter penalty + // Weaker matches get pushed down more aggressively + if (matchScore >= 800) { + // Light penalty for exact prefix matches - just deprioritize slightly + item.addScoreBoost(-200); + } else { + // Heavy penalty for fuzzy/substring matches - push to bottom + item.addScoreBoost(-matchScore); + } + } + } + + /** + * Apply penalty to inherited Object methods to push them to bottom. + * Strong matches get lighter penalty, weak matches get pushed all the way down. + */ + protected void applyObjectMethodPenalty(AutocompleteItem item) { + if (!item.isInheritedObjectMethod()) { + return; + } + + int matchScore = item.getMatchScore(); + // Strong prefix matches (score >= 900) get a moderate penalty + // Everything else gets pushed to the very bottom + if (matchScore >= 900) { + // Strong match - moderate penalty to keep it visible but below normal methods + item.addScoreBoost(-500); + } else { + // Weak match - heavy penalty to push to bottom + item.addScoreBoost(-10000); + } + } + + /** + * Push keywords below non-keywords unless user typed a longer prefix. + */ + protected void applyKeywordPenalty(AutocompleteItem item, String prefix) { + if (item.getKind() != AutocompleteItem.Kind.KEYWORD) { + return; + } + + if (prefix == null || prefix.length() < 2) { + item.addScoreBoost(-10000); + } + } + + /** + * Builder class for AutocompleteItem to handle cases without source data. + */ + private static class AutocompleteItemBuilder { + // This would be needed if AutocompleteItem had a builder pattern + } +} 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..6d23e0c2f --- /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 ==================== + + private 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/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/ErrorUnderlineRenderer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ErrorUnderlineRenderer.java new file mode 100644 index 000000000..1e3bae054 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ErrorUnderlineRenderer.java @@ -0,0 +1,292 @@ +package noppes.npcs.client.gui.util.script.interpreter; + +import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.util.script.interpreter.field.AssignmentInfo; +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; +import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo; +import org.lwjgl.opengl.GL11; + +/** + * Helper class for rendering error underlines in script editor lines. + * Handles the repetitive calculation of underline positions and drawing of curly underlines. + */ +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. + * + * @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) { + + if (doc == null) + return; + + + // Check all method calls in the document + for (MethodCallInfo call : doc.getMethodCalls()) { + // Skip method declarations that were erroneously recorded as calls + boolean isDeclaration = false; + int methodStart = call.getMethodNameStart(); + for (MethodInfo mi : doc.getAllMethods()) { + //!call.isConstructor for enum declarations + if (!call.isConstructor() && mi.getDeclarationOffset() <= methodStart && mi.getBodyStart() >= methodStart) { + isDeclaration = true; + break; + } + } + if (isDeclaration) + continue; + + // Skip if this call doesn't intersect this line + if (call.getCloseParenOffset() < lineStart || call.getOpenParenOffset() > lineEnd) + continue; + + // Handle arg count errors (underline the method name) + if (call.hasArgCountError()) { + int methodEnd = methodStart + call.getMethodName().length(); + drawUnderlineForSpan(methodStart, methodEnd, lineStartX, baselineY, + lineText, lineStart, lineEnd, ERROR_COLOR); + } else if (call.hasArgTypeError()) { + // Handle return type mismatch (underline the method name) - currently commented out + // if (call.hasReturnTypeMismatch()) { ... } + + // Handle arg type errors (underline specific arguments) + + for (MethodCallInfo.ArgumentTypeError error : call.getArgumentTypeErrors()) { + MethodCallInfo.Argument arg = error.getArg(); + drawUnderlineForSpan(arg.getStartOffset(), arg.getEndOffset(), + lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR); + } + } else if(call.hasError()){ + // Handle other call errors (underline the whole call) + drawUnderlineForSpan(call.getMethodNameStart(), call.getCloseParenOffset() + 1, + lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR); + } + } + + // Check all field accesses in the document (currently commented out) + // for (FieldAccessInfo access : doc.getFieldAccesses()) { ... } + + // Check all errored assignments in the document + for (AssignmentInfo assign : doc.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; + } + + drawUnderlineForSpan(underlineStart, underlineEnd, lineStartX, baselineY, + lineText, lineStart, lineEnd, ERROR_COLOR); + } + + // Check all method declarations for errors + for (MethodInfo method : doc.getAllMethods()) { + if (!method.isDeclaration() || !method.hasError()) + continue; + + // Handle return statement type errors + if (method.hasReturnStatementErrors()) { + for (MethodInfo.ReturnStatementError returnError : method.getReturnStatementErrors()) { + drawUnderlineForSpan(returnError.getStartOffset(), returnError.getEndOffset(), + lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR); + } + } + + // Handle missing return error (underline the method name) + else if (method.hasMissingReturnError()) { + int methodNameStart = method.getNameOffset(); + int methodNameEnd = methodNameStart + method.getName().length(); + drawUnderlineForSpan(methodNameStart, methodNameEnd, lineStartX, baselineY, + lineText, lineStart, lineEnd, ERROR_COLOR); + } + // Handle parameter errors + 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(); + drawUnderlineForSpan(paramStart, paramEnd, lineStartX, baselineY, + lineText, lineStart, lineEnd, ERROR_COLOR); + } + } + + // Handle all other errors + else if (method.hasError()) { + drawUnderlineForSpan(method.getFullDeclarationOffset(), method.getDeclarationEnd(), lineStartX, + baselineY, lineText, lineStart, lineEnd, ERROR_COLOR); + } + + } + + + for(ScriptTypeInfo types : doc.getScriptTypes()){ + if(!types.hasError()) + continue; + + int typeStart = types.getDeclarationOffset(); + int typeEnd = types.getBodyStart(); + drawUnderlineForSpan(typeStart, typeEnd, lineStartX, baselineY, + lineText, lineStart, lineEnd, ERROR_COLOR); + } + } + + /** + * Calculate underline position for a span of text within a line. + * Handles clipping to line boundaries and pixel 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 + * @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) { + + // 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 + String beforeSpan = lineText.substring(0, lineLocalStart); + int beforeWidth = ClientProxy.Font.width(beforeSpan); + + int spanWidth; + if (lineLocalEnd > lineText.length()) { + // Span extends past line end + spanWidth = ClientProxy.Font.width(lineText.substring(lineLocalStart)); + } else { + // Span is fully on this line (or clipped) + 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) { + + UnderlinePosition pos = calculateUnderlinePosition( + spanStart, spanEnd, lineStartX, lineText, lineStart, lineEnd); + + 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..edd06f0a3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/FieldChainMarker.java @@ -0,0 +1,517 @@ +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() || text.charAt(pos) != '.') break; + pos++; // Skip dot + + pos = document.skipWhitespace(pos); + if (pos >= text.length() || !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. + if (currentType instanceof ScriptTypeInfo) { + ScriptTypeInfo innerClass = ((ScriptTypeInfo) currentType).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() || text.charAt(pos) != '.') break; + pos++; // Skip dot + + pos = document.skipWhitespace(pos); + if (pos >= text.length() || !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..b71a8438a --- /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]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*:\\s*([^)]+)\\)"); + private static final Pattern CLASSIC_FOR = Pattern.compile( + "\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>\\[\\] \\t]*?(?:\\[\\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..de3e56d5e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptDocument.java @@ -0,0 +1,9650 @@ +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.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_<>\\[\\]]*)\\s+([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_]*)"); + + // 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<>(); + + // 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<>(); + + // 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) + 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(); + + // 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); + } + + // 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 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(); + + // 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(); + } + } + + /** + * 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 extendsClause; + final String implementsClause; + final JSDocInfo jsDoc; + + RawTypeDeclaration(String name, TypeInfo.Kind kind, int declOffset, int bodyStart, int bodyEnd, + int modifiers, 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.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) ========== + Pattern typeDecl = Pattern.compile( + "(?:(?:public|private|protected|static|final|abstract)\\s+)*(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)\\s*(?:\\(\\))?\\s*(?:extends\\s+([A-Za-z_][a-zA-Z0-9_.]*))?\\s*(?:implements\\s+([A-Za-z_][a-zA-Z0-9_.,\\s]*))?\\s*\\{"); + + 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); + String extendsClause = m.group(3); + String implementsClause = m.group(4); + + int bodyStart = text.indexOf('{', m.start()); + 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(), m.end()); + int modifiers = parseModifiers(fullMatch); + JSDocInfo jsDoc = jsDocParser.extractJSDocBefore(text, m.start()); + + rawDeclarations.add(new RawTypeDeclaration( + typeName, kind, m.start(), bodyStart, bodyEnd, + modifiers, extendsClause, implementsClause, jsDoc)); + } + + // ========== PASS 2: Build hierarchy using stack-based containment ========== + // Sort by bodyStart ascending so outer types are processed before inner types + rawDeclarations.sort(Comparator.comparingInt(r -> r.bodyStart)); + + // Stack tracks the nesting chain: top = current innermost enclosing type + Deque parentStack = new ArrayDeque<>(); + + for (RawTypeDeclaration raw : rawDeclarations) { + // Pop any parent whose body has ended before this declaration starts. + // This handles sibling types at the same level: when we reach InnerB, + // InnerA (whose bodyEnd <= InnerB.bodyStart) gets popped, leaving Outer on top. + while (!parentStack.isEmpty() && parentStack.peek().getBodyEnd() <= raw.bodyStart) { + parentStack.pop(); + } + + ScriptTypeInfo scriptType; + if (parentStack.isEmpty()) { + // Top-level type: no enclosing parent + scriptType = ScriptTypeInfo.create( + raw.name, raw.kind, raw.declOffset, raw.bodyStart, raw.bodyEnd, raw.modifiers); + scriptTypes.put(raw.name, scriptType); + } else { + // Inner type: parent is top of stack. createInner sets outerClass link + // and adds this type to the parent's innerClasses list. + ScriptTypeInfo parent = parentStack.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); + } + + // Register in all lookup maps for O(1) access by any naming convention + scriptTypesByFullName.put(scriptType.getFullName(), scriptType); + scriptTypesByDotName.put(scriptType.getDotSeparatedName(), scriptType); + + // Push onto stack — this type can contain further nested types + parentStack.push(scriptType); + + // Resolve extends clause (parent class inheritance) + if (raw.extendsClause != null && !raw.extendsClause.trim().isEmpty()) { + String parentName = raw.extendsClause.trim(); + TypeInfo parentType = resolveType(parentName, raw.declOffset); + if (parentType == null) { + parentType = TypeInfo.unresolved(parentName, parentName); + } + scriptType.setSuperClass(parentType, parentName); + } + + // Resolve implements clause (interfaces) + if (raw.implementsClause != null && !raw.implementsClause.trim().isEmpty()) { + String[] interfaceNames = raw.implementsClause.split(","); + for (String ifaceName : interfaceNames) { + String trimmedName = ifaceName.trim(); + if (trimmedName.isEmpty()) + continue; + TypeInfo ifaceType = resolveType(trimmedName, raw.declOffset); + if (ifaceType == null) { + ifaceType = TypeInfo.unresolved(trimmedName, trimmedName); + } + scriptType.addImplementedInterface(ifaceType, trimmedName); + } + } + + // Parse fields and methods inside this type + parseScriptTypeMembers(scriptType); + } + } + + /** + * 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_<>\\[\\]]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(([^)]*)\\)\\s*(\\{|;)"); + + Matcher m = methodWithBody.matcher(text); + while (m.find()) { + String methodName = m.group(2); + + if (isExcluded(m.start()) || isKeyword(methodName)) + 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; + } + + // Pattern: Type varName (with optional spaces) + Pattern paramPattern = Pattern.compile( + "([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*(?:\\.{3})?)\\s+([a-zA-Z_][a-zA-Z0-9_]*)"); + Matcher m = paramPattern.matcher(paramList); + while (m.find()) { + String typeName = m.group(1); + String paramName = m.group(2); + boolean isVarArg = typeName.endsWith("..."); + if (isVarArg) typeName = typeName.substring(0, typeName.length() - 3); + TypeInfo typeInfo = resolveType(typeName, paramListStart); + // Store the absolute position of the parameter name + int paramNameStart = paramListStart + m.start(2); + 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() { + for (MethodInfo method : getAllMethods()) { + 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(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; + + // --- 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(rangeText); + while (m.find()) { + int declPos = start + m.start(); + if (declPos < start || declPos >= end) continue; + if (isExcluded(declPos)) 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 + int paramOffset = text.indexOf(param, offset); + if (paramOffset < 0) 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); + int nameOffset = text.indexOf(paramName, paramOffset); + if (nameOffset < 0) nameOffset = paramOffset; + 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]; + int nameOffset = text.indexOf(paramName, paramOffset); + if (nameOffset < 0) nameOffset = paramOffset; + FieldInfo paramInfo = FieldInfo.parameter(paramName, paramType, nameOffset, null); + scope.addParameter(paramInfo); + } + + offset = paramOffset + param.length(); + } + } + } else { + // Single identifier: x -> + String paramName = headerText; + int nameOffset = text.indexOf(paramName, headerStart); + if (nameOffset < 0) 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) 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) 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(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; + + // --- 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) 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) 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) + 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) 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); + } + + /** + * 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 resolved; + } + + // Positional fallback: only applies to simple names (no dots) that could be + // inner classes visible from the current scope. Dot-separated names like + // "Outer.Inner" are already handled by scriptTypesByDotName in resolveType(). + if (typeName != null && !typeName.contains(".")) { + // Walk the enclosing type hierarchy upward from the innermost type at this position. + // At each level, check if there's an inner class matching the name. + // This mirrors Java's scoping rules where inner classes shadow outer-scope types. + ScriptTypeInfo enclosing = findEnclosingScriptType(position); + while (enclosing != null) { + 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); + } + // 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.MODIFIER); + } + + // 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)); + } + } + } + } + + private void parseObjectLiterals() { + if (!isJavaScript()) return; + 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; + } + String objectLiteral = text.substring(brace, end); + ObjectLiteralParser.ObjectLiteralAnalysis analysis = + ObjectLiteralParser.parse(objectLiteral, brace, true, true, this::resolveExpressionType, this::getScriptMethodInfo); + if (analysis != null) + objectLiterals.put(brace, analysis); + + i = brace + 1; + } + // Wire each object-literal inner scope to its containing object type (needs the cache) + for (InnerCallableScope scope : innerScopes) + ObjectLiteralParser.attachObjectLiteralContext(scope, this); + + } + + 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.IMPORT_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) { + // Extended pattern to capture extends and implements clauses + // Groups: 1=class|interface|enum, 2=TypeName, 3=extends clause, 4=implements clause + Pattern classWithInheritance = Pattern.compile( + "\\b(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)\\s*(?:\\(\\))?\\s*" + + "(?:(extends)\\s+([A-Za-z_][a-zA-Z0-9_.]*))?\\s*" + + "(?:(implements)\\s+([A-Za-z_][a-zA-Z0-9_.,\\s]*))?\\s*(?=\\{)"); + + Matcher m = classWithInheritance.matcher(text); + while (m.find()) { + if (isExcluded(m.start())) + continue; + + // Mark the keyword (class/interface/enum) + marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.CLASS_KEYWORD)); + + // Mark the class name + 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); + // Look up the ScriptTypeInfo: try top-level first, then search all types + // by simple name + declaration range (declarationOffset..bodyEnd) to handle inner classes. + // Cannot use containsPosition() here because the class NAME sits before the opening '{', + // i.e., in [declarationOffset, bodyStart) — outside the body range checked by containsPosition. + 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)); + + // Mark extends clause + if (m.group(3) != null) { + //Extends key word + marks.add(new ScriptLine.Mark(m.start(3), m.end(3), TokenType.IMPORT_KEYWORD)); + markExtendsClause(marks, m.start(4), m.group(4)); + } + + // Mark implements clause + if (m.group(5) != null) { + //Implements key word + marks.add(new ScriptLine.Mark(m.start(5),m.end(5), TokenType.IMPORT_KEYWORD)); + markImplementsClause(marks, m.start(6), m.group(6)); + } + } + } + + /** + * 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 the main type + TypeInfo info = resolveType(typeName); + 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); + } + } + + 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) { + 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); + + // Only process if it's an actual type (check via resolveType) + TypeInfo typeCheck = resolveType(typeName); + if (typeCheck != null && typeCheck.isResolved()) { + int absStart = baseOffset + start; + int absEnd = baseOffset + i; + + if (!isExcluded(absStart)) { + TypeInfo info = resolveType(typeName); + TokenType tokenType = (info != null && info.isResolved()) ? info.getTokenType() : TokenType.UNDEFINED_VAR; + marks.add(new ScriptLine.Mark(absStart, absEnd, tokenType, 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++; + + // 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); + } + } + } + } + + /** + * 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(text); + while (m.find()) { + if (isExcluded(m.start())) + 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); + + // 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; + if (receiverType instanceof ScriptTypeInfo) { + hasMethod = ((ScriptTypeInfo) receiverType).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); + + + 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); + } + + // 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); + } + + 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); + } + 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 || text.charAt(pos) != '.') + return false; + + // Skip the dot and any whitespace + pos--; + while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) + pos--; + + if (pos < 0) + 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 && 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 + * @return List of parsed arguments with resolved types + */ + public List parseMethodArguments(int start, int end, MethodInfo methodInfo) { + 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); + + 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 == '}' || c == '>') { + 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]*\\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; + } + + // 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; + 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--; + + if (scanPos < 0 || 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 = line.indexOf("//"); + 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(); + } + + /** + * 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; + if (currentType instanceof ScriptTypeInfo) { + hasMethod = ((ScriptTypeInfo) currentType).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; + + if (currentType instanceof ScriptTypeInfo) { + hasField = ((ScriptTypeInfo) currentType).hasFieldInHierarchy(segment.name); + if (hasField) { + fieldInfo = ((ScriptTypeInfo) currentType).getFieldInfoInHierarchy(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 (currentType instanceof ScriptTypeInfo) { + ScriptTypeInfo innerClass = ((ScriptTypeInfo) currentType).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 + return resolveType(typeName); + } + } + + // 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 to check for chained identifier (preceded by a dot) + int checkPos = pos; + while (checkPos >= 0 && Character.isWhitespace(text.charAt(checkPos))) checkPos--; + // If it's part of a chained identifier (preceded by a dot), continue + if (checkPos >= 0 && 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); + 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.IMPORT_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(); + } + + // 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; + } + } + + 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++; + + 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); + 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); + } + } + + // 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 { + // Use factory method for regular types + 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 : info.getTokenType(); + 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) == '.'; + } + + 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; + } + } + 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 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. + */ + 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()); + } + } + + + // Include declaration errors (duplicates, etc.) + errored.addAll(declarationErrors); + + return errored; + } + + 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..f3deb5ecf --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptLine.java @@ -0,0 +1,431 @@ +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.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; + + for (Mark mark : marks) { + // Skip marks that don't overlap this line + if (mark.end <= globalStart || mark.start >= globalEnd) { + continue; + } + + // Clamp mark to line boundaries + int tokenStart = Math.max(mark.start, globalStart); + int tokenEnd = Math.min(mark.end, globalEnd); + + // 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 + if (cursor < globalEnd) { + int end = Math.min(globalEnd, fullText.length()); + if (cursor < end) { + String trailingText = fullText.substring(cursor, end); + addToken(Token.defaultToken(trailingText, cursor, end)); + } + } + } + + public void applyTokenMetadata(Token token, Object metadata) { + if (metadata instanceof TypeInfo) { + token.setTypeInfo((TypeInfo) metadata); + } 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 ==================== + + /** + * 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()); + + // 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) { + // Build the complete text with all tokens and gaps, draw it as ONE string + // to match the spacing behavior of drawString which draws everything at once + StringBuilder fullText = new StringBuilder(); + int lastIndex = 0; + + // Build segments with token position info + 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(fullText.length(), gap, 0xFFFFFFFF, false)); + fullText.append(gap); + } + + // Add the colored token + String styledText = t.getStylePrefix() + t.getText(); + segments.add(new TextSegment(fullText.length(), styledText, t.getHexColor(), true)); + fullText.append(styledText); + + lastIndex = tokenStart + styledText.length(); + } + + // Add any remaining text after the last token + if (lastIndex < text.length()) { + String remaining = text.substring(lastIndex); + segments.add(new TextSegment(fullText.length(), remaining, 0xFFFFFFFF, false)); + fullText.append(remaining); + } + + // Draw each segment at the correct position + // Calculate positions based on the full string to match drawString's spacing + for (TextSegment seg : segments) { + if (!seg.text.isEmpty()) { + // Get the width of everything before this segment + String prefix = fullText.substring(0, seg.startPos); + int prefixWidth = ClientProxy.Font.width(prefix); + int color = (seg.color & 0xFF000000) == 0 ? (0xFF000000 | seg.color) : seg.color; + + // Draw this segment at the correct position + ClientProxy.Font.drawString(seg.text, x + prefixWidth, y, color); + // Minecraft.getMinecraft().fontRenderer.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, + 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..05da45227 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java @@ -0,0 +1,261 @@ +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.CLASS_KEYWORD) return JavaTextContainer.TokenType.CLASS_KEYWORD; + if (type == noppes.npcs.client.gui.util.script.interpreter.token.TokenType.IMPORT_KEYWORD) return JavaTextContainer.TokenType.IMPORT_KEYWORD; + 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.MODIFIER) return JavaTextContainer.TokenType.MODIFIER; + 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..565dd9717 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/AssignmentInfo.java @@ -0,0 +1,249 @@ +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.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 = targetType.getSimpleName(); + this.providedType = sourceType.getSimpleName(); + 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..f86b3e146 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/EnumConstantInfo.java @@ -0,0 +1,317 @@ +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 + ); + + // 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..466f1d8c4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/field/FieldInfo.java @@ -0,0 +1,616 @@ +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.type.TypeSubstitutor; +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; +import java.util.Map; + +/** + * 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)) { + Map receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType); + if (!receiverBindings.isEmpty()) { + type = TypeSubstitutor.substitute(type, receiverBindings); + } + } + + // 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; } + 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..3c5087533 --- /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, 0xFF000000 | 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..7618561c5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java @@ -0,0 +1,558 @@ +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 = 100; + + // ==================== 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; + + // ==================== 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); + } + } + } + + /** + * 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); + } + } + } + + /** + * 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; + } + } + } + + /** + * 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; + } + + /** + * Unpin any pinned token and hide tooltip. + */ + public void unpin() { + this.pinnedToken = null; + this.pinnedHoverInfo = null; + this.tooltipVisible = false; + this.hoverInfo = null; + } + + public boolean isPinned() { return pinnedToken != null; } + + // ==================== POSITION CALCULATION ==================== + + /** + * Get the character index within a line at the given X pixel position. + */ + 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 = noppes.npcs.client.ClientProxy.Font.width(String.valueOf(text.charAt(i))); + 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 + String lineText = line.getText(); + int tokenLocalStart = token.getGlobalStart() - line.getGlobalStart(); + tokenLocalStart = Math.max(0, Math.min(tokenLocalStart, lineText.length())); + + String textBefore = lineText.substring(0, tokenLocalStart); + tokenScreenX = viewportX + noppes.npcs.client.ClientProxy.Font.width(textBefore); + + // Y position: line position minus scroll + int lineY = line.getLineIndex(); + tokenScreenY = viewportY + (int) ((lineY - scrollOffset) * lineHeight); + + // Token width + tokenWidth = noppes.npcs.client.ClientProxy.Font.width(token.getText()); + } + + 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..3e2912bf6 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java @@ -0,0 +1,1787 @@ +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.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.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: + 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 MODIFIER: + 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) { + // Check if this token is part of a method call argument (positional lookup) + MethodCallInfo containingCall = findMethodCallContainingPosition(token); + if (containingCall != null) { + MethodCallInfo.Argument containingArg = findArgumentContainingPosition(containingCall, token.getGlobalStart()); + if (containingArg != null) { + // Show only this argument's specific error + MethodCallInfo.ArgumentTypeError argError = findArgumentError(containingCall, containingArg); + if (argError != null) { + errors.add(argError.getMessage()); + return; // Only show argument error, not method-level errors + } + } + } + + // Show method-level errors if this is the method name itself + MethodCallInfo callInfo = token.isEnumConstant()? containingCall : token.getMethodCallInfo(); + if (callInfo != null) { + if (callInfo.hasArgCountError()) { + errors.add(callInfo.getErrorMessage()); + } + if (callInfo.hasArgTypeError()) { + for (MethodCallInfo.ArgumentTypeError error : callInfo.getArgumentTypeErrors()) { + errors.add(error.getMessage()); + } + } + if (callInfo.hasReturnTypeMismatch()) { + errors.add(callInfo.getErrorMessage()); + } + if (callInfo.hasStaticAccessError()) { + errors.add(callInfo.getErrorMessage()); + } + if (callInfo.getErrorType() == MethodCallInfo.ErrorType.UNRESOLVED_METHOD) { + errors.add(callInfo.getErrorMessage()); + } + } + + // Show field access errors + FieldAccessInfo fieldAccessInfo = token.getFieldAccessInfo(); + if (fieldAccessInfo != null && fieldAccessInfo.hasError()) { + errors.add(fieldAccessInfo.getErrorMessage()); + } + + // Show assignment errors (type mismatch, final reassignment, etc.) + // Search through FieldInfo's assignments by position + AssignmentInfo assignmentInfo = findAssignmentContainingPosition(token); + if (assignmentInfo != null && assignmentInfo.hasError()) { + errors.add(assignmentInfo.getErrorMessage()); + } + + // Show unresolved field errors + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo != null && !fieldInfo.isResolved()) { + errors.add("Cannot resolve symbol '" + token.getText() + "'"); + } + + // Show method declaration errors (missing return, parameter errors, return type errors) + MethodInfo methodDecl = findMethodDeclarationContainingPosition(token); + if (methodDecl != null && methodDecl.hasError()) { + int tokenStart = token.getGlobalStart(); + int tokenEnd = token.getGlobalEnd(); + + // If hovering over the method name, show missing return error + if (methodDecl.hasMissingReturnError()) { + int methodNameStart = methodDecl.getNameOffset(); + int methodNameEnd = methodNameStart + methodDecl.getName().length(); + + if (tokenStart >= methodNameStart && tokenEnd <= methodNameEnd) { + errors.add(methodDecl.getErrorMessage()); + } + } + + // If hovering over a parameter with an error, show that error + else if (methodDecl.hasParameterErrors()) { + for (MethodInfo.ParameterError paramError : methodDecl.getParameterErrors()) { + FieldInfo param = paramError.getParameter(); + if (param != null && param.getDeclarationOffset() >= 0) { + int paramStart = param.getDeclarationOffset(); + int paramEnd = paramStart + param.getName().length(); + + if (tokenStart >= paramStart && tokenEnd <= paramEnd) { + errors.add(paramError.getMessage()); + } + } + } + } + + // If hovering over a return statement with a type error, show that error + else if (methodDecl.hasReturnStatementErrors()) { + for (MethodInfo.ReturnStatementError returnError : methodDecl.getReturnStatementErrors()) { + int returnStart = returnError.getStartOffset(); + int returnEnd = returnError.getEndOffset(); + + if (tokenStart >= returnStart && tokenEnd <= returnEnd) { + errors.add(returnError.getMessage()); + } + } + } + + + // All other errors + else if (methodDecl.hasError()) { + int declStart = methodDecl.getFullDeclarationOffset(); + int declEnd = methodDecl.getDeclarationEnd(); + + if (tokenStart >= declStart && tokenEnd <= declEnd) { + errors.add(methodDecl.getErrorMessage()); + } + } + } + + ScriptTypeInfo scriptType = findScriptTypeContainingPosition(token); + if (scriptType != null && 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()); + } + } + + EnumConstantInfo enumConst = findEnumConstantContainingPosition(token); + if (enumConst != null && enumConst.hasError()) { + errors.add(enumConst.getErrorMessage()); + } + + 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()); + } + } + + /** + * Find an assignment that contains this token's position. + * Searches through all assignments (script fields and external fields). + */ + private AssignmentInfo findAssignmentContainingPosition(Token token) { + ScriptLine line = token.getParentLine(); + if (line == null || line.getParent() == null) { + return null; + } + + ScriptDocument doc = line.getParent(); + int tokenStart = token.getGlobalStart(); + + // Use ScriptDocument's method which handles all prioritization + return doc.findAssignmentAtPosition(tokenStart); + } + + /** + * Find the method call that contains this token's position within its argument list. + */ + private MethodCallInfo findMethodCallContainingPosition(Token token) { + ScriptLine line = token.getParentLine(); + if (line == null || line.getParent() == null) { + return null; + } + + ScriptDocument doc = line.getParent(); + int tokenStart = token.getGlobalStart(); + + for (MethodCallInfo call : doc.getMethodCalls()) { + boolean isWithinName = tokenStart >= call.getMethodNameStart() && tokenStart <= call.getMethodNameEnd(); + + // If this is an enum constant, return methodCall on name itself + if (token.isEnumConstant() && isWithinName) + return call; + + // Check if token is within the argument list + if (tokenStart >= call.getOpenParenOffset() && tokenStart <= call.getCloseParenOffset()) { + // Make sure it's not the method name itself + if (isWithinName) { + continue; + } + return call; + } + } + return null; + } + + /** + * Find the method declaration that contains this token's position. + * Returns null if the token is not within a method declaration (header or body). + */ + private MethodInfo findMethodDeclarationContainingPosition(Token token) { + ScriptLine line = token.getParentLine(); + if (line == null || line.getParent() == null) { + return null; + } + + ScriptDocument doc = line.getParent(); + int tokenStart = token.getGlobalStart(); + + for (MethodInfo method : doc.getAllMethods()) { + if (!method.isDeclaration()) + continue; + + // Check if token is within the method declaration header OR body + int methodStart = method.getFullDeclarationOffset(); + if (methodStart < 0) methodStart = method.getTypeOffset(); + int bodyEnd = method.getBodyEnd(); + + // Token is within the method (header + body) + if (tokenStart >= methodStart && tokenStart <= bodyEnd) { + return method; + } + } + return null; + } + + private ScriptTypeInfo findScriptTypeContainingPosition(Token token) { + ScriptLine line = token.getParentLine(); + if (line == null || line.getParent() == null) { + return null; + } + + ScriptDocument doc = line.getParent(); + int tokenStart = token.getGlobalStart(); + + for (ScriptTypeInfo scriptType : doc.getScriptTypes()) { + int typeStart = scriptType.getDeclarationOffset(); + int typeEnd = scriptType.getBodyStart(); + + // Token is within the type declaration + if (tokenStart >= typeStart && tokenStart <= typeEnd) { + return scriptType; + } + } + return null; + } + + private EnumConstantInfo findEnumConstantContainingPosition(Token token) { + ScriptLine line = token.getParentLine(); + if (line == null || line.getParent() == null) { + return null; + } + + ScriptDocument doc = line.getParent(); + int tokenStart = token.getGlobalStart(); + + for (EnumConstantInfo enumConst : doc.getAllEnumConstants()) { + int constStart = enumConst.getDeclarationOffset(); + int constEnd = constStart + enumConst.getName().length(); + + // Token is within the enum constant declaration + if (tokenStart >= constStart && tokenStart <= constEnd) { + return enumConst; + } + } + return null; + } + + /** + * Find the argument that contains the given position. + */ + private MethodCallInfo.Argument findArgumentContainingPosition(MethodCallInfo callInfo, int position) { + for (MethodCallInfo.Argument arg : callInfo.getArguments()) { + if (position >= arg.getStartOffset() && position <= arg.getEndOffset()) { + return arg; + } + } + return null; + } + + /** + * Find the type error for a specific argument. + */ + private MethodCallInfo.ArgumentTypeError findArgumentError(MethodCallInfo callInfo, MethodCallInfo.Argument argument) { + if (!callInfo.hasArgTypeError()) { + return null; + } + + int argIndex = callInfo.getArguments().indexOf(argument); + if (argIndex < 0) { + return null; + } + + for (MethodCallInfo.ArgumentTypeError error : callInfo.getArgumentTypeErrors()) { + if (error.getArgIndex() == argIndex) { + return error; + } + } + return null; + } + + private int getExpectedArgCount(MethodCallInfo callInfo) { + MethodInfo method = callInfo.getResolvedMethod(); + if (method != null) { + return method.getParameterCount(); + } + return 0; + } + + private void extractClassInfo(Token token) { + TypeInfo typeInfo = token.getTypeInfo(); + if (typeInfo == null) 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.MODIFIER.getHexColor()); + if (Modifier.isAbstract(mods) && !clazz.isInterface()) addSegment("abstract ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isFinal(mods) && !isEnum) addSegment("final ", TokenType.MODIFIER.getHexColor()); + + // Class type keyword + if (clazz.isInterface()) { + addSegment("interface ", TokenType.MODIFIER.getHexColor()); + } else if (isEnum) { + addSegment("enum ", TokenType.MODIFIER.getHexColor()); + } else { + addSegment("class ", TokenType.MODIFIER.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); + + // Extends + Class superclass = clazz.getSuperclass(); + if (superclass != null && superclass != Object.class && !isEnum) { + addSegment(" extends ", TokenType.MODIFIER.getHexColor()); + addSegment(superclass.getSimpleName(), getColorForClass(superclass)); + } + + List declaration = null; + + // Implements + Class[] interfaces = clazz.getInterfaces(); + if (interfaces.length > 0) { + addSegment(clazz.isInterface() ? " extends " : " implements ", TokenType.MODIFIER.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.MODIFIER.getHexColor()); + if (Modifier.isAbstract(mods) && scriptType.getKind() != TypeInfo.Kind.INTERFACE) + addSegment("abstract ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isFinal(mods)) addSegment("final ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isStatic(mods)) addSegment("static ", TokenType.MODIFIER.getHexColor()); + + // Class type keyword + if (scriptType.getKind() == TypeInfo.Kind.INTERFACE) { + addSegment("interface ", TokenType.MODIFIER.getHexColor()); + } else if (scriptType.getKind() == TypeInfo.Kind.ENUM) { + addSegment("enum ", TokenType.MODIFIER.getHexColor()); + } else { + addSegment("class ", TokenType.MODIFIER.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); + + // Extends clause for ScriptTypeInfo + if (scriptType.hasSuperClass()) { + addSegment(" extends ", TokenType.MODIFIER.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.MODIFIER.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.MODIFIER.getHexColor()); + addTypeSegments(typeInfo); + + if (jsType.getExtendsType() != null) { + addSegment(" extends ", TokenType.MODIFIER.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 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.getJavaMethod(), 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.MODIFIER.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; + + 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 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.MODIFIER.getHexColor()); + else if (Modifier.isProtected(mods)) addSegment("protected ", TokenType.MODIFIER.getHexColor()); + else if (Modifier.isPrivate(mods)) addSegment("private ", TokenType.MODIFIER.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(Method method, TypeInfo containingType) { + int mods = method.getModifiers(); + + // Annotations (show @Contract if present, etc.) + // Skip for now - could add later + + // Modifiers + if (Modifier.isPublic(mods)) addSegment("public ", TokenType.MODIFIER.getHexColor()); + else if (Modifier.isProtected(mods)) addSegment("protected ", TokenType.MODIFIER.getHexColor()); + else if (Modifier.isPrivate(mods)) addSegment("private ", TokenType.MODIFIER.getHexColor()); + + if (Modifier.isStatic(mods)) addSegment("static ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isFinal(mods)) addSegment("final ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isAbstract(mods)) addSegment("abstract ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isSynchronized(mods)) addSegment("synchronized ", TokenType.MODIFIER.getHexColor()); + + // Return type - check for actual type color (handle array suffix coloring) + Class returnType = method.getReturnType(); + String returnTypeName = returnType.getSimpleName(); + splitAndAddTypeName(returnTypeName, getColorForTypeInfo(containingType)); + addSegment(" ", TokenType.DEFAULT.getHexColor()); + + // Method name + addSegment(method.getName(), TokenType.METHOD_DECL.getHexColor()); + + // Parameters + addSegment("(", TokenType.DEFAULT.getHexColor()); + Class[] paramTypes = method.getParameterTypes(); + java.lang.reflect.Parameter[] params = method.getParameters(); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor()); + int paramTypeColor = getColorForClass(paramTypes[i]); + String paramTypeName = paramTypes[i].getSimpleName(); + splitAndAddTypeName(paramTypeName, paramTypeColor); + if (method.isVarArgs() && i == paramTypes.length - 1) { + addSegment("...", TokenType.DEFAULT.getHexColor()); + } + addSegment(" ", TokenType.DEFAULT.getHexColor()); + // Try to get parameter name if available + String paramName = params.length > i ? params[i].getName() : "arg" + i; + addSegment(paramName, 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.MODIFIER.getHexColor()); + } + } else { + // Fallback: show static if we know it + if (methodInfo.isStatic()) { + addSegment("static ", TokenType.MODIFIER.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.MODIFIER.getHexColor()); + else if (Modifier.isProtected(mods)) + addSegment("protected ", TokenType.MODIFIER.getHexColor()); + else if (Modifier.isPrivate(mods)) + addSegment("private ", TokenType.MODIFIER.getHexColor()); + + if (Modifier.isStatic(mods)) + addSegment("static ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isFinal(mods)) + addSegment("final ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isVolatile(mods)) + addSegment("volatile ", TokenType.MODIFIER.getHexColor()); + if (Modifier.isTransient(mods)) + addSegment("transient ", TokenType.MODIFIER.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..f3215b1a9 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java @@ -0,0 +1,744 @@ +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 = 4; + + /** 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 + int tooltipX = positionOverridden ? hoverState.getOverriddenTooltipX() : tokenX; + int tooltipY = positionOverridden ? hoverState.getOverriddenTooltipY() : 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 - VERTICAL_OFFSET; // try above token + } + } + 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, union the token bottom and the tooltip rect so both directions are covered + if (hoverState.hasOverriddenPosition()) { + hoverState.setTooltipBounds(tooltipX, tooltipY, boxWidth, boxHeight); + } else { + int boundsTopY = Math.min(tokenY + lineHeight, tooltipY); + int boundsBottomY = Math.max(tooltipY + boxHeight, tokenY + lineHeight); + hoverState.setTooltipBounds(tooltipX, boundsTopY, boxWidth, boundsBottomY - boundsTopY); + } + + // 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 + BOTTOM_GAP)); + + // 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 = 0xFF000000 | 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..d30503e8b --- /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..0926ceafe --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/JSTypeInfo.java @@ -0,0 +1,311 @@ +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()); + } + } + + /** + * Resolves a type parameter to its bound TypeInfo. + * For example, if this type has "T extends EntityPlayerMP", resolveTypeParam("T") returns the TypeInfo for EntityPlayerMP. + * If no type parameter is found with that name, returns null. + */ + public TypeInfo resolveTypeParamToTypeInfo(String typeName) { + TypeParamInfo param = getTypeParam(typeName); + if (param != null) { + return param.getBoundTypeInfo(); + } + return null; + } + + /** + * Resolves a type parameter to its bound type name (for backward compatibility). + * @deprecated Use resolveTypeParamToTypeInfo instead + */ + @Deprecated + public String resolveTypeParam(String typeName) { + TypeParamInfo param = getTypeParam(typeName); + if (param != null && param.getBoundTypeInfo() != null) { + return param.getBoundTypeInfo().getSimpleName(); + } + return typeName; + } + + /** + * 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..83e11d317 --- /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..846a23f47 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/js_parser/TypeParamInfo.java @@ -0,0 +1,68 @@ +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; + +/** + * Represents a generic type parameter like "T extends Entity". + * Stores the parameter name and both the string representation (for deferred resolution) + * and the resolved TypeInfo for the bound. + */ +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 bound (resolved in Phase 2) + + /** + * 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 + } + + public String getName() { return name; } + + public TypeInfo getBoundTypeInfo() { + return boundTypeInfo; + } + + /** + * 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() { + if (boundTypeInfo != null) { + return name + " extends " + boundTypeInfo.getDisplayName(); + } else if (boundType != null || fullBoundType != null) { + return name + " extends " + (boundType != null ? boundType : fullBoundType); + } + return name; + } +} 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..9b4716ec9 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodCallInfo.java @@ -0,0 +1,458 @@ +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 " + paramType.getDisplayName() + + " but got " + argType.getDisplayName()); + } + } 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() + "'"); + } + } + } + + @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..a16943e4b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/method/MethodInfo.java @@ -0,0 +1,746 @@ +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.TypeSubstitutor; +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) + Map receiverBindings = null; + if (GenericContext.hasGenerics(containingType)) { + receiverBindings = TypeSubstitutor.createBindingsFromReceiver(containingType); + if (!receiverBindings.isEmpty()) { + returnType = TypeSubstitutor.substitute(returnType, receiverBindings); + } + } + 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 (receiverBindings != null && !receiverBindings.isEmpty()) { + paramType = TypeSubstitutor.substitute(paramType, receiverBindings); + } + + // 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(); } + + /** + * 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/Token.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/Token.java new file mode 100644 index 000000000..b7b81af9e --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/Token.java @@ -0,0 +1,271 @@ +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 modifier(String text, int start, int end) { + return new Token(text, start, end, TokenType.MODIFIER); + } + + 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 || type == TokenType.MODIFIER || + type == TokenType.CLASS_KEYWORD || type == TokenType.IMPORT_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(); + } + + @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..2cb57da62 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/token/TokenType.java @@ -0,0 +1,150 @@ +package noppes.npcs.client.gui.util.script.interpreter.token; + +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. + */ +public enum TokenType { + // Comments and strings have highest priority - they override everything inside them + COMMENT(0x777777, 140), + STRING(0xCC8855, 130), + + // JSDoc elements - lower priority but will fill gaps left by fragmented comment marking + JSDOC_TAG(0xCC9933, 125), // @param, @type, @return etc. (gold/orange) + JSDOC_TYPE(0x00AAAA, 124), // {TypeName} in JSDoc (aqua like types) + + UNUSED_IMPORT(0x666666, 119), // unused import statements (gray) + + // Keywords and modifiers + CLASS_KEYWORD(0xFF5555, 115), // 'class', 'interface', 'enum' keywords + IMPORT_KEYWORD(0xFFAA00, 110), // 'import' keyword + KEYWORD(0xFF5555, 100), // control flow: if, else, for, while, etc. + MODIFIER(0xFFAA00, 90), // public, private, static, final, etc. + + // Type declarations and references + INTERFACE_DECL(0x55FFFF, 85), // interface names (aqua) + ENUM_DECL(0xFF55FF, 85), // enum names (magenta) + ENUM_CONSTANT(0x55FFFF, 84, true, false), // enum constant values (blue, bold+italic) - like IntelliJ + CLASS_DECL(0x00AAAA, 85), // class names in declarations + IMPORTED_CLASS(0x00AAAA, 75), // imported class usages + TYPE_DECL(0x00AAAA, 70), // package paths, type references + + // Methods + METHOD_DECL(0x00AA00, 60), // method declarations (green) + METHOD_CALL(0x55FF55, 50), // method calls (bright green) + + // Variables and fields + UNDEFINED_VAR(0xAA0000, 20), // unresolved variables (dark red) - high priority + PARAMETER(0x5555FF, 36), // method parameters (blue) + GLOBAL_FIELD(0x55FFFF, 35), // class-level fields (aqua) + LOCAL_FIELD(0xFFFF55, 25), // local variables (yellow) + STATIC_FINAL_FIELD(0xFF55FF, 36, false, true), // static final fields (magenta, italic) + + // Literals + LITERAL(0x777777, 40), // numeric and boolean literals + + // Default + VARIABLE(0xFFFFFF, 30), // generic variables + DEFAULT(0xFFFFFF, 0); // default text color (white) + + private final int hexColor; + private final int priority; + private final boolean bold; + private final boolean italic; + + TokenType(int hexColor, int priority) { + this(hexColor, priority, false, false); + } + + TokenType(int hexColor, int priority, boolean bold, boolean italic) { + this.hexColor = hexColor; + this.priority = priority; + this.bold = bold; + this.italic = italic; + } + + public int getHexColor() { + return hexColor; + } + + public int getPriority() { + return priority; + } + + public boolean isBold() { + return bold; + } + + public boolean isItalic() { + return italic; + } + + 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(); + } + + /** + * 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 CLASS_KEYWORD: + case KEYWORD: + return 'c'; // red + case IMPORT_KEYWORD: + case MODIFIER: + return '6'; // gold + 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 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..916623586 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/GenericContext.java @@ -0,0 +1,276 @@ +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; + +/** + * A context for resolving and substituting declared type parameters (T, E, K, V...) + * based on a receiver type. + * + * Policy: + * - Prefer applied type arguments when present (e.g. List binds E -> String). + * - Fall back to declared bounds when no applied argument exists (e.g. T extends Entity -> Entity). + */ +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 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 bound = declared.getBoundTypeInfo(); + if (bound != null && bound.isResolved()) { + bounds.put(name, bound); + } + } + } + + 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 (unresolved types represent type variables like T). + if (!type.isResolved()) { + TypeInfo substitution = resolveTypeVariable(type.getSimpleName()); + 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/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..0ed37fcdc --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/ScriptTypeInfo.java @@ -0,0 +1,945 @@ +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.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.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 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<>(); + + // 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; } + + // ==================== 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; + + 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(); + } + + 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. + */ + 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) { + return methods.containsKey(methodName); + } + + @Override + public boolean hasMethod(String methodName, int paramCount) { + List overloads = methods.get(methodName); + if (overloads == null) return false; + for (MethodInfo m : overloads) { + if (m.getParameterCount() == paramCount) { + return true; + } + } + return false; + } + + @Override + public MethodInfo getMethodInfo(String methodName) { + List overloads = methods.get(methodName); + return (overloads != null && !overloads.isEmpty()) ? overloads.get(0) : null; + } + + /** + * Get all method overloads with the given name. + */ + public List getAllMethodOverloads(String methodName) { + return methods.getOrDefault(methodName, new ArrayList<>()); + } + + /** + * 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; + } + + // ==================== 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()) { + boolean parentHasNoArg = false; + + if (superClass instanceof ScriptTypeInfo) { + ScriptTypeInfo parentScript = (ScriptTypeInfo) superClass; + if (!parentScript.hasConstructors() || parentScript.findConstructor(0) != null) { + parentHasNoArg = true; + } + } else { + Class javaClass = superClass.getJavaClass(); + if (javaClass != null) { + try { + for (java.lang.reflect.Constructor ctor : javaClass.getConstructors()) { + if (ctor.getParameterCount() == 0) { + parentHasNoArg = true; + break; + } + } + } catch (Exception e) { + // Security error + } + } + } + + if (!parentHasNoArg) { + addConstructorMismatchError(superClass, superClass.getSimpleName()); + } + } + // 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..a9516f3e5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeChecker.java @@ -0,0 +1,566 @@ +package noppes.npcs.client.gui.util.script.interpreter.type; + +import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo; + +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 + + // 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; + + // Exact match by simple name + if (expectedName.equals(actualName)) return true; + + // Exact match by full name + if (expected.getFullName() != null && actual.getFullName() != null) { + if (expected.getFullName().equals(actual.getFullName())) 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; + } + } + + // 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 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..f7b552323 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeInfo.java @@ -0,0 +1,1248 @@ +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.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +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; + + // 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 final List appliedTypeArgs = new ArrayList<>(); + + // For parameterized types, the raw/base type (e.g., List for List) + // Null for non-parameterized types + private final 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); + } + + 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) { + 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) : 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); + 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()); + if (elementType != null) { + return arrayOf(elementType); + } + return fromClass(Object[].class); + } + + if (type instanceof TypeVariable) { + // Type variable like T, E, K, V + TypeVariable typeVar = (TypeVariable) type; + String varName = typeVar.getName(); + // Create an unresolved type representing the type variable + // The substitution system will handle replacing this with the actual type + return TypeInfo.unresolved(varName, varName); + } + + 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]); + } + + // 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, true, 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)); + 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 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; + } + + /** + * 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(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; + } + } + + /** + * 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 + } + } + + 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 + } + } + 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) return false; + try { + return javaClass.getConstructors().length > 0; + } catch (Exception e) { + // Security or linkage error + 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) return result; + + 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; + } + + /** + * 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) return 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; + } + + public MethodInfo findConstructor(TypeInfo[] argTypes) { + if (javaClass == null) return 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; + } + + /** + * 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) return false; + 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; + } + + public boolean hasEnumConstant(String constantName) { + if (javaClass == null || !javaClass.isEnum()) return false; + 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; + } + + /** + * Get an enum constant by name. + */ + public EnumConstantInfo getEnumConstant(String constantName) { + if (javaClass == null || !javaClass.isEnum()) return null; + 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; + } + + /** + * 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 + } + } + 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; + } + 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) return null; + try { + for (java.lang.reflect.Field f : javaClass.getFields()) { + if (f.getName().equals(fieldName)) { + // Create a synthetic FieldInfo from reflection + return FieldInfo.fromReflection(f, this); + } + } + } catch (Exception e) { + // Security or linkage error + } + 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 + 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; + } + + /** + * Resolves a type parameter to its bound TypeInfo. + * For example, if this type has "T extends EntityPlayerMP", resolveTypeParamToTypeInfo("T") returns the TypeInfo for EntityPlayerMP. + * If no type parameter is found with that name, returns null. + */ + public TypeInfo resolveTypeParamToTypeInfo(String typeName) { + TypeParamInfo param = getTypeParam(typeName); + if (param != null) { + return param.getBoundTypeInfo(); + } + 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 == null || getClass() != o.getClass()) return false; + TypeInfo typeInfo = (TypeInfo) o; + return fullName.equals(typeInfo.fullName); + } + + @Override + public int hashCode() { + return fullName.hashCode(); + } +} 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/TypeSubstitutor.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeSubstitutor.java new file mode 100644 index 000000000..514174743 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/type/TypeSubstitutor.java @@ -0,0 +1,197 @@ +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; + +/** + * Utility for substituting type variables (like T, E, K, V) with concrete types. + * + * Used when resolving members on parameterized types: + * - List.get(int) returns String (not T/Object) + * - Map.get(Object) returns Integer (not V) + * + * Handles nested generics: + * - List>.get(0) returns Map + */ +public class TypeSubstitutor { + + /** + * Create a binding map from declared type parameters to applied type arguments. + * + * Example: For List where List is declared as interface List: + * - declaredParams = [TypeParamInfo("E", ...)] + * - appliedArgs = [TypeInfo(String)] + * - Result: {"E" -> TypeInfo(String)} + * + * @param declaredParams The declared type parameters (from the generic type definition) + * @param appliedArgs The applied type arguments (from the parameterized usage) + * @return A map from type parameter names to their concrete TypeInfo values + */ + public static Map createBindings(List declaredParams, List appliedArgs) { + Map bindings = new HashMap<>(); + + if (declaredParams == null || appliedArgs == null) { + return bindings; + } + + int count = Math.min(declaredParams.size(), appliedArgs.size()); + for (int i = 0; i < count; i++) { + String paramName = declaredParams.get(i).getName(); + TypeInfo argType = appliedArgs.get(i); + if (paramName != null && argType != null) { + bindings.put(paramName, argType); + } + } + + return bindings; + } + + /** + * Create bindings from a parameterized receiver type. + * + * @param receiverType The parameterized type (e.g., List) + * @return Bindings from the type's declared params to its applied args + */ + public static Map createBindingsFromReceiver(TypeInfo receiverType) { + if (receiverType == null) { + return new HashMap<>(); + } + + // Get the raw type to access declared type parameters + TypeInfo rawType = receiverType.getRawType(); + List declaredParams = null; + + // Get declared params from JSTypeInfo or reflection + if (rawType.isJSType() && rawType.getJSTypeInfo() != null) { + declaredParams = rawType.getJSTypeInfo().getTypeParams(); + } else { + declaredParams = rawType.getTypeParams(); + } + + // Get applied args from the parameterized type + List appliedArgs = receiverType.getAppliedTypeArgs(); + + return createBindings(declaredParams, appliedArgs); + } + + /** + * Substitute type variables in a type using the given bindings. + * + * @param type The type to substitute (may contain type variables like T, E) + * @param bindings The map from type variable names to concrete types + * @return The substituted type + */ + public static TypeInfo substitute(TypeInfo type, Map bindings) { + if (type == null || bindings == null || bindings.isEmpty()) { + return type; + } + + String typeName = type.getSimpleName(); + + // Check if this type is itself a type variable + if (!type.isResolved()) { + TypeInfo substitution = bindings.get(typeName); + if (substitution != null) { + return substitution; + } + } + + // If the type has applied type arguments, substitute within them recursively + if (type.isParameterized()) { + List originalArgs = type.getAppliedTypeArgs(); + List substitutedArgs = new ArrayList<>(); + boolean changed = false; + + for (TypeInfo arg : originalArgs) { + TypeInfo substitutedArg = substitute(arg, bindings); + substitutedArgs.add(substitutedArg); + if (substitutedArg != arg) { + changed = true; + } + } + + if (changed) { + // Create a new parameterized type with substituted args + return type.getRawType().parameterize(substitutedArgs); + } + } + + // Handle array types - substitute the element type + if (type.getSimpleName().endsWith("[]")) { + TypeStringNormalizer.ArraySplit split = TypeStringNormalizer.splitArraySuffixes(typeName); + String elementTypeName = split.base; + int dims = split.dimensions; + TypeInfo elementSubstitution = elementTypeName != null ? bindings.get(elementTypeName) : null; + if (elementSubstitution != null) { + TypeInfo result = elementSubstitution; + for (int i = 0; i < dims; i++) { + result = TypeInfo.arrayOf(result); + } + return result; + } + } + + return type; + } + + /** + * Substitute type variables in a type string using the given bindings. + * Used when we have a raw type string (like "T" or "List") that needs substitution. + * + * @param typeString The raw type string + * @param bindings The map from type variable names to concrete types + * @param resolver The type resolver to use for parsing + * @return The substituted TypeInfo + */ + public static TypeInfo substituteString(String typeString, Map bindings, TypeResolver resolver) { + if (typeString == null || typeString.isEmpty()) { + return null; + } + + // First check if the whole string is a type variable + String trimmed = TypeStringNormalizer.stripImportTypeSyntax(typeString); + trimmed = TypeStringNormalizer.pickPreferredUnionBranch(trimmed); + trimmed = TypeStringNormalizer.stripNullableSuffix(trimmed); + + TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(trimmed); + String baseName = arraySplit.base; + int arrayDims = arraySplit.dimensions; + + // Strip generic args to check the base name + String bareBaseName = GenericTypeParser.stripGenerics(baseName); + + // If bare base name is a type variable, substitute + TypeInfo directSubstitution = bindings.get(bareBaseName); + if (directSubstitution != null) { + // It's a type variable, return the substitution + TypeInfo result = directSubstitution; + for (int i = 0; i < arrayDims; i++) { + result = TypeInfo.arrayOf(result); + } + return result; + } + + // Parse and resolve the type, then substitute within it + TypeInfo resolved = resolver.resolveJSType(typeString); + return substitute(resolved, bindings); + } + + /** + * Get the return type for a method on a parameterized receiver, with type variable substitution. + * + * @param rawReturnType The method's raw return type (may contain type variables) + * @param rawReturnTypeString The method's raw return type as a string (for unresolved types) + * @param receiverType The parameterized receiver type + * @param resolver The type resolver + * @return The substituted return type + */ + public static TypeInfo getSubstitutedReturnType(TypeInfo rawReturnType, String rawReturnTypeString, + TypeInfo receiverType, TypeResolver resolver) { + GenericContext ctx = GenericContext.forReceiver(receiverType); + return ctx.substituteType(rawReturnType, rawReturnTypeString, resolver); + } +} 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/KeyEvent.java b/src/main/java/noppes/npcs/client/key/KeyEvent.java new file mode 100644 index 000000000..1948e2f78 --- /dev/null +++ b/src/main/java/noppes/npcs/client/key/KeyEvent.java @@ -0,0 +1,41 @@ +package noppes.npcs.client.key; + +public class KeyEvent { + public final KeyPreset.PressType type; + public final KeyPreset preset; + public final int keyCode; + public final boolean isMouse; + public final long timestamp; + + public KeyEvent(KeyPreset.PressType type, KeyPreset preset) { + this.type = type; + this.preset = preset; + this.keyCode = preset.keyCode(); + this.isMouse = preset.isMouseKey(); + this.timestamp = System.currentTimeMillis(); + } + + public boolean is(KeyPreset.PressType t) { + return this.type == t; + } + + public boolean isPress() { + return is(KeyPreset.PressType.PRESS); + } + + public boolean isHold() { + return is(KeyPreset.PressType.HOLD); + } + + public boolean isRelease() { + return is(KeyPreset.PressType.RELEASE); + } + + public boolean isSinglePress() { + return is(KeyPreset.PressType.SINGLE_PRESS); + } + + public boolean isPressRelease() { + return is(KeyPreset.PressType.PRESS_RELEASE); + } +} diff --git a/src/main/java/noppes/npcs/client/key/KeyPreset.java b/src/main/java/noppes/npcs/client/key/KeyPreset.java new file mode 100644 index 000000000..57ef067e1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/key/KeyPreset.java @@ -0,0 +1,304 @@ +package noppes.npcs.client.key; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.GameSettings; +import net.minecraft.nbt.NBTTagCompound; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +import java.util.function.Consumer; + +public class KeyPreset { + /** + * @field SINGLE_PRESS => on releasing before 5 ticks press time + * @field PRESS_RELEASE => on pressing and releasing + */ + /** + * Press types for key events. + */ + public enum PressType {PRESS, HOLD, RELEASE, SINGLE_PRESS, PRESS_RELEASE} + + public KeyState defaultState = new KeyState(); + public KeyState currentState = new KeyState(); + + public String name, description; + public boolean shouldConflict = true; + public Consumer task; + + // Throttling for hold-down behavior + private long lastActionTime = 0; + private long throttleInterval = 25; + private long firstThrottleInterval = 500; + private boolean isFirstAction = true; + + private long pressStartMs = 0; + public boolean isDown; + + + public KeyPreset(String name) { + this.name = name; + } + + public KeyPreset setDefaultState(int keyCode, boolean hasCtrl, boolean hasAlt, boolean hasShift) { + defaultState.setState(keyCode, hasCtrl, hasAlt, hasShift); + currentState.setState(keyCode, hasCtrl, hasAlt, hasShift); + return this; + } + + public KeyPreset setDescription(String description) { + this.description = description; + return this; + } + + public KeyPreset setTask(Consumer task) { + this.task = task; + return this; + } + + public KeyPreset shouldConflict(boolean shouldConflict) { + this.shouldConflict = shouldConflict; + return this; + } + + /** + * Fire every X ms when holding + */ + public KeyPreset setThrottleInterval(long ms) { + this.throttleInterval = ms; + return this; + } + + /** + * Set throttle interval for the first action (initial press) + */ + public KeyPreset setFirstThrottleInterval(long ms) { + this.firstThrottleInterval = ms; + return this; + } + + /** + * Determine whether the given press type should be throttled. Only HOLD events are throttled. + */ + public boolean shouldThrottle(PressType pressType) { + if (throttleInterval <= 0) return false; + long currentTime = System.currentTimeMillis(); + long intervalToUse = pressType == PressType.HOLD && isFirstAction && firstThrottleInterval > 0 ? + firstThrottleInterval : throttleInterval; + if (currentTime - lastActionTime < intervalToUse) return true; + lastActionTime = currentTime; + isFirstAction = false; + return false; + } + + public void tick() { + int keyCode = keyCode(); + if (keyCode == -1 || keyCode == 0) + return; + + setDown(currentState.isDown()); + } + + private static final long SHORT_PRESS_MS = 250L; + + public void setDown(boolean down) { + if (down && !isDown) { // just pressed + pressStartMs = System.currentTimeMillis(); + onAction(PressType.PRESS, PressType.PRESS_RELEASE); + isFirstAction = true; // Reset for new press sequence + } + + if (!down && isDown) { // just released + if (getPressTime() <= SHORT_PRESS_MS) + onAction(PressType.SINGLE_PRESS); + onAction(PressType.RELEASE, PressType.PRESS_RELEASE); + pressStartMs = 0; + } + + if (down) // while held + onAction(PressType.HOLD); + + this.isDown = down; + } + + public long getPressTime() { + return pressStartMs > 0 ? (System.currentTimeMillis() - pressStartMs) : 0L; + } + + public KeyPreset onAction(PressType... pressTypes) { + if (task == null) + return this; + + for (PressType pressType : pressTypes) + if (!shouldThrottle(pressType)) + this.task.accept(new KeyEvent(pressType, this)); + + return this; + } + + public boolean isDefault() { + return currentState.equals(defaultState); + } + + public boolean isMouseKey() { + return keyCode() < -1; + } + + public int keyCode() { + return currentState.keyCode; + } + + public boolean hasCtrl() { + return currentState.hasCtrl; + } + + public boolean hasAlt() { + return currentState.hasAlt; + } + + public boolean hasShift() { + return currentState.hasShift; + } + + public String getKeyName() { + return currentState.getName(); + } + + public void clear() { + currentState.clear(); + } + + public void writeToNbt(NBTTagCompound c) { + c.setTag(name, currentState.writeToNbt()); + } + + public void readFromNbt(NBTTagCompound compound) { + currentState.readFromNbt(compound.getCompoundTag(name)); + } + + public boolean equals(Object preset) { + if (preset == this) + return true; + + if (preset instanceof KeyPreset) { + KeyPreset key = (KeyPreset) preset; + return key.currentState.equals(currentState); + } + + return false; + } + + public static class KeyState { + public int keyCode = -1; + public boolean hasCtrl, hasAlt, hasShift; + + public void setState(int keyCode, boolean hasCtrl, boolean hasAlt, boolean hasShift) { + this.keyCode = keyCode; + this.hasCtrl = hasCtrl; + this.hasAlt = hasAlt; + this.hasShift = hasShift; + } + + public void readFrom(KeyState state) { + keyCode = state.keyCode; + hasCtrl = state.hasCtrl; + hasShift = state.hasShift; + hasAlt = state.hasAlt; + } + + public void writeTo(KeyState state) { + 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; + } + + public void clear() { + this.keyCode = -1; + hasCtrl = hasAlt = hasShift = false; + } + + public boolean equals(Object preset) { + if (preset == this) + return true; + + if (preset instanceof KeyState) { + KeyState state = (KeyState) preset; + return state.keyCode == keyCode && state.hasCtrl == hasCtrl && state.hasAlt == hasAlt && state.hasShift == hasShift; + } + + return false; + } + + public NBTTagCompound writeToNbt() { + NBTTagCompound compound = new NBTTagCompound(); + compound.setInteger("keyCode", keyCode); + compound.setBoolean("hasCtrl", hasCtrl); + compound.setBoolean("hasShift", hasShift); + compound.setBoolean("hasAlt", hasAlt); + return compound; + } + + public void readFromNbt(NBTTagCompound compound) { + this.keyCode = compound.getInteger("keyCode"); + this.hasCtrl = compound.getBoolean("hasCtrl"); + this.hasShift = compound.getBoolean("hasShift"); + 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 = ""; + + if (code == LEFT_MOUSE) + name = "Left Mouse"; + else if (code == RIGHT_MOUSE) + name = "Right Mouse"; + else if (code == MIDDLE_MOUSE) + name = "Middle Mouse"; + else { + name = code == -1 ? "" : GameSettings.getKeyDisplayString(code); + if (name.contains("Button")) + name = name.replace("Button", "Mouse"); + } + + return (hasCtrl ? "CTRL " : "") + (hasAlt ? "ALT " : "") + (hasShift ? "SHIFT " : "") + name; + } + } + + public static final int LEFT_MOUSE = -100, RIGHT_MOUSE = -99, MIDDLE_MOUSE = -98, MOUSE_4 = -97, MOUSE_5 = -96; + + public static boolean isCtrlKeyDown() { + return Minecraft.isRunningOnMac ? Keyboard.isKeyDown(219) || Keyboard.isKeyDown(220) : Keyboard.isKeyDown(29) || Keyboard.isKeyDown(157); + } + + public static boolean isAltKeyDown() { + return Keyboard.isKeyDown(56) || Keyboard.isKeyDown(184); + } + + public static boolean isShiftKeyDown() { + return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54); + } + + public static boolean isNotCtrlAltShift(int key) { + return key != 219 && key != 220 && key != 29 && key != 157 && key != 42 && key != 54 && key != 56 && key != 184; + } +} diff --git a/src/main/java/noppes/npcs/client/key/KeyPresetManager.java b/src/main/java/noppes/npcs/client/key/KeyPresetManager.java new file mode 100644 index 000000000..df68eb812 --- /dev/null +++ b/src/main/java/noppes/npcs/client/key/KeyPresetManager.java @@ -0,0 +1,87 @@ +package noppes.npcs.client.key; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcs; +import noppes.npcs.LogWriter; +import noppes.npcs.util.NBTJsonUtil; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class KeyPresetManager { + public List keys = new ArrayList<>(); + public String fileName; + + + public KeyPresetManager(String fileName) { + this.fileName = fileName; + } + + public KeyPreset add(String name) { + KeyPreset preset = new KeyPreset(name); + keys.add(preset); + 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(); + } + + + public void load() { + try { + File dir = getDir(); + File file = new File(dir, fileName + ".json"); + if (!file.exists()) + return; + + NBTTagCompound compound = NBTJsonUtil.LoadFile(file); + for (KeyPreset key : keys) + key.readFromNbt(compound); + + } catch (Exception e) { + LogWriter.except(e); + } + } + + public void save() { + try { + File dir = getDir(); + String filename = fileName + ".json"; + + File newFile = new File(dir, filename + "_new"); + File originalFile = new File(dir, filename); + + NBTTagCompound compound = new NBTTagCompound(); + for (KeyPreset key : keys) + key.writeToNbt(compound); + + NBTJsonUtil.SaveFile(newFile, compound); + + if (originalFile.exists()) + originalFile.delete(); + + newFile.renameTo(originalFile); + } catch (Exception e) { + LogWriter.except(e); + } + } + + public File getDir() { + File dir = new File(CustomNpcs.Dir, "keypresets"); + if (!dir.exists()) + dir.mkdir(); + return dir; + } +} diff --git a/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java b/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java new file mode 100644 index 000000000..3029d4424 --- /dev/null +++ b/src/main/java/noppes/npcs/client/key/impl/ScriptEditorKeys.java @@ -0,0 +1,47 @@ +package noppes.npcs.client.key.impl; + +import noppes.npcs.client.key.KeyPreset; +import noppes.npcs.client.key.KeyPresetManager; +import org.lwjgl.input.Keyboard; + +public class ScriptEditorKeys extends KeyPresetManager { + + /// ///////////////// + // Editor shortcuts (mapped from GuiScriptTextArea.handleShortcutKeys) + public final KeyPreset COPY = add("Copy").setDefaultState(Keyboard.KEY_C, true, false, false); + public final KeyPreset PASTE = add("Paste").setDefaultState(Keyboard.KEY_V, true, false, false); + public final KeyPreset CUT = add("Cut").setDefaultState(Keyboard.KEY_X, true, false, false); + public final KeyPreset DUPLICATE = add("Duplicate").setDefaultState(Keyboard.KEY_D, true, false, false); + public final KeyPreset UNDO = add("Undo").setDefaultState(Keyboard.KEY_Z, true, false, false); + public final KeyPreset REDO = add("Redo").setDefaultState(Keyboard.KEY_Y, true, false, false); + + 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); + + // Navigation + public final KeyPreset GO_TO_LINE = add("Go to Line").setDefaultState(Keyboard.KEY_G, true, false, false); + + // Refactoring + public final KeyPreset RENAME = add("Rename").setDefaultState(Keyboard.KEY_R, true, false, false); + + // 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"); + load(); + } +} + 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/ModelPony.java b/src/main/java/noppes/npcs/client/model/ModelPony.java index b0d23b40a..203a1d12b 100644 --- a/src/main/java/noppes/npcs/client/model/ModelPony.java +++ b/src/main/java/noppes/npcs/client/model/ModelPony.java @@ -17,7 +17,7 @@ import noppes.npcs.entity.EntityNpcPony; import org.lwjgl.opengl.GL11; import javax.imageio.ImageIO; -import java.awt.*; +import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; 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/ImageBufferDownloadAlt.java b/src/main/java/noppes/npcs/client/renderer/ImageBufferDownloadAlt.java index 252f0af65..90172ce6f 100644 --- a/src/main/java/noppes/npcs/client/renderer/ImageBufferDownloadAlt.java +++ b/src/main/java/noppes/npcs/client/renderer/ImageBufferDownloadAlt.java @@ -2,7 +2,7 @@ package noppes.npcs.client.renderer; import net.minecraft.client.renderer.ImageBufferDownload; -import java.awt.*; +import java.awt.Graphics; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; 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..748db40d4 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; @@ -601,7 +609,26 @@ public class RenderNPCInterface extends RenderLiving { 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 +644,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/RenderNPCPony.java b/src/main/java/noppes/npcs/client/renderer/RenderNPCPony.java index a82ba93a8..b018adf60 100644 --- a/src/main/java/noppes/npcs/client/renderer/RenderNPCPony.java +++ b/src/main/java/noppes/npcs/client/renderer/RenderNPCPony.java @@ -25,7 +25,7 @@ import noppes.npcs.entity.EntityNpcPony; import org.lwjgl.opengl.GL11; import javax.imageio.ImageIO; -import java.awt.*; +import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java b/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java index 64b37340f..7f9fdd19b 100644 --- a/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java +++ b/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java @@ -26,8 +26,8 @@ public class BlockBeamRenderer extends BlockRendererInterface { public void renderTileEntityAt(TileEntity var1, double var2, double var4, double var6, float var8) { TileVariant tile = (TileVariant) var1; - GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPushMatrix(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glTranslatef((float) var2 + 0.5f, (float) var4 + 1.5f, (float) var6 + 0.5f); //GL11.glScalef(1.2f, 1.1f, 1.2f); GL11.glRotatef(180, 0, 0, 1); diff --git a/src/main/java/noppes/npcs/client/renderer/blocks/BlockScriptedRenderer.java b/src/main/java/noppes/npcs/client/renderer/blocks/BlockScriptedRenderer.java index 9aa8cdcaa..5be3a9492 100644 --- a/src/main/java/noppes/npcs/client/renderer/blocks/BlockScriptedRenderer.java +++ b/src/main/java/noppes/npcs/client/renderer/blocks/BlockScriptedRenderer.java @@ -23,7 +23,7 @@ import noppes.npcs.blocks.tiles.TileScripted.TextPlane; import noppes.npcs.client.TextBlockClient; import org.lwjgl.opengl.GL11; -import java.awt.*; +import java.awt.Color; import java.util.Random; public class BlockScriptedRenderer extends BlockRendererInterface { 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/client/util/Color.java b/src/main/java/noppes/npcs/client/util/Color.java new file mode 100644 index 000000000..75450aeee --- /dev/null +++ b/src/main/java/noppes/npcs/client/util/Color.java @@ -0,0 +1,114 @@ +package noppes.npcs.client.util; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.nbt.NBTTagCompound; +import org.lwjgl.opengl.GL11; + +public class Color { + public int color; + public float alpha; + + public Color(int color) { + setColor(color, 1); + } + + public Color(int color, float alpha) { + setColor(color, alpha); + } + + public Color(int red, int green, int blue, float alpha) { + setColor(red, green, blue, alpha); + } + + public void setColor(int color, float alpha) { + this.color = color; + this.alpha = alpha; + } + + public void setColor(int red, int green, int blue, float alpha) { + this.color = (red << 16) + (green << 8) + blue; + this.alpha = alpha; + } + + public static Color lerpRGBA(Color color1, Color color2, float fraction) { + fraction = Math.min(fraction, 1f); + int red = (int) (color1.getRed() + ((color2.getRed() - color1.getRed()) * fraction)); + int green = (int) (color1.getGreen() + ((color2.getGreen() - color1.getGreen()) * fraction)); + int blue = (int) (color1.getBlue() + ((color2.getBlue() - color1.getBlue()) * fraction)); + float newAlpha = color1.alpha + ((color2.alpha - color1.alpha) * fraction); + int newColor = (red << 16) + (green << 8) + blue; + return new Color(newColor, newAlpha); + } + + public Color lerpRGBA(Color color2, float fraction) { + return Color.lerpRGBA(this, color2, fraction); + } + + public Color multiply(float multi) { + if (multi == 1) + return this.clone(); + + int r = (int) ((getRed() * multi)); + int g = (int) ((getGreen() * multi)); + int b = (int) ((getBlue() * multi)); + float a = alpha * multi; + return new Color((r << 16) + (g << 8) + b, a); + } + + @SideOnly(Side.CLIENT) + public void glColor() { + GL11.glColor4f(getRedF(), getGreenF(), getBlueF(), alpha); + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound, String name) { + compound.setInteger(name + "Color", color); + compound.setFloat(name + "Alpha", alpha); + + return compound; + } + + public void readFromNBT(NBTTagCompound compound, String name) { + setColor(compound.getInteger(name + "Color"), compound.getFloat(name + "Alpha")); + } + + public int getRed() { + return (color >> 16 & 0xFF); + } + + public float getRedF() { + return (float) (color >> 16 & 0xFF) / 255f; + } + + public int getGreen() { + return (color >> 8 & 0xFF); + } + + public float getGreenF() { + return (float) (color >> 8 & 0xFF) / 255f; + } + + public int getBlue() { + return (color & 0xFF); + } + + public float getBlueF() { + return (float) (color & 0xFF) / 255f; + } + + public static String getColor(int color) { + String str; + for (str = Integer.toHexString(color); str.length() < 6; str = "0" + str) { + } + return str; + } + + public static String getColor(int color, float alpha) { + String str = getColor(color); + return str + " | " + (int) (alpha * 255); + } + + public Color clone() { + return new Color(color, alpha); + } +} diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index c24a2e301..ea87eeaf9 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -17,11 +17,15 @@ 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"; /** * General Properties **/ + public static Property AllowClientScriptsProperty; + public static boolean AllowClientScripts = true; + public static Property CacheLifeProperty; public static int CacheLife = 10; @@ -49,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 **/ @@ -66,10 +84,10 @@ 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 = 31; public static Property QuestOverlayScaleProperty; public static int QuestOverlayScale = 223; @@ -81,10 +99,10 @@ public class ConfigClient { public static boolean CompassEnabled = true; public static Property CompassOverlayXProperty; - public static int CompassOverlayX = 37; + public static float CompassOverlayX = 37; public static Property CompassOverlayYProperty; - public static int CompassOverlayY = 0; + public static float CompassOverlayY = 0; public static Property CompassOverlayScaleProperty; public static int CompassOverlayScale = 276; @@ -92,6 +110,41 @@ public class ConfigClient { public static Property CompassOverlayWidthProperty; public static int CompassOverlayWidth = 200; + // Ability Hotbar HUD + public static Property AbilityHotbarEnabledProperty; + public static boolean AbilityHotbarEnabled = true; + + public static Property AbilityHotbarXProperty; + public static float AbilityHotbarX = 3; + + public static Property AbilityHotbarYProperty; + public static float AbilityHotbarY = 50; + + public static Property AbilityHotbarScaleProperty; + public static int AbilityHotbarScale = 100; + + public static Property AbilityHotbarHorizontalProperty; + public static boolean AbilityHotbarHorizontal = false; + + public static Property AbilityHotbarAltTextureProperty; + public static boolean AbilityHotbarAltTexture = false; + + // 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 **/ @@ -114,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); @@ -122,11 +176,11 @@ 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", 31.0, "Y position of the quest overlay."); + QuestOverlayY = (float) QuestOverlayYProperty.getDouble(31); QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 223, "Scale percentage of the quest overlay."); QuestOverlayScale = QuestOverlayScaleProperty.getInt(223); @@ -146,22 +200,18 @@ public class ConfigClient { CompassOverlayXProperty = config.get( HUD, "Compass Hud X", - 37, - "Horizontal position of compass overlay (0-100 percentage)", - 0, - 100 + 37.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, @@ -183,8 +233,41 @@ public class ConfigClient { ); 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", 3.0, "Horizontal position (0-100 percentage)"); + AbilityHotbarX = (float) AbilityHotbarXProperty.getDouble(); + + AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 50.0, "Vertical position (0-100 percentage)"); + AbilityHotbarY = (float) AbilityHotbarYProperty.getDouble(); + + AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 100, "Scale percentage", 50, 300); + 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", false, "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."); + AllowClientScripts = AllowClientScriptsProperty.getBoolean(true); + CacheLifeProperty = config.get(GENERAL, "Cache Life", 10, "How long should downloaded imagery data be saved client side? (In minutes)"); CacheLife = CacheLifeProperty.getInt(10); @@ -210,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); @@ -223,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); @@ -253,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 new file mode 100644 index 000000000..976452d08 --- /dev/null +++ b/src/main/java/noppes/npcs/config/ConfigMarket.java @@ -0,0 +1,257 @@ +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; +import java.util.ArrayList; +import java.util.Arrays; + +public class ConfigMarket { + public static Configuration config; + + public final static String CURRENCY = "Market.Currency"; + public final static String AUCTION = "Market.Auction"; + public final static String AUCTION_BLACKLIST = "Market.Auction.Blacklist"; + public final static String AUCTION_LOGGING = "Market.Auction.Logging"; + + // Max trades grid = 9x5 = 45 slots + public static final int MAX_TRADE_SLOTS = 45; + public static final int MIN_TRADE_SLOTS = 1; + + // ========================================= + // Currency Settings + // ========================================= + public static boolean UseVault = false; + public static String CurrencyName = "Coins"; + public static long StartingBalance = 0; + public static long MaxBalance = Long.MAX_VALUE; + + // ========================================= + // Auction Settings + // ========================================= + public static boolean AuctionEnabled = true; + public static int AuctionDurationHours = 24; + public static long ListingFee = 10; + public static long MinimumListingPrice = 1; + public static double SalesTaxPercent = 0.05; + public static int DefaultMaxTrades = 8; + public static int SnipeProtectionMinutes = 2; + public static int ClaimExpirationDays = 20; + public static double MinBidIncrementPercent = 0.05; + public static double CancellationPenaltyPercent = 0.10; + + // ========================================= + // Auction Blacklist Settings + // ========================================= + public static boolean BlacklistEnabled = true; + public static String[] BlacklistedItems = new String[]{}; + public static String[] BlacklistedMods = new String[]{}; + public static String[] BlacklistedNBTTags = new String[]{}; + + // ========================================= + // Auction Logging Settings + // ========================================= + public static boolean AuctionLoggingEnabled = false; + public static boolean LogAuctionCreated = true; + public static boolean LogAuctionBid = true; + public static boolean LogAuctionBuyout = true; + public static boolean LogAuctionSold = true; + public static boolean LogAuctionExpired = true; + public static boolean LogAuctionCancelled = true; + public static boolean LogAuctionClaimed = true; + + public static void init(File configFile) { + config = new Configuration(configFile); + + try { + config.load(); + + // ========================================= + // Currency Settings + // ========================================= + config.setCategoryComment(CURRENCY, "CNPC+ Currency system settings. When UseVault is enabled, all currency operations use Vault instead of the built-in system."); + + UseVault = config.get(CURRENCY, "Use Vault", false, + "If true, use Vault API for all currency operations instead of CNPC+ built-in currency. The built-in currency data will be preserved but unused.").getBoolean(false); + + CurrencyName = config.get(CURRENCY, "Currency Name", "Coins", + "Display name for the currency (e.g. 'Coins', 'Gold', 'Credits')").getString(); + + StartingBalance = parseLongConfig(config.get(CURRENCY, "Starting Balance", "0", + "Starting currency balance for new players").getString(), 0); + + 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 + // ========================================= + config.setCategoryComment(AUCTION, "Auction system settings. The Auction allows players to list items for sale with bidding and buyout options."); + + AuctionEnabled = config.get(AUCTION, "Enable Auction", true, + "Enable the Auction system").getBoolean(true); + + AuctionDurationHours = config.get(AUCTION, "Auction Duration Hours", 24, + "Default duration for auctions in hours").getInt(24); + if (AuctionDurationHours < 1) AuctionDurationHours = 1; + + ListingFee = parseLongConfig(config.get(AUCTION, "Listing Fee", "10", + "Flat fee charged when creating a listing").getString(), 10); + if (ListingFee < 0) ListingFee = 0; + + 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); + DefaultMaxTrades = Math.max(MIN_TRADE_SLOTS, Math.min(MAX_TRADE_SLOTS, maxTrades)); + + 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)"); + + BlacklistEnabled = config.get(AUCTION_BLACKLIST, "Enable Blacklist", true, + "Enable item blacklist checking when creating listings").getBoolean(true); + + BlacklistedItems = config.get(AUCTION_BLACKLIST, "Blacklisted Items", new String[]{ + "minecraft:bedrock", + "minecraft:command_block", + "customnpcs:npcWand", + "customnpcs:npcMobCloner", + "customnpcs:npcScripter", + "customnpcs:npcMovingPath", + "customnpcs:npcMounter", + "customnpcs:npcTeleporter", + "customnpcs:npcTool", + "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(); + + 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(); + + 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(); + + // ========================================= + // Auction Logging Settings + // ========================================= + config.setCategoryComment(AUCTION_LOGGING, "Auction logging settings. Enable specific log types to track auction activity."); + + AuctionLoggingEnabled = config.get(AUCTION_LOGGING, "Enable Auction Logging", false, + "Master switch for auction logging. If false, no auction events are logged.").getBoolean(false); + + LogAuctionCreated = config.get(AUCTION_LOGGING, "Log Created", true, + "Log when auctions are created").getBoolean(true); + + LogAuctionBid = config.get(AUCTION_LOGGING, "Log Bid", true, + "Log when bids are placed").getBoolean(true); + + LogAuctionBuyout = config.get(AUCTION_LOGGING, "Log Buyout", true, + "Log when auctions are bought out").getBoolean(true); + + LogAuctionSold = config.get(AUCTION_LOGGING, "Log Sold", true, + "Log when auctions end with a winner").getBoolean(true); + + LogAuctionExpired = config.get(AUCTION_LOGGING, "Log Expired", true, + "Log when auctions expire with no bids").getBoolean(true); + + LogAuctionCancelled = config.get(AUCTION_LOGGING, "Log Cancelled", true, + "Log when auctions are cancelled").getBoolean(true); + + LogAuctionClaimed = config.get(AUCTION_LOGGING, "Log Claimed", true, + "Log when claims are collected").getBoolean(true); + + // Set category order + config.setCategoryPropertyOrder(CURRENCY, new ArrayList<>(Arrays.asList( + "Use Vault", + "Currency Name", + "Starting Balance", + "Max Balance" + ))); + + config.setCategoryPropertyOrder(AUCTION, new ArrayList<>(Arrays.asList( + "Enable Auction", + "Auction Duration Hours", + "Listing Fee", + "Minimum Listing Price", + "Sales Tax Percent", + "Default Max Trades", + "Snipe Protection Minutes", + "Claim Expiration Days", + "Min Bid Increment Percent", + "Cancellation Penalty Percent" + ))); + + config.setCategoryPropertyOrder(AUCTION_BLACKLIST, new ArrayList<>(Arrays.asList( + "Enable Blacklist", + "Blacklisted Items", + "Blacklisted Mods", + "Blacklisted NBT Tags" + ))); + + config.setCategoryPropertyOrder(AUCTION_LOGGING, new ArrayList<>(Arrays.asList( + "Enable Auction Logging", + "Log Created", + "Log Bid", + "Log Buyout", + "Log Sold", + "Log Expired", + "Log Cancelled", + "Log Claimed" + ))); + + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "CNPC+ has had a problem loading its market configuration"); + } finally { + if (config.hasChanged()) { + config.save(); + } + } + } + + 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 98474c493..86f34d433 100644 --- a/src/main/java/noppes/npcs/config/GlyphCache.java +++ b/src/main/java/noppes/npcs/config/GlyphCache.java @@ -5,7 +5,13 @@ import net.minecraft.client.renderer.GLAllocation; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -import java.awt.*; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; +import java.awt.Rectangle; +import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.Point2D; diff --git a/src/main/java/noppes/npcs/config/LoadConfiguration.java b/src/main/java/noppes/npcs/config/LoadConfiguration.java index 19fad65c2..0fc46e3e3 100644 --- a/src/main/java/noppes/npcs/config/LoadConfiguration.java +++ b/src/main/java/noppes/npcs/config/LoadConfiguration.java @@ -9,6 +9,8 @@ public class LoadConfiguration { public static File debugConfigFile; 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"); @@ -17,6 +19,8 @@ public class LoadConfiguration { scriptConfigFile = new File(configpath + "script.cfg"); 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); @@ -24,5 +28,7 @@ public class LoadConfiguration { ConfigScript.init(scriptConfigFile); 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 263b480b9..c40d59f1c 100644 --- a/src/main/java/noppes/npcs/config/StringCache.java +++ b/src/main/java/noppes/npcs/config/StringCache.java @@ -5,7 +5,8 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -import java.awt.*; +import java.awt.Font; +import java.awt.Point; import java.awt.font.GlyphVector; import java.lang.ref.WeakReference; import java.text.Bidi; 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/EnumAuctionSort.java b/src/main/java/noppes/npcs/constants/EnumAuctionSort.java new file mode 100644 index 000000000..115f13dc9 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionSort.java @@ -0,0 +1,40 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; + +public enum EnumAuctionSort { + NEWEST("auction.sort.newest"), + ENDING_SOON("auction.sort.endingSoon"), + PRICE_LOW("auction.sort.priceLow"), + PRICE_HIGH("auction.sort.priceHigh"), + MOST_BIDS("auction.sort.mostBids"); + + private final String langKey; + + EnumAuctionSort(String langKey) { + this.langKey = langKey; + } + + public String getLangKey() { + return langKey; + } + + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + public static String[] getDisplayNames() { + String[] names = new String[values().length]; + for (int i = 0; i < values().length; i++) { + names[i] = values()[i].getDisplayName(); + } + return names; + } + + public static EnumAuctionSort fromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } + return NEWEST; + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumAuctionStatus.java b/src/main/java/noppes/npcs/constants/EnumAuctionStatus.java new file mode 100644 index 000000000..14fc0f4ff --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumAuctionStatus.java @@ -0,0 +1,47 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; + +public enum EnumAuctionStatus { + ACTIVE("auction.status.active"), + ENDED("auction.status.ended"), + CANCELLED("auction.status.cancelled"), + CLAIMED("auction.status.claimed"); + + private final String langKey; + + EnumAuctionStatus(String langKey) { + this.langKey = langKey; + } + + public String getLangKey() { + return langKey; + } + + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + public boolean isActive() { + return this == ACTIVE; + } + + public boolean isEnded() { + return this == ENDED || this == CANCELLED || this == CLAIMED; + } + + public boolean canBid() { + return this == ACTIVE; + } + + public boolean canCancel() { + return this == ACTIVE; + } + + public static EnumAuctionStatus fromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } + return ACTIVE; + } +} 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/EnumClaimType.java b/src/main/java/noppes/npcs/constants/EnumClaimType.java new file mode 100644 index 000000000..35fbf2003 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumClaimType.java @@ -0,0 +1,38 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; + +public enum EnumClaimType { + ITEM("auction.claim.item"), + CURRENCY("auction.claim.currency"), + REFUND("auction.claim.refund"); + + private final String langKey; + + EnumClaimType(String langKey) { + this.langKey = langKey; + } + + public String getLangKey() { + return langKey; + } + + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + public boolean isItem() { + return this == ITEM; + } + + public boolean isCurrency() { + return this == CURRENCY || this == REFUND; + } + + public static EnumClaimType fromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } + return ITEM; + } +} diff --git a/src/main/java/noppes/npcs/constants/EnumGuiType.java b/src/main/java/noppes/npcs/constants/EnumGuiType.java index d0919b9b1..1859b2616 100644 --- a/src/main/java/noppes/npcs/constants/EnumGuiType.java +++ b/src/main/java/noppes/npcs/constants/EnumGuiType.java @@ -63,5 +63,11 @@ public enum EnumGuiType { ScriptItem, ScriptBlock, Paintbrush, - MagicBook; + MagicBook, + ManageAbilities, + PlayerAuction, + PlayerAuctionSell, + PlayerAuctionTrades, + PlayerAuctionBidding, + ManageAuction; } diff --git a/src/main/java/noppes/npcs/constants/EnumNotificationType.java b/src/main/java/noppes/npcs/constants/EnumNotificationType.java new file mode 100644 index 000000000..02130e710 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumNotificationType.java @@ -0,0 +1,32 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; + +public enum EnumNotificationType { + AUCTION_WON("auction.notify.won"), + AUCTION_OUTBID("auction.notify.outbid"), + AUCTION_SOLD("auction.notify.sold"), + AUCTION_EXPIRED("auction.notify.expired"), + CLAIM_READY("auction.notify.claim"); + + private final String langKey; + + EnumNotificationType(String langKey) { + this.langKey = langKey; + } + + public String getLangKey() { + return langKey; + } + + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + public static EnumNotificationType fromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } + return CLAIM_READY; + } +} 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/EnumRoleType.java b/src/main/java/noppes/npcs/constants/EnumRoleType.java index 624658fb3..33f36941a 100644 --- a/src/main/java/noppes/npcs/constants/EnumRoleType.java +++ b/src/main/java/noppes/npcs/constants/EnumRoleType.java @@ -2,5 +2,5 @@ package noppes.npcs.constants; public enum EnumRoleType { - None, Trader, Follower, Bank, Transporter, Postman, Companion, Mount + None, Trader, Follower, Bank, Transporter, Postman, Companion, Mount, Auctioneer } diff --git a/src/main/java/noppes/npcs/constants/EnumScriptType.java b/src/main/java/noppes/npcs/constants/EnumScriptType.java index 14ce38f41..f6d05d65b 100644 --- a/src/main/java/noppes/npcs/constants/EnumScriptType.java +++ b/src/main/java/noppes/npcs/constants/EnumScriptType.java @@ -114,13 +114,62 @@ public enum EnumScriptType { PROFILE("profile"), PROFILE_CHANGE("profileChange"), PROFILE_REMOVE("profileRemove"), - PROFILE_CREATE("profileCreate"); + PROFILE_CREATE("profileCreate"), + + ON_EFFECT_ADD("onEffectAdd"), + ON_EFFECT_TICK("onEffectTick"), + ON_EFFECT_REMOVE("onEffectRemove"), + + ABILITY_START("abilityStart"), + ABILITY_EXECUTE("abilityExecute"), + ABILITY_INTERRUPT("abilityInterrupt"), + ABILITY_COMPLETE("abilityComplete"), + ABILITY_HIT("abilityHit"), + 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 52a9575f1..bfa6e09a7 100644 --- a/src/main/java/noppes/npcs/constants/EnumScrollData.java +++ b/src/main/java/noppes/npcs/constants/EnumScrollData.java @@ -5,5 +5,13 @@ public enum EnumScrollData { MAGIC, MAGIC_CYCLES, DIALOG_GROUP, - QUEST_GROUP + QUEST_GROUP, + ABILITY_TYPES, + CUSTOM_ABILITIES, + BUILTIN_ABILITIES, + ANIMATIONS, + BUILTIN_ANIMATIONS, + CHAINED_ABILITIES, + CATEGORY_GROUP, + CATEGORY_LIST } diff --git a/src/main/java/noppes/npcs/constants/EnumStockReset.java b/src/main/java/noppes/npcs/constants/EnumStockReset.java new file mode 100644 index 000000000..485318dd5 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/EnumStockReset.java @@ -0,0 +1,75 @@ +package noppes.npcs.constants; + +import net.minecraft.util.StatCollector; + +/** + * Stock reset types for Trader NPCs. + * Mirrors EnumQuestRepeat pattern for consistency. + */ +public enum EnumStockReset { + NONE("stock.reset.never"), + MCDAILY("stock.reset.mcdaily"), + MCWEEKLY("stock.reset.mcweekly"), + MCCUSTOM("stock.reset.mccustom"), + RLDAILY("stock.reset.rldaily"), + RLWEEKLY("stock.reset.rlweekly"), + RLCUSTOM("stock.reset.rlcustom"); + + private final String langKey; + + EnumStockReset(String langKey) { + this.langKey = langKey; + } + + /** + * Get reset interval in milliseconds for real-time types + * or ticks for MC-time types + */ + public long getDefaultInterval() { + switch (this) { + case MCDAILY: + return 24000; // MC ticks + case MCWEEKLY: + return 168000; // MC ticks (7 days) + case RLDAILY: + return 86400000L; // 24 hours in ms + case RLWEEKLY: + return 604800000L; // 7 days in ms + default: + return 0; + } + } + + /** + * Check if this reset type uses real-world time + */ + public boolean isRealTime() { + return this == RLDAILY || this == RLWEEKLY || this == RLCUSTOM; + } + + /** + * Check if this reset type uses Minecraft time + */ + public boolean isMinecraftTime() { + return this == MCDAILY || this == MCWEEKLY || this == MCCUSTOM; + } + + /** + * Get display name for GUI (translated) + */ + public String getDisplayName() { + return StatCollector.translateToLocal(langKey); + } + + /** + * Get all display names for dropdown menus + */ + public static String[] getDisplayNames() { + EnumStockReset[] values = values(); + String[] names = new String[values.length]; + for (int i = 0; i < values.length; i++) { + names[i] = values[i].getDisplayName(); + } + return names; + } +} 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 new file mode 100644 index 000000000..572b8e038 --- /dev/null +++ b/src/main/java/noppes/npcs/constants/ScriptContext.java @@ -0,0 +1,326 @@ +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; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Represents a script context that maps to one or more event interface namespaces. + *

+ * A script context can have multiple namespaces because script editors often + * support hooks from multiple event types. For example, Player scripts support: + * - IPlayerEvent (core player hooks) + * - IAnimationEvent (animation hooks) + * - IPartyEvent (party hooks) + * - ICustomGuiEvent (custom GUI hooks) + * - etc. + *

+ * Each context also has a hookContext string used by ScriptHookController for + * hook registration and lookup. + *

+ * This is a registerable system - any mod can register their own contexts: + *

+ * // Register a new context with multiple namespaces: + * ScriptContext.register("DBC", "dbc", IDBCEvent.class, IDBCPlayerEvent.class); + *

+ * // Or add namespaces to an existing context: + * ScriptContext.PLAYER.addNamespace("IDBCPlayerEvent"); + */ +public class ScriptContext { + + // Registry of all script contexts + private static final Map REGISTRY = new ConcurrentHashMap<>(); + + // ==================== BUILT-IN CONTEXTS ==================== + + public static final ScriptContext NPC = register("NPC", "npc", + INpcEvent.class, + IProjectileEvent.class, + IEnergyProjectileEvent.class, + IEnergyBarrierEvent.class, + IAbilityEvent.class, + IChainEvent.class, + IAnimationEvent.class + ); + + public static final ScriptContext PLAYER = register("PLAYER", "player", + IPlayerEvent.class, + IAnimationEvent.class, + IPartyEvent.class, + IDialogEvent.class, + IQuestEvent.class, + IFactionEvent.class, + ICustomGuiEvent.class, + IEnergyProjectileEvent.class, + IEnergyBarrierEvent.class, + IAbilityEvent.class, + IChainEvent.class, + IAuctionEvent.class + ); + + public static final ScriptContext BLOCK = register("BLOCK", "block", + IBlockEvent.class + ); + + public static final ScriptContext ITEM = register("ITEM", "item", + IItemEvent.class + ); + + public static final ScriptContext FORGE = register("FORGE", "forge", + IForgeEvent.class + ); + + public static final ScriptContext LINKED_ITEM = register("LINKED_ITEM", "linked_item", + ILinkedItemEvent.class, + IItemEvent.class + ); + + public static final ScriptContext RECIPE = register("RECIPE", "recipe", + IRecipeEvent.class + ); + + public static final ScriptContext EFFECT = register("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", "", + "Global" // Special case: Global namespace doesn't have a corresponding event class + ); + + // ==================== INSTANCE FIELDS ==================== + + /** + * Unique identifier for this context (e.g., "NPC", "PLAYER", "DBC") + */ + public final String id; + + /** + * Hook context identifier used by ScriptHookController (e.g., "npc", "player") + */ + public final String hookContext; + + /** + * The event interface namespaces this context supports + */ + 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) { + this.id = id; + this.hookContext = hookContext != null ? hookContext : ""; + this.namespaces = new ArrayList<>(Arrays.asList(namespaces)); + } + + // ==================== NAMESPACE ACCESS ==================== + + /** + * Get all namespaces this context supports. + * + * @return Unmodifiable list of namespace strings + */ + public List getNamespaces() { + 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. + * + * @param namespace The namespace to check (e.g., "IPlayerEvent") + * @return true if this context supports hooks from that namespace + */ + public boolean hasNamespace(String namespace) { + return namespaces.contains(namespace); + } + + /** + * Add a namespace to this context. + * Mods can use this to extend built-in contexts with their own event types. + * + * @param namespace The namespace to add (e.g., "IDBCPlayerEvent") + */ + public void addNamespace(String namespace) { + if (!namespaces.contains(namespace)) { + namespaces.add(namespace); + } + } + + /** + * Get the primary namespace (first one registered). + * This is mainly for backward compatibility. + * + * @return The first namespace, or "Global" if none + */ + public String getPrimaryNamespace() { + return namespaces.isEmpty() ? "Global" : namespaces.get(0); + } + + // ==================== REGISTRATION API ==================== + + /** + * Register a new script context with a hook context and one or more namespaces. + * + * @param id Unique identifier (e.g., "DBC", "CUSTOM") + * @param hookContext The hook context string for ScriptHookController (e.g., "dbc") + * @param namespaces The event interface names (e.g., "IDBCEvent", "IDBCPlayerEvent") + * @return The registered ScriptContext + */ + public static ScriptContext register(String id, String hookContext, String... namespaces) { + ScriptContext context = new ScriptContext(id, hookContext, namespaces); + REGISTRY.put(id, context); + return context; + } + + /** + * Register a new script context using event interface classes. + * Automatically extracts the simple name from each class. + *

+ * Example: + * ScriptContext.register("NPC", "npc", INpcEvent.class, IProjectileEvent.class); + * + * @param id Unique identifier (e.g., "DBC", "CUSTOM") + * @param hookContext The hook context string for ScriptHookController (e.g., "npc") + * @param eventClasses The event interface classes (simple names will be extracted) + * @return The registered ScriptContext + */ + public static ScriptContext register(String id, String hookContext, Class... eventClasses) { + String[] namespaces = new String[eventClasses.length]; + for (int i = 0; i < eventClasses.length; i++) { + namespaces[i] = eventClasses[i].getSimpleName(); + } + ScriptContext context = register(id, hookContext, namespaces); + for (Class clazz : eventClasses) { + context.namespaceFQNs.add(clazz.getName().replace('$', '.')); + } + return context; + } + + /** + * Get a script context by its ID. + * + * @param id The context ID (e.g., "NPC", "PLAYER", "DBC") + * @return The ScriptContext, or GLOBAL if not found + */ + public static ScriptContext byId(String id) { + return REGISTRY.getOrDefault(id, GLOBAL); + } + + /** + * Find a script context that contains a specific namespace. + * + * @param namespace The event interface namespace (e.g., "INpcEvent") + * @return The first ScriptContext that contains this namespace, or GLOBAL if not found + */ + public static ScriptContext byNamespace(String namespace) { + if (namespace == null) return GLOBAL; + for (ScriptContext ctx : REGISTRY.values()) { + if (ctx.hasNamespace(namespace)) { + return ctx; + } + } + return GLOBAL; + } + + /** + * Find a script context by its hook context string. + * + * @param hookContext The hook context string (e.g., "npc", "player") + * @return The ScriptContext with that hook context, or GLOBAL if not found + */ + public static ScriptContext byHookContext(String hookContext) { + if (hookContext == null || hookContext.isEmpty()) return GLOBAL; + for (ScriptContext ctx : REGISTRY.values()) { + if (hookContext.equals(ctx.hookContext)) { + return ctx; + } + } + return GLOBAL; + } + + /** + * Get all registered script contexts. + * + * @return Unmodifiable collection of all registered contexts + */ + public static Collection values() { + return Collections.unmodifiableCollection(REGISTRY.values()); + } + + /** + * Check if a context with the given ID exists. + * + * @param id The context ID to check + * @return true if registered + */ + public static boolean exists(String id) { + return REGISTRY.containsKey(id); + } + + // ==================== OBJECT METHODS ==================== + + @Override + public String toString() { + return id + " -> " + namespaces; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof ScriptContext)) return false; + ScriptContext other = (ScriptContext) obj; + return id.equals(other.id); + } + + @Override + public int hashCode() { + return id.hashCode(); + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerAuction.java b/src/main/java/noppes/npcs/containers/ContainerAuction.java new file mode 100644 index 000000000..0741fdd9a --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerAuction.java @@ -0,0 +1,82 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import noppes.npcs.entity.EntityNPCInterface; + +/** + * Base container for all auction GUIs. + * Provides player inventory at the correct position for the 256x256 auction texture. + * Player inventory is display-only - no modifications allowed. + */ +public class ContainerAuction extends ContainerNpcInterface { + public final EntityNPCInterface npc; + + // Player inventory layout for 256x256 auction texture + // Top-left slot background at (47, 163) + // Item renders at +1 offset inside the 18x18 slot background + public static final int PLAYER_INV_X = 48; // 47 + 1 for item offset + public static final int PLAYER_INV_Y = 164; // 163 + 1 for item offset + public static final int HOTBAR_Y = 222; // PLAYER_INV_Y + (3 * 18) + 4 gap + + // Player inventory slots are added first (36 slots: 0-35) + public static final int PLAYER_INV_SLOT_COUNT = 36; + + public ContainerAuction(EntityNPCInterface npc, EntityPlayer player) { + super(player); + this.npc = npc; + this.player = player; + + addPlayerInventory(); + } + + protected void addPlayerInventory() { + // Main inventory (3 rows of 9) + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 9; col++) { + int slotIndex = col + row * 9 + 9; // Slots 9-35 + int x = PLAYER_INV_X + col * 18; + int y = PLAYER_INV_Y + row * 18; + addSlotToContainer(new Slot(player.inventory, slotIndex, x, y)); + } + } + + // Hotbar (1 row of 9) + for (int col = 0; col < 9; col++) { + int x = PLAYER_INV_X + col * 18; + addSlotToContainer(new Slot(player.inventory, col, x, HOTBAR_Y)); + } + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { + return null; // Disable shift-clicking + } + + @Override + public ItemStack slotClick(int slotIndex, int mouseButton, int mode, EntityPlayer player) { + // Block all slot interactions by default in auction containers + // This prevents picking up, placing, and swapping items + // Subclasses can override to allow specific interactions + return null; + } + + /** + * Check if the slot index is a player inventory slot. + */ + public boolean isPlayerInventorySlot(int slotIndex) { + return slotIndex >= 0 && slotIndex < PLAYER_INV_SLOT_COUNT; + } + + /** + * Get the ItemStack in a player inventory slot. + * + * @param containerSlotIndex The container slot index (0-35 for player inv) + */ + public ItemStack getPlayerInventoryStack(int containerSlotIndex) { + if (!isPlayerInventorySlot(containerSlotIndex)) return null; + Slot slot = (Slot) inventorySlots.get(containerSlotIndex); + return slot != null ? slot.getStack() : null; + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java b/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java new file mode 100644 index 000000000..2b6f9a67f --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionBidding.java @@ -0,0 +1,68 @@ +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.controllers.data.AuctionListing; +import noppes.npcs.entity.EntityNPCInterface; + +/** + * Container for the auction bidding/purchase view. + * Displays a single item slot showing the listing's item. + */ +public class ContainerAuctionBidding extends ContainerAuction { + // Display slot layout + 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; + + public ContainerAuctionBidding(EntityNPCInterface npc, EntityPlayer player) { + super(npc, player); + displayInventory = new InventoryBasic("Display", false, 1); + + // Display slot (read-only) + addSlotToContainer(new Slot(displayInventory, 0, ITEM_SLOT_X, ITEM_SLOT_Y) { + @Override + public boolean isItemValid(ItemStack stack) { + return false; + } + + @Override + public boolean canTakeStack(EntityPlayer player) { + return false; + } + }); + } + + /** + * Set the listing to display. + */ + public void setListing(AuctionListing listing) { + this.listing = listing; + if (listing != null && listing.item != null) { + displayInventory.setInventorySlotContents(0, listing.item.copy()); + } else { + displayInventory.setInventorySlotContents(0, null); + } + } + + public AuctionListing getListing() { + return listing; + } + + public ItemStack getDisplayItem() { + return displayInventory.getStackInSlot(0); + } + + /** + * Check if this is the display slot. + */ + public boolean isDisplaySlot(int slotIndex) { + return slotIndex == ITEM_SLOT_INDEX; + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionListing.java b/src/main/java/noppes/npcs/containers/ContainerAuctionListing.java new file mode 100644 index 000000000..9691935be --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionListing.java @@ -0,0 +1,133 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import noppes.npcs.controllers.AuctionController; +import noppes.npcs.controllers.data.AuctionFilter; +import noppes.npcs.controllers.data.AuctionListing; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +/** + * Container for the auction listing browse view. + * Displays a 9x5 grid of auction listings (45 slots). + */ +public class ContainerAuctionListing extends ContainerAuction { + // Listing grid layout + public static final int LISTING_START_X = 57; // 56 + 1 for item offset + public static final int LISTING_START_Y = 47; // 46 + 1 for item offset + public static final int LISTING_COLS = 9; + public static final int LISTING_ROWS = 5; + public static final int LISTING_SLOT_COUNT = LISTING_COLS * LISTING_ROWS; + + public final InventoryAuctionDisplay displayInventory; + private int currentPage = 0; + private AuctionFilter filter = new AuctionFilter(); + + public ContainerAuctionListing(EntityNPCInterface npc, EntityPlayer player) { + super(npc, player); + + // Create display inventory for listings + displayInventory = new InventoryAuctionDisplay(LISTING_SLOT_COUNT); + + // Add listing display slots (9x5 grid) + for (int row = 0; row < LISTING_ROWS; row++) { + for (int col = 0; col < LISTING_COLS; col++) { + int slotIndex = col + row * LISTING_COLS; + int x = LISTING_START_X + col * 18; + int y = LISTING_START_Y + row * 18; + addSlotToContainer(new SlotAuctionDisplay(displayInventory, slotIndex, x, y)); + } + } + + // Load initial listings + refreshListings(); + } + + public void refreshListings() { + if (AuctionController.Instance == null) return; + + List listings = AuctionController.Instance.getActiveListings( + filter, currentPage, LISTING_SLOT_COUNT); + + displayInventory.clear(); + for (int i = 0; i < listings.size() && i < LISTING_SLOT_COUNT; i++) { + displayInventory.setListing(i, listings.get(i)); + } + } + + public AuctionListing getListingAt(int slotIndex) { + return displayInventory.getListing(slotIndex); + } + + /** + * Find a listing by matching ItemStack. + */ + public AuctionListing getListingForItem(ItemStack stack) { + if (stack == null) return null; + + for (int i = 0; i < LISTING_SLOT_COUNT; i++) { + AuctionListing listing = displayInventory.getListing(i); + if (listing != null && listing.item != null && ItemStack.areItemStacksEqual(listing.item, stack)) { + return listing; + } + } + return null; + } + + public int getCurrentPage() { + return currentPage; + } + + public void setPage(int page) { + this.currentPage = Math.max(0, page); + refreshListings(); + } + + public void nextPage() { + setPage(currentPage + 1); + } + + public void prevPage() { + if (currentPage > 0) { + setPage(currentPage - 1); + } + } + + public int getTotalPages() { + if (AuctionController.Instance == null) return 1; + int totalListings = AuctionController.Instance.getTotalActiveListings(filter); + return Math.max(1, (int) Math.ceil((double) totalListings / LISTING_SLOT_COUNT)); + } + + public int getTotalListings() { + if (AuctionController.Instance == null) return 0; + return AuctionController.Instance.getTotalActiveListings(filter); + } + + public AuctionFilter getFilter() { + return filter; + } + + public void setFilter(AuctionFilter filter) { + this.filter = filter; + this.currentPage = 0; + refreshListings(); + } + + /** + * Check if a slot index is a display slot. + */ + public boolean isDisplaySlot(int slotIndex) { + int start = getDisplaySlotStart(); + return slotIndex >= start && slotIndex < start + LISTING_SLOT_COUNT; + } + + /** + * Get the starting slot index for display slots. + */ + public int getDisplaySlotStart() { + return PLAYER_INV_SLOT_COUNT; + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java b/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java new file mode 100644 index 000000000..f703a206d --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionSell.java @@ -0,0 +1,136 @@ +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.entity.EntityNPCInterface; + +/** + * Container for creating auction listings with a single sell slot. + * Items are cloned from inventory, not moved. Validation happens on submit. + */ +public class ContainerAuctionSell extends ContainerAuction { + 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; + + public ContainerAuctionSell(EntityNPCInterface npc, EntityPlayer player) { + super(npc, player); + sellInventory = new InventoryBasic("Sell", false, 1); + + // Sell slot blocks direct interaction + addSlotToContainer(new Slot(sellInventory, 0, SELL_SLOT_X, SELL_SLOT_Y) { + @Override + public boolean isItemValid(ItemStack stack) { + return false; + } + + @Override + public boolean canTakeStack(EntityPlayer player) { + return false; + } + }); + } + + public ItemStack getItemToSell() { + return sellInventory.getStackInSlot(0); + } + + public void clearSellSlot() { + sellInventory.setInventorySlotContents(0, null); + } + + /** + * 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 + */ + public void addToSellSlot(int sourceSlot, boolean fullStack) { + if (!isPlayerInventorySlot(sourceSlot)) return; + + ItemStack source = getPlayerInventoryStack(sourceSlot); + if (source == null) return; + + ItemStack sellStack = sellInventory.getStackInSlot(0); + int toAdd = fullStack ? source.stackSize : 1; + + if (sellStack == null) { + // Empty slot - create new stack + ItemStack newStack = source.copy(); + 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 = MAX_STACK - sellStack.stackSize; + int add = Math.min(toAdd, space); + if (add > 0) { + sellStack.stackSize += add; + } + } else { + // Different item - replace + ItemStack newStack = source.copy(); + 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) { + ItemStack sellStack = sellInventory.getStackInSlot(0); + if (sellStack == null) return; + + if (removeAll || sellStack.stackSize <= 1) { + sellInventory.setInventorySlotContents(0, null); + } else { + sellStack.stackSize--; + } + } + + /** + * Check if sell slot is this container slot index + */ + public boolean isSellSlot(int slotIndex) { + return slotIndex == SELL_SLOT_INDEX; + } + + /** + * 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); + } + + /** + * Count total items of a specific type across player inventory. + * Used for submit validation and UI indicator. + */ + public int countItemInInventory(ItemStack target) { + if (target == null) return 0; + int total = 0; + for (int i = 0; i < PLAYER_INV_SLOT_COUNT; i++) { + ItemStack stack = getPlayerInventoryStack(i); + if (stack != null && itemsMatch(stack, target)) { + total += stack.stackSize; + } + } + return total; + } + + @Override + public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + clearSellSlot(); + } +} diff --git a/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java b/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java new file mode 100644 index 000000000..187d50d13 --- /dev/null +++ b/src/main/java/noppes/npcs/containers/ContainerAuctionTrades.java @@ -0,0 +1,402 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +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; + +/** + * Container for viewing player's auction trades. + * Shows active listings, bids, and claims in a 9x5 grid. + * Order: SOLD claims, OUTBID claims, WON claims, SELLING, BIDDING, EXPIRED claims + */ +public class ContainerAuctionTrades extends ContainerAuction { + // Grid layout + public static final int GRID_X = 57; + public static final int GRID_Y = 47; + public static final int COLS = 9; + public static final int ROWS = 5; + public static final int SLOT_COUNT = COLS * ROWS; + + public final InventoryAuctionDisplay displayInventory; + private List activeListings = new ArrayList<>(); + private List activeBids = new ArrayList<>(); + private List claims = new ArrayList<>(); + private int hiddenSlot = -1; + private int maxTradeSlots = 8; // Player's max trade slots (permission-aware, synced from server) + + // Slot type tracking for proper accessor methods + private EnumTradeSlotType[] slotTypes = new EnumTradeSlotType[SLOT_COUNT]; + private int[] slotDataIndex = new int[SLOT_COUNT]; // Index into respective list + + public ContainerAuctionTrades(EntityNPCInterface npc, EntityPlayer player) { + super(npc, player); + displayInventory = new InventoryAuctionDisplay(SLOT_COUNT); + + // Add display slots (9x5 grid) + for (int row = 0; row < ROWS; row++) { + for (int col = 0; col < COLS; col++) { + int idx = col + row * COLS; + int x = GRID_X + col * 18; + int y = GRID_Y + row * 18; + addSlotToContainer(new SlotAuctionDisplay(displayInventory, idx, x, y)); + } + } + refreshData(); + } + + /** + * Refresh data from controller (server-side only) + */ + public void refreshData() { + // Clear existing data + clearData(); + + // Only works on server where AuctionController exists + if (AuctionController.Instance == null) return; + + List newListings = AuctionController.Instance.getPlayerActiveListings(player.getUniqueID()); + List newBids = AuctionController.Instance.getPlayerActiveBids(player.getUniqueID()); + List newClaims = AuctionController.Instance.getPlayerClaims(player.getUniqueID()); + + populateDisplay(newListings, newBids, newClaims); + } + + /** + * Set data from NBT received from server (client-side) + */ + public void setTradesData(NBTTagCompound compound) { + // Clear existing data + clearData(); + + // Read player's max trade slots (permission-aware) + if (compound.hasKey("MaxTradeSlots")) { + maxTradeSlots = compound.getInteger("MaxTradeSlots"); + } + + List newListings = new ArrayList<>(); + List newBids = new ArrayList<>(); + List newClaims = new ArrayList<>(); + + // Parse active listings + if (compound.hasKey("ActiveListings")) { + NBTTagList listingsNBT = compound.getTagList("ActiveListings", 10); + for (int i = 0; i < listingsNBT.tagCount(); i++) { + newListings.add(AuctionListing.fromNBT(listingsNBT.getCompoundTagAt(i))); + } + } + + // Parse active bids + if (compound.hasKey("ActiveBids")) { + NBTTagList bidsNBT = compound.getTagList("ActiveBids", 10); + for (int i = 0; i < bidsNBT.tagCount(); i++) { + newBids.add(AuctionListing.fromNBT(bidsNBT.getCompoundTagAt(i))); + } + } + + // Parse claims + if (compound.hasKey("Claims")) { + NBTTagList claimsNBT = compound.getTagList("Claims", 10); + for (int i = 0; i < claimsNBT.tagCount(); i++) { + newClaims.add(AuctionClaim.fromNBT(claimsNBT.getCompoundTagAt(i))); + } + } + + populateDisplay(newListings, newBids, newClaims); + } + + /** + * Clear all data and reset display + */ + private void clearData() { + activeListings.clear(); + activeBids.clear(); + claims.clear(); + displayInventory.clear(); + + // Reset slot tracking + Arrays.fill(slotTypes, EnumTradeSlotType.EMPTY); + for (int i = 0; i < SLOT_COUNT; i++) { + slotDataIndex[i] = -1; + } + } + + /** + * Populate display from provided data lists + */ + private void populateDisplay(List newListings, List newBids, List allClaims) { + activeListings = new ArrayList<>(newListings); + activeBids = new ArrayList<>(newBids); + + // Sort claims into categories for proper display order + List soldClaims = new ArrayList<>(); // CURRENCY - sold items + List outbidClaims = new ArrayList<>(); // REFUND - outbid refunds + List wonClaims = new ArrayList<>(); // ITEM won (isReturned=false) + List expiredClaims = new ArrayList<>(); // ITEM returned (isReturned=true) + + for (AuctionClaim claim : allClaims) { + 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); + } + } + } + + // Populate display in order: SOLD, OUTBID, WON, SELLING, BIDDING, EXPIRED + int slot = 0; + + // 1. Sold claims (green) - you have money to claim! + for (AuctionClaim claim : soldClaims) { + if (slot >= SLOT_COUNT) break; + claims.add(claim); + displayInventory.setClaimItem(slot, claim); + slotTypes[slot] = EnumTradeSlotType.CLAIM; + slotDataIndex[slot] = claims.size() - 1; + slot++; + } + + // 2. Outbid claims (yellow) - refunds available + for (AuctionClaim claim : outbidClaims) { + if (slot >= SLOT_COUNT) break; + claims.add(claim); + displayInventory.setClaimItem(slot, claim); + slotTypes[slot] = EnumTradeSlotType.CLAIM; + slotDataIndex[slot] = claims.size() - 1; + slot++; + } + + // 3. Won claims (green) - items to claim! + for (AuctionClaim claim : wonClaims) { + if (slot >= SLOT_COUNT) break; + claims.add(claim); + displayInventory.setClaimItem(slot, claim); + slotTypes[slot] = EnumTradeSlotType.CLAIM; + slotDataIndex[slot] = claims.size() - 1; + slot++; + } + + // 4. Active listings (blue) - items you're selling + int listingIdx = 0; + for (AuctionListing listing : activeListings) { + if (slot >= SLOT_COUNT) break; + if (listing.item != null) displayInventory.setInventorySlotContents(slot, listing.item.copy()); + slotTypes[slot] = EnumTradeSlotType.SELLING; + slotDataIndex[slot] = listingIdx; + slot++; + listingIdx++; + } + + // 5. Active bids (blue) - items you're bidding on + int bidIdx = 0; + for (AuctionListing bid : activeBids) { + if (slot >= SLOT_COUNT) break; + if (bid.item != null) displayInventory.setInventorySlotContents(slot, bid.item.copy()); + slotTypes[slot] = EnumTradeSlotType.BIDDING; + slotDataIndex[slot] = bidIdx; + slot++; + bidIdx++; + } + + // 6. Expired claims (red) - returned items (lowest priority) + for (AuctionClaim claim : expiredClaims) { + if (slot >= SLOT_COUNT) break; + claims.add(claim); + displayInventory.setClaimItem(slot, claim); + slotTypes[slot] = EnumTradeSlotType.CLAIM; + slotDataIndex[slot] = claims.size() - 1; + slot++; + } + } + + // ========== Slot Data Accessors ========== + + /** + * Get listing at slot (or null if claim/empty) + */ + public AuctionListing getListingAt(int slot) { + if (slot < 0 || slot >= SLOT_COUNT) return null; + EnumTradeSlotType type = slotTypes[slot]; + int idx = slotDataIndex[slot]; + if (idx < 0) return null; + + if (type == EnumTradeSlotType.SELLING && idx < activeListings.size()) { + return activeListings.get(idx); + } else if (type == EnumTradeSlotType.BIDDING && idx < activeBids.size()) { + return activeBids.get(idx); + } + return null; + } + + /** + * 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] == EnumTradeSlotType.CLAIM) { + int idx = slotDataIndex[slot]; + if (idx >= 0 && idx < claims.size()) { + return claims.get(idx); + } + } + return null; + } + + /** + * Check if slot is player's active listing + */ + public boolean isSellingAt(int slot) { + return slot >= 0 && slot < SLOT_COUNT && slotTypes[slot] == EnumTradeSlotType.SELLING; + } + + /** + * Check if slot is player's active bid + */ + public boolean isBiddingAt(int slot) { + return slot >= 0 && slot < SLOT_COUNT && slotTypes[slot] == EnumTradeSlotType.BIDDING; + } + + /** + * Find listing matching item (searches both selling and bidding) + */ + public AuctionListing getListingForItem(ItemStack stack) { + if (stack == null) return null; + for (AuctionListing listing : activeListings) { + if (listing.item != null && ItemStack.areItemStacksEqual(listing.item, stack)) return listing; + } + for (AuctionListing bid : activeBids) { + if (bid.item != null && ItemStack.areItemStacksEqual(bid.item, stack)) return bid; + } + return null; + } + + /** + * Find listing in selling list + */ + public AuctionListing getSellingListingForItem(ItemStack stack) { + if (stack == null) return null; + for (AuctionListing listing : activeListings) { + if (listing.item != null && ItemStack.areItemStacksEqual(listing.item, stack)) return listing; + } + return null; + } + + /** + * Find listing in bidding list + */ + public AuctionListing getBiddingListingForItem(ItemStack stack) { + if (stack == null) return null; + for (AuctionListing bid : activeBids) { + if (bid.item != null && ItemStack.areItemStacksEqual(bid.item, stack)) return bid; + } + return null; + } + + /** + * Find claim matching item + */ + public AuctionClaim getClaimForItem(ItemStack stack) { + if (stack == null) return null; + for (AuctionClaim claim : claims) { + if (claim.item != null && ItemStack.areItemStacksEqual(claim.item, stack)) return claim; + } + return null; + } + + // ========== 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(); + } + + // ========== Slot Hiding (for pending operations) ========== + + /** + * Hide slot for pending operation display + */ + public void setHiddenSlot(int slot) { + if (hiddenSlot >= 0 && hiddenSlot < SLOT_COUNT) { + restoreSlotItem(hiddenSlot); + } + hiddenSlot = slot; + if (hiddenSlot >= 0 && hiddenSlot < SLOT_COUNT) { + displayInventory.setInventorySlotContents(hiddenSlot, null); + } + } + + /** + * Restore hidden slot + */ + public void clearHiddenSlot() { + if (hiddenSlot >= 0 && hiddenSlot < SLOT_COUNT) { + restoreSlotItem(hiddenSlot); + } + hiddenSlot = -1; + } + + /** + * Restore item at slot from data using slot tracking + */ + private void restoreSlotItem(int slot) { + if (slot < 0 || slot >= SLOT_COUNT) return; + + EnumTradeSlotType type = slotTypes[slot]; + int idx = slotDataIndex[slot]; + if (idx < 0) return; + + 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 == 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 == EnumTradeSlotType.CLAIM && idx < claims.size()) { + // Claim + displayInventory.setClaimItem(slot, claims.get(idx)); + } + } + + public int getHiddenSlot() { + return hiddenSlot; + } + + /** + * 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/containers/ContainerNPCTrader.java b/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java index 71dcd6fa6..03a690bcd 100644 --- a/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java +++ b/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java @@ -1,44 +1,71 @@ package noppes.npcs.containers; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import noppes.npcs.NoppesUtilPlayer; +import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.roles.RoleTrader; public class ContainerNPCTrader extends ContainerNpcInterface { public RoleTrader role; + private final EntityNPCInterface npc; + + // Layout constants for 256px wide GUI + public static final int COLUMN_WIDTH = 80; + public static final int COLUMN_START_X = 8; + public static final int ROW_HEIGHT = 22; + public static final int ROW_START_Y = 6; + + // Slot offsets within each column (for 18x18 slots, items render centered) + public static final int CURRENCY1_OFFSET = 2; // Primary currency slot + public static final int CURRENCY2_OFFSET = 20; // Secondary currency slot + public static final int OUTPUT_OFFSET = 50; // Output slot public ContainerNPCTrader(EntityNPCInterface npc, EntityPlayer player) { super(player); + this.npc = npc; role = (RoleTrader) npc.roleInterface; - for (int i = 0; i < 18; i++) { - int x = 53; - x += i % 3 * 72; - int y = 7; - y += i / 3 * 21; + // Register this player as viewing the trader (server-side only) + // Needed for shared stock (not per-player) to sync updates to other viewers + // Works for both linked markets (MarketRegistry) and normal traders (local viewers) + if (player instanceof EntityPlayerMP && !role.stock.perPlayer) { + role.registerViewer((EntityPlayerMP) player); + } - ItemStack item = role.inventoryCurrency.items.get(i); - ItemStack item2 = role.inventoryCurrency.items.get(i + 18); - if (item == null) { - item = item2; - item2 = null; - } - addSlotToContainer(new Slot(role.inventorySold, i, x, y)); + // Trade slots: 3 columns x 6 rows, 80px column width + // Layout per column: [Slot1][Slot2] = [Output] + for (int i = 0; i < 18; i++) { + int col = i % 3; + int row = i / 3; + int x = COLUMN_START_X + col * COLUMN_WIDTH; + int y = ROW_START_Y + row * ROW_HEIGHT; + // Output slot position (slot texture is 18x18, item renders centered at +1) + addSlotToContainer(new Slot(role.inventorySold, i, x + OUTPUT_OFFSET + 1, y + 1)); } for (int i1 = 0; i1 < 3; i1++) { for (int l1 = 0; l1 < 9; l1++) { - addSlotToContainer(new Slot(player.inventory, l1 + i1 * 9 + 9, 32 + l1 * 18, 140 + i1 * 18)); + addSlotToContainer(new Slot(player.inventory, l1 + i1 * 9 + 9, 48 + l1 * 18, 137 + i1 * 18)); } - } + // Player hotbar for (int j1 = 0; j1 < 9; j1++) { - addSlotToContainer(new Slot(player.inventory, j1, 32 + j1 * 18, 198)); + addSlotToContainer(new Slot(player.inventory, j1, 48 + j1 * 18, 195)); + } + } + + @Override + public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + // Unregister this player from viewer tracking (only if registered for shared stock) + if (player instanceof EntityPlayerMP && !role.stock.perPlayer) { + role.unregisterViewer((EntityPlayerMP) player); } } @@ -61,17 +88,53 @@ public class ContainerNPCTrader extends ContainerNpcInterface { ItemStack item = slot.getStack(); if (!canGivePlayer(item, entityplayer)) return null; - if (!canBuy(i, entityplayer)) - return null; if (!isSlotEnabled(i, entityplayer)) return null; + + // Check stock availability + String playerName = entityplayer.getCommandSenderName(); + if (!role.hasStock(i, playerName, 1)) { + return null; // Out of stock + } + + // Item-based currency + if (!canBuy(i, entityplayer)) + return null; + + // Currency cost check (additive to item costs) + long currencyCost = role.getCurrencyCost(i); + if (currencyCost > 0) { + PlayerData data = PlayerData.get(entityplayer); + if (data.tradeData.getBalance() < currencyCost) { + return null; // Can't afford currency cost + } + } + + // Consume item currency NoppesUtilPlayer.consumeItem(entityplayer, role.inventoryCurrency.getStackInSlot(i), role.ignoreDamage, role.ignoreNBT); NoppesUtilPlayer.consumeItem(entityplayer, role.inventoryCurrency.getStackInSlot(i + 18), role.ignoreDamage, role.ignoreNBT); + + // Withdraw currency cost (after item consumption to maintain order) + if (currencyCost > 0) { + PlayerData data = PlayerData.get(entityplayer); + data.tradeData.withdraw(currencyCost); + } + + // Consume stock + role.consumeStock(i, playerName, 1); + ItemStack soldItem = item.copy(); givePlayer(soldItem, entityplayer); role.addPurchase(i, entityplayer.getDisplayName()); - return soldItem; + // Always sync the purchasing player's data (balance + stock) after trade. + // For shared stocks, consumeStock() syncs stock to other viewers, + // but the purchasing player's balance still needs an explicit sync. + if (entityplayer instanceof EntityPlayerMP) { + role.syncToPlayer((EntityPlayerMP) entityplayer); + } + + return soldItem; } public boolean isSlotEnabled(int slot, EntityPlayer player) { diff --git a/src/main/java/noppes/npcs/containers/ContainerNPCTraderSetup.java b/src/main/java/noppes/npcs/containers/ContainerNPCTraderSetup.java index 8209f22a8..f5d347e16 100644 --- a/src/main/java/noppes/npcs/containers/ContainerNPCTraderSetup.java +++ b/src/main/java/noppes/npcs/containers/ContainerNPCTraderSetup.java @@ -13,15 +13,19 @@ public class ContainerNPCTraderSetup extends Container { public ContainerNPCTraderSetup(EntityNPCInterface npc, EntityPlayer player) { role = (RoleTrader) npc.roleInterface; + // New layout: $[Currency TextField], Item Cost 1, Item Cost 2, =, Output + // Column width: 130px for better spacing for (int i = 0; i < 18; i++) { int x = 7; - x += i % 3 * 94; + x += i % 3 * 130; int y = 15; y += i / 3 * 22; - addSlotToContainer(new Slot(role.inventoryCurrency, i + 18, x, y)); - addSlotToContainer(new Slot(role.inventoryCurrency, i, x + 18, y)); - addSlotToContainer(new Slot(role.inventorySold, i, x + 43, y)); - + // Item Cost 1 (primary currency) + addSlotToContainer(new Slot(role.inventoryCurrency, i, x + 51, y)); + // Item Cost 2 (secondary currency) + addSlotToContainer(new Slot(role.inventoryCurrency, i + 18, x + 69, y)); + // Output (sold item) + addSlotToContainer(new Slot(role.inventorySold, i, x + 105, y)); } for (int i1 = 0; i1 < 3; i1++) { diff --git a/src/main/java/noppes/npcs/containers/InventoryAuctionDisplay.java b/src/main/java/noppes/npcs/containers/InventoryAuctionDisplay.java new file mode 100644 index 000000000..50d2b50e7 --- /dev/null +++ b/src/main/java/noppes/npcs/containers/InventoryAuctionDisplay.java @@ -0,0 +1,159 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +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; + +/** + * Virtual inventory for displaying auction listings and claims. + * This inventory holds ItemStacks from AuctionListings/Claims for display purposes. + */ +public class InventoryAuctionDisplay implements IInventory { + private final ItemStack[] items; + private final List listings; + private final List claims; + private final int size; + + public InventoryAuctionDisplay(int size) { + this.size = size; + this.items = new ItemStack[size]; + this.listings = new ArrayList<>(size); + this.claims = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + listings.add(null); + claims.add(null); + } + } + + public void setListing(int slot, AuctionListing listing) { + if (slot >= 0 && slot < size) { + listings.set(slot, listing); + claims.set(slot, null); + items[slot] = listing != null ? listing.item : null; + } + } + + public AuctionListing getListing(int slot) { + if (slot >= 0 && slot < size) { + return listings.get(slot); + } + return null; + } + + /** + * Set a claim item in the inventory. + * Shows actual item for ITEM claims. + * For CURRENCY claims, shows coin icon (null item). + * For REFUND claims, shows item if present (for rebid option), otherwise coin icon. + */ + public void setClaimItem(int slot, AuctionClaim claim) { + if (slot >= 0 && slot < size) { + claims.set(slot, claim); + listings.set(slot, null); + if (claim != null) { + if (claim.type == EnumClaimType.CURRENCY) { + // Sold - gold coin icon drawn by GUI + items[slot] = null; + } else if (claim.type == EnumClaimType.REFUND) { + // Outbid - show item if present (for rebid), otherwise coin + items[slot] = claim.item != null ? claim.item.copy() : null; + } else if (claim.item != null) { + // Show actual item for ITEM claims + items[slot] = claim.item.copy(); + } else { + items[slot] = null; + } + } else { + items[slot] = null; + } + } + } + + public AuctionClaim getClaim(int slot) { + if (slot >= 0 && slot < size) { + return claims.get(slot); + } + return null; + } + + public void clear() { + for (int i = 0; i < size; i++) { + items[i] = null; + listings.set(i, null); + claims.set(i, null); + } + } + + @Override + public int getSizeInventory() { + return size; + } + + @Override + public ItemStack getStackInSlot(int slot) { + if (slot >= 0 && slot < size) { + return items[slot]; + } + return null; + } + + @Override + public ItemStack decrStackSize(int slot, int amount) { + return null; // Display only + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + if (slot >= 0 && slot < size) { + items[slot] = stack; + } + } + + @Override + public String getInventoryName() { + return "Auction Display"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public void markDirty() { + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return true; + } + + @Override + public void openInventory() { + } + + @Override + public void closeInventory() { + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + return false; + } +} diff --git a/src/main/java/noppes/npcs/containers/SlotAuctionDisplay.java b/src/main/java/noppes/npcs/containers/SlotAuctionDisplay.java new file mode 100644 index 000000000..43b745051 --- /dev/null +++ b/src/main/java/noppes/npcs/containers/SlotAuctionDisplay.java @@ -0,0 +1,31 @@ +package noppes.npcs.containers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +/** + * A display-only slot for auction listings. + * Items cannot be placed or taken from this slot. + */ +public class SlotAuctionDisplay extends Slot { + public SlotAuctionDisplay(IInventory inventory, int slotIndex, int x, int y) { + super(inventory, slotIndex, x, y); + } + + @Override + public boolean isItemValid(ItemStack stack) { + return false; + } + + @Override + public boolean canTakeStack(EntityPlayer player) { + return false; + } + + @Override + public int getSlotStackLimit() { + return 64; + } +} diff --git a/src/main/java/noppes/npcs/controllers/AnimationController.java b/src/main/java/noppes/npcs/controllers/AnimationController.java index 65adfcd3d..2d9758734 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; @@ -8,31 +9,53 @@ import noppes.npcs.LogWriter; import noppes.npcs.api.handler.IAnimationHandler; import noppes.npcs.api.handler.data.IAnimation; import noppes.npcs.controllers.data.Animation; +import noppes.npcs.controllers.data.BuiltInAnimation; import noppes.npcs.util.NBTJsonUtil; import java.io.BufferedInputStream; +import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Stream; import java.util.zip.GZIPInputStream; public class AnimationController implements IAnimationHandler { public HashMap animations; private HashMap bootOrder; - public static AnimationController Instance; + // 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"; + + 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() { @@ -42,57 +65,185 @@ public class AnimationController implements IAnimationHandler { public void load() { bootOrder = new HashMap<>(); animations = new HashMap<>(); + 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. + * These animations are read-only and accessed by name only (no IDs). + * Scans the folder directly instead of using a manifest. + */ + private void loadBuiltInAnimations() { + try { + URL resourceUrl = CustomNpcs.class.getResource(BUILTIN_ANIMATIONS_PATH); + if (resourceUrl == null) { + LogWriter.info("Built-in animations folder not found: " + BUILTIN_ANIMATIONS_PATH); + return; + } + + URI uri = resourceUrl.toURI(); + Path animationsPath; + + if (uri.getScheme().equals("jar")) { + // Running from JAR - need to create a FileSystem to access it + FileSystem fileSystem = null; + try { + fileSystem = FileSystems.getFileSystem(uri); + } catch (Exception e) { + fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap()); + } + animationsPath = fileSystem.getPath(BUILTIN_ANIMATIONS_PATH); + } else { + // Running from file system (dev environment) + animationsPath = Paths.get(uri); + } + + // Scan the directory for .json files + try (Stream paths = Files.walk(animationsPath, 1)) { + paths.filter(path -> path.toString().endsWith(".json")) + .forEach(path -> { + String fileName = path.getFileName().toString(); + String animName = fileName.substring(0, fileName.length() - 5); // Remove .json + try { + loadBuiltInAnimation(animName); + } catch (Exception e) { + LogWriter.error("Error loading built-in animation: " + animName, e); + } + }); + } + + LogWriter.info("Loaded " + builtInAnimations.size() + " built-in animations."); + } catch (Exception e) { + LogWriter.error("Error scanning built-in animations folder", e); + } + } + + public void loadBuiltInAnimation(Class modClass, String path, String animName) throws Exception { + String resourcePath = path + "/" + animName + ".json"; + try (InputStream stream = modClass.getResourceAsStream(resourcePath)) { + if (stream == null) { + LogWriter.error("Animation not found: " + animName.toLowerCase()); + return; + } + + // Read JSON content + StringBuilder content = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + String line; + while ((line = reader.readLine()) != null) { + content.append(line); + } + reader.close(); + + // Parse NBT from JSON + NBTTagCompound nbt = NBTJsonUtil.Convert(content.toString()); + + BuiltInAnimation animation = new BuiltInAnimation(animName); + animation.readFromNBT(nbt); + + // Store with lowercase key for case-insensitive lookup + builtInAnimations.put(animName.toLowerCase(), animation); + LogWriter.info("Registered animation: " + animName.toLowerCase()); + } + } + + /** + * Load a single built-in animation by name from assets folder. + */ + private void loadBuiltInAnimation(String animName) throws Exception { + loadBuiltInAnimation(CustomNpcs.class, BUILTIN_ANIMATIONS_PATH, animName); + } + private void loadAnimations() { animations.clear(); 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); + return; + } - 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"); } @@ -110,6 +261,12 @@ public class AnimationController implements IAnimationHandler { } public IAnimation saveAnimation(IAnimation animation) { + // Reject saving built-in animations + if (animation instanceof BuiltInAnimation) { + LogWriter.info("Cannot save built-in animation: " + animation.getName()); + return animation; + } + if (animation.getID() < 0) { animation.setID(getUnusedId()); while (hasName(animation.getName())) @@ -127,7 +284,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(); @@ -157,39 +314,29 @@ public class AnimationController implements IAnimationHandler { public void delete(String name) { Animation delete = getAnimationFromName(name); if (delete != null) { - 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) { - if (!this.animations.containsKey(id)) + 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(); } } @@ -199,27 +346,111 @@ public class AnimationController implements IAnimationHandler { } public IAnimation get(String name) { - return getAnimationFromName(name); + return get(name, false); } + public IAnimation get(String name, boolean builtIn) { + // Check user/custom animations first (allows overriding built-in) + for (Map.Entry entry : animations.entrySet()) { + if (entry.getValue().name.equalsIgnoreCase(name)) { + return entry.getValue(); + } + } + // Then check built-in animations + if (builtIn) { + BuiltInAnimation builtInAnim = builtInAnimations.get(name.toLowerCase()); + if (builtInAnim != null) { + return builtInAnim; + } + } + + return null; + } + + /** + * Get a user animation by ID. + * Built-in animations have no IDs and cannot be retrieved this way. + */ public IAnimation get(int id) { + // Only user animations have valid IDs + if (id < 0) { + return null; + } return this.animations.get(id); } + /** + * Get a built-in animation by name. + * + * @param name The animation name (case-insensitive) + * @return The built-in animation, or null if not found + */ + public BuiltInAnimation getBuiltInAnimation(String name) { + return builtInAnimations.get(name.toLowerCase()); + } + public IAnimation[] getAnimations() { ArrayList animations = new ArrayList<>(this.animations.values()); return animations.toArray(new IAnimation[0]); } + /** + * Get all built-in animations. + */ + public IAnimation[] getBuiltInAnimations() { + return builtInAnimations.values().toArray(new IAnimation[0]); + } + + /** + * Get all animations (both built-in and user-created). + */ + public IAnimation[] getAllAnimations() { + ArrayList all = new ArrayList<>(); + all.addAll(builtInAnimations.values()); + all.addAll(animations.values()); + return all.toArray(new IAnimation[0]); + } + + /** + * 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 + */ + public boolean isBuiltIn(String name) { + return builtInAnimations.containsKey(name.toLowerCase()); + } + + /** + * @deprecated Built-in animations no longer use IDs. Use isBuiltIn(String name) instead. + */ + @Deprecated + public boolean isBuiltIn(int id) { + return false; // Built-in animations have no IDs + } + public Animation getAnimationFromName(String animation) { - for (Map.Entry entryAnimation : AnimationController.getInstance().animations.entrySet()) { + // Check user/custom animations first (allows overriding built-in) + for (Map.Entry entryAnimation : animations.entrySet()) { if (entryAnimation.getValue().name.equalsIgnoreCase(animation)) { return entryAnimation.getValue(); } } + // Then check built-in animations + BuiltInAnimation builtIn = builtInAnimations.get(animation.toLowerCase()); + if (builtIn != null) { + return builtIn; + } return null; } + /** + * Get names of all built-in animations. + */ + public String[] getBuiltInAnimationNames() { + return builtInAnimations.keySet().toArray(new String[0]); + } + public String[] getNames() { String[] names = new String[animations.size()]; int i = 0; @@ -231,10 +462,9 @@ public class AnimationController implements IAnimationHandler { } - //////////////////////////////////////////////////////// - //////////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////// // ANIMATION MAP - public File getMapDir() { File dir = CustomNpcs.getWorldSaveDirectory(); if (!dir.exists()) @@ -325,5 +555,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 new file mode 100644 index 000000000..dae214f5c --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/AuctionConfigSync.java @@ -0,0 +1,49 @@ +package noppes.npcs.controllers; + +import kamkeel.npcs.util.VaultUtil; +import net.minecraft.nbt.NBTTagCompound; +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 { + + /** + * 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. + */ + public static NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("AuctionEnabled", ConfigMarket.AuctionEnabled); + compound.setLong("ListingFee", ConfigMarket.ListingFee); + compound.setString("CurrencyName", getEffectiveCurrencyName()); + compound.setInteger("AuctionDurationHours", ConfigMarket.AuctionDurationHours); + compound.setDouble("MinBidIncrement", ConfigMarket.MinBidIncrementPercent); + compound.setInteger("MaxActiveListings", ConfigMarket.DefaultMaxTrades); + compound.setInteger("ClaimExpirationDays", ConfigMarket.ClaimExpirationDays); + return compound; + } + + /** + * Get the effective currency name for display. + * Uses Vault currency name if Vault is enabled and available, + * otherwise uses ConfigMarket.CurrencyName. + * + * @return The currency name to display + */ + public static String getEffectiveCurrencyName() { + if (ConfigMarket.UseVault && VaultUtil.isEnabled()) { + String vaultName = VaultUtil.getCurrencyNamePlural(); + if (vaultName != null && !vaultName.isEmpty()) { + return vaultName; + } + } + return ConfigMarket.CurrencyName; + } +} diff --git a/src/main/java/noppes/npcs/controllers/AuctionController.java b/src/main/java/noppes/npcs/controllers/AuctionController.java new file mode 100644 index 000000000..e51c07a5d --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/AuctionController.java @@ -0,0 +1,1930 @@ +package noppes.npcs.controllers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +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; +import noppes.npcs.constants.EnumNotificationType; +import noppes.npcs.controllers.data.AuctionBlacklist; +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.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) + * - Player-specific queries use indexed maps for fast lookups + */ +public class AuctionController implements IAuctionHandler { + public static AuctionController Instance; + + // Main data stores - listings only, claims are stored in PlayerData + private final Map listings = new ConcurrentHashMap<>(); + // 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 + */ + private final Map> playerListingIds = new ConcurrentHashMap<>(); + + /** + * 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 + */ + private final Map playerMaxTradesCache = new ConcurrentHashMap<>(); + + // ========================================= + // Threading & State + // ========================================= + + /** + * Flag indicating data needs to be saved + */ + private final AtomicBoolean dirty = new AtomicBoolean(false); + + /** + * 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) + */ + private static final int TICK_INTERVAL = 600; + + public AuctionController() { + Instance = this; + AuctionBlacklist.reload(); + load(); + } + + public static AuctionController getInstance() { + if (Instance == null || needsNewInstance()) { + Instance = new AuctionController(); + } + return Instance; + } + + private static boolean needsNewInstance() { + if (Instance == null) return true; + File file = CustomNpcs.getWorldSaveDirectory(); + if (file == null) return false; + return !Instance.filePath.equals(file.getAbsolutePath()); + } + + // ========================================= + // Tick Processing + // ========================================= + + public void onServerTick() { + if (!ConfigMarket.AuctionEnabled) return; + + tickCounter++; + + // Process auctions and save every 30 seconds + if (tickCounter >= TICK_INTERVAL) { + tickCounter = 0; + processEndedAuctions(); + if (dirty.get()) { + saveAsync(); + } + } + } + + private void processEndedAuctions() { + boolean changed = false; + for (AuctionListing listing : listings.values()) { + if (listing.status == EnumAuctionStatus.ACTIVE && listing.isExpired()) { + endAuction(listing); + changed = true; + } + } + if (changed) { + markDirty(); + } + } + + private void endAuction(AuctionListing listing) { + synchronized (listing) { + if (listing.status != EnumAuctionStatus.ACTIVE) return; + + listing.status = EnumAuctionStatus.ENDED; + boolean isGlobalListing = listing.isGlobalListing; + + // Remove from seller's active listings + if (!isGlobalListing && listing.sellerUUID != null) { + removeFromPlayerListings(listing.sellerUUID, listing.id); + } + + // Remove from bidder's active bids if any + if (listing.highBidderUUID != null) { + removeFromPlayerBids(listing.highBidderUUID, listing.id); + } + + // Get item display name safely + String itemDisplayName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item"; + + if (listing.hasBids()) { + // Auction sold - create claims + AuctionClaim itemClaim = AuctionClaim.createItemWonClaim( + listing.highBidderUUID, listing.highBidderName, listing.id, listing.item); + addClaimToPlayer(listing.highBidderUUID, itemClaim); + + long saleAmount = listing.currentBid; + long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent); + long sellerReceives = saleAmount - tax; + + AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim( + listing.sellerUUID, listing.sellerName, listing.id, sellerReceives, + itemDisplayName, listing.highBidderName); + if (isGlobalListing) { + addGlobalClaim(currencyClaim); + } else { + addClaimToPlayer(listing.sellerUUID, currencyClaim); + } + + // 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 + "!"); + } + + 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(EnumAuctionLogAction.EXPIRED, listing.sellerName, itemDisplayName, listing.startingPrice, + "No bids" + (isGlobalListing ? ", Global listing" : "")); + } + } + } + + // ========================================= + // Index Management + // ========================================= + + 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); + if (ids.isEmpty()) { + playerListingIds.remove(playerUUID); + } + } + } + + 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); + if (ids.isEmpty()) { + playerBidIds.remove(playerUUID); + } + } + } + + /** + * Add a claim to a player's trade data. + * If player is online, adds directly. If offline, loads their data file and updates it. + */ + private void addClaimToPlayer(UUID playerUUID, AuctionClaim claim) { + if (playerUUID == null || claim == null) return; + + PlayerData data = PlayerDataController.Instance.getData(playerUUID); + if (data != null) { + data.tradeData.addClaim(claim); + data.updateClient = true; + data.save(); + } + } + + /** + * 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 + // ========================================= + + public String createListing(EntityPlayer player, ItemStack item, long startingPrice, long buyoutPrice) { + if (!ConfigMarket.AuctionEnabled) { + return "Auction is disabled."; + } + + // Check blacklist (with bypass for admins) + if (AuctionBlacklist.isBlacklistedForPlayer(item, player)) { + return "This item cannot be listed on the Auction House."; + } + + // 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(); + + // Check trade slot limit (listings + bids + claims) + int currentTrades = getPlayerTradeSlotCount(player); + int maxTrades = getMaxTradesForPlayer(player); + if (currentTrades >= maxTrades) { + return "You have reached your maximum trade slots (" + maxTrades + ")."; + } + + // Check listing fee + PlayerData playerData = PlayerData.get(player); + if (playerData == null) { + return "Could not access player data."; + } + + PlayerTradeData currency = playerData.tradeData; + long fee = ConfigMarket.ListingFee; + 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 (fee > 0 && !currency.withdraw(fee)) { + return "Failed to deduct listing fee."; + } + + // Calculate duration + long durationMs = ConfigMarket.AuctionDurationHours * 60L * 60L * 1000L; + + // Create listing + AuctionListing listing = new AuctionListing(playerUUID, playerName, item, startingPrice, buyoutPrice, durationMs); + listings.put(listing.id, listing); + addToPlayerListings(playerUUID, listing.id); + + markDirty(); + + 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 (isAdmin && listing.isGlobalListing) { + return adminStopListingToGlobal(listingId, player, true); + } + + 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(); + } + + return null; // Success + } + + // ========================================= + // Bidding + // ========================================= + + public String placeBid(String listingId, EntityPlayer player, long bidAmount) { + if (!ConfigMarket.AuctionEnabled) { + return "Auction is disabled."; + } + + // Validate bid amount + if (bidAmount <= 0) { + return "Bid amount must be positive."; + } + + UUID playerUUID = player.getUniqueID(); + String playerName = player.getCommandSenderName(); + + AuctionListing listing = listings.get(listingId); + if (listing == null) { + return "Listing not found."; + } + + 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); + } + + markDirty(); + + logAuction(EnumAuctionLogAction.BID, playerName, listing.item.getDisplayName(), bidAmount, + "Bids: " + listing.bidCount + ", Seller: " + listing.sellerName); + + return null; // Success + } + + public String buyout(String listingId, EntityPlayer player) { + if (!ConfigMarket.AuctionEnabled) { + return "Auction is disabled."; + } + + UUID playerUUID = player.getUniqueID(); + String playerName = player.getCommandSenderName(); + + AuctionListing listing = listings.get(listingId); + if (listing == null) { + return "Listing not found."; + } + + synchronized (listing) { + // 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."; + } + 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" : "")); + } + + return null; // Success + } + + // ========================================= + // Claims - Now stored in PlayerData + // ========================================= + + /** + * Get player claims from PlayerData. + */ + public List getPlayerClaims(EntityPlayer player) { + PlayerData playerData = PlayerData.get(player); + if (playerData == null) { + return new ArrayList<>(); + } + return playerData.tradeData.getClaimsList(); + } + + /** + * Get player claims by UUID (for login notification). + */ + public List getPlayerClaims(UUID playerUUID) { + EntityPlayerMP onlinePlayer = (EntityPlayerMP) PlayerDataController.getPlayerFromUUID(playerUUID); + if (onlinePlayer != null) { + return getPlayerClaims(onlinePlayer); + } + 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) { + return "Could not access player data."; + } + + AuctionClaim claim = playerData.tradeData.getClaimInternal(claimId); + if (claim == null) { + return "Claim not found."; + } + + if (claim.claimed) { + return "Already claimed."; + } + + if (!claim.type.isItem()) { + return "This is not an item claim."; + } + + if (claim.item == null) { + return "Item data is missing."; + } + + // 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; + playerData.save(); + + // Cleanup listing if no more claims + cleanupListingIfComplete(claim.listingId); + + logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), claim.item.getDisplayName(), 0, "Item claimed"); + + return null; // Success + } + + public String claimCurrency(String claimId, EntityPlayer player) { + PlayerData playerData = PlayerData.get(player); + if (playerData == null) { + return "Could not access player data."; + } + + AuctionClaim claim = playerData.tradeData.getClaimInternal(claimId); + if (claim == null) { + return "Claim not found."; + } + + if (claim.claimed) { + return "Already claimed."; + } + + if (!claim.type.isCurrency()) { + 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."; + } + + // Remove claim from player's auction data + playerData.tradeData.claimAndRemove(claimId); + playerData.updateClient = true; + playerData.save(); + + // Cleanup listing if no more claims + cleanupListingIfComplete(claim.listingId); + + 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. + */ + private void cleanupListingIfComplete(String listingId) { + if (listingId == null || listingId.isEmpty()) return; + + AuctionListing listing = listings.get(listingId); + if (listing == null) return; + + // Only cleanup ended/cancelled listings + if (listing.status == EnumAuctionStatus.ACTIVE) return; + + // Remove ended listings (claims are now in PlayerData, not here) + listings.remove(listingId); + markDirty(); + } + + public int claimAll(EntityPlayer player) { + int claimedCount = 0; + List playerClaims = getPlayerClaims(player); + + for (AuctionClaim claim : playerClaims) { + String result; + if (claim.type.isItem()) { + result = claimItem(claim.id, player); + } else { + result = claimCurrency(claim.id, player); + } + if (result == null) { + claimedCount++; + } + } + + return claimedCount; + } + + // ========================================= + // Queries - Using Indexed Lookups + // ========================================= + + public List getActiveListings(AuctionFilter filter, int page, int pageSize) { + List result = new ArrayList<>(); + + 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()) { + String itemName = listing.item != null ? listing.item.getDisplayName() : ""; + String sellerName = listing.sellerName != null ? listing.sellerName : ""; + if (!filter.matchesSearch(itemName, sellerName)) continue; + } + + result.add(listing); + } + + // Sort + sortListings(result, filter.sortBy); + + // Paginate + int start = page * pageSize; + int end = Math.min(start + pageSize, result.size()); + if (start >= result.size()) { + return new ArrayList<>(); + } + return new ArrayList<>(result.subList(start, end)); + } + + private void sortListings(List list, EnumAuctionSort sortBy) { + Comparator comparator; + switch (sortBy) { + case ENDING_SOON: + comparator = Comparator.comparingLong(AuctionListing::getTimeRemaining); + break; + case PRICE_LOW: + comparator = Comparator.comparingLong(AuctionListing::getEffectivePrice); + break; + case PRICE_HIGH: + comparator = Comparator.comparingLong(AuctionListing::getEffectivePrice).reversed(); + break; + case MOST_BIDS: + comparator = Comparator.comparingInt(l -> -l.bidCount); + break; + case NEWEST: + default: + comparator = Comparator.comparingLong(l -> -l.createdTime); + break; + } + list.sort(comparator); + } + + public int getTotalActiveListings(AuctionFilter filter) { + 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 : ""; + if (!filter.matchesSearch(itemName, sellerName)) continue; + } + count++; + } + return count; + } + + @Override + public AuctionListing getListing(String listingId) { + return listings.get(listingId); + } + + /** + * Get a player's current currency balance. + */ + public long getPlayerBalance(EntityPlayer player) { + PlayerData playerData = PlayerData.get(player); + if (playerData == null || playerData.tradeData == null) { + return 0; + } + return playerData.tradeData.getBalance(); + } + + /** + * Get player listing count using index + */ + public int getPlayerListingCount(UUID playerUUID) { + Set ids = playerListingIds.get(playerUUID); + return ids != null ? ids.size() : 0; + } + + /** + * Get player's active listings using indexed lookup + */ + public List getPlayerActiveListings(UUID playerUUID) { + Set listingIds = playerListingIds.get(playerUUID); + if (listingIds == null || listingIds.isEmpty()) { + return new ArrayList<>(); + } + + List result = new ArrayList<>(); + for (String listingId : listingIds) { + AuctionListing listing = listings.get(listingId); + if (listing != null && listing.status == EnumAuctionStatus.ACTIVE) { + result.add(listing); + } + } + return result; + } + + /** + * Get all active auctions where the player is currently the highest bidder. + * Uses indexed lookup for O(1) access to player's bid set. + */ + public List getPlayerActiveBids(UUID playerUUID) { + Set bidListingIds = playerBidIds.get(playerUUID); + if (bidListingIds == null || bidListingIds.isEmpty()) { + return new ArrayList<>(); + } + + List result = new ArrayList<>(); + for (String listingId : bidListingIds) { + AuctionListing listing = listings.get(listingId); + if (listing != null && listing.status == EnumAuctionStatus.ACTIVE && + listing.highBidderUUID != null && listing.highBidderUUID.equals(playerUUID)) { + result.add(listing); + } + } + return result; + } + + /** + * Get the total number of trade slots used by a player. + * Includes active listings, active bids, and pending claims. + */ + public int getPlayerTradeSlotCount(EntityPlayer player) { + UUID playerUUID = player.getUniqueID(); + int count = 0; + // Active listings + Set listingIds = playerListingIds.get(playerUUID); + if (listingIds != null) count += listingIds.size(); + // Active bids + Set bidIds = playerBidIds.get(playerUUID); + if (bidIds != null) count += bidIds.size(); + // Pending claims (from PlayerData) + PlayerData playerData = PlayerData.get(player); + if (playerData != null) { + count += playerData.tradeData.getClaimCount(); + } + return count; + } + + /** + * Get the total number of trade slots used by a player (UUID version). + * For offline players, only returns listings + bids (claims are in their PlayerData). + */ + public int getPlayerTradeSlotCount(UUID playerUUID) { + int count = 0; + // Active listings + Set listingIds = playerListingIds.get(playerUUID); + if (listingIds != null) count += listingIds.size(); + // Active bids + Set bidIds = playerBidIds.get(playerUUID); + if (bidIds != null) count += bidIds.size(); + // Can't get claims for offline player without loading their data + return count; + } + + /** + * Get the maximum trade slots for a player. + * Uses cached value if available, otherwise computes from permissions. + */ + public int getMaxTradesForPlayer(EntityPlayer player) { + UUID playerUUID = player.getUniqueID(); + + // Check cache first + Integer cached = playerMaxTradesCache.get(playerUUID); + if (cached != null) { + return cached; + } + + // Compute and cache + int maxTrades = computeMaxTradesForPlayer(player); + playerMaxTradesCache.put(playerUUID, maxTrades); + return maxTrades; + } + + /** + * Compute max trade slots from permissions. + * Checks for customnpcs.auction.trades.X permissions where X is the slot count. + * Uses the highest permission found, or DefaultMaxTrades if no permissions or lower. + * Capped at MAX_TRADE_SLOTS (45). + */ + private int computeMaxTradesForPlayer(EntityPlayer player) { + // Check for unlimited permission + if (CustomNpcsPermissions.hasCustomPermission(player, "customnpcs.auction.trades.*")) { + return ConfigMarket.MAX_TRADE_SLOTS; + } + + // Find highest allowed slot count from permissions + int highestAllowed = 0; + for (int i = 1; i <= ConfigMarket.MAX_TRADE_SLOTS; i++) { + String perm = "customnpcs.auction.trades." + i; + if (CustomNpcsPermissions.hasCustomPermission(player, perm)) { + highestAllowed = i; + } + } + + // Use default if no permissions found or permission is lower than default + if (highestAllowed == 0 || highestAllowed < ConfigMarket.DefaultMaxTrades) { + highestAllowed = ConfigMarket.DefaultMaxTrades; + } + + // Cap at maximum + return Math.min(highestAllowed, ConfigMarket.MAX_TRADE_SLOTS); + } + + /** + * Refresh a player's cached max trades (call when permissions change). + */ + public void refreshPlayerMaxTrades(EntityPlayer player) { + UUID playerUUID = player.getUniqueID(); + int maxTrades = computeMaxTradesForPlayer(player); + playerMaxTradesCache.put(playerUUID, maxTrades); + } + + /** + * Clear a player's cached max trades (call on logout). + */ + public void clearPlayerMaxTradesCache(UUID playerUUID) { + playerMaxTradesCache.remove(playerUUID); + } + + // ========================================= + // Notifications + // ========================================= + + /** + * Send a notification to a player. + * If player is online, sends immediately. Otherwise, discards (claims will notify on login). + */ + private void sendNotificationToPlayer(UUID playerUUID, EnumNotificationType type, String listingId, String message) { + // Try to send immediately if player is online + EntityPlayerMP player = (EntityPlayerMP) PlayerDataController.getPlayerFromUUID(playerUUID); + if (player != null) { + sendNotificationMessage(player, type, message); + } + // If offline, no need to store - they'll get notified about claims on login + } + + /** + * Send a notification chat message to a player. + */ + private void sendNotificationMessage(EntityPlayerMP player, EnumNotificationType type, String message) { + EnumChatFormatting color; + switch (type) { + case AUCTION_WON: + case AUCTION_SOLD: + color = EnumChatFormatting.GREEN; + break; + case AUCTION_OUTBID: + color = EnumChatFormatting.YELLOW; + break; + case AUCTION_EXPIRED: + color = EnumChatFormatting.RED; + break; + default: + color = EnumChatFormatting.GRAY; + } + player.addChatMessage(new ChatComponentText( + EnumChatFormatting.GOLD + "[Auction] " + color + message)); + } + + public void onPlayerLogin(EntityPlayer player) { + // Cache player's max trades permission + refreshPlayerMaxTrades(player); + + // Process expired claims for this player + PlayerData playerData = PlayerData.get(player); + if (playerData != null) { + int expired = playerData.tradeData.processExpiredClaims(); + if (expired > 0) { + playerData.updateClient = true; + playerData.save(); + logAuction(EnumAuctionLogAction.CLAIM_EXPIRED, player.getCommandSenderName(), "Multiple", expired, + expired + " claims expired on login"); + } + } + + // Check for pending claims and notify + List claims = getPlayerClaims(player); + if (!claims.isEmpty()) { + int itemClaims = 0; + int currencyClaims = 0; + long totalCurrency = 0; + + for (AuctionClaim claim : claims) { + if (claim.type.isItem()) { + itemClaims++; + } else { + currencyClaims++; + totalCurrency += claim.currency; + } + } + + StringBuilder msg = new StringBuilder(); + msg.append(EnumChatFormatting.GOLD).append("[Auction] "); + msg.append(EnumChatFormatting.YELLOW).append("You have "); + + if (itemClaims > 0 && currencyClaims > 0) { + msg.append(itemClaims).append(" item(s) and "); + msg.append(String.format("%,d", totalCurrency)).append(" ").append(ConfigMarket.CurrencyName); + } else if (itemClaims > 0) { + msg.append(itemClaims).append(" item(s)"); + } else { + msg.append(String.format("%,d", totalCurrency)).append(" ").append(ConfigMarket.CurrencyName); + } + msg.append(" to claim!"); + + 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) { + // Clear cached permission + clearPlayerMaxTradesCache(playerUUID); + } + + // ========================================= + // Logging + // ========================================= + + private void logAuction(EnumAuctionLogAction action, String playerName, String itemName, long amount, String details) { + if (!action.shouldLog()) return; + + 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 + */ + private void markDirty() { + dirty.set(true); + } + + /** + * Save synchronously - used for server shutdown + */ + public void save() { + if (!dirty.compareAndSet(true, false)) { + return; // Nothing to save + } + saveInternal(); + } + + /** + * Save asynchronously on CNPC+ thread + */ + public void saveAsync() { + if (!dirty.compareAndSet(true, false)) { + return; // Nothing to save + } + + if (!saving.compareAndSet(false, true)) { + // Another save is in progress, mark dirty again + dirty.set(true); + return; + } + + // Take a snapshot of the data for async save + final NBTTagCompound compound = writeToNBT(new NBTTagCompound()); + + CustomNPCsThreader.customNPCThread.execute(() -> { + try { + saveToFile(compound); + } catch (Exception e) { + LogWriter.error("Error saving auction data asynchronously", e); + // Mark dirty again so we retry + dirty.set(true); + } finally { + saving.set(false); + } + }); + } + + /** + * Internal synchronous save + */ + private void saveInternal() { + try { + NBTTagCompound compound = writeToNBT(new NBTTagCompound()); + saveToFile(compound); + } catch (Exception e) { + LogWriter.error("Error saving auction data", e); + } + } + + private void saveToFile(NBTTagCompound compound) { + try { + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) return; + + File fileNew = new File(saveDir, "auction.dat_new"); + File fileOld = new File(saveDir, "auction.dat_old"); + File fileCurrent = new File(saveDir, "auction.dat"); + + try (FileOutputStream fos = new FileOutputStream(fileNew)) { + CompressedStreamTools.writeCompressed(compound, fos); + } + + // Backup rotation + if (fileOld.exists()) fileOld.delete(); + if (fileCurrent.exists()) fileCurrent.renameTo(fileOld); + if (fileCurrent.exists()) fileCurrent.delete(); + fileNew.renameTo(fileCurrent); + if (fileNew.exists()) fileNew.delete(); + + } catch (Exception e) { + LogWriter.error("Error saving auction data to file", e); + } + } + + public void load() { + listings.clear(); + globalClaims.clear(); + playerListingIds.clear(); + playerBidIds.clear(); + + File saveDir = CustomNpcs.getWorldSaveDirectory(); + if (saveDir == null) return; + filePath = saveDir.getAbsolutePath(); + + // Try current file + try { + File file = new File(saveDir, "auction.dat"); + if (file.exists()) { + loadFromFile(file); + rebuildIndices(); + return; + } + } catch (Exception e) { + LogWriter.error("Error loading auction.dat, trying backup", e); + } + + // Try backup file + try { + File file = new File(saveDir, "auction.dat_old"); + if (file.exists()) { + loadFromFile(file); + rebuildIndices(); + LogWriter.info("Loaded auction data from backup file"); + } + } catch (Exception e) { + LogWriter.error("Error loading auction.dat_old", e); + } + } + + /** + * Rebuild all indices from loaded data + */ + private void rebuildIndices() { + playerListingIds.clear(); + playerBidIds.clear(); + + // Index listings + for (AuctionListing listing : listings.values()) { + if (listing.status == EnumAuctionStatus.ACTIVE) { + if (!listing.isGlobalListing && listing.sellerUUID != null) { + addToPlayerListings(listing.sellerUUID, listing.id); + } + if (listing.highBidderUUID != null) { + addToPlayerBids(listing.highBidderUUID, listing.id); + } + } + } + + // Claims are now stored in PlayerData, not indexed here + LogWriter.info("Rebuilt auction indices: " + playerListingIds.size() + " sellers, " + + playerBidIds.size() + " bidders"); + } + + private void loadFromFile(File file) throws Exception { + NBTTagCompound compound; + try (FileInputStream fis = new FileInputStream(file)) { + compound = CompressedStreamTools.readCompressed(fis); + } + readFromNBT(compound); + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + // 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); + } + } + } + } + + // ========================================= + // IAuctionHandler Implementation + // ========================================= + + @Override + public boolean isEnabled() { + return ConfigMarket.AuctionEnabled; + } + + @Override + public IAuctionListing[] getActiveListings() { + List active = new ArrayList<>(); + for (AuctionListing listing : listings.values()) { + if (listing.status == EnumAuctionStatus.ACTIVE && !listing.isExpired()) { + active.add(listing); + } + } + return active.toArray(new IAuctionListing[0]); + } + + @Override + public IAuctionListing[] getListingsBySeller(String sellerUUID) { + if (sellerUUID == null) return new IAuctionListing[0]; + try { + UUID uuid = UUID.fromString(sellerUUID); + List result = getPlayerActiveListings(uuid); + return result.toArray(new IAuctionListing[0]); + } catch (IllegalArgumentException e) { + return new IAuctionListing[0]; + } + } + + @Override + public IAuctionListing[] getListingsByBidder(String bidderUUID) { + if (bidderUUID == null) return new IAuctionListing[0]; + try { + UUID uuid = UUID.fromString(bidderUUID); + List result = getPlayerActiveBids(uuid); + return result.toArray(new IAuctionListing[0]); + } catch (IllegalArgumentException e) { + return new IAuctionListing[0]; + } + } + + @Override + public int getActiveListingCount() { + int count = 0; + for (AuctionListing listing : listings.values()) { + if (listing.status == EnumAuctionStatus.ACTIVE && !listing.isExpired()) { + count++; + } + } + return count; + } + + @Override + public IAuctionListing createListing(IPlayer player, IItemStack item, long startingPrice, long buyoutPrice) { + if (player == null || item == null) return null; + EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity(); + ItemStack mcItem = item.getMCItemStack(); + String result = createListing(entityPlayer, mcItem, startingPrice, buyoutPrice); + if (result != null) { + return null; // Failed + } + // Find the just-created listing + Set playerListings = playerListingIds.get(entityPlayer.getUniqueID()); + if (playerListings != null && !playerListings.isEmpty()) { + // Get the most recent one + long latestTime = 0; + AuctionListing latestListing = null; + for (String id : playerListings) { + AuctionListing listing = listings.get(id); + if (listing != null && listing.createdTime > latestTime) { + latestTime = listing.createdTime; + latestListing = listing; + } + } + return latestListing; + } + return null; + } + + @Override + public String placeBid(String listingId, IPlayer player, long amount) { + if (player == null) return "Player is null"; + EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity(); + return placeBid(listingId, entityPlayer, amount); + } + + @Override + public String buyout(String listingId, IPlayer player) { + if (player == null) return "Player is null"; + EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity(); + return buyout(listingId, entityPlayer); + } + + @Override + public String cancelListing(String listingId, IPlayer player, boolean isAdmin) { + if (player == null) return "Player is null"; + EntityPlayer entityPlayer = (EntityPlayer) player.getMCEntity(); + return cancelListing(listingId, entityPlayer, isAdmin); + } + + @Override + public long getListingFee() { + return ConfigMarket.ListingFee; + } + + @Override + public double getSalesTaxPercent() { + return ConfigMarket.SalesTaxPercent; + } + + @Override + public double getMinBidIncrementPercent() { + return ConfigMarket.MinBidIncrementPercent; + } + + @Override + public int getAuctionDurationHours() { + return ConfigMarket.AuctionDurationHours; + } + + @Override + public int getSnipeProtectionMinutes() { + return ConfigMarket.SnipeProtectionMinutes; + } + + @Override + public String getCurrencyName() { + return ConfigMarket.CurrencyName; + } + + @Override + public long getMinimumListingPrice() { + return ConfigMarket.MinimumListingPrice; + } + + @Override + public IAuctionListing[] searchListings(String searchText) { + if (searchText == null || searchText.trim().isEmpty()) { + return getActiveListings(); + } + String search = searchText.toLowerCase().trim(); + List result = new ArrayList<>(); + for (AuctionListing listing : listings.values()) { + if (listing.status != EnumAuctionStatus.ACTIVE || listing.isExpired()) continue; + String itemName = listing.item != null ? listing.item.getDisplayName().toLowerCase() : ""; + String sellerName = listing.sellerName != null ? listing.sellerName.toLowerCase() : ""; + if (itemName.contains(search) || sellerName.contains(search)) { + result.add(listing); + } + } + return result.toArray(new IAuctionListing[0]); + } + + // ========================================= + // Admin Methods + // ========================================= + + public List getAllListings() { + 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) { + 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); + + // Rebuild indices + rebuildIndices(); + markDirty(); + } + + /** + * Check if a player is the seller of a listing. + * Used for GUI visibility checks. + */ + public boolean isPlayerSeller(String listingId, UUID playerUUID) { + AuctionListing listing = listings.get(listingId); + return listing != null && listing.isSeller(playerUUID); + } + + /** + * Reload the item blacklist from config. + */ + public void reloadBlacklist() { + AuctionBlacklist.reload(); + } + + /** + * Check if an item is blacklisted. + */ + public boolean isItemBlacklisted(ItemStack item) { + return AuctionBlacklist.isBlacklisted(item); + } +} 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..a4d14def4 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/CategoryManager.java @@ -0,0 +1,248 @@ +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 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) { + 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) 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 (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) { + 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..bff6b64bd 100644 --- a/src/main/java/noppes/npcs/controllers/CustomEffectController.java +++ b/src/main/java/noppes/npcs/controllers/CustomEffectController.java @@ -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(EnumSyncType.CUSTOM_EFFECTS, foundEffect.getID()); saveEffectLoadMap(); } } @@ -319,52 +328,67 @@ 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); - } - } + return; } + + 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 +471,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 +503,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 +631,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 +681,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(); @@ -663,4 +708,23 @@ public class CustomEffectController implements ICustomEffectHandler { return getCustomEffects().get(customEffect.getID()); } + public CustomEffect cloneEffect(int originalId) { + CustomEffect original = getCustomEffects().get(originalId); + if (original == null) return null; + + 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; + + saveEffect(clone); + return clone; + } + } diff --git a/src/main/java/noppes/npcs/controllers/HookDefinition.java b/src/main/java/noppes/npcs/controllers/HookDefinition.java new file mode 100644 index 000000000..be6c09397 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/HookDefinition.java @@ -0,0 +1,306 @@ +package noppes.npcs.controllers; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import noppes.npcs.api.handler.IHookDefinition; +import noppes.npcs.janino.annotations.ParamName; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; + +/** + * Implementation of {@link IHookDefinition} with a fluent builder API. + * + *

Usage Examples

+ *
{@code
+ * // Recommended: auto-derives imports from event class
+ * HookDefinition.of("onDBCTransform", IDBCEvent.TransformEvent.class);
+ *
+ * // Full control with builder
+ * HookDefinition.builder("onDBCPowerUp")
+ *     .eventClass(IDBCEvent.PowerUpEvent.class)
+ *     .cancelable(true)
+ *     .build();
+ *
+ * // Simple hook (no event metadata)
+ * HookDefinition.simple("customHook");
+ * }
+ */ +public class HookDefinition implements IHookDefinition { + + private final String hookName; + private final String eventClassName; + private final String[] paramNames; + private final String[] requiredImports; + private final boolean cancelable; + + private transient Class cachedEventClass; + private transient boolean classResolutionAttempted; + + private HookDefinition(Builder builder) { + this.hookName = builder.hookName; + this.eventClassName = builder.eventClassName; + this.paramNames = builder.paramNames != null ? builder.paramNames : new String[]{"event"}; + this.requiredImports = builder.requiredImports != null ? builder.requiredImports : new String[0]; + this.cancelable = builder.cancelable; + } + + // ==================== IHookDefinition Implementation ==================== + + @Override + public String hookName() { + return hookName; + } + + @Override + public String eventClassName() { + return eventClassName; + } + + @Override + public String[] paramNames() { + return paramNames; + } + + @Override + public String[] requiredImports() { + return requiredImports; + } + + @Override + public boolean isCancelable() { + return cancelable; + } + + @Override + public Class getEventClass() { + if (classResolutionAttempted) { + return cachedEventClass; + } + + classResolutionAttempted = true; + if (eventClassName == null || eventClassName.isEmpty()) { + return null; + } + + try { + cachedEventClass = Class.forName(eventClassName); + } catch (ClassNotFoundException e) { + cachedEventClass = null; + } + + return cachedEventClass; + } + + // ==================== Factory Methods ==================== + + /** + * Create a hook definition from a hook name and event class. + * Automatically derives imports from the event class. + * + * @param hookName The hook function name + * @param eventClass The event class (e.g., INpcEvent.InitEvent.class) + * @return A hook definition with auto-derived imports + */ + public static HookDefinition of(String hookName, Class eventClass) { + return builder(hookName).eventClass(eventClass).build(); + } + + /** + * Create a simple hook definition with just a name (no event metadata). + * + * @param hookName The hook function name + * @return A minimal hook definition + */ + public static HookDefinition simple(String hookName) { + return builder(hookName).build(); + } + + /** + * Create a new builder for a hook definition. + * + * @param hookName The hook function name + * @return A new builder instance + */ + public static Builder builder(String hookName) { + return new Builder(hookName); + } + + /** + * Create a hook definition from an interface method. + * Automatically extracts metadata from the method signature and @ParamName annotations. + * This provides backward compatibility with the annotation-based hook definition approach. + * + * @param hookName The hook name (may differ from method name) + * @param method The method to extract metadata from + * @return A hook definition with extracted metadata + */ + public static HookDefinition fromMethod(String hookName, Method method) { + Builder builder = builder(hookName); + + // Extract event type from first parameter + if (method.getParameterCount() > 0) { + Class eventType = method.getParameterTypes()[0]; + builder.eventClass(eventType); + + // Auto-detect cancelable from event class + if (eventType.isAnnotationPresent(Cancelable.class)) { + builder.cancelable(true); + } + + // Build required imports from event type + String[] importNames = getImportsForClass(eventType); + if (importNames.length > 0) { + builder.requiredImports(importNames); + } + } + + // Extract parameter names from @ParamName annotations + Parameter[] params = method.getParameters(); + if (params.length > 0) { + String[] names = new String[params.length]; + for (int i = 0; i < params.length; i++) { + ParamName annotation = params[i].getAnnotation(ParamName.class); + if (annotation != null) { + names[i] = annotation.value(); + } else { + // Fallback: use lowercase simple type name + names[i] = Character.toLowerCase(params[i].getType().getSimpleName().charAt(0)) + + params[i].getType().getSimpleName().substring(1); + } + } + builder.paramNames(names); + } + + return builder.build(); + } + + /** + * Create a hook definition from a method using its name as the hook name. + * + * @param method The method to extract metadata from + * @return A hook definition with extracted metadata + */ + public static HookDefinition fromMethod(Method method) { + return fromMethod(method.getName(), method); + } + + /** + * Get the import statements needed for a class. + * For nested classes, includes both enclosing and nested names. + */ + private static String[] getImportsForClass(Class clazz) { + if (clazz == null || clazz.isPrimitive()) { + return new String[0]; + } + + String fullName = clazz.getName(); + if (fullName.startsWith("java.lang.")) { + return new String[0]; + } + + Class enclosing = clazz; + while (enclosing.getEnclosingClass() != null) { + enclosing = enclosing.getEnclosingClass(); + } + + String enclosingName = enclosing.getName(); + String nestedName = fullName.replace('$', '.'); + if (!nestedName.equals(enclosingName)) { + return new String[]{enclosingName, nestedName}; + } + + return new String[]{enclosingName}; + } + + // ==================== Builder ==================== + + public static class Builder { + private final String hookName; + private String eventClassName; + private String[] paramNames; + private String[] requiredImports; + private boolean cancelable; + + private Builder(String hookName) { + if (hookName == null || hookName.isEmpty()) { + throw new IllegalArgumentException("hookName cannot be null or empty"); + } + this.hookName = hookName; + } + + /** + * Set the event class directly. + * Automatically derives: class name, required imports, and cancelable status. + */ + public Builder eventClass(Class clazz) { + if (clazz != null) { + this.eventClassName = clazz.getName(); + + String[] importNames = getImportsForClass(clazz); + if (importNames.length > 0) { + this.requiredImports = importNames; + } + + if (clazz.isAnnotationPresent(Cancelable.class)) { + this.cancelable = true; + } + } + return this; + } + + /** + * Set the event class by name (for addon classes that may not be loaded). + */ + public Builder eventClass(String className) { + this.eventClassName = className; + return this; + } + + /** + * Set parameter names for stub generation. + */ + public Builder paramNames(String... names) { + this.paramNames = names; + return this; + } + + /** + * Set required imports (only needed if using eventClass(String)). + */ + public Builder requiredImports(String... imports) { + this.requiredImports = imports; + return this; + } + + /** + * Set whether the event is cancelable. + */ + public Builder cancelable(boolean cancelable) { + this.cancelable = cancelable; + return this; + } + + public HookDefinition build() { + return new HookDefinition(this); + } + } + + // ==================== Object Methods ==================== + + @Override + public String toString() { + return "HookDefinition{hookName='" + hookName + "', eventClass='" + eventClassName + "'}"; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof HookDefinition)) return false; + return hookName.equals(((HookDefinition) obj).hookName); + } + + @Override + public int hashCode() { + return hookName.hashCode(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/LinkedItemController.java b/src/main/java/noppes/npcs/controllers/LinkedItemController.java index c2bc19044..e0aeccb71 100644 --- a/src/main/java/noppes/npcs/controllers/LinkedItemController.java +++ b/src/main/java/noppes/npcs/controllers/LinkedItemController.java @@ -5,9 +5,10 @@ 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.INpcScriptHandler; +import noppes.npcs.controllers.data.IScriptHandler; import noppes.npcs.controllers.data.LinkedItem; import noppes.npcs.controllers.data.LinkedItemScript; import noppes.npcs.util.NBTJsonUtil; @@ -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,24 +88,27 @@ 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 INpcScriptHandler getScriptHandler(int id) { + public IScriptHandler getScriptHandler(int id) { return this.linkedItemsScripts.get(id); } - //////////////////////////////////////////////////////// - //////////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////// public void load() { lastUsedID = 0; @@ -113,45 +126,62 @@ 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); + return; + } - 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 +217,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 +241,25 @@ public class LinkedItemController { return linkedItems.get(linkedItem.getId()); } + public LinkedItem cloneLinkedItem(int originalId) { + LinkedItem original = linkedItems.get(originalId); + if (original == null) return null; + + 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; + + 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,38 +269,29 @@ 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"); } - //////////////////////////////////////////////////////// - //////////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////// + /// ///////////////////////////////////////////////////// // LINKED ITEMS MAP - public File getMapDir() { File dir = CustomNpcs.getWorldSaveDirectory(); if (!dir.exists()) @@ -343,5 +384,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/MarketRegistry.java b/src/main/java/noppes/npcs/controllers/MarketRegistry.java new file mode 100644 index 000000000..55de3a0bf --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/MarketRegistry.java @@ -0,0 +1,214 @@ +package noppes.npcs.controllers; + +import foxz.utils.Market; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.roles.RoleTrader; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Central registry for linked market synchronization. + * Tracks which RoleTrader instances use which markets, + * and which players are viewing each market. + *

+ * This enables immediate sync across all traders sharing + * the same market when a purchase occurs. + */ +public class MarketRegistry { + + // marketName -> Set of traders using this market (WeakHashMap for auto-cleanup) + private static final Map> marketTraders = new ConcurrentHashMap<>(); + + // marketName -> Set of players viewing this market (across all NPCs) + private static final Map> marketViewers = new ConcurrentHashMap<>(); + + // ==================== Trader Registration ==================== + + /** + * Register a trader as using a linked market. + * Should be called when NPC loads or marketName is set. + */ + public static void registerTrader(String marketName, RoleTrader trader) { + if (marketName == null || marketName.isEmpty() || trader == null) return; + + Set traders = marketTraders.computeIfAbsent(marketName, + k -> Collections.newSetFromMap(new WeakHashMap<>())); + + synchronized (traders) { + traders.add(trader); + } + } + + /** + * Unregister a trader from a linked market. + * Should be called when NPC unloads or marketName changes. + */ + public static void unregisterTrader(String marketName, RoleTrader trader) { + if (marketName == null || marketName.isEmpty() || trader == null) return; + + Set traders = marketTraders.get(marketName); + if (traders != null) { + synchronized (traders) { + traders.remove(trader); + if (traders.isEmpty()) { + marketTraders.remove(marketName); + } + } + } + } + + /** + * Change a trader's market registration. + * Handles unregistering from old market and registering to new. + */ + public static void updateTraderMarket(String oldMarket, String newMarket, RoleTrader trader) { + if (trader == null) return; + + if (oldMarket != null && !oldMarket.isEmpty()) { + unregisterTrader(oldMarket, trader); + } + if (newMarket != null && !newMarket.isEmpty()) { + registerTrader(newMarket, trader); + } + } + + // ==================== Viewer Registration ==================== + + /** + * Register a player as viewing a market (via any NPC). + * Should be called when player opens trader GUI with linked market. + */ + public static void registerViewer(String marketName, EntityPlayerMP player) { + if (marketName == null || marketName.isEmpty() || player == null) return; + + Set viewers = marketViewers.computeIfAbsent(marketName, + k -> Collections.newSetFromMap(new WeakHashMap<>())); + + synchronized (viewers) { + viewers.add(player); + } + } + + /** + * Unregister a player from viewing a market. + * Should be called when player closes trader GUI. + */ + public static void unregisterViewer(String marketName, EntityPlayerMP player) { + if (marketName == null || marketName.isEmpty() || player == null) return; + + Set viewers = marketViewers.get(marketName); + if (viewers != null) { + synchronized (viewers) { + viewers.remove(player); + if (viewers.isEmpty()) { + marketViewers.remove(marketName); + } + } + } + } + + // ==================== Synchronization ==================== + + /** + * Sync stock data to all traders and viewers of a market. + * Called after a purchase to update all linked traders and their viewers. + * + * @param marketName The market to sync + */ + public static void syncMarket(String marketName) { + if (marketName == null || marketName.isEmpty()) return; + + // Get latest data from cache + NBTTagCompound marketData = Market.getMarketCache(marketName); + if (marketData == null) return; + + // Update all traders' internal stock data + Set traders = marketTraders.get(marketName); + if (traders != null) { + NBTTagCompound stockData = marketData.getCompoundTag("Stock"); + + synchronized (traders) { + // Clean up any null references (WeakHashMap cleanup) + traders.removeIf(t -> t == null || t.npc == null); + + for (RoleTrader trader : traders) { + // Update stock data from cache + if (stockData != null && stockData.hasKey("EnableStock")) { + trader.stock.readFromNBT(stockData); + } + } + } + } + + // Sync all viewers (across all NPCs for this market) + syncMarketViewers(marketName); + } + + /** + * Sync stock data to all players viewing a specific market. + * Each viewer gets data relative to their own player (for per-player stock display). + */ + public static void syncMarketViewers(String marketName) { + if (marketName == null || marketName.isEmpty()) return; + + Set viewers = marketViewers.get(marketName); + if (viewers == null || viewers.isEmpty()) return; + + // Find any trader with this market to use for sync (they all have same data now) + Set traders = marketTraders.get(marketName); + if (traders == null || traders.isEmpty()) return; + + RoleTrader syncSource = null; + synchronized (traders) { + for (RoleTrader trader : traders) { + if (trader != null && trader.npc != null) { + syncSource = trader; + break; + } + } + } + + if (syncSource == null) return; + + // Sync to all viewers + synchronized (viewers) { + // Remove disconnected players + viewers.removeIf(p -> p == null || p.playerNetServerHandler == null); + + for (EntityPlayerMP viewer : viewers) { + syncSource.syncToPlayer(viewer); + } + } + } + + // ==================== Utility ==================== + + /** + * Get count of traders registered to a market (for debugging/info). + */ + public static int getTraderCount(String marketName) { + Set traders = marketTraders.get(marketName); + return traders != null ? traders.size() : 0; + } + + /** + * Get count of viewers for a market (for debugging/info). + */ + public static int getViewerCount(String marketName) { + Set viewers = marketViewers.get(marketName); + return viewers != null ? viewers.size() : 0; + } + + /** + * Clear all registrations (for server shutdown/reload). + */ + public static void clear() { + marketTraders.clear(); + marketViewers.clear(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/PlayerDataController.java b/src/main/java/noppes/npcs/controllers/PlayerDataController.java index c8964b31d..235e2a9f8 100644 --- a/src/main/java/noppes/npcs/controllers/PlayerDataController.java +++ b/src/main/java/noppes/npcs/controllers/PlayerDataController.java @@ -364,6 +364,17 @@ public class PlayerDataController { return data; } + public PlayerData getData(UUID uuid) { + EntityPlayer player = getPlayerFromUUID(uuid); + PlayerData data; + if (player == null) { + data = new PlayerData(); + data.setNBT(PlayerDataController.Instance.loadPlayerData(uuid.toString())); + } else + data = PlayerData.get(player); + return data; + } + public void addPlayerMessage(String username, PlayerMail mail) { mail.time = System.currentTimeMillis(); diff --git a/src/main/java/noppes/npcs/controllers/PlayerQuestController.java b/src/main/java/noppes/npcs/controllers/PlayerQuestController.java index 7b99f40d8..288c24f79 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 kamkeel.npcs.controllers.data.profile.Profile; 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,29 @@ 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 (ConfigMain.ProfilesEnabled && quest.profileOptions.enableOptions) { + Profile profile = ProfileController.Instance.getProfile(player); + if (profile != null && profile.sharedQuestTimestamps.containsKey(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/QuestController.java b/src/main/java/noppes/npcs/controllers/QuestController.java index 72688b7e5..e9b403ee7 100644 --- a/src/main/java/noppes/npcs/controllers/QuestController.java +++ b/src/main/java/noppes/npcs/controllers/QuestController.java @@ -80,7 +80,9 @@ public class QuestController implements IQuestHandler { ite.remove(); } 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); } } @@ -225,7 +227,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); } diff --git a/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java b/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java new file mode 100644 index 000000000..9e322ea10 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java @@ -0,0 +1,25 @@ +package noppes.npcs.controllers; + +import net.minecraft.nbt.NBTTagCompound; +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 { + + /** + * Write script config to NBT for sending to client. + * Called on server side when building login packet. + */ + public static NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("ScriptingEnabled", ConfigScript.ScriptingEnabled); + compound.setBoolean("RunLoadedScriptsFirst", ConfigScript.RunLoadedScriptsFirst); + compound.setBoolean("GlobalPlayerScripts", ConfigScript.GlobalPlayerScripts); + compound.setBoolean("GlobalForgeScripts", ConfigScript.GlobalForgeScripts); + compound.setBoolean("GlobalNPCScripts", ConfigScript.GlobalNPCScripts); + return compound; + } +} diff --git a/src/main/java/noppes/npcs/controllers/ScriptContainer.java b/src/main/java/noppes/npcs/controllers/ScriptContainer.java index 3ea46b6a7..57c0a0ca1 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptContainer.java +++ b/src/main/java/noppes/npcs/controllers/ScriptContainer.java @@ -3,12 +3,15 @@ package noppes.npcs.controllers; import cpw.mods.fml.common.eventhandler.Event; import jdk.nashorn.api.scripting.ScriptObjectMirror; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcs; import noppes.npcs.NBTTags; import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumScriptType; 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; @@ -24,7 +27,7 @@ import java.util.Map; import java.util.Objects; import java.util.TreeMap; -public class ScriptContainer { +public class ScriptContainer implements IScriptUnit { private static final String lock = "lock"; public static ScriptContainer Current; private static String CurrentType; @@ -44,10 +47,46 @@ public class ScriptContainer { private CompiledScript compScript = null; private final HashMap cachedFunctions = new HashMap<>(); + /** + * 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"); @@ -66,9 +105,16 @@ public class ScriptContainer { 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) { + compound.setString(IScriptUnit.NBT_TYPE_KEY, IScriptUnit.TYPE_ECMASCRIPT); if (this.script.length() < 65535) { compound.setString("Script", this.script); } else { @@ -95,6 +141,11 @@ public class ScriptContainer { //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; } @@ -102,7 +153,7 @@ public class ScriptContainer { if (!this.evaluated) { // build includes first depending on config setting StringBuilder sb = new StringBuilder(); - if (ConfigScript.RunLoadedScriptsFirst) { + if (CustomNpcs.proxy.isRunLoadedScriptsFirst()) { this.appendExternalScripts(sb); } @@ -112,7 +163,7 @@ public class ScriptContainer { } // build includes last if not built first - if (!ConfigScript.RunLoadedScriptsFirst) { + if (!CustomNpcs.proxy.isRunLoadedScriptsFirst()) { this.appendExternalScripts(sb); } this.fullscript = sb.toString(); @@ -156,17 +207,17 @@ public class ScriptContainer { } public void run(EnumScriptType type, Event event) { - if (!ConfigScript.ScriptingEnabled) + if (!CustomNpcs.proxy.isScriptingEnabled()) return; this.run((String) type.function, (Object) event); } public void run(String type, Object event) { - if (!ConfigScript.ScriptingEnabled || errored || !hasCode() || unknownFunctions.contains(type)) + if (!CustomNpcs.proxy.isScriptingEnabled() || errored || !hasCode() || unknownFunctions.contains(type)) return; - this.setEngine(handler.getLanguage()); + this.setEngine(this.getLanguage()); if (engine == null) return; @@ -185,20 +236,33 @@ public class ScriptContainer { 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 + if (instanceBindings != null) { + instanceBindings.put("API", NpcAPI.Instance()); + HashMap engineEntries = new HashMap<>(NpcAPI.engineObjects); + for (Map.Entry objectEntry : engineEntries.entrySet()) { + instanceBindings.put(objectEntry.getKey(), objectEntry.getValue()); + } + } else { + engine.put("API", NpcAPI.Instance()); + HashMap engineEntries = new HashMap<>(NpcAPI.engineObjects); + for (Map.Entry objectEntry : engineEntries.entrySet()) { + engine.put(objectEntry.getKey(), objectEntry.getValue()); + } } 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); @@ -210,8 +274,14 @@ public class ScriptContainer { } } 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); @@ -251,6 +321,7 @@ public class ScriptContainer { return evaluated && !errored; } + @Override public boolean hasCode() { if (!scripts.isEmpty()) return true; @@ -259,6 +330,8 @@ public class ScriptContainer { 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"); @@ -267,4 +340,79 @@ public class ScriptContainer { this.evaluated = false; } } + + // ==================== IScriptUnit IMPLEMENTATION ==================== + + @Override + public String getScript() { + return this.script; + } + + @Override + public void setScript(String script) { + this.script = script; + this.evaluated = false; + } + + @Override + public List getExternalScripts() { + return this.scripts; + } + + @Override + public void setExternalScripts(List scripts) { + this.scripts = scripts; + this.evaluated = false; + } + + @Override + public TreeMap getConsole() { + return this.console; + } + + @Override + public void clearConsole() { + this.console.clear(); + } + + @Override + public String getLanguage() { + // 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.language, language)) { + this.language = language; + this.evaluated = false; + } + } + + @Override + public String generateHookStub(String hookName, Object hookData) { + // ECMAScript function template + return "function " + hookName + "(event) {\n \n}\n"; + } + + @Override + public void ensureCompiled() { + } + + @Override + public boolean hasErrored() { + return this.errored; + } + + @Override + public void setErrored(boolean errored) { + this.errored = errored; + } + + @Override + public boolean isJanino() { + return false; + } } + diff --git a/src/main/java/noppes/npcs/controllers/ScriptController.java b/src/main/java/noppes/npcs/controllers/ScriptController.java index d4246440b..546b3680d 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptController.java +++ b/src/main/java/noppes/npcs/controllers/ScriptController.java @@ -3,7 +3,9 @@ package noppes.npcs.controllers; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import jdk.nashorn.api.scripting.ClassFilter; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; +import kamkeel.npcs.network.packets.request.script.ScriptFilesPacket; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; @@ -21,6 +23,7 @@ import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.scripted.ScriptWorld; import noppes.npcs.util.JsonException; import noppes.npcs.util.NBTJsonUtil; +import somehussar.janino.EntityUnloadListener; import javax.script.ScriptContext; import javax.script.ScriptEngine; @@ -45,7 +48,7 @@ public class ScriptController { public static boolean HasStart = false; private final ScriptEngineManager manager; private ScriptEngineFactory nashornFactory; - public Map languages = new HashMap(); + public final Map languages = new HashMap(); public Map scripts = new HashMap(); public long lastLoaded = 0; public File dir; @@ -61,10 +64,16 @@ public class ScriptController { public GlobalNPCDataScript globalNpcScripts = new GlobalNPCDataScript((EntityNPCInterface) null); public long lastGlobalNpcUpdate = 0L; + /** + * Incremented whenever external scripts loaded. + */ + public int globalRevision; + + public ScriptController() { Instance = this; manager = new ScriptEngineManager(); - if (!ConfigScript.ScriptingEnabled) + if (!CustomNpcs.proxy.isScriptingEnabled()) return; LogWriter.info("Script Engines Available:"); @@ -97,6 +106,7 @@ public class ScriptController { } catch (Exception ignored) { } } + languages.put("Java", ".java"); } private File forgeScriptsFile() { @@ -124,7 +134,7 @@ public class ScriptController { File file = this.forgeScriptsFile(); try { NBTJsonUtil.SaveFile(file, this.forgeScripts.writeToNBT(new NBTTagCompound())); - this.forgeScripts.lastInited = -1L; + this.forgeScripts.resetLastInited(); } catch (IOException | JsonException var4) { var4.printStackTrace(); } @@ -160,7 +170,7 @@ public class ScriptController { File file = this.playerScriptsFile(); try { NBTJsonUtil.SaveFile(file, this.playerScripts.writeToNBT(new NBTTagCompound())); - this.playerScripts.lastInited = -1L; + this.playerScripts.resetLastInited(); } catch (IOException | JsonException var4) { var4.printStackTrace(); } @@ -202,7 +212,7 @@ public class ScriptController { File file = this.npcScriptsFile(); try { NBTJsonUtil.SaveFile(file, this.globalNpcScripts.writeToNBT(new NBTTagCompound())); - this.globalNpcScripts.lastInited = -1L; + this.globalNpcScripts.resetLastInited(); } catch (IOException | JsonException var4) { var4.printStackTrace(); } @@ -217,7 +227,7 @@ public class ScriptController { File file = this.playerScriptsFile(); try { NBTJsonUtil.SaveFile(file, this.playerScripts.writeToNBT(new NBTTagCompound())); - this.playerScripts.lastInited = -1L; + this.playerScripts.resetLastInited(); } catch (IOException | JsonException var4) { var4.printStackTrace(); } @@ -228,6 +238,14 @@ public class ScriptController { customNPCThread.execute(this::saveGlobalNpcScripts); } + public void syncClientScripts(EntityPlayerMP player) { + if (player != null) { + ScriptFilesPacket.sendToPlayer(player, "Java"); + } else { + ScriptFilesPacket.sendToAll("Java"); + } + } + public void loadCategories() { dir = new File(CustomNpcs.getWorldSaveDirectory(), "scripts"); if (!dir.exists()) @@ -245,6 +263,7 @@ public class ScriptController { loadDir(scriptDir, "", ext); } lastLoaded = System.currentTimeMillis(); + globalRevision++; } private void loadDir(File dir, String name, String ext) { @@ -348,7 +367,7 @@ public class ScriptController { return list; } - private List getScripts(String language) { + public List getScripts(String language) { List list = new ArrayList(); String ext = languages.get(language); if (ext == null) @@ -361,6 +380,11 @@ public class ScriptController { return list; } + @SubscribeEvent + public void addWorldAccess(WorldEvent.Load event) { + event.world.addWorldAccess(new EntityUnloadListener()); + } + @SubscribeEvent public void invoke(WorldEvent.Save event) { if (!shouldSave || event.world.isRemote || event.world != MinecraftServer.getServer().worldServers[0]) diff --git a/src/main/java/noppes/npcs/controllers/ScriptHookController.java b/src/main/java/noppes/npcs/controllers/ScriptHookController.java new file mode 100644 index 000000000..5547fb203 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/ScriptHookController.java @@ -0,0 +1,539 @@ +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; +import noppes.npcs.api.event.ILinkedItemEvent; +import noppes.npcs.api.event.INpcEvent; +import noppes.npcs.api.event.IPartyEvent; +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 noppes.npcs.api.handler.IHookDefinition; +import noppes.npcs.api.handler.IScriptHookHandler; +import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.controllers.data.RecipeScript; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static noppes.npcs.constants.EnumScriptType.*; +import static noppes.npcs.constants.ScriptContext.BLOCK; +import static noppes.npcs.constants.ScriptContext.EFFECT; +import static noppes.npcs.constants.ScriptContext.FORGE; +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; + +/** + * Controller for managing script hooks. + * Allows addon mods to register custom hooks that appear in script editor GUIs. + * + *

Addon Hook Registration

+ *
{@code
+ * ScriptHookController.Instance.registerHook("player",
+ *     HookDefinition.of("onDBCTransform", IDBCEvent.TransformEvent.class));
+ * }
+ */ +public class ScriptHookController implements IScriptHookHandler { + + public static ScriptHookController Instance; + + private final Map> hookDefinitions = new HashMap<>(); + private int hookRevision = 0; + + public ScriptHookController() { + Instance = this; + initializeBuiltInHooks(); + } + + // ==================== INITIALIZATION ==================== + + private void initializeBuiltInHooks() { + for (ScriptContext context : ScriptContext.values()) { + if (!context.hookContext.isEmpty()) { + hookDefinitions.put(context.hookContext, new LinkedHashMap<>()); + } + } + + initializeNpcHooks(); + initializePlayerHooks(); + initializeBlockHooks(); + initializeItemHooks(); + initializeLinkedItemHooks(); + initializeRecipeHooks(); + initializeEffectHooks(); + initializeAbilityHooks(); + initializeForgeHooks(); + } + + private void initializeNpcHooks() { + // Core lifecycle + hook(NPC, INIT, INpcEvent.InitEvent.class); + hook(NPC, TICK, INpcEvent.UpdateEvent.class); + hook(NPC, TIMER, INpcEvent.TimerEvent.class); + + // Interaction + hook(NPC, INTERACT, INpcEvent.InteractEvent.class); + hook(NPC, DIALOG, INpcEvent.DialogEvent.class); + hook(NPC, DIALOG_CLOSE, INpcEvent.DialogClosedEvent.class); + hook(NPC, COLLIDE, INpcEvent.CollideEvent.class); + + // Combat + hook(NPC, DAMAGED, INpcEvent.DamagedEvent.class); + hook(NPC, KILLED, INpcEvent.DiedEvent.class); + hook(NPC, KILLS, INpcEvent.KilledEntityEvent.class); + hook(NPC, ATTACK_MELEE, INpcEvent.MeleeAttackEvent.class); + hook(NPC, ATTACK_SWING, INpcEvent.SwingEvent.class); + hook(NPC, RANGED_LAUNCHED, INpcEvent.RangedLaunchedEvent.class); + hook(NPC, TARGET, INpcEvent.TargetEvent.class); + hook(NPC, TARGET_LOST, INpcEvent.TargetLostEvent.class); + + // Projectile + 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_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() { + // Core lifecycle + hook(PLAYER, INIT, IPlayerEvent.InitEvent.class); + hook(PLAYER, TICK, IPlayerEvent.UpdateEvent.class); + hook(PLAYER, TIMER, IPlayerEvent.TimerEvent.class); + + // Combat + hook(PLAYER, ATTACK, IPlayerEvent.AttackEvent.class); + hook(PLAYER, ATTACKED, IPlayerEvent.AttackedEvent.class); + hook(PLAYER, DAMAGED, IPlayerEvent.DamagedEvent.class); + hook(PLAYER, DAMAGED_ENTITY, IPlayerEvent.DamagedEntityEvent.class); + hook(PLAYER, KILLS, IPlayerEvent.KilledEntityEvent.class); + hook(PLAYER, KILLED, IPlayerEvent.DiedEvent.class); + + // Interaction + hook(PLAYER, INTERACT, IPlayerEvent.InteractEvent.class); + hook(PLAYER, RIGHT_CLICK, IPlayerEvent.RightClickEvent.class); + hook(PLAYER, BREAK_BLOCK, IPlayerEvent.BreakEvent.class); + hook(PLAYER, CHAT, IPlayerEvent.ChatEvent.class); + + // Connection + hook(PLAYER, LOGIN, IPlayerEvent.LoginEvent.class); + hook(PLAYER, LOGOUT, IPlayerEvent.LogoutEvent.class); + hook(PLAYER, RESPAWN, IPlayerEvent.RespawnEvent.class); + + // Input + hook(PLAYER, KEY_PRESSED, IPlayerEvent.KeyPressedEvent.class); + hook(PLAYER, MOUSE_CLICKED, IPlayerEvent.MouseClickedEvent.class); + + // Items + hook(PLAYER, PICKUP, IPlayerEvent.PickUpEvent.class); + hook(PLAYER, TOSS, IPlayerEvent.TossEvent.class); + hook(PLAYER, DROP, IPlayerEvent.DropEvent.class); + hook(PLAYER, PICKUP_XP, IPlayerEvent.PickupXPEvent.class); + hook(PLAYER, START_USING_ITEM, IPlayerEvent.StartUsingItem.class); + hook(PLAYER, USING_ITEM, IPlayerEvent.UsingItem.class); + hook(PLAYER, STOP_USING_ITEM, IPlayerEvent.StopUsingItem.class); + hook(PLAYER, FINISH_USING_ITEM, IPlayerEvent.FinishUsingItem.class); + hook(PLAYER, CONTAINER_OPEN, IPlayerEvent.ContainerOpen.class); + + // Movement + hook(PLAYER, JUMP, IPlayerEvent.JumpEvent.class); + hook(PLAYER, FALL, IPlayerEvent.FallEvent.class); + hook(PLAYER, CHANGED_DIM, IPlayerEvent.ChangedDimension.class); + + // World + hook(PLAYER, RANGED_CHARGE, IPlayerEvent.RangedChargeEvent.class); + hook(PLAYER, RANGED_LAUNCHED, IPlayerEvent.RangedLaunchedEvent.class); + hook(PLAYER, USE_HOE, IPlayerEvent.UseHoeEvent.class); + hook(PLAYER, BONEMEAL, IPlayerEvent.BonemealEvent.class); + hook(PLAYER, FILL_BUCKET, IPlayerEvent.FillBucketEvent.class); + hook(PLAYER, WAKE_UP, IPlayerEvent.WakeUpEvent.class); + hook(PLAYER, SLEEP, IPlayerEvent.SleepEvent.class); + hook(PLAYER, PLAYSOUND, IPlayerEvent.SoundEvent.class); + hook(PLAYER, LIGHTNING, IPlayerEvent.LightningEvent.class); + hook(PLAYER, SCRIPT_COMMAND, ICustomNPCsEvent.ScriptedCommandEvent.class); + + // Quest + hook(PLAYER, QUEST_START, IQuestEvent.QuestStartEvent.class); + hook(PLAYER, QUEST_COMPLETED, IQuestEvent.QuestCompletedEvent.class); + hook(PLAYER, QUEST_TURNIN, IQuestEvent.QuestTurnedInEvent.class); + + // Dialog + hook(PLAYER, DIALOG_OPEN, IDialogEvent.DialogOpen.class); + hook(PLAYER, DIALOG_OPTION, IDialogEvent.DialogOption.class); + hook(PLAYER, DIALOG_CLOSE, IDialogEvent.DialogClosed.class); + + // Faction + hook(PLAYER, FACTION_POINTS, IFactionEvent.FactionPoints.class); + + // Custom GUI + hook(PLAYER, CUSTOM_GUI_CLOSED, ICustomGuiEvent.CloseEvent.class); + hook(PLAYER, CUSTOM_GUI_BUTTON, ICustomGuiEvent.ButtonEvent.class); + hook(PLAYER, CUSTOM_GUI_SLOT, ICustomGuiEvent.SlotEvent.class); + hook(PLAYER, CUSTOM_GUI_SLOT_CLICKED, ICustomGuiEvent.SlotClickEvent.class); + hook(PLAYER, CUSTOM_GUI_SCROLL, ICustomGuiEvent.ScrollEvent.class); + hook(PLAYER, CUSTOM_GUI_TEXTFIELD, ICustomGuiEvent.UnfocusedEvent.class); + + // Party + hook(PLAYER, PARTY_QUEST_COMPLETED, IPartyEvent.PartyQuestCompletedEvent.class); + hook(PLAYER, PARTY_QUEST_SET, IPartyEvent.PartyQuestSetEvent.class); + hook(PLAYER, PARTY_QUEST_TURNED_IN, IPartyEvent.PartyQuestTurnedInEvent.class); + hook(PLAYER, PARTY_INVITE, IPartyEvent.PartyInviteEvent.class); + hook(PLAYER, PARTY_KICK, IPartyEvent.PartyKickEvent.class); + hook(PLAYER, PARTY_LEAVE, IPartyEvent.PartyLeaveEvent.class); + hook(PLAYER, PARTY_DISBAND, IPartyEvent.PartyDisbandEvent.class); + + // Animation + hook(PLAYER, ANIMATION_START, IAnimationEvent.Started.class); + hook(PLAYER, ANIMATION_END, IAnimationEvent.Ended.class); + 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_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); + hook(PLAYER, PROFILE_CREATE, IPlayerEvent.ProfileEvent.Create.class); + + // Effect (player context) + hook(PLAYER, ON_EFFECT_ADD, IPlayerEvent.EffectEvent.Added.class); + hook(PLAYER, ON_EFFECT_TICK, IPlayerEvent.EffectEvent.Ticked.class); + hook(PLAYER, ON_EFFECT_REMOVE, IPlayerEvent.EffectEvent.Removed.class); + } + + private void initializeBlockHooks() { + hook(BLOCK, INIT, IBlockEvent.InitEvent.class); + hook(BLOCK, TICK, IBlockEvent.UpdateEvent.class); + hook(BLOCK, INTERACT, IBlockEvent.InteractEvent.class); + hook(BLOCK, FALLEN_UPON, IBlockEvent.EntityFallenUponEvent.class); + hook(BLOCK, REDSTONE, IBlockEvent.RedstoneEvent.class); + hook(BLOCK, BROKEN, IBlockEvent.BreakEvent.class); + hook(BLOCK, EXPLODED, IBlockEvent.ExplodedEvent.class); + hook(BLOCK, RAIN_FILLED, IBlockEvent.RainFillEvent.class); + hook(BLOCK, NEIGHBOR_CHANGED, IBlockEvent.NeighborChangedEvent.class); + hook(BLOCK, CLICKED, IBlockEvent.ClickedEvent.class); + hook(BLOCK, HARVESTED, IBlockEvent.HarvestedEvent.class); + hook(BLOCK, COLLIDE, IBlockEvent.CollidedEvent.class); + hook(BLOCK, TIMER, IBlockEvent.TimerEvent.class); + } + + private void initializeItemHooks() { + hook(ITEM, INIT, IItemEvent.InitEvent.class); + hook(ITEM, TICK, IItemEvent.UpdateEvent.class); + hook(ITEM, TOSSED, IItemEvent.TossedEvent.class); + hook(ITEM, PICKEDUP, IItemEvent.PickedUpEvent.class); + hook(ITEM, SPAWN, IItemEvent.SpawnEvent.class); + hook(ITEM, INTERACT, IItemEvent.InteractEvent.class); + hook(ITEM, RIGHT_CLICK, IItemEvent.RightClickEvent.class); + hook(ITEM, ATTACK, IItemEvent.AttackEvent.class); + hook(ITEM, START_USING_ITEM, IItemEvent.StartUsingItem.class); + hook(ITEM, USING_ITEM, IItemEvent.UsingItem.class); + hook(ITEM, STOP_USING_ITEM, IItemEvent.StopUsingItem.class); + hook(ITEM, FINISH_USING_ITEM, IItemEvent.FinishUsingItem.class); + } + + private void initializeLinkedItemHooks() { + // Linked item specific + hook(LINKED_ITEM, LINKED_ITEM_BUILD, ILinkedItemEvent.BuildEvent.class); + hook(LINKED_ITEM, LINKED_ITEM_VERSION, ILinkedItemEvent.VersionChangeEvent.class); + + // Standard item hooks + hook(LINKED_ITEM, INIT, IItemEvent.InitEvent.class); + hook(LINKED_ITEM, TICK, IItemEvent.UpdateEvent.class); + hook(LINKED_ITEM, TOSSED, IItemEvent.TossedEvent.class); + hook(LINKED_ITEM, PICKEDUP, IItemEvent.PickedUpEvent.class); + hook(LINKED_ITEM, SPAWN, IItemEvent.SpawnEvent.class); + hook(LINKED_ITEM, INTERACT, IItemEvent.InteractEvent.class); + hook(LINKED_ITEM, RIGHT_CLICK, IItemEvent.RightClickEvent.class); + hook(LINKED_ITEM, ATTACK, IItemEvent.AttackEvent.class); + hook(LINKED_ITEM, START_USING_ITEM, IItemEvent.StartUsingItem.class); + hook(LINKED_ITEM, USING_ITEM, IItemEvent.UsingItem.class); + hook(LINKED_ITEM, STOP_USING_ITEM, IItemEvent.StopUsingItem.class); + hook(LINKED_ITEM, FINISH_USING_ITEM, IItemEvent.FinishUsingItem.class); + } + + private void initializeRecipeHooks() { + hook(RECIPE, RecipeScript.ScriptType.PRE.function, IRecipeEvent.Pre.class); + hook(RECIPE, RecipeScript.ScriptType.POST.function, IRecipeEvent.Post.class); + } + + private void initializeEffectHooks() { + // Effect context uses IPlayerEvent.EffectEvent (same as player context) + hook(EFFECT, ON_EFFECT_ADD, IPlayerEvent.EffectEvent.Added.class); + hook(EFFECT, ON_EFFECT_TICK, IPlayerEvent.EffectEvent.Ticked.class); + 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_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); + hook(FORGE, FORGE_ENTITY, IForgeEvent.EntityEvent.class); + hook(FORGE, CNPC_NATURAL_SPAWN, ICustomNPCsEvent.CNPCNaturalSpawnEvent.class); + } + + // ==================== INTERNAL REGISTRATION ==================== + + private void hook(ScriptContext context, EnumScriptType type, Class eventClass) { + hookDefinitions.get(context.hookContext) + .put(type.function, HookDefinition.of(type.function, eventClass)); + } + + private void hook(ScriptContext context, EnumScriptType type) { + hookDefinitions.get(context.hookContext) + .put(type.function, HookDefinition.simple(type.function)); + } + + private void hook(ScriptContext context, String hookName) { + hookDefinitions.get(context.hookContext) + .put(hookName, HookDefinition.simple(hookName)); + } + + private void hook(ScriptContext context, String hookName, Class eventClass) { + hookDefinitions.get(context.hookContext) + .put(hookName, HookDefinition.of(hookName, eventClass)); + } + + // ==================== PUBLIC API ==================== + + /** + * Register a hook with event class (auto-derives imports). + * For addon mods to register custom hooks. + * + * @param context Hook context (e.g., "npc", "player") + * @param hookName Function name in scripts + * @param eventClass The event class (imports auto-derived from enclosing class) + */ + public void registerHook(String context, String hookName, Class eventClass) { + if (context == null || hookName == null) + return; + + Map contextDefs = hookDefinitions.get(context); + if (contextDefs == null) { + contextDefs = new LinkedHashMap<>(); + hookDefinitions.put(context, contextDefs); + } + + contextDefs.put(hookName, HookDefinition.of(hookName, eventClass)); + hookRevision++; + } + + public void registerHook(ScriptContext context, String hookName, Class eventClass) { + registerHook(context.hookContext, hookName, eventClass); + } + + /** + * Register a simple hook with no event class metadata. + */ + public void registerHook(String context, String hookName) { + if (context == null || hookName == null) + return; + + Map contextDefs = hookDefinitions.get(context); + if (contextDefs == null) { + contextDefs = new LinkedHashMap<>(); + hookDefinitions.put(context, contextDefs); + } + + if (!contextDefs.containsKey(hookName)) { + contextDefs.put(hookName, HookDefinition.simple(hookName)); + hookRevision++; + } + } + + public void registerHook(ScriptContext context, String hookName) { + registerHook(context.hookContext, hookName); + } + + /** + * Register a hook definition for addon mods. + */ + public void registerHook(String context, HookDefinition definition) { + if (context == null || definition == null) + return; + + Map contextDefs = hookDefinitions.get(context); + if (contextDefs == null) { + contextDefs = new LinkedHashMap<>(); + hookDefinitions.put(context, contextDefs); + } + + contextDefs.put(definition.hookName(), definition); + hookRevision++; + } + + public void registerHook(ScriptContext context, HookDefinition definition) { + registerHook(context.hookContext, definition); + } + + @Override + public void registerHookDefinition(String context, IHookDefinition definition) { + if (definition instanceof HookDefinition) { + registerHook(context, (HookDefinition) definition); + } else if (definition != null) { + registerHook(context, HookDefinition.builder(definition.hookName()) + .eventClass(definition.eventClassName()) + .paramNames(definition.paramNames()) + .requiredImports(definition.requiredImports()) + .cancelable(definition.isCancelable()) + .build()); + } + } + + @Override + public IHookDefinition getHookDefinition(String context, String hookName) { + if (context == null || hookName == null) + return null; + + Map contextDefs = hookDefinitions.get(context); + return contextDefs != null ? contextDefs.get(hookName) : null; + } + + @Override + public List getAllHookDefinitions(String context) { + if (context == null) + return Collections.emptyList(); + + Map contextDefs = hookDefinitions.get(context); + if (contextDefs == null || contextDefs.isEmpty()) + return Collections.emptyList(); + + return new ArrayList<>(contextDefs.values()); + } + + @Override + public List getAllHooks(String context) { + if (context == null) + return Collections.emptyList(); + + Map contextDefs = hookDefinitions.get(context); + if (contextDefs == null || contextDefs.isEmpty()) + return Collections.emptyList(); + + return new ArrayList<>(contextDefs.keySet()); + } + + @Override + public boolean hasHook(String context, String hookName) { + if (context == null || hookName == null) + return false; + + Map contextDefs = hookDefinitions.get(context); + return contextDefs != null && contextDefs.containsKey(hookName); + } + + @Override + public int getHookRevision() { + return hookRevision; + } + + @Override + public String[] getContexts() { + return hookDefinitions.keySet().toArray(new String[0]); + } +} diff --git a/src/main/java/noppes/npcs/controllers/ServerCloneController.java b/src/main/java/noppes/npcs/controllers/ServerCloneController.java index ea61a0112..32bd0e15c 100644 --- a/src/main/java/noppes/npcs/controllers/ServerCloneController.java +++ b/src/main/java/noppes/npcs/controllers/ServerCloneController.java @@ -15,6 +15,7 @@ import noppes.npcs.api.IPos; import noppes.npcs.api.IWorld; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.handler.ICloneHandler; +import noppes.npcs.controllers.data.CloneFolder; import noppes.npcs.controllers.data.TagMap; import noppes.npcs.scripted.CustomNPCsException; import noppes.npcs.scripted.NpcAPI; @@ -27,6 +28,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -34,8 +36,11 @@ import java.util.UUID; public class ServerCloneController implements ICloneHandler { public static ServerCloneController Instance; + protected Map folders = new LinkedHashMap<>(); + public ServerCloneController() { loadClones(); + loadFolders(); } private void loadClones() { @@ -103,6 +108,8 @@ public class ServerCloneController implements ICloneHandler { return clones; } + // ==================== Tab-Based Clone Operations ==================== + public NBTTagCompound getCloneData(ICommandSender player, String name, int tab) { File file = new File(new File(getDir(), tab + ""), name + ".json"); if (!file.exists()) { @@ -194,6 +201,250 @@ public class ServerCloneController implements ICloneHandler { return name; } + // ==================== Folder Registry ==================== + + public void loadFolders() { + folders.clear(); + File dir = getDir(); + File[] files = dir.listFiles(); + if (files != null) { + List folderDirs = new ArrayList<>(); + for (File f : files) { + if (!f.isDirectory()) continue; + String name = f.getName(); + if (name.startsWith("___")) continue; + try { + Integer.parseInt(name); + continue; + } catch (NumberFormatException ignored) { + } + folderDirs.add(f); + } + folderDirs.sort(Comparator.comparing(File::getName)); + for (File f : folderDirs) { + CloneFolder folder = new CloneFolder(f.getName()); + folder.createdDate = f.lastModified(); + folders.put(f.getName(), folder); + } + } + } + + public List getFolderList() { + return new ArrayList<>(folders.values()); + } + + public List getFolderNames() { + return new ArrayList<>(folders.keySet()); + } + + public boolean hasFolder(String name) { + return folders.containsKey(name); + } + + // ==================== Folder CRUD ==================== + + public CloneFolder createFolder(String name) { + if (!CloneFolder.isValidName(name) || folders.containsKey(name)) { + return null; + } + CloneFolder folder = new CloneFolder(name); + File dir = getFolderDir(name); + if (!dir.exists()) { + dir.mkdir(); + } + folders.put(name, folder); + return folder; + } + + public boolean renameFolder(String oldName, String newName) { + if (!folders.containsKey(oldName) || !CloneFolder.isValidName(newName) || folders.containsKey(newName)) { + return false; + } + CloneFolder folder = folders.get(oldName); + File oldDir = getFolderDir(oldName); + File newDir = new File(getDir(), newName); + if (!oldDir.renameTo(newDir)) { + return false; + } + folders.remove(oldName); + folder.name = newName; + folders.put(newName, folder); + return true; + } + + public boolean deleteFolder(String name) { + if (!folders.containsKey(name)) { + return false; + } + List clones = getClones(name); + if (!clones.isEmpty()) { + return false; + } + File dir = getFolderDir(name); + if (dir.exists()) { + File tagMapFile = new File(dir, "___tagmap.dat"); + if (tagMapFile.exists()) tagMapFile.delete(); + File tagMapOld = new File(dir, "___tagmap.dat_old"); + if (tagMapOld.exists()) tagMapOld.delete(); + File tagMapNew = new File(dir, "___tagmap.dat_new"); + if (tagMapNew.exists()) tagMapNew.delete(); + dir.delete(); + } + folders.remove(name); + return true; + } + + // ==================== Folder-Based Clone Operations ==================== + + public File getFolderDir(String folderName) { + return new File(getDir(), folderName); + } + + public List getClones(String folderName) { + List list = new ArrayList<>(); + File dir = getFolderDir(folderName); + if (!dir.exists() || !dir.isDirectory()) + return list; + for (String file : dir.list()) { + if (file.endsWith(".json")) + list.add(file.substring(0, file.length() - 5)); + } + return list; + } + + public List getClonesDate(String folderName) { + List list = new ArrayList<>(); + File dir = getFolderDir(folderName); + if (!dir.exists() || !dir.isDirectory()) + return list; + File[] files = dir.listFiles(); + if (files == null) return list; + Arrays.sort(files, new Comparator() { + public int compare(File f1, File f2) { + return Long.compare(f1.lastModified(), f2.lastModified()); + } + }); + for (File file : files) { + String fileName = file.getName(); + if (fileName.endsWith(".json")) + list.add(fileName.substring(0, fileName.length() - 5)); + } + return list; + } + + public NBTTagCompound getCloneData(ICommandSender player, String name, String folderName) { + File file = new File(getFolderDir(folderName), name + ".json"); + if (!file.exists()) { + if (player != null) + player.addChatMessage(new ChatComponentText("Could not find clone file")); + return null; + } + try { + return NBTJsonUtil.LoadFile(file); + } catch (Exception e) { + LogWriter.error("Error loading: " + file.getAbsolutePath(), e); + if (player != null) + player.addChatMessage(new ChatComponentText(e.getMessage())); + } + return null; + } + + public void saveClone(String folderName, String name, NBTTagCompound compound) { + try { + File dir = getFolderDir(folderName); + if (!dir.exists()) dir.mkdir(); + String filename = name + ".json"; + File file = new File(dir, filename + "_new"); + File file2 = new File(dir, filename); + NBTJsonUtil.SaveFile(file, compound); + addToTagMap(compound, name, folderName); + if (file2.exists()) { + file2.delete(); + } + file.renameTo(file2); + } catch (Exception e) { + LogWriter.except(e); + } + } + + public boolean removeClone(String name, String folderName) { + File file = new File(getFolderDir(folderName), name + ".json"); + if (!file.exists()) + return false; + file.delete(); + removeFromTagMap(name, folderName); + return true; + } + + public String addClone(NBTTagCompound nbttagcompound, String name, String folderName) { + cleanTags(nbttagcompound); + saveClone(folderName, name, nbttagcompound); + return name; + } + + public String addClone(NBTTagCompound nbttagcompound, String name, String folderName, NBTTagCompound tempTags) { + cleanTagList(nbttagcompound, tempTags); + cleanTags(nbttagcompound); + saveClone(folderName, name, nbttagcompound); + return name; + } + + // ==================== Move Operations ==================== + + public boolean moveClone(String cloneName, int fromTab, String toFolder) { + NBTTagCompound data = getCloneData(null, cloneName, fromTab); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromTab(cloneName, fromTab); + + saveClone(toFolder, cloneName, data); + setTagUUIDsForFolder(cloneName, toFolder, tagUUIDs); + + removeClone(cloneName, fromTab); + return true; + } + + public boolean moveClone(String cloneName, String fromFolder, int toTab) { + NBTTagCompound data = getCloneData(null, cloneName, fromFolder); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromFolder(cloneName, fromFolder); + + saveClone(toTab, cloneName, data); + setTagUUIDsForTab(cloneName, toTab, tagUUIDs); + + removeClone(cloneName, fromFolder); + return true; + } + + public boolean moveClone(String cloneName, String fromFolder, String toFolder) { + NBTTagCompound data = getCloneData(null, cloneName, fromFolder); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromFolder(cloneName, fromFolder); + + saveClone(toFolder, cloneName, data); + setTagUUIDsForFolder(cloneName, toFolder, tagUUIDs); + + removeClone(cloneName, fromFolder); + return true; + } + + public boolean moveClone(String cloneName, int fromTab, int toTab) { + NBTTagCompound data = getCloneData(null, cloneName, fromTab); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromTab(cloneName, fromTab); + + saveClone(toTab, cloneName, data); + setTagUUIDsForTab(cloneName, toTab, tagUUIDs); + + removeClone(cloneName, fromTab); + return true; + } + + // ==================== Tag Utilities ==================== + public NBTTagCompound cleanTagList(NBTTagCompound nbttagcompound, NBTTagCompound tempTags) { HashSet tagUUIDs = new HashSet(); if (nbttagcompound.hasKey("TagUUIDs")) { @@ -243,6 +494,25 @@ public class ServerCloneController implements ICloneHandler { return true; } + public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) { + HashSet tagUUIDs = new HashSet<>(); + if (nbttagcompound.hasKey("TagUUIDs")) { + NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8); + for (int i = 0; i < nbtTagList.tagCount(); i++) { + tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i))); + } + } + + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + if (!tagUUIDs.isEmpty()) { + tagMap.putClone(name, tagUUIDs); + } else { + tagMap.removeClone(name); + } + ServerTagMapController.Instance.saveTagMap(tagMap); + return true; + } + public boolean removeFromTagMap(String name, int tab) { TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); if (tagMap.removeClone(name)) { @@ -252,6 +522,41 @@ public class ServerCloneController implements ICloneHandler { return false; } + public boolean removeFromTagMap(String name, String folderName) { + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + if (tagMap.removeClone(name)) { + ServerTagMapController.Instance.saveTagMap(tagMap); + return true; + } + return false; + } + + protected HashSet getTagUUIDsFromTab(String cloneName, int tab) { + TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + protected HashSet getTagUUIDsFromFolder(String cloneName, String folderName) { + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + protected void setTagUUIDsForTab(String cloneName, int tab, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); + tagMap.putClone(cloneName, tagUUIDs); + ServerTagMapController.Instance.saveTagMap(tagMap); + } + + protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + tagMap.putClone(cloneName, tagUUIDs); + ServerTagMapController.Instance.saveTagMap(tagMap); + } + public void cleanTags(NBTTagCompound nbttagcompound) { if (nbttagcompound.hasKey("ItemGiverId")) nbttagcompound.setInteger("ItemGiverId", 0); @@ -288,6 +593,8 @@ public class ServerCloneController implements ICloneHandler { } } + // ==================== API Methods (ICloneHandler) ==================== + public IEntity spawn(double x, double y, double z, int tab, String name, IWorld world, boolean ignoreProtection) { NBTTagCompound compound = this.getCloneData((ICommandSender) null, name, tab); if (compound == null) { @@ -327,7 +634,7 @@ public class ServerCloneController implements ICloneHandler { for (File file : dir.listFiles()) { if (file.getName().endsWith(".json")) { NBTTagCompound compound = NBTJsonUtil.LoadFile(file); - Instance.cleanTags(compound); + cleanTags(compound); Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); arrayList.add(entity == null ? null : NpcAPI.Instance().getIEntity(entity)); } @@ -343,7 +650,7 @@ public class ServerCloneController implements ICloneHandler { if (compound == null) { throw new CustomNPCsException("Unknown clone tab:" + tab + " name:" + name, new Object[0]); } else { - Instance.cleanTags(compound); + cleanTags(compound); Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); return entity == null ? null : NpcAPI.Instance().getIEntity(entity); } @@ -354,7 +661,6 @@ public class ServerCloneController implements ICloneHandler { return compound != null; } - public void set(int tab, String name, IEntity entity) { NBTTagCompound compound = new NBTTagCompound(); if (!entity.getMCEntity().writeMountToNBT(compound)) @@ -367,4 +673,85 @@ public class ServerCloneController implements ICloneHandler { public void remove(int tab, String name) { this.removeClone(name, tab); } + + // --- Folder API Methods --- + + public String[] getFolders() { + return getFolderNames().toArray(new String[0]); + } + + public IEntity spawn(double x, double y, double z, String folderName, String name, IWorld world, boolean ignoreProtection) { + NBTTagCompound compound = getCloneData(null, name, folderName); + if (compound == null) { + throw new CustomNPCsException("Unknown clone folder:" + folderName + " name:" + name, new Object[0]); + } + Entity entity; + if (!ignoreProtection) { + entity = NoppesUtilServer.spawnCloneWithProtection(compound, (int) x, (int) y, (int) z, world.getMCWorld()); + } else { + entity = NoppesUtilServer.spawnClone(compound, (int) x, (int) y, (int) z, world.getMCWorld()); + } + return entity == null ? null : NpcAPI.Instance().getIEntity(entity); + } + + public IEntity spawn(IPos pos, String folderName, String name, IWorld world, boolean ignoreProtection) { + return this.spawn(pos.getX(), pos.getY(), pos.getZ(), folderName, name, world, ignoreProtection); + } + + public IEntity spawn(double x, double y, double z, String folderName, String name, IWorld world) { + return spawn(x, y, z, folderName, name, world, true); + } + + public IEntity spawn(IPos pos, String folderName, String name, IWorld world) { + return this.spawn(pos.getX(), pos.getY(), pos.getZ(), folderName, name, world); + } + + public IEntity[] getFolder(String folderName, IWorld world) { + File dir = getFolderDir(folderName); + if (!dir.exists() || !dir.isDirectory() || dir.listFiles() == null) { + return new IEntity[]{}; + } + + ArrayList arrayList = new ArrayList<>(); + try { + for (File file : dir.listFiles()) { + if (file.getName().endsWith(".json")) { + NBTTagCompound compound = NBTJsonUtil.LoadFile(file); + cleanTags(compound); + Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); + arrayList.add(entity == null ? null : NpcAPI.Instance().getIEntity(entity)); + } + } + } catch (Exception ignored) { + } + return arrayList.toArray(new IEntity[]{}); + } + + public IEntity get(String folderName, String name, IWorld world) { + NBTTagCompound compound = getCloneData(null, name, folderName); + if (compound == null) { + throw new CustomNPCsException("Unknown clone folder:" + folderName + " name:" + name, new Object[0]); + } + cleanTags(compound); + Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); + return entity == null ? null : NpcAPI.Instance().getIEntity(entity); + } + + public boolean has(String folderName, String name) { + NBTTagCompound compound = getCloneData(null, name, folderName); + return compound != null; + } + + public void set(String folderName, String name, IEntity entity) { + NBTTagCompound compound = new NBTTagCompound(); + if (!entity.getMCEntity().writeMountToNBT(compound)) + throw new CustomNPCsException("Cannot save dead entities", new Object[0]); + + this.cleanTags(compound); + this.saveClone(folderName, name, compound); + } + + public void remove(String folderName, String name) { + this.removeClone(name, folderName); + } } diff --git a/src/main/java/noppes/npcs/controllers/ServerTagMapController.java b/src/main/java/noppes/npcs/controllers/ServerTagMapController.java index 0221481e3..42ca6afeb 100644 --- a/src/main/java/noppes/npcs/controllers/ServerTagMapController.java +++ b/src/main/java/noppes/npcs/controllers/ServerTagMapController.java @@ -35,6 +35,13 @@ public class ServerTagMapController { return dir; } + public File getCloneFolderDir(String folderName) { + File dir = new File(getDir(), folderName); + if (!dir.exists()) + dir.mkdir(); + return dir; + } + public TagMap getTagMap(int tab) { this.tagMap = new TagMap(tab); try { @@ -65,9 +72,33 @@ public class ServerTagMapController { this.tagMap.readNBT(nbtCompound); } + public TagMap getTagMap(String folderName) { + this.tagMap = new TagMap(folderName); + try { + File file = new File(getCloneFolderDir(folderName), "___tagmap.dat"); + if (file.exists()) { + loadTagMapFile(file); + } + } catch (Exception e) { + try { + File file = new File(getCloneFolderDir(folderName), "___tagmap.dat_old"); + if (file.exists()) { + loadTagMapFile(file); + } + } catch (Exception ignored) { + } + } + return this.tagMap; + } + public void saveTagMap(TagMap tagMap) { try { - File saveDir = getCloneTabDir(tagMap.cloneTab); + File saveDir; + if (tagMap.cloneFolder != null) { + saveDir = getCloneFolderDir(tagMap.cloneFolder); + } else { + saveDir = getCloneTabDir(tagMap.cloneTab); + } File file = new File(saveDir, "___tagmap.dat_new"); File file1 = new File(saveDir, "___tagmap.dat_old"); File file2 = new File(saveDir, "___tagmap.dat"); 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/Animation.java b/src/main/java/noppes/npcs/controllers/data/Animation.java index b60f9ad4d..8cf9b3827 100644 --- a/src/main/java/noppes/npcs/controllers/data/Animation.java +++ b/src/main/java/noppes/npcs/controllers/data/Animation.java @@ -12,7 +12,10 @@ import noppes.npcs.constants.EnumAnimationPart; import noppes.npcs.controllers.AnimationController; import java.util.ArrayList; - +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; public class Animation implements IAnimation { public AnimationData parent; //Client-sided only @@ -34,6 +37,12 @@ public class Animation implements IAnimation { //Client-sided public boolean paused; + protected final Map dataStore = new HashMap<>(); + + public Consumer onAnimationStart; + public BiConsumer onAnimationFrame; + public Consumer onAnimationEnd; + public Animation() { } @@ -175,6 +184,28 @@ public class Animation implements IAnimation { return time; } + @Override + public boolean hasData(String key) { + return dataStore.containsKey(key); + } + + @Override + public Object getData(String key) { + return dataStore.get(key); + } + + @Override + public IAnimation setData(String key, Object v) { + dataStore.put(key, v); + return this; + } + + @Override + public IAnimation removeData(String key) { + dataStore.remove(key); + return this; + } + public void readFromNBT(NBTTagCompound compound) { if (compound.hasKey("ID")) { id = compound.getInteger("ID"); @@ -254,8 +285,10 @@ public class Animation implements IAnimation { if (this.currentFrame() != null) { EventHooks.onAnimationFrameEntered(this, this.currentFrame()); + fireFrameTask(this.currentFrame); } else { EventHooks.onAnimationEnded(this); + fireEndTask(); } if (nextFrame != null) { @@ -294,4 +327,61 @@ public class Animation implements IAnimation { } } } + + @Override + public IAnimation onStart(Consumer task) { + this.onAnimationStart = task; + return this; + } + + @Override + public IAnimation onFrame(BiConsumer task) { + this.onAnimationFrame = task; + return this; + } + + @Override + public IAnimation onEnd(Consumer task) { + this.onAnimationEnd = task; + return this; + } + + protected void fireStartTask() { + if (this.onAnimationStart != null) { + this.onAnimationStart.accept(this); + } + } + + protected void fireFrameTask(int frame) { + if (this.onAnimationFrame != null) { + this.onAnimationFrame.accept(frame, this); + } + } + + protected void fireEndTask() { + if (this.onAnimationEnd != null) { + this.onAnimationEnd.accept(this); + } + } + + /** + * Only called on setAnimation, to transfer tasks from + * this global instance stored in AnimationController + * to the new local instance on entity's AnimationData, + * and clear them from the global instance. + */ + public void moveFromGlobalToLocal(Animation animation) { + this.onAnimationStart = animation.onAnimationStart; + this.onAnimationFrame = animation.onAnimationFrame; + this.onAnimationEnd = animation.onAnimationEnd; + + animation.onAnimationEnd = null; + animation.onAnimationFrame = null; + animation.onAnimationStart = null; + + this.dataStore.putAll(animation.dataStore); + animation.dataStore.clear(); + } + + } diff --git a/src/main/java/noppes/npcs/controllers/data/AnimationData.java b/src/main/java/noppes/npcs/controllers/data/AnimationData.java index c537d94e1..f5e6d80b4 100644 --- a/src/main/java/noppes/npcs/controllers/data/AnimationData.java +++ b/src/main/java/noppes/npcs/controllers/data/AnimationData.java @@ -98,15 +98,18 @@ public class AnimationData implements IAnimationData { this.isClientAnimating = this.allowAnimation && this.animation != null; if (prevIsClientAnimating && (!this.isClientAnimating || this.animation != this.currentClientAnimation)) { EventHooks.onAnimationEnded(this.currentClientAnimation); + this.currentClientAnimation.fireEndTask(); } if (this.isClientAnimating) { this.currentClientAnimation = this.animation; } if (this.animation != null && this.allowAnimation) { + this.animation.fireStartTask(); if (EventHooks.onAnimationStarted(this.animation)) return; EventHooks.onAnimationFrameEntered(this.animation, this.animation.currentFrame()); + this.animation.fireFrameTask(this.animation.currentFrame); } List entities = sendingEntity.worldObj.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.getBoundingBox( @@ -269,6 +272,7 @@ public class AnimationData implements IAnimationData { newAnim.currentFrame = 0; newAnim.currentFrameTime = 0; newAnim.parent = this; + newAnim.moveFromGlobalToLocal((Animation) animation); } diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java b/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java new file mode 100644 index 000000000..1f4d331a4 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AuctionBlacklist.java @@ -0,0 +1,274 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.registry.GameRegistry; +import kamkeel.npcs.util.AttributeItemUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +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 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"; + private static final String PROFILE_SLOT_KEY = "cnpc_profile_slot"; + + // Bypass permission + private static final String BYPASS_PERMISSION = "customnpcs.auction.blacklist.bypass"; + + public static void reload() { + Set newItems = new HashSet<>(); + Set newWildcards = new HashSet<>(); + Set newMods = new HashSet<>(); + Set newNBTTags = new HashSet<>(); + + // Load blacklisted items + for (String item : ConfigMarket.BlacklistedItems) { + if (item == null || item.isEmpty()) continue; + item = item.toLowerCase().trim(); + + if (item.contains("*")) { + String regex = "^" + item.replace(".", "\\.").replace("*", ".*") + "$"; + newWildcards.add(Pattern.compile(regex)); + } else { + newItems.add(item); + } + } + + // Load blacklisted mods + for (String mod : ConfigMarket.BlacklistedMods) { + if (mod == null || mod.isEmpty()) continue; + newMods.add(mod.toLowerCase().trim()); + } + + // Load blacklisted NBT tags + for (String tag : ConfigMarket.BlacklistedNBTTags) { + if (tag == null || tag.isEmpty()) continue; + newNBTTags.add(tag.trim()); + } + + // Atomic swap + blacklistedItems = newItems; + wildcardPatterns = newWildcards; + blacklistedMods = newMods; + blacklistedNBTTags = newNBTTags; + } + + /** + * Check if player can bypass the blacklist (OP or has permission) + */ + public static boolean canBypass(EntityPlayer player) { + if (player == null) return false; + + // Check OP status + if (player.canCommandSenderUseCommand(2, BYPASS_PERMISSION)) { + return true; + } + + // Check custom permission + return CustomNpcsPermissions.hasCustomPermission(player, BYPASS_PERMISSION); + } + + /** + * Check if item is blacklisted (without bypass check) + */ + public static boolean isBlacklisted(ItemStack item) { + if (item == null || item.getItem() == null) return true; + + // Check bound items (always blocked, even if blacklist is "disabled") + if (hasBoundRequirement(item)) { + return true; + } + + if (!ConfigMarket.BlacklistEnabled) return false; + + // Get registry name + GameRegistry.UniqueIdentifier uid = GameRegistry.findUniqueIdentifierFor(item.getItem()); + if (uid == null) return true; + + String registryName = (uid.modId + ":" + uid.name).toLowerCase(); + String modId = uid.modId.toLowerCase(); + + // Check exact item match + if (blacklistedItems.contains(registryName)) { + return true; + } + + // Check wildcard patterns + for (Pattern pattern : wildcardPatterns) { + if (pattern.matcher(registryName).matches()) { + return true; + } + } + + // Check mod blacklist + if (blacklistedMods.contains(modId)) { + return true; + } + + // Check NBT tags + if (item.hasTagCompound() && !blacklistedNBTTags.isEmpty()) { + NBTTagCompound tag = item.getTagCompound(); + for (String nbtKey : blacklistedNBTTags) { + if (tag.hasKey(nbtKey)) { + return true; + } + } + } + + return false; + } + + /** + * Check if item is blacklisted for a specific player (with bypass check) + */ + public static boolean isBlacklistedForPlayer(ItemStack item, EntityPlayer player) { + if (canBypass(player)) return false; + return isBlacklisted(item); + } + + /** + * Get the registry name of an item + */ + public static String getRegistryName(ItemStack item) { + if (item == null || item.getItem() == null) return null; + GameRegistry.UniqueIdentifier uid = GameRegistry.findUniqueIdentifierFor(item.getItem()); + if (uid == null) return null; + return uid.modId + ":" + uid.name; + } + + // ========================================= + // Bound Item Checking (RPGCore/Requirements) + // ========================================= + + /** + * Check if item has soulbind or profile slot requirement. + * Requirements are stored under: item.stackTagCompound/RPGCore/Requirements + */ + private static boolean hasBoundRequirement(ItemStack item) { + if (item == null || !item.hasTagCompound()) return false; + + NBTTagCompound root = item.getTagCompound(); + if (!root.hasKey(AttributeItemUtil.TAG_RPGCORE)) return false; + + NBTTagCompound rpgCore = root.getCompoundTag(AttributeItemUtil.TAG_RPGCORE); + if (!rpgCore.hasKey(AttributeItemUtil.TAG_REQUIREMENTS)) return false; + + NBTTagCompound requirements = rpgCore.getCompoundTag(AttributeItemUtil.TAG_REQUIREMENTS); + return requirements.hasKey(SOULBIND_KEY) || requirements.hasKey(PROFILE_SLOT_KEY); + } + + // ========================================= + // Runtime Blacklist Management + // ========================================= + + public static boolean addItem(String registryName) { + if (registryName == null || registryName.isEmpty()) return false; + registryName = registryName.toLowerCase().trim(); + + if (registryName.contains("*")) { + String regex = "^" + registryName.replace(".", "\\.").replace("*", ".*") + "$"; + Set newWildcards = new HashSet<>(wildcardPatterns); + newWildcards.add(Pattern.compile(regex)); + wildcardPatterns = newWildcards; + } else { + Set newItems = new HashSet<>(blacklistedItems); + newItems.add(registryName); + blacklistedItems = newItems; + } + return true; + } + + public static boolean removeItem(String registryName) { + if (registryName == null || registryName.isEmpty()) return false; + registryName = registryName.toLowerCase().trim(); + + if (registryName.contains("*")) { + String regex = "^" + registryName.replace(".", "\\.").replace("*", ".*") + "$"; + 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 { + 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; + 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; + 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; + 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; + Set newTags = new HashSet<>(blacklistedNBTTags); + boolean removed = newTags.remove(tag.trim()); + blacklistedNBTTags = newTags; + return removed; + } + + // ========================================= + // Getters for listing + // ========================================= + + public static List getBlacklistedItems() { + List result = new ArrayList<>(blacklistedItems); + for (Pattern p : wildcardPatterns) { + // Convert regex back to wildcard format + String pattern = p.pattern(); + pattern = pattern.substring(1, pattern.length() - 1); // Remove ^ and $ + pattern = pattern.replace("\\.", ".").replace(".*", "*"); + result.add(pattern); + } + return result; + } + + public static List getBlacklistedMods() { + return new ArrayList<>(blacklistedMods); + } + + public static List getBlacklistedNBTTags() { + return new ArrayList<>(blacklistedNBTTags); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java b/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java new file mode 100644 index 000000000..604ff1023 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AuctionClaim.java @@ -0,0 +1,256 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.handler.data.IAuctionClaim; +import noppes.npcs.api.item.IItemStack; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumClaimType; +import noppes.npcs.scripted.NpcAPI; + +import java.util.UUID; + +public class AuctionClaim implements IAuctionClaim { + public String id; + public UUID playerUUID; + public String playerName; + public String listingId; + public EnumClaimType type; + public ItemStack item; // The item (for ITEM claims only) + public String itemName; // Display name of item (for CURRENCY/REFUND tooltip) + public String otherPlayerName; // Buyer name (CURRENCY) or who outbid (REFUND) + public long currency; + public long createdTime; + public boolean claimed; + public boolean isReturned; // For ITEM claims: true if returned to seller, false if won by buyer + + public AuctionClaim() { + this.id = UUID.randomUUID().toString(); + this.createdTime = System.currentTimeMillis(); + this.claimed = false; + this.isReturned = false; + this.itemName = ""; + this.otherPlayerName = ""; + } + + /** + * 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; + claim.playerName = playerName; + claim.listingId = listingId; + claim.type = EnumClaimType.ITEM; + claim.item = item != null ? item.copy() : null; + claim.currency = 0; + claim.isReturned = false; + return claim; + } + + /** + * 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; + claim.playerName = playerName; + claim.listingId = listingId; + claim.type = EnumClaimType.ITEM; + claim.item = item != null ? item.copy() : null; + claim.currency = 0; + claim.isReturned = true; + return claim; + } + + /** + * 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; + claim.playerName = playerName; + claim.listingId = listingId; + claim.type = EnumClaimType.CURRENCY; + claim.item = null; // No item stored for currency claims + claim.itemName = itemName != null ? itemName : ""; + claim.otherPlayerName = buyerName != null ? buyerName : ""; + claim.currency = currency; + claim.isReturned = false; + return claim; + } + + /** + * 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; + claim.playerName = playerName; + claim.listingId = listingId; + claim.type = EnumClaimType.REFUND; + claim.item = item != null ? item.copy() : null; // Store item for display and rebid + claim.itemName = itemName != null ? itemName : ""; + claim.otherPlayerName = outbidderName != null ? outbidderName : ""; + claim.currency = currency; + claim.isReturned = false; + return claim; + } + + public boolean isExpired(int expirationDays) { + long expirationMs = expirationDays * 24L * 60L * 60L * 1000L; + return System.currentTimeMillis() - createdTime > expirationMs; + } + + public long getDaysUntilExpiration(int expirationDays) { + long expirationMs = expirationDays * 24L * 60L * 60L * 1000L; + long remaining = (createdTime + expirationMs) - System.currentTimeMillis(); + return Math.max(0, remaining / (24L * 60L * 60L * 1000L)); + } + + public boolean isForPlayer(UUID uuid) { + return playerUUID != null && playerUUID.equals(uuid); + } + + // ========================================= + // IAuctionClaim Implementation + // ========================================= + + @Override + public String getId() { + return id; + } + + @Override + public String getPlayerUUID() { + return playerUUID != null ? playerUUID.toString() : null; + } + + @Override + public String getPlayerName() { + return playerName; + } + + @Override + public String getListingId() { + return listingId; + } + + @Override + public int getType() { + return type.ordinal(); + } + + @Override + public boolean isItemClaim() { + return type == EnumClaimType.ITEM; + } + + @Override + public boolean isCurrencyClaim() { + return type.isCurrency(); + } + + @Override + public boolean isRefundClaim() { + return type == EnumClaimType.REFUND; + } + + @Override + public IItemStack getItem() { + return item != null ? NpcAPI.Instance().getIItemStack(item) : null; + } + + @Override + public String getItemName() { + return itemName; + } + + @Override + public long getCurrency() { + return currency; + } + + @Override + public String getOtherPlayerName() { + return otherPlayerName; + } + + @Override + public long getCreatedTime() { + return createdTime; + } + + @Override + public boolean isClaimed() { + return claimed; + } + + @Override + public boolean isReturnedItem() { + return isReturned; + } + + @Override + public long getDaysUntilExpiration() { + return getDaysUntilExpiration(ConfigMarket.ClaimExpirationDays); + } + + @Override + public boolean isExpired() { + return isExpired(ConfigMarket.ClaimExpirationDays); + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setString("ID", id); + compound.setString("PlayerUUID", playerUUID != null ? playerUUID.toString() : ""); + compound.setString("PlayerName", playerName != null ? playerName : ""); + compound.setString("ListingID", listingId != null ? listingId : ""); + compound.setInteger("Type", type.ordinal()); + + if (item != null) { + NBTTagCompound itemTag = new NBTTagCompound(); + item.writeToNBT(itemTag); + compound.setTag("Item", itemTag); + } + + compound.setString("ItemName", itemName != null ? itemName : ""); + compound.setString("OtherPlayerName", otherPlayerName != null ? otherPlayerName : ""); + compound.setLong("Currency", currency); + compound.setLong("CreatedTime", createdTime); + compound.setBoolean("Claimed", claimed); + compound.setBoolean("IsReturned", isReturned); + + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + id = compound.getString("ID"); + + String playerUUIDStr = compound.getString("PlayerUUID"); + playerUUID = playerUUIDStr.isEmpty() ? null : UUID.fromString(playerUUIDStr); + playerName = compound.getString("PlayerName"); + + listingId = compound.getString("ListingID"); + type = EnumClaimType.fromOrdinal(compound.getInteger("Type")); + + if (compound.hasKey("Item")) { + item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); + } else { + item = null; + } + + itemName = compound.getString("ItemName"); + otherPlayerName = compound.getString("OtherPlayerName"); + currency = compound.getLong("Currency"); + createdTime = compound.getLong("CreatedTime"); + claimed = compound.getBoolean("Claimed"); + isReturned = compound.getBoolean("IsReturned"); + } + + public static AuctionClaim fromNBT(NBTTagCompound compound) { + AuctionClaim claim = new AuctionClaim(); + claim.readFromNBT(compound); + return claim; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java b/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java new file mode 100644 index 000000000..e6841fcea --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AuctionFilter.java @@ -0,0 +1,130 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumChatFormatting; +import noppes.npcs.constants.EnumAuctionSort; + +/** + * Filter for auction listings. + * Supports search by item name or seller name and sorting options. + */ +public class AuctionFilter { + private String searchText; + public EnumAuctionSort sortBy; + + // Cached normalized search for efficiency + private String normalizedSearch; + + public AuctionFilter() { + this.searchText = ""; + this.sortBy = EnumAuctionSort.NEWEST; + this.normalizedSearch = ""; + } + + public boolean hasSearchText() { + return searchText != null && !searchText.trim().isEmpty(); + } + + /** + * Normalize string for search (strip colors, lowercase, trim) + */ + public static String normalizeForSearch(String input) { + if (input == null || input.isEmpty()) return ""; + String stripped = EnumChatFormatting.getTextWithoutFormattingCodes(input); + return stripped != null ? stripped.toLowerCase().trim() : input.toLowerCase().trim(); + } + + /** + * 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); + String normalizedSeller = normalizeForSearch(sellerName); + // Match if search text is found in either item name or seller name + return normalizedItem.contains(normalizedSearch) || normalizedSeller.contains(normalizedSearch); + } + + /** + * 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 + */ + public boolean matchesSearchAdvanced(String itemName, String sellerName) { + if (!hasSearchText()) return true; + String normalizedItem = normalizeForSearch(itemName); + String normalizedSeller = normalizeForSearch(sellerName); + String[] words = normalizedSearch.split("\\s+"); + for (String word : words) { + if (!word.isEmpty()) { + // Word must be in item name OR seller name + if (!normalizedItem.contains(word) && !normalizedSeller.contains(word)) { + return false; + } + } + } + return true; + } + + /** + * Legacy method - only checks item name + */ + public boolean matchesSearchAdvanced(String itemName) { + return matchesSearchAdvanced(itemName, ""); + } + + public void reset() { + searchText = ""; + sortBy = EnumAuctionSort.NEWEST; + normalizedSearch = ""; + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setString("SearchText", searchText != null ? searchText : ""); + compound.setInteger("SortBy", sortBy.ordinal()); + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + searchText = compound.getString("SearchText"); + normalizedSearch = normalizeForSearch(searchText); + sortBy = EnumAuctionSort.fromOrdinal(compound.getInteger("SortBy")); + } + + public static AuctionFilter fromNBT(NBTTagCompound compound) { + AuctionFilter filter = new AuctionFilter(); + filter.readFromNBT(compound); + return filter; + } + + public AuctionFilter copy() { + AuctionFilter copy = new AuctionFilter(); + copy.searchText = this.searchText; + copy.normalizedSearch = this.normalizedSearch; + copy.sortBy = this.sortBy; + return copy; + } + + // Getters and setters + 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; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/AuctionListing.java b/src/main/java/noppes/npcs/controllers/data/AuctionListing.java new file mode 100644 index 000000000..93fc70674 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AuctionListing.java @@ -0,0 +1,269 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.handler.data.IAuctionListing; +import noppes.npcs.api.item.IItemStack; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumAuctionStatus; +import noppes.npcs.scripted.NpcAPI; + +import java.util.UUID; + +public class AuctionListing implements IAuctionListing { + public String id; + public UUID sellerUUID; + public String sellerName; + public ItemStack item; + public long startingPrice; + public long buyoutPrice; + public long currentBid; + public UUID highBidderUUID; + public String highBidderName; + public int bidCount; + public long createdTime; + public long endTime; + public EnumAuctionStatus status; + public boolean isGlobalListing; + + public AuctionListing() { + this.id = UUID.randomUUID().toString(); + this.status = EnumAuctionStatus.ACTIVE; + 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) { + this(); + this.sellerUUID = sellerUUID; + this.sellerName = sellerName; + this.item = item.copy(); + this.startingPrice = startingPrice; + this.buyoutPrice = buyoutPrice; + this.currentBid = 0; + this.endTime = this.createdTime + durationMs; + } + + public long getTimeRemaining() { + return Math.max(0, endTime - System.currentTimeMillis()); + } + + public long getEffectivePrice() { + return hasBids() ? currentBid : startingPrice; + } + + public long getMinimumBid(double minIncrementPercent) { + if (!hasBids()) { + return startingPrice; + } + long increment = (long) Math.ceil(currentBid * minIncrementPercent); + return currentBid + Math.max(1, increment); + } + + public boolean isSeller(UUID playerUUID) { + return sellerUUID != null && sellerUUID.equals(playerUUID); + } + + public boolean isHighBidder(UUID playerUUID) { + return highBidderUUID != null && highBidderUUID.equals(playerUUID); + } + + public void extendForSnipeProtection(int snipeProtectionMinutes) { + long snipeProtectionMs = snipeProtectionMinutes * 60 * 1000L; + long timeRemaining = getTimeRemaining(); + if (timeRemaining < snipeProtectionMs) { + endTime = System.currentTimeMillis() + snipeProtectionMs; + } + } + + // ========================================= + // IAuctionListing Implementation + // ========================================= + + @Override + public String getId() { + return id; + } + + @Override + public String getSellerUUID() { + return sellerUUID != null ? sellerUUID.toString() : null; + } + + @Override + public String getSellerName() { + return sellerName; + } + + @Override + public IItemStack getItem() { + return item != null ? NpcAPI.Instance().getIItemStack(item) : null; + } + + @Override + public long getStartingPrice() { + return startingPrice; + } + + @Override + public long getBuyoutPrice() { + return buyoutPrice; + } + + @Override + public long getCurrentBid() { + return currentBid; + } + + @Override + public String getHighBidderUUID() { + return highBidderUUID != null ? highBidderUUID.toString() : null; + } + + @Override + public String getHighBidderName() { + return highBidderName; + } + + @Override + public int getBidCount() { + return bidCount; + } + + @Override + public long getCreatedTime() { + return createdTime; + } + + @Override + public long getEndTime() { + return endTime; + } + + @Override + public long getRemainingTime() { + return getTimeRemaining(); + } + + @Override + public int getStatus() { + return status.ordinal(); + } + + @Override + public long getMinimumBid() { + return getMinimumBid(ConfigMarket.MinBidIncrementPercent); + } + + @Override + public boolean isSeller(String playerUUID) { + if (playerUUID == null || sellerUUID == null) return false; + return sellerUUID.toString().equals(playerUUID); + } + + @Override + public boolean isHighBidder(String playerUUID) { + if (playerUUID == null || highBidderUUID == null) return false; + return highBidderUUID.toString().equals(playerUUID); + } + + @Override + public String getRemainingTimeFormatted() { + long remaining = getTimeRemaining(); + if (remaining <= 0) return "Ended"; + + long hours = remaining / (60 * 60 * 1000); + long minutes = (remaining % (60 * 60 * 1000)) / (60 * 1000); + + if (hours > 0) { + return hours + "h " + minutes + "m"; + } else if (minutes > 0) { + return minutes + "m"; + } else { + long seconds = (remaining % (60 * 1000)) / 1000; + return seconds + "s"; + } + } + + // Override existing methods with @Override annotation + @Override + public boolean hasBids() { + return bidCount > 0 && highBidderUUID != null; + } + + @Override + public boolean hasBuyout() { + return buyoutPrice > 0; + } + + @Override + public boolean isExpired() { + return System.currentTimeMillis() >= endTime; + } + + @Override + public boolean isActive() { + return status == EnumAuctionStatus.ACTIVE && !isExpired(); + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setString("ID", id); + compound.setString("SellerUUID", sellerUUID != null ? sellerUUID.toString() : ""); + compound.setString("SellerName", sellerName != null ? sellerName : ""); + + if (item != null) { + NBTTagCompound itemTag = new NBTTagCompound(); + item.writeToNBT(itemTag); + compound.setTag("Item", itemTag); + } + + compound.setLong("StartingPrice", startingPrice); + compound.setLong("BuyoutPrice", buyoutPrice); + compound.setLong("CurrentBid", currentBid); + + compound.setString("HighBidderUUID", highBidderUUID != null ? highBidderUUID.toString() : ""); + compound.setString("HighBidderName", highBidderName != null ? highBidderName : ""); + + compound.setInteger("BidCount", bidCount); + compound.setLong("CreatedTime", createdTime); + compound.setLong("EndTime", endTime); + compound.setInteger("Status", status.ordinal()); + compound.setBoolean("IsGlobalListing", isGlobalListing); + + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + id = compound.getString("ID"); + + String sellerUUIDStr = compound.getString("SellerUUID"); + sellerUUID = sellerUUIDStr.isEmpty() ? null : UUID.fromString(sellerUUIDStr); + sellerName = compound.getString("SellerName"); + + if (compound.hasKey("Item")) { + item = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("Item")); + } + + startingPrice = compound.getLong("StartingPrice"); + buyoutPrice = compound.getLong("BuyoutPrice"); + currentBid = compound.getLong("CurrentBid"); + + String highBidderUUIDStr = compound.getString("HighBidderUUID"); + highBidderUUID = highBidderUUIDStr.isEmpty() ? null : UUID.fromString(highBidderUUIDStr); + highBidderName = compound.getString("HighBidderName"); + + bidCount = compound.getInteger("BidCount"); + createdTime = compound.getLong("CreatedTime"); + endTime = compound.getLong("EndTime"); + status = EnumAuctionStatus.fromOrdinal(compound.getInteger("Status")); + isGlobalListing = compound.getBoolean("IsGlobalListing"); + } + + public static AuctionListing fromNBT(NBTTagCompound compound) { + AuctionListing listing = new AuctionListing(); + listing.readFromNBT(compound); + return listing; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java b/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java new file mode 100644 index 000000000..50ef13c0e --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/BuiltInAnimation.java @@ -0,0 +1,97 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.handler.data.IAnimation; + +/** + * A read-only animation loaded from mod assets. + * Built-in animations are identified by name only, never by ID. + * They cannot be saved, deleted, or modified. + */ +public class BuiltInAnimation extends Animation { + + public BuiltInAnimation() { + super(); + this.id = -1; // No valid ID for built-in animations + } + + public BuiltInAnimation(String name) { + super(); + this.name = name; + this.id = -1; + } + + /** + * Built-in animations cannot be saved. + * + * @return this animation unchanged + */ + @Override + public IAnimation save() { + // Do nothing - built-in animations are read-only + return this; + } + + /** + * Built-in animations have no valid ID. + * + * @return always -1 + */ + @Override + public int getID() { + return -1; + } + + /** + * Built-in animations cannot have their ID changed. + */ + @Override + public void setID(int newID) { + // Ignore - built-in animations don't use IDs + } + + /** + * Check if this is a built-in animation. + * + * @return always true for BuiltInAnimation + */ + public boolean isBuiltIn() { + return true; + } + + /** + * Read animation data from NBT. + * Preserves the name set in constructor (from filename) rather than reading from NBT. + */ + @Override + public void readFromNBT(NBTTagCompound compound) { + // Preserve the name set in constructor - don't read from NBT + // (filename is the source of truth for built-in animations) + String preservedName = this.name; + + speed = compound.getFloat("Speed"); + smooth = compound.getByte("Smooth"); + loop = compound.getInteger("Loop"); + + frames.clear(); + net.minecraft.nbt.NBTTagList list = compound.getTagList("Frames", 10); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound item = list.getCompoundTagAt(i); + Frame frame = new Frame(); + frame.parent = this; + frame.readFromNBT(item); + frames.add(frame); + } + + this.whileStanding = compound.getBoolean("WhileStanding"); + this.whileMoving = compound.getBoolean("WhileWalking"); + this.whileAttacking = compound.getBoolean("WhileAttacking"); + + this.currentFrame = compound.getInteger("CurrentFrame"); + this.currentFrameTime = compound.getInteger("CurrentFrameTime"); + + // Ensure name and ID are preserved + this.name = preservedName; + this.id = -1; + } +} 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/CloneFolder.java b/src/main/java/noppes/npcs/controllers/data/CloneFolder.java new file mode 100644 index 000000000..d2d0c7bcf --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/CloneFolder.java @@ -0,0 +1,61 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class CloneFolder { + public String name; + public long createdDate; + + public CloneFolder() { + this.name = ""; + this.createdDate = System.currentTimeMillis(); + } + + public CloneFolder(String name) { + this.name = name; + this.createdDate = System.currentTimeMillis(); + } + + public void readNBT(NBTTagCompound compound) { + name = compound.getString("Name"); + createdDate = compound.getLong("Created"); + } + + public NBTTagCompound writeNBT(NBTTagCompound compound) { + compound.setString("Name", name); + compound.setLong("Created", createdDate); + return compound; + } + + public static boolean isValidName(String name) { + if (name == null || name.isEmpty()) { + return false; + } + if (name.length() > 32) { + return false; + } + if (!name.equals(name.trim())) { + return false; + } + if (name.equals(".") || name.equals("..")) { + return false; + } + if (name.startsWith("___")) { + return false; + } + try { + Integer.parseInt(name); + return false; + } catch (NumberFormatException ignored) { + } + for (char c : name.toCharArray()) { + if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') { + return false; + } + if (c < 32) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/CustomEffect.java b/src/main/java/noppes/npcs/controllers/data/CustomEffect.java index 3834bef08..582098c87 100644 --- a/src/main/java/noppes/npcs/controllers/data/CustomEffect.java +++ b/src/main/java/noppes/npcs/controllers/data/CustomEffect.java @@ -7,9 +7,13 @@ import noppes.npcs.EventHooks; import noppes.npcs.NoppesUtilServer; 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 { @@ -25,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() { } @@ -142,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; @@ -168,32 +203,16 @@ 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; } - script.callScript(EffectScript.ScriptType.OnEffectAdd, event); + script.callScript(EnumScriptType.ON_EFFECT_ADD, event); } EventHooks.onEffectAdded(iPlayer, playerEffect); @@ -203,17 +222,12 @@ 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; } - script.callScript(EffectScript.ScriptType.OnEffectTick, event); + script.callScript(EnumScriptType.ON_EFFECT_TICK, event); } EventHooks.onEffectTick(iPlayer, playerEffect); @@ -224,17 +238,12 @@ 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; } - script.callScript(EffectScript.ScriptType.OnEffectRemove, event); + script.callScript(EnumScriptType.ON_EFFECT_REMOVE, event); } EventHooks.onEffectRemove(iPlayer, playerEffect, type); @@ -253,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(); @@ -295,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 bf4327d38..7d9fb5c3a 100644 --- a/src/main/java/noppes/npcs/controllers/data/DataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/DataScript.java @@ -3,40 +3,39 @@ package noppes.npcs.controllers.data; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.relauncher.Side; +import kamkeel.npcs.network.packets.request.script.EventScriptPacket; import net.minecraft.entity.Entity; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import net.minecraft.world.WorldServer; +import noppes.npcs.CustomNpcs; import noppes.npcs.EventHooks; import noppes.npcs.LogWriter; import noppes.npcs.NBTTags; import noppes.npcs.api.IWorld; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.config.ConfigDebug; -import noppes.npcs.config.ConfigScript; 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; import noppes.npcs.scripted.ScriptWorld; 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 INpcScriptHandler { - public List eventScripts = new ArrayList<>(); +public class DataScript implements IScriptHandlerPacket { + public List eventScripts = new ArrayList<>(); private HashMap scripts = new HashMap<>(); private final static EntityType entities = new EntityType(); @@ -53,6 +52,17 @@ public class DataScript implements INpcScriptHandler { 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)); @@ -71,7 +81,7 @@ public class DataScript implements INpcScriptHandler { public void readFromNBT(NBTTagCompound compound) { scripts = readScript(compound.getTagList("ScriptsContainers", 10)); this.scriptLanguage = compound.getString("ScriptLanguage"); - if (!ScriptController.Instance.languages.containsKey(scriptLanguage)) { + if (scriptLanguage == null || scriptLanguage.isEmpty()) { if (!ScriptController.Instance.languages.isEmpty()) { this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; } else { @@ -146,13 +156,13 @@ public class DataScript implements INpcScriptHandler { if (!hasInited && !npc.isRemote() && type != EnumScriptType.INIT) { hasInited = true; - for (ScriptContainer scriptContainer : this.eventScripts) { - scriptContainer.errored = false; + for (IScriptUnit scriptUnit : this.eventScripts) { + scriptUnit.setErrored(false); } EventHooks.onNPCInit(this.npc); } - for (ScriptContainer script : this.eventScripts) { + for (IScriptUnit script : this.eventScripts) { script.run(type, event); } @@ -177,21 +187,12 @@ public class DataScript implements INpcScriptHandler { 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) { @@ -206,7 +207,22 @@ public class DataScript implements INpcScriptHandler { } public boolean isEnabled() { - return enabled && ScriptController.HasStart && !npc.worldObj.isRemote && !scripts.isEmpty() && ConfigScript.ScriptingEnabled; + return enabled && ScriptController.HasStart && !npc.worldObj.isRemote && !scripts.isEmpty() && CustomNpcs.proxy.isScriptingEnabled(); + } + + @Override + public ScriptContext getContext() { + return ScriptContext.NPC; + } + + @Override + public void requestData() { + EventScriptPacket.Get(); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + EventScriptPacket.Save(index, totalCount, nbt); } public Map getOldConsoleText() { @@ -221,24 +237,6 @@ public class DataScript implements INpcScriptHandler { return map; } - public Map getConsoleText() { - TreeMap map = new TreeMap<>(); - int tab = 0; - for (ScriptContainer script : this.getScripts()) { - ++tab; - - for (Map.Entry longStringEntry : script.console.entrySet()) { - map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + longStringEntry.getValue()); - } - } - return map; - } - - public void clearConsole() { - for (ScriptContainer script : this.getScripts()) { - script.console.clear(); - } - } @Override public void callScript(EnumScriptType type, Event event) { @@ -254,6 +252,61 @@ public class DataScript implements INpcScriptHandler { } } + 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); + } + + engine.put("API", NpcAPI.Instance()); + for (Map.Entry engineObjects : NpcAPI.engineObjects.entrySet()) { + engine.put(engineObjects.getKey(), engineObjects.getValue()); + } + } + + // 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(); } @@ -274,11 +327,11 @@ public class DataScript implements INpcScriptHandler { this.scriptLanguage = lang; } - public void setScripts(List list) { + public void setScripts(List list) { this.eventScripts = list; } - public List getScripts() { + public List getScripts() { return this.eventScripts; } @@ -312,4 +365,9 @@ public class DataScript implements INpcScriptHandler { public Collection getNPCScripts() { return this.scripts.values(); } + + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.NPC); + } } diff --git a/src/main/java/noppes/npcs/controllers/data/EffectScript.java b/src/main/java/noppes/npcs/controllers/data/EffectScript.java index bd2b75dae..06b38af89 100644 --- a/src/main/java/noppes/npcs/controllers/data/EffectScript.java +++ b/src/main/java/noppes/npcs/controllers/data/EffectScript.java @@ -1,183 +1,62 @@ package noppes.npcs.controllers.data; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.Event; -import io.netty.buffer.ByteBuf; -import kamkeel.npcs.util.ByteBufUtils; +import kamkeel.npcs.network.packets.request.script.EffectScriptPacket; import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.common.util.Constants; -import noppes.npcs.config.ConfigScript; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.ScriptController; -import noppes.npcs.scripted.event.player.PlayerEvent; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +/** + * Script handler for CustomEffect scripts. + * Manages a single script container for effect hooks (onEffectAdd, onEffectTick, onEffectRemove). + */ +public class EffectScript extends SingleScriptHandler implements IScriptHandlerPacket { -public class EffectScript implements INpcScriptHandler { - public ScriptContainer container; - public String scriptLanguage = "ECMAScript"; - public boolean enabled = false; + /** + * The effect ID for packet communication. -1 if not bound to an effect. + */ + private int effectId = -1; - - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setString("ScriptLanguage", scriptLanguage); - compound.setBoolean("ScriptEnabled", enabled); - - if (container != null) - compound.setTag("ScriptContent", container.writeToNBT(new NBTTagCompound())); - return compound; + /** + * Create an unbound EffectScript (for server-side use). + */ + public EffectScript() { } - public EffectScript readFromNBT(NBTTagCompound compound) { - scriptLanguage = compound.getString("ScriptLanguage"); - enabled = compound.getBoolean("ScriptEnabled"); - - if (compound.hasKey("ScriptContent", Constants.NBT.TAG_COMPOUND)) { - container = new ScriptContainer(this); - container.readFromNBT(compound.getCompoundTag("ScriptContent")); - } - return this; - } - - public void callScript(ScriptType type, PlayerEvent.EffectEvent event) { - callScript(type.function, event); - } - - public boolean isEnabled() { - return this.enabled && ScriptController.HasStart && container != null && ConfigScript.ScriptingEnabled; + /** + * Create an EffectScript bound to a specific effect (for GUI use). + * + * @param effectId The ID of the CustomEffect + */ + public EffectScript(int effectId) { + this.effectId = effectId; } @Override - public void callScript(EnumScriptType type, Event event) { - this.callScript(type.function, event); + public ScriptContext getContext() { + return ScriptContext.EFFECT; } @Override - public void callScript(String s, Event event) { - if (!this.isEnabled()) { - return; - } - container.run(s, event); - } - - @Override - public boolean isClient() { - return FMLCommonHandler.instance().getEffectiveSide().isClient(); - } - - @Override - public boolean getEnabled() { - return this.enabled; - } - - @Override - public void setEnabled(boolean b) { - this.enabled = b; - } - - @Override - public String getLanguage() { - return this.scriptLanguage; - } - - @Override - public void setLanguage(String s) { - this.scriptLanguage = s; - } - - @Override - public void setScripts(List list) { - if (list == null || list.isEmpty()) { - container = null; - return; - } - container = list.get(0); - } - - @Override - public List getScripts() { - if (container == null) - return new ArrayList<>(); - return Collections.singletonList(container); + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.EFFECT); } @Override public String noticeString() { - return ""; + return effectId >= 0 ? "CustomEffect[" + effectId + "]" : "CustomEffect"; + } + + + @Override + public void requestData() { + if (effectId >= 0) + EffectScriptPacket.Get(effectId); } @Override - public Map getConsoleText() { - TreeMap map = new TreeMap(); - int tab = 0; - Iterator var3 = this.getScripts().iterator(); - - while (var3.hasNext()) { - ScriptContainer script = (ScriptContainer) var3.next(); - ++tab; - Iterator var5 = script.console.entrySet().iterator(); - - while (var5.hasNext()) { - Map.Entry longStringEntry = (Map.Entry) var5.next(); - map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + (String) longStringEntry.getValue()); - } - } - - return map; + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (effectId >= 0) + EffectScriptPacket.Save(effectId, index, totalCount, nbt); } - @Override - public void clearConsole() { - Iterator var1 = this.getScripts().iterator(); - - while (var1.hasNext()) { - ScriptContainer script = (ScriptContainer) var1.next(); - script.console.clear(); - } - } - - public void saveScript(ByteBuf buffer) throws IOException { - int tab = buffer.readInt(); - int totalScripts = buffer.readInt(); - if (totalScripts == 0) { - this.container = null; - } - - if (tab == 0) { - NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer); - ScriptContainer script = new ScriptContainer(this); - script.readFromNBT(tabCompound); - this.container = script; - } else { - NBTTagCompound compound = ByteBufUtils.readNBT(buffer); - this.setLanguage(compound.getString("ScriptLanguage")); - if (!ScriptController.Instance.languages.containsKey(this.getLanguage())) { - if (!ScriptController.Instance.languages.isEmpty()) { - this.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]); - } else { - this.setLanguage("ECMAScript"); - } - } - this.setEnabled(compound.getBoolean("ScriptEnabled")); - } - } - - public enum ScriptType { - OnEffectAdd("onEffectAdd"), - OnEffectTick("onEffectTick"), - OnEffectRemove("onEffectRemove"); - - public final String function; - - ScriptType(String functionName) { - this.function = functionName; - } - } } diff --git a/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java b/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java index dde123aae..26685aee8 100644 --- a/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java @@ -1,142 +1,174 @@ package noppes.npcs.controllers.data; +import com.google.common.reflect.ClassPath; import cpw.mods.fml.common.eventhandler.Event; +import cpw.mods.fml.common.gameevent.TickEvent; +import cpw.mods.fml.common.network.FMLNetworkEvent; +import kamkeel.npcs.network.packets.request.script.ForgeScriptPacket; import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.event.entity.EntityEvent; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; +import net.minecraftforge.event.world.ChunkDataEvent; +import net.minecraftforge.event.world.ChunkEvent; +import net.minecraftforge.event.world.ChunkWatchEvent; +import net.minecraftforge.event.world.WorldEvent; +import noppes.npcs.CustomNpcs; import noppes.npcs.EventHooks; -import noppes.npcs.NBTTags; -import noppes.npcs.config.ConfigScript; -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.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.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; -public class ForgeDataScript implements INpcScriptHandler { - private List scripts = new ArrayList(); - private String scriptLanguage = "ECMAScript"; - public long lastInited = -1L; +public class ForgeDataScript extends MultiScriptHandler { + private static final Object HOOK_LOCK = new Object(); + private static List cachedHooks; + private long lastForgeUpdate = -1L; - private boolean enabled = false; public ForgeDataScript() { } - public void clear() { - this.scripts = new ArrayList(); - } - - public void readFromNBT(NBTTagCompound compound) { - if (compound.hasKey("Scripts")) { - this.scripts = NBTTags.GetScriptOld(compound.getTagList("Scripts", 10), this); - } else { - this.scripts = NBTTags.GetScript(compound, this); - } - this.scriptLanguage = compound.getString("ScriptLanguage"); - if (!ScriptController.Instance.languages.containsKey(scriptLanguage)) { - if (!ScriptController.Instance.languages.isEmpty()) { - this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; - } else { - this.scriptLanguage = "ECMAScript"; - } - } - this.enabled = compound.getBoolean("ScriptEnabled"); - } - - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setInteger("TotalScripts", this.scripts.size()); - for (int i = 0; i < this.scripts.size(); i++) { - compound.setTag("Tab" + i, this.scripts.get(i).writeToNBT(new NBTTagCompound())); - } - compound.setString("ScriptLanguage", this.scriptLanguage); - compound.setBoolean("ScriptEnabled", this.enabled); - return compound; + public boolean isEnabled() { + return this.enabled && CustomNpcs.proxy.isGlobalForgeScripts() && ScriptController.HasStart && this.scripts.size() > 0; } @Override - public void callScript(EnumScriptType var1, Event var2) { - this.callScript(var1.function, var2); + protected boolean canRunScripts() { + return isEnabled(); } - public void callScript(String type, Event event) { - if (this.isEnabled()) { - if (ScriptController.Instance.lastLoaded > this.lastInited || ScriptController.Instance.lastForgeUpdate > this.lastForgeUpdate) { - this.lastInited = ScriptController.Instance.lastLoaded; - this.lastForgeUpdate = ScriptController.Instance.lastForgeUpdate; + @Override + public ScriptContext getContext() { + return ScriptContext.FORGE; + } - for (ScriptContainer script : this.scripts) { - script.errored = false; - } + @Override + protected boolean needsReInit() { + return ScriptController.Instance.lastLoaded > lastInited || ScriptController.Instance.lastForgeUpdate > lastForgeUpdate; + } - if (!type.equals("init")) { - EventHooks.onForgeInit(this); - } - } + @Override + protected void reInitScripts() { + lastInited = ScriptController.Instance.lastLoaded; + lastForgeUpdate = ScriptController.Instance.lastForgeUpdate; - for (ScriptContainer script : this.scripts) { - if (script == null || script.errored || !script.hasCode()) - continue; - - script.run(type, event); - } + for (IScriptUnit script : this.scripts) { + if (script instanceof ScriptContainer) + ((ScriptContainer) script).errored = false; } } - public boolean isEnabled() { - return this.enabled && ConfigScript.GlobalForgeScripts && ScriptController.HasStart && this.scripts.size() > 0; + @Override + public void callScript(String type, Event event) { + if (!canRunScripts()) { + return; + } + + if (needsReInit()) { + reInitScripts(); + if (!type.equals("init")) { + EventHooks.onForgeInit(this); + } + } + + for (IScriptUnit script : this.scripts) { + if (script == null || script.hasErrored() || !script.hasCode()) + continue; + script.run(type, event); + } } + @Override + public List getHooks() { + if (cachedHooks != null) + return new ArrayList<>(cachedHooks); + + synchronized (HOOK_LOCK) { + if (cachedHooks != null) + return new ArrayList<>(cachedHooks); + + // Start with built-in + addon hooks from ScriptHookController + List hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(ScriptContext.FORGE.hookContext)); + + // Dynamically discover Forge event classes + ArrayList list = new ArrayList<>(); + try { + list.addAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("cpw.mods.fml.common.gameevent")); + list.addAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("net.minecraftforge.event")); + list.removeAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("net.minecraftforge.event.terraingen")); + } catch (IOException e) { + e.printStackTrace(); + } + + for (ClassPath.ClassInfo classInfo : list) { + Class infoClass = classInfo.load(); + List> classes = new ArrayList<>(Arrays.asList(infoClass.getDeclaredClasses())); + if (classes.isEmpty()) { + classes.add(infoClass); + } + + for (Class eventClass : classes) { + if (isValidForgeEvent(eventClass)) { + String eventName = eventClass.getName(); + int lastDot = eventName.lastIndexOf("."); + eventName = StringUtils.uncapitalize(eventName.substring(lastDot + 1).replace("$", "")); + + if (!hookList.contains(eventName)) { + hookList.add(eventName); + } + } + } + } + + cachedHooks = hookList; + } + + return new ArrayList<>(cachedHooks); + } + + /** + * Check if a class is a valid Forge event that should be exposed as a hook. + */ + private boolean isValidForgeEvent(Class eventClass) { + return Event.class.isAssignableFrom(eventClass) + && Modifier.isPublic(eventClass.getModifiers()) + && !Modifier.isAbstract(eventClass.getModifiers()) + && !EntityEvent.EntityConstructing.class.isAssignableFrom(eventClass) + && !WorldEvent.PotentialSpawns.class.isAssignableFrom(eventClass) + && !TickEvent.RenderTickEvent.class.isAssignableFrom(eventClass) + && !TickEvent.ClientTickEvent.class.isAssignableFrom(eventClass) + && !FMLNetworkEvent.ClientCustomPacketEvent.class.isAssignableFrom(eventClass) + && !ItemTooltipEvent.class.isAssignableFrom(eventClass) + && !ChunkEvent.class.isAssignableFrom(eventClass) + && !ChunkWatchEvent.class.isAssignableFrom(eventClass) + && !ChunkDataEvent.class.isAssignableFrom(eventClass); + } + + @Override + public void requestData() { + ForgeScriptPacket.Get(); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + ForgeScriptPacket.Save(index, totalCount, nbt); + } + + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.FORGE); + } + + @Override public boolean isClient() { return false; } - - public boolean getEnabled() { - return this.enabled; - } - - public void setEnabled(boolean bo) { - this.enabled = bo; - } - - public String getLanguage() { - return this.scriptLanguage; - } - - public void setLanguage(String lang) { - this.scriptLanguage = lang; - } - - public void setScripts(List list) { - this.scripts = list; - } - - public List getScripts() { - return this.scripts; - } - - public String noticeString() { - return "ForgeScript"; - } - - public Map getConsoleText() { - TreeMap map = new TreeMap<>(); - int tab = 0; - for (ScriptContainer script : this.getScripts()) { - ++tab; - - for (Entry longStringEntry : script.console.entrySet()) { - map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + longStringEntry.getValue()); - } - } - return map; - } - - public void clearConsole() { - for (ScriptContainer script : this.getScripts()) { - script.console.clear(); - } - } } diff --git a/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java b/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java index 335256e0f..6f8a057cd 100644 --- a/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java @@ -1,39 +1,21 @@ package noppes.npcs.controllers.data; -import com.google.common.base.Preconditions; -import cpw.mods.fml.common.eventhandler.Event; +import kamkeel.npcs.network.packets.request.script.GlobalNPCScriptPacket; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; -import noppes.npcs.NBTTags; +import noppes.npcs.CustomNpcs; import noppes.npcs.api.entity.ICustomNpc; -import noppes.npcs.config.ConfigScript; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; +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; -import javax.annotation.CheckForNull; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.OptionalDouble; -import java.util.OptionalInt; -import java.util.OptionalLong; -import java.util.TreeMap; - -public class GlobalNPCDataScript implements INpcScriptHandler { - public List scripts = new ArrayList(); - public String scriptLanguage = "ECMAScript"; +public class GlobalNPCDataScript extends MultiScriptHandler { private EntityNPCInterface npc; private ICustomNpc npcAPI; - public long lastInited = -1L; private long lastNpcUpdate = -1L; - public boolean enabled = false; public GlobalNPCDataScript(EntityNPCInterface npc) { if (npc != null) { @@ -41,100 +23,58 @@ public class GlobalNPCDataScript implements INpcScriptHandler { } } - public void clear() { - this.scripts = new ArrayList(); - } - - public void readFromNBT(NBTTagCompound compound) { - if (compound.hasKey("Scripts")) { - this.scripts = NBTTags.GetScriptOld(compound.getTagList("Scripts", 10), this); - } else { - this.scripts = NBTTags.GetScript(compound, this); - } - this.scriptLanguage = compound.getString("ScriptLanguage"); - if (!ScriptController.Instance.languages.containsKey(scriptLanguage)) { - if (!ScriptController.Instance.languages.isEmpty()) { - this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; - } else { - this.scriptLanguage = "ECMAScript"; - } - } - this.enabled = compound.getBoolean("ScriptEnabled"); - } - - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setInteger("TotalScripts", this.scripts.size()); - for (int i = 0; i < this.scripts.size(); i++) { - compound.setTag("Tab" + i, this.scripts.get(i).writeToNBT(new NBTTagCompound())); - } - compound.setString("ScriptLanguage", this.scriptLanguage); - compound.setBoolean("ScriptEnabled", this.enabled); - return compound; + @Override + protected boolean canRunScripts() { + return isEnabled(); } public boolean isEnabled() { - return ConfigScript.GlobalNPCScripts && this.enabled && ScriptController.HasStart && this.scripts.size() > 0; - } - - public void callScript(EnumScriptType type, Event event) { - this.callScript(type.function, event); + return CustomNpcs.proxy.isGlobalNPCScripts() && this.enabled && ScriptController.HasStart && this.scripts.size() > 0; } @Override - public void callScript(String hookName, Event event) { - if (this.isEnabled()) { - if (ScriptController.Instance.lastLoaded > this.lastInited || ScriptController.Instance.lastGlobalNpcUpdate > this.lastNpcUpdate) { - this.lastInited = ScriptController.Instance.lastLoaded; - this.lastNpcUpdate = ScriptController.Instance.lastGlobalNpcUpdate; - - for (ScriptContainer script : this.scripts) { - script.errored = false; - } - } - - for (ScriptContainer script : this.scripts) { - if (script == null || script.errored || !script.hasCode()) - continue; - - script.run(hookName, event); - } - } + public ScriptContext getContext() { + return ScriptContext.NPC; } + @Override + protected boolean needsReInit() { + return ScriptController.Instance.lastLoaded > lastInited || ScriptController.Instance.lastGlobalNpcUpdate > lastNpcUpdate; + } + + @Override + protected void reInitScripts() { + super.reInitScripts(); + lastNpcUpdate = ScriptController.Instance.lastGlobalNpcUpdate; + } + + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.NPC); + } + + @Override + public void requestData() { + GlobalNPCScriptPacket.Get(); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + GlobalNPCScriptPacket.Save(index, totalCount, nbt); + } + + @Override public boolean isClient() { - return this.npc.isClientWorld(); - } - - public boolean getEnabled() { - return this.enabled; - } - - public void setEnabled(boolean bo) { - this.enabled = bo; - } - - public String getLanguage() { - return this.scriptLanguage; - } - - public void setLanguage(String lang) { - this.scriptLanguage = lang; - } - - public void setScripts(List list) { - this.scripts = list; - } - - public List getScripts() { - return this.scripts; + return this.npc != null && this.npc.isClientWorld(); } + @Override public String noticeString() { if (this.npc == null) { return "Global script"; } else { BlockPos pos = new BlockPos(this.npc); - return GlobalNPCDataScript.toStringHelper(this.npc).add("x", pos.getX()).add("y", pos.getY()).add("z", pos.getZ()).toString(); + return ScriptToStringHelper.toStringHelper(this.npc).add("x", pos.getX()).add("y", pos.getY()).add("z", pos.getZ()).toString(); } } @@ -144,216 +84,4 @@ public class GlobalNPCDataScript implements INpcScriptHandler { } return this.npcAPI; } - - public Map getConsoleText() { - TreeMap map = new TreeMap<>(); - int tab = 0; - for (ScriptContainer script : this.getScripts()) { - ++tab; - - for (Map.Entry longStringEntry : script.console.entrySet()) { - map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + longStringEntry.getValue()); - } - } - return map; - } - - public void clearConsole() { - for (ScriptContainer script : this.getScripts()) { - script.console.clear(); - } - } - - public static final class ToStringHelper { - private final String className; - private final GlobalNPCDataScript.ToStringHelper.ValueHolder holderHead; - private GlobalNPCDataScript.ToStringHelper.ValueHolder holderTail; - private boolean omitNullValues; - private boolean omitEmptyValues; - - private ToStringHelper(String className) { - this.holderHead = new GlobalNPCDataScript.ToStringHelper.ValueHolder(); - this.holderTail = this.holderHead; - this.omitNullValues = false; - this.omitEmptyValues = false; - this.className = (String) Preconditions.checkNotNull(className); - } - - public GlobalNPCDataScript.ToStringHelper omitNullValues() { - this.omitNullValues = true; - return this; - } - - public GlobalNPCDataScript.ToStringHelper add(String name, @CheckForNull Object value) { - return this.addHolder(name, value); - } - - public GlobalNPCDataScript.ToStringHelper add(String name, boolean value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper add(String name, char value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper add(String name, double value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper add(String name, float value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper add(String name, int value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper add(String name, long value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper addValue(@CheckForNull Object value) { - return this.addHolder(value); - } - - public GlobalNPCDataScript.ToStringHelper addValue(boolean value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper addValue(char value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper addValue(double value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper addValue(float value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper addValue(int value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public GlobalNPCDataScript.ToStringHelper addValue(long value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - private static boolean isEmpty(Object value) { - if (value instanceof CharSequence) { - return ((CharSequence) value).length() == 0; - } else if (value instanceof Collection) { - return ((Collection) value).isEmpty(); - } else if (value instanceof Map) { - return ((Map) value).isEmpty(); - } else if (value instanceof Optional) { - return !((Optional) value).isPresent(); - } else if (value instanceof OptionalInt) { - return !((OptionalInt) value).isPresent(); - } else if (value instanceof OptionalLong) { - return !((OptionalLong) value).isPresent(); - } else if (value instanceof OptionalDouble) { - return !((OptionalDouble) value).isPresent(); - } else if (value instanceof com.google.common.base.Optional) { - return !((com.google.common.base.Optional) value).isPresent(); - } else if (value.getClass().isArray()) { - return Array.getLength(value) == 0; - } else { - return false; - } - } - - public String toString() { - boolean omitNullValuesSnapshot = this.omitNullValues; - boolean omitEmptyValuesSnapshot = this.omitEmptyValues; - String nextSeparator = ""; - StringBuilder builder = (new StringBuilder(32)).append(this.className).append('{'); - for (GlobalNPCDataScript.ToStringHelper.ValueHolder valueHolder = this.holderHead.next; valueHolder != null; valueHolder = valueHolder.next) { - Object value = valueHolder.value; - if (!(valueHolder instanceof GlobalNPCDataScript.ToStringHelper.UnconditionalValueHolder)) { - if (value == null) { - if (omitNullValuesSnapshot) { - continue; - } - } else if (omitEmptyValuesSnapshot && isEmpty(value)) { - continue; - } - } - builder.append(nextSeparator); - nextSeparator = ", "; - if (valueHolder.name != null) { - builder.append(valueHolder.name).append('='); - } - if (value != null && value.getClass().isArray()) { - Object[] objectArray = new Object[]{value}; - String arrayString = Arrays.deepToString(objectArray); - builder.append(arrayString, 1, arrayString.length() - 1); - } else { - builder.append(value); - } - } - return builder.append('}').toString(); - } - - private GlobalNPCDataScript.ToStringHelper.ValueHolder addHolder() { - GlobalNPCDataScript.ToStringHelper.ValueHolder valueHolder = new GlobalNPCDataScript.ToStringHelper.ValueHolder(); - this.holderTail = this.holderTail.next = valueHolder; - return valueHolder; - } - - private GlobalNPCDataScript.ToStringHelper addHolder(@CheckForNull Object value) { - GlobalNPCDataScript.ToStringHelper.ValueHolder valueHolder = this.addHolder(); - valueHolder.value = value; - return this; - } - - private GlobalNPCDataScript.ToStringHelper addHolder(String name, @CheckForNull Object value) { - GlobalNPCDataScript.ToStringHelper.ValueHolder valueHolder = this.addHolder(); - valueHolder.value = value; - valueHolder.name = (String) Preconditions.checkNotNull(name); - return this; - } - - private GlobalNPCDataScript.ToStringHelper.UnconditionalValueHolder addUnconditionalHolder() { - GlobalNPCDataScript.ToStringHelper.UnconditionalValueHolder valueHolder = new GlobalNPCDataScript.ToStringHelper.UnconditionalValueHolder(); - this.holderTail = this.holderTail.next = valueHolder; - return valueHolder; - } - - private GlobalNPCDataScript.ToStringHelper addUnconditionalHolder(Object value) { - GlobalNPCDataScript.ToStringHelper.UnconditionalValueHolder valueHolder = this.addUnconditionalHolder(); - valueHolder.value = value; - return this; - } - - private GlobalNPCDataScript.ToStringHelper addUnconditionalHolder(String name, Object value) { - GlobalNPCDataScript.ToStringHelper.UnconditionalValueHolder valueHolder = this.addUnconditionalHolder(); - valueHolder.value = value; - valueHolder.name = (String) Preconditions.checkNotNull(name); - return this; - } - - private static final class UnconditionalValueHolder extends GlobalNPCDataScript.ToStringHelper.ValueHolder { - private UnconditionalValueHolder() { - super(); - } - } - - private static class ValueHolder { - @CheckForNull - String name; - @CheckForNull - Object value; - @CheckForNull - GlobalNPCDataScript.ToStringHelper.ValueHolder next; - - private ValueHolder() { - } - } - } - - public static GlobalNPCDataScript.ToStringHelper toStringHelper(Object self) { - return new GlobalNPCDataScript.ToStringHelper(self.getClass().getSimpleName()); - } } 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/INpcScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/INpcScriptHandler.java index 508836d1c..82119a6d4 100644 --- a/src/main/java/noppes/npcs/controllers/data/INpcScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/INpcScriptHandler.java @@ -1,8 +1,7 @@ package noppes.npcs.controllers.data; -import cpw.mods.fml.common.eventhandler.Event; -import noppes.npcs.constants.EnumScriptType; - public interface INpcScriptHandler extends IScriptHandler { - void callScript(EnumScriptType var1, Event var2); + // This interface is now empty - callScript methods moved to IScriptHandler + // Kept for backward compatibility + } diff --git a/src/main/java/noppes/npcs/controllers/data/IScriptBlockHandler.java b/src/main/java/noppes/npcs/controllers/data/IScriptBlockHandler.java index c0445594e..f39b87112 100644 --- a/src/main/java/noppes/npcs/controllers/data/IScriptBlockHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/IScriptBlockHandler.java @@ -2,7 +2,7 @@ package noppes.npcs.controllers.data; import noppes.npcs.api.IBlock; -public interface IScriptBlockHandler extends INpcScriptHandler { +public interface IScriptBlockHandler extends IScriptHandler { IBlock getBlock(); } diff --git a/src/main/java/noppes/npcs/controllers/data/IScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/IScriptHandler.java index be37c86f1..812bef6d8 100644 --- a/src/main/java/noppes/npcs/controllers/data/IScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/IScriptHandler.java @@ -1,15 +1,71 @@ package noppes.npcs.controllers.data; +import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.Event; -import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.controllers.ScriptHookController; +import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.TreeMap; public interface IScriptHandler { + default void callScript(EnumScriptType type, Event event) { + if (type != null) + callScript(type.function, event); + + } + void callScript(String hookName, Event event); - boolean isClient(); + /** + * Call a function by name and return its result. + *

+ * Default implementation calls the function on each script unit (in order) and returns + * the first non-null value. + */ + default Object callFunction(String hookName, Object... args) { + if (hookName == null || hookName.isEmpty()) + return null; + + if (!getEnabled()) + return null; + + List scripts = getScripts(); + if (scripts == null || scripts.isEmpty()) + return null; + + for (IScriptUnit script : scripts) { + if (script == null || script.hasErrored() || !script.hasCode()) + continue; + + Object result = script.callFunction(hookName, args); + if (result != null) + return result; + } + + return null; + } + + /** + * Typed convenience wrapper around {@link #callFunction(String, Object...)}. + */ + default S callFunction(String hookName, Class returnType, Object... args) { + Object result = callFunction(hookName, args); + if (result == null || returnType == null) + return null; + + if (returnType.isInstance(result)) + return returnType.cast(result); + + return null; + } + + default boolean isClient() { + return FMLCommonHandler.instance().getEffectiveSide().isClient(); + } boolean getEnabled(); @@ -19,13 +75,138 @@ public interface IScriptHandler { void setLanguage(String language); - void setScripts(List list); + void setScripts(List list); - List getScripts(); + List getScripts(); - String noticeString(); + default String noticeString() { + return ""; + } - Map getConsoleText(); + default Map getConsoleText() { + Map map = new TreeMap<>(); + int tab = 0; - void clearConsole(); + for (IScriptUnit script : getScripts()) { + ++tab; + for (Map.Entry entry : script.getConsole().entrySet()) { + map.put(entry.getKey(), " tab " + tab + ":\n" + entry.getValue()); + } + } + return map; + } + + default void clearConsole() { + for (IScriptUnit script : getScripts()) + script.clearConsole(); + + } + + /** + * Create a new Janino (Java) script unit for this handler. + * Handlers that don't support Janino scripts should return null. + * + * @return A new JaninoScript instance, or null if not supported + */ + default IScriptUnit createJaninoScriptUnit() { + return null; // Default: Janino not supported + } + + /** + * Check if this handler supports Janino (Java) scripts. + * + * @return true if createJaninoScriptUnit() can create valid Janino scripts + */ + default boolean supportsJanino() { + return createJaninoScriptUnit() != null; + } + + /** + * Get the script context for autocomplete and type resolution. + * + * @return The script context (default: GLOBAL) + */ + default ScriptContext getContext() { + return ScriptContext.GLOBAL; + } + + /** + * Get the hook context identifier for this handler. + * Used by ScriptHookController to look up available hooks. + *

+ * By default, derives from getContext().hookContext. + * Override if a different hook context is needed. + * + * @return The context string (e.g., "effect", "npc"), or empty if none + */ + default String getHookContext() { + ScriptContext ctx = getContext(); + return ctx != null ? ctx.hookContext : ""; + } + + /** + * Get the list of available hooks for this handler. + * Uses getHookContext() to look up hooks from ScriptHookController. + * + * @return List of hook names, or empty list if no context + */ + default List getHooks() { + String context = getHookContext(); + if (context == null || context.isEmpty()) + return Collections.emptyList(); + + return ScriptHookController.Instance.getAllHooks(context); + } + + /** + * Check if this handler manages only a single script container. + * Single-container handlers use simplified UI (no numbered tabs). + * + * @return true if this handler uses a single container + */ + default boolean isSingleContainer() { + return false; + } + + /** + * Get the single script unit for single-container handlers. + * Convenience method that returns the first script or null. + * + * @return The single script unit, or null if none exists + */ + default IScriptUnit getSingleScript() { + List scripts = getScripts(); + return (scripts != null && !scripts.isEmpty()) ? scripts.get(0) : null; + } + + /** + * Add a script unit to this handler. + * For single-container handlers, replaces the current unit. + */ + default void addScriptUnit(IScriptUnit unit) { + if (unit != null) + getScripts().add(unit); + } + + /** + * Replace a script unit at the given index. + * For single-container handlers, replaces the current unit. + */ + default void replaceScriptUnit(int index, IScriptUnit unit) { + List scripts = getScripts(); + if (index < 0 || index >= scripts.size()) + scripts.add(unit); + else + scripts.set(index, unit); + } + + /** + * Remove a script unit at the given index. + * For single-container handlers, clears the unit. + */ + default void removeScriptUnit(int index) { + List scripts = getScripts(); + if (index >= 0 && index < scripts.size()) + scripts.remove(index); + } } diff --git a/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java b/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java new file mode 100644 index 000000000..fdc3e3202 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/IScriptHandlerPacket.java @@ -0,0 +1,92 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NBTTags; + +import java.util.List; + +public interface IScriptHandlerPacket extends IScriptHandler { + + /** + * Client-side: request initial script data from the server (typically a {@code ...Packet.Get(...)}). + */ + void requestData(); + + /** + * Client-side: send a script container packet to the server. + * + * @param index {@code >= 0} for a script tab, {@code -1} for handler metadata (language/enabled/console) + * @param totalCount Total number of scripts for this handler + * @param nbt The script container NBT (tab content or metadata) + */ + void sendSavePacket(int index, int totalCount, NBTTagCompound nbt); + + enum GuiDataKind { + LOAD_COMPLETE, + METADATA, + TAB + } + + class GuiDataResult { + public final GuiDataKind kind; + public final int tabIndex; + + public GuiDataResult(GuiDataKind kind, int tabIndex) { + this.kind = kind; + this.tabIndex = tabIndex; + } + } + + /** + * Apply one incoming gui-data payload to this handler. + *

+ * Notes: + *

    + *
  • {@code Languages} / {@code ScriptConsole} are not consumed here; GuiScriptInterface owns those UI concerns.
  • + *
  • Tab payloads are converted to an {@link IScriptUnit} via {@link IScriptUnit#createFromNBT}.
  • + *
+ * + * @return A small classification result so GuiScriptInterface can update GUI state. + */ + default GuiDataResult setGuiData(NBTTagCompound compound) { + if (compound.hasKey("LoadComplete")) { + 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")); + return new GuiDataResult(GuiDataKind.METADATA, -1); + } + + int tab = compound.getInteger("Tab"); + NBTTagCompound scriptCompound = compound.getCompoundTag("Script"); + IScriptUnit unit = IScriptUnit.createFromNBT(scriptCompound, this); + replaceScriptUnit(tab, unit); + return new GuiDataResult(GuiDataKind.TAB, tab); + } + + /** + * Emit save packets for all tabs plus one metadata packet. + * GuiScriptInterface is responsible for updating the active {@link IScriptUnit} with current editor text first. + */ + default void sync() { + List containers = getScripts(); + for (int i = 0; i < containers.size(); i++) { + IScriptUnit container = containers.get(i); + sendSavePacket(i, containers.size(), container.writeToNBT(new NBTTagCompound())); + } + + NBTTagCompound scriptData = new NBTTagCompound(); + scriptData.setString("ScriptLanguage", getLanguage()); + scriptData.setBoolean("ScriptEnabled", getEnabled()); + scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(getConsoleText())); + sendSavePacket(-1, containers.size(), scriptData); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java b/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java new file mode 100644 index 000000000..2e4b25bad --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/IScriptUnit.java @@ -0,0 +1,211 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.eventhandler.Event; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.controllers.ScriptContainer; + +import java.util.List; +import java.util.TreeMap; + +/** + * Common interface for script units that can be edited in a script GUI. + * Implemented by both ScriptContainer (ECMAScript) and JaninoScript (Java/Janino). + * This allows GuiScriptInterface to work with both script types uniformly. + */ +public interface IScriptUnit { + + // NBT type identifiers + String NBT_TYPE_KEY = "ScriptUnitType"; + String TYPE_ECMASCRIPT = "ECMAScript"; + String TYPE_JANINO = "Janino"; + + /** + * Create an IScriptUnit from NBT data. + * Uses the "ScriptUnitType" tag to determine which implementation to create. + * + * @param compound The NBT data + * @param handler The script handler (used for ScriptContainer) + * @return A ScriptContainer or JaninoScript based on the NBT type + */ + static IScriptUnit createFromNBT(NBTTagCompound compound, IScriptHandler handler) { + String type = compound.getString(NBT_TYPE_KEY); + IScriptUnit unit; + + if (TYPE_JANINO.equals(type)) { + // Create appropriate JaninoScript based on handler + unit = handler.createJaninoScriptUnit(); + if (unit == null) { + // Fallback to ScriptContainer if handler doesn't support Janino + unit = new ScriptContainer(handler); + } + } else { + // Default to ScriptContainer for ECMAScript or missing type + unit = new ScriptContainer(handler); + } + + unit.readFromNBT(compound); + return unit; + } + + // ==================== SCRIPT CONTENT ==================== + + /** + * Get the main script text content. + */ + String getScript(); + + /** + * Set the main script text content. + */ + void setScript(String script); + + /** + * Get the list of external script file names loaded for this unit. + */ + List getExternalScripts(); + + /** + * Set the list of external script file names to load. + */ + void setExternalScripts(List scripts); + + // ==================== CONSOLE ==================== + + /** + * Get the console output map (timestamp -> message). + */ + TreeMap getConsole(); + + /** + * Clear all console output. + */ + void clearConsole(); + + /** + * Append a message to the console. + */ + void appendConsole(String message); + + // ==================== LANGUAGE ==================== + + /** + * Get the scripting language for this unit. + * Returns "ECMAScript", "Java", etc. + */ + String getLanguage(); + + /** + * Set the scripting language for this unit. + * + * @param language The language name (e.g., "ECMAScript", "Java") + */ + void setLanguage(String language); + + /** + * Check if this script unit uses Janino (Java) compilation. + */ + default boolean isJanino() { + return "Java".equals(getLanguage()); + } + + // ==================== HOOK GENERATION ==================== + + /** + * Generate a stub/template for the given hook name. + * ECMAScript: function hookName(event) { } + * Janino: full Java method signature with return type + * + * @param hookName The hook name to generate a stub for + * @param hookData Optional data (e.g., Method object for Janino) + * @return The generated stub string + */ + String generateHookStub(String hookName, Object hookData); + + // ==================== NBT ==================== + + /** + * Write this script unit to NBT. + */ + NBTTagCompound writeToNBT(NBTTagCompound compound); + + /** + * Read this script unit from NBT. + */ + void readFromNBT(NBTTagCompound compound); + + // ==================== STATE ==================== + + /** + * Ensure this script unit is compiled (for Janino). + * No-op for ScriptContainer. + */ + void ensureCompiled(); + + /** + * Check if this script unit has any code (script or external scripts). + */ + boolean hasCode(); + + /** + * Check if this script unit has encountered an error during execution. + */ + boolean hasErrored(); + + /** + * Set the error state of this script unit. + */ + 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); + + // ==================== EXECUTION ==================== + + /** + * Execute this script unit for the given hook type and event. + * + * @param type The script hook type + * @param event The event object + */ + void run(EnumScriptType type, Event event); + + /** + * Execute this script unit for the given hook name and event. + * + * @param hookName The hook name (e.g., "init", "interact") + * @param event The event object + */ + void run(String hookName, Object event); + + /** + * Call a script function by name and return its result. + *

+ * Default implementation returns null (not supported). + */ + default Object callFunction(String hookName, Object... args) { + return null; + } + + /** + * Typed convenience wrapper around {@link #callFunction(String, Object...)}. + */ + default S callFunction(String hookName, Class returnType, Object... args) { + Object result = callFunction(hookName, args); + if (result == null || returnType == null) + return null; + + if (returnType.isInstance(result)) + return returnType.cast(result); + + return null; + } +} 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 new file mode 100644 index 000000000..cbe1230e0 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/JaninoScriptHandler.java @@ -0,0 +1,136 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.eventhandler.Event; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.janino.JaninoScript; + +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +/** + * Reusable IScriptHandler implementation for objects that own an optional single JaninoScript unit. + *

+ * This is meant for "function provider" scripts (not EnumScriptType driven). Execution is typically + * initiated by the owning system calling script.call(...) directly. + *

+ * NBT storage is kept under the parent compound key "Script" (same convention as JaninoScriptable). + */ +public class JaninoScriptHandler> extends ScriptHandler { + + protected S script; + + private final Supplier factory; + private final Class scriptClass; + + public JaninoScriptHandler(Supplier factory, Class scriptClass) { + this.factory = factory; + this.scriptClass = scriptClass; + scriptLanguage = "Java"; + } + + // -------------------- Script ownership (JaninoScriptable) -------------------- + + public boolean hasScript() { + return script != null; + } + + public S getScript() { + return script; + } + + public JaninoScript createScript() { + if (script == null) + script = factory.get(); + + return script; + } + + public void deleteScript() { + script = null; + } + + // -------------------- NBT helpers -------------------- + + 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); + } + + public void writeToNBT(NBTTagCompound compound) { + JaninoScript.writeToNBT(compound, (JaninoScript) script); + } + + // -------------------- IScriptHandler -------------------- + + @Override + public void callScript(String hookName, Event event) { + // No-op: these scripts are not executed through the global hook dispatcher. + } + + @Override + public void callScript(EnumScriptType type, Event event) { + // No-op + } + + @Override + public void setScripts(List list) { + if (list == null || list.isEmpty() || list.get(0) == null) { + deleteScript(); + return; + } + + IScriptUnit unit = list.get(0); + if (scriptClass.isInstance(unit)) { + this.script = scriptClass.cast(unit); + return; + } + + // Fallback: copy code into a real instance of this script type. + S target = scriptClass.cast(createScript()); + target.setScript(unit.getScript()); + target.setExternalScripts(unit.getExternalScripts()); + } + + @Override + public List getScripts() { + if (script == null) + return Collections.emptyList(); + + return Collections.singletonList(script); + } + + @Override + public void addScriptUnit(IScriptUnit unit) { + setScripts(Collections.singletonList(unit)); + } + + @Override + public void replaceScriptUnit(int index, IScriptUnit unit) { + setScripts(Collections.singletonList(unit)); + } + + @Override + public void removeScriptUnit(int index) { + deleteScript(); + } + + public List getHooks() { + if (script != null) + return script.getHookList(); + + return Collections.emptyList(); + } + + @Override + public IScriptUnit createJaninoScriptUnit() { + return factory.get(); + } + + @Override + public boolean supportsJanino() { + return true; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/LinkedItem.java b/src/main/java/noppes/npcs/controllers/data/LinkedItem.java index f1840a625..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")); @@ -249,8 +259,8 @@ public class LinkedItem implements ILinkedItem { @Override public void setAttackSpeed(int time) { - if(time <= 0) { - time = 10; + if (time <= 0) { + time = 10; } this.attackSpeed = time; } diff --git a/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java b/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java index cce8df255..841f6b063 100644 --- a/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java +++ b/src/main/java/noppes/npcs/controllers/data/LinkedItemScript.java @@ -1,105 +1,44 @@ package noppes.npcs.controllers.data; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.Event; -import io.netty.buffer.ByteBuf; -import kamkeel.npcs.util.ByteBufUtils; +import kamkeel.npcs.network.packets.request.script.item.LinkedItemScriptPacket; import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.common.util.Constants; -import noppes.npcs.config.ConfigScript; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.ScriptController; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +/** + * Script handler for LinkedItem scripts. + * Manages a single script container for linked item hooks. + */ +public class LinkedItemScript extends SingleScriptHandler implements IScriptHandlerPacket { -public class LinkedItemScript implements INpcScriptHandler { - public ScriptContainer container; - public String scriptLanguage = "ECMAScript"; - public boolean enabled = false; + /** + * The linked item ID for packet communication. -1 if not bound. + */ + private int linkedItemId = -1; - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setString("ScriptLanguage", scriptLanguage); - compound.setBoolean("ScriptEnabled", enabled); - - if (container != null) - compound.setTag("ScriptContent", container.writeToNBT(new NBTTagCompound())); - return compound; + /** + * Create an unbound LinkedItemScript (for server-side use). + */ + public LinkedItemScript() { } - public LinkedItemScript readFromNBT(NBTTagCompound compound) { - scriptLanguage = compound.getString("ScriptLanguage"); - enabled = compound.getBoolean("ScriptEnabled"); - - if (compound.hasKey("ScriptContent", Constants.NBT.TAG_COMPOUND)) { - container = new ScriptContainer(this); - container.readFromNBT(compound.getCompoundTag("ScriptContent")); - } - return this; - } - - public boolean isEnabled() { - return this.enabled && ScriptController.HasStart && container != null && ConfigScript.ScriptingEnabled; + /** + * Create a LinkedItemScript bound to a specific linked item (for GUI use). + * + * @param linkedItemId The ID of the LinkedItem + */ + public LinkedItemScript(int linkedItemId) { + this.linkedItemId = linkedItemId; } @Override - public void callScript(EnumScriptType type, Event event) { - this.callScript(type.function, event); + public ScriptContext getContext() { + return ScriptContext.LINKED_ITEM; } @Override - public void callScript(String s, Event event) { - if (!this.isEnabled()) { - return; - } - container.run(s, event); - } - - @Override - public boolean isClient() { - return FMLCommonHandler.instance().getEffectiveSide().isClient(); - } - - @Override - public boolean getEnabled() { - return this.enabled; - } - - @Override - public void setEnabled(boolean b) { - this.enabled = b; - } - - @Override - public String getLanguage() { - return this.scriptLanguage; - } - - @Override - public void setLanguage(String s) { - this.scriptLanguage = s; - } - - @Override - public void setScripts(List list) { - if (list == null || list.isEmpty()) { - container = null; - return; - } - container = list.get(0); - } - - @Override - public List getScripts() { - if (container == null) - return new ArrayList<>(); - return Collections.singletonList(container); + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.LINKED_ITEM); } @Override @@ -108,58 +47,15 @@ public class LinkedItemScript implements INpcScriptHandler { } @Override - public Map getConsoleText() { - TreeMap map = new TreeMap(); - int tab = 0; - Iterator var3 = this.getScripts().iterator(); - - while (var3.hasNext()) { - ScriptContainer script = (ScriptContainer) var3.next(); - ++tab; - Iterator var5 = script.console.entrySet().iterator(); - - while (var5.hasNext()) { - Map.Entry longStringEntry = (Map.Entry) var5.next(); - map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + (String) longStringEntry.getValue()); - } - } - - return map; + public void requestData() { + if (linkedItemId >= 0) + LinkedItemScriptPacket.Get(linkedItemId); } @Override - public void clearConsole() { - Iterator var1 = this.getScripts().iterator(); + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (linkedItemId >= 0) + LinkedItemScriptPacket.Save(linkedItemId, index, totalCount, nbt); - while (var1.hasNext()) { - ScriptContainer script = (ScriptContainer) var1.next(); - script.console.clear(); - } - } - - public void saveScript(ByteBuf buffer) throws IOException { - int tab = buffer.readInt(); - int totalScripts = buffer.readInt(); - if (totalScripts == 0) { - this.container = null; - } - - if (tab == 0) { - NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer); - ScriptContainer script = new ScriptContainer(this); - script.readFromNBT(tabCompound); - this.container = script; - } else { - NBTTagCompound compound = ByteBufUtils.readNBT(buffer); - this.setLanguage(compound.getString("ScriptLanguage")); - if (!ScriptController.Instance.languages.containsKey(this.getLanguage())) { - if (!ScriptController.Instance.languages.isEmpty()) { - this.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]); - } else { - this.setLanguage("ECMAScript"); - } - } - this.setEnabled(compound.getBoolean("ScriptEnabled")); - } } } 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/MultiScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/MultiScriptHandler.java new file mode 100644 index 000000000..699b0542d --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/MultiScriptHandler.java @@ -0,0 +1,109 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.eventhandler.Event; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NBTTags; +import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.controllers.ScriptController; + +import java.util.ArrayList; + +/** + * Base class for script handlers that manage multiple script containers (tabs). + * Provides shared NBT serialization and common script execution patterns. + *

+ * Subclasses should: + * - Override getContext() to return the appropriate ScriptContext + * - Override getHookContext() if not using ScriptContext's hookContext + * - Override requestData() and sendSavePacket() for packet communication + * - Override isEnabled() if custom enable logic is needed + */ +public abstract class MultiScriptHandler extends ScriptHandler implements IScriptHandlerPacket { + + // ==================== NBT SERIALIZATION ==================== + + /** + * Read script data from NBT using the Tab0/Tab1/etc. format. + */ + public void readFromNBT(NBTTagCompound compound) { + if (compound.hasKey("Scripts")) { + this.scripts = new ArrayList<>(NBTTags.GetScriptOld(compound.getTagList("Scripts", 10), this)); + } else { + this.scripts = new ArrayList<>(NBTTags.GetScript(compound, this)); + } + + this.scriptLanguage = compound.getString("ScriptLanguage"); + normalizeLanguage(); + + this.enabled = compound.getBoolean("ScriptEnabled"); + } + + /** + * Write script data to NBT using the Tab0/Tab1/etc. format. + */ + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setInteger("TotalScripts", this.scripts.size()); + for (int i = 0; i < this.scripts.size(); i++) { + compound.setTag("Tab" + i, this.scripts.get(i).writeToNBT(new NBTTagCompound())); + } + compound.setString("ScriptLanguage", this.scriptLanguage); + compound.setBoolean("ScriptEnabled", this.enabled); + return compound; + } + + /** + * Normalize the language to a valid one if the current language is not available. + */ + protected void normalizeLanguage() { + if (this.scriptLanguage == null || this.scriptLanguage.isEmpty()) { + if (!ScriptController.Instance.languages.isEmpty()) { + this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; + } else { + this.scriptLanguage = "ECMAScript"; + } + } + } + + // ==================== SCRIPT EXECUTION ==================== + + /** + * Check if scripts need to be re-initialized due to reload. + * Subclasses can override to add additional update tracking (e.g., lastPlayerUpdate). + * + * @return true if scripts should be re-initialized + */ + protected boolean needsReInit() { + return ScriptController.Instance.lastLoaded > lastInited; + } + + /** + * Called when scripts need re-initialization. + * Clears error state on all script containers. + */ + protected void reInitScripts() { + lastInited = ScriptController.Instance.lastLoaded; + for (IScriptUnit script : this.scripts) { + if (script instanceof ScriptContainer) { + ((ScriptContainer) script).errored = false; + } + } + } + + @Override + public void callScript(String hookName, Event event) { + if (!canRunScripts()) { + return; + } + + if (needsReInit()) { + reInitScripts(); + } + + for (IScriptUnit script : this.scripts) { + if (script == null || script.hasErrored() || !script.hasCode()) { + continue; + } + script.run(hookName, event); + } + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java new file mode 100644 index 000000000..35d6c4239 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -0,0 +1,1093 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; +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; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +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 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) + * - Player manually selects ability (no weighted random) + * - Conditions requiring a target are skipped + * - Uses ability's base cooldownTicks only + */ +public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerAbilityData { + + private final PlayerData playerData; + + // ═══════════════════════════════════════════════════════════════════ + // CONFIGURATION (saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + /** + * List of unlocked ability keys (preset names or built-in keys). + * Order matters - determines selection index. + */ + private List unlockedAbilities = new ArrayList<>(); + + /** + * Currently selected ability index in the unlocked list. + */ + private int selectedIndex = 0; + + /** + * Tracks whether the current animation was started by an ability. + * Persisted to NBT so orphaned ability animations can be detected and + * cleared on login (ability state is transient, but animation state is not). + */ + private boolean playingAbilityAnimation = false; + + // ═══════════════════════════════════════════════════════════════════ + // PLAYER-SPECIFIC RUNTIME STATE (not saved) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Current ability's key (for cooldown tracking after completion). + */ + private transient String currentAbilityKey; + + /** + * Target for the current ability (can be null for self-targeting). + */ + 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 + // ═══════════════════════════════════════════════════════════════════ + + public PlayerAbilityData(PlayerData playerData) { + 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) { + int duration = chain.getCooldownTicks(); + cooldownEndTime = getWorldTime() + duration; + 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 + // ═══════════════════════════════════════════════════════════════════ + + /** + * Main tick method - handles ability execution. + * Should be called every server tick. + */ + public void tick(EntityPlayer player) { + if (player.worldObj.isRemote || player.isDead) { + return; + } + + // Tick active toggles (independent of currentAbility) + tickActiveToggles(); + + boolean hasActiveAbility = chainDelayRemaining > 0 || (currentAbility != null && currentAbility.isExecuting()); + + 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; + } + } + + // Update tracked position for next tick's comparison + lastAbilityTickX = player.posX; + lastAbilityTickY = player.posY; + lastAbilityTickZ = player.posZ; + trackingAbilityPosition = true; + + 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); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ABILITY ACTIVATION - Called on Special Key press + // ═══════════════════════════════════════════════════════════════════ + + /** + * Activate the currently selected ability. + * Called when the player presses the Special Key. + * + * @param player The player + * @return true if the ability was started + */ + public boolean activateAbility(EntityPlayer player) { + if (player.worldObj.isRemote) return false; + if (unlockedAbilities.isEmpty()) return false; + if (selectedIndex < 0 || selectedIndex >= unlockedAbilities.size()) return false; + + String key = unlockedAbilities.get(selectedIndex); + return activateAbility(player, 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), 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 via unified resolver + IAbilityAction action = resolveActionKey(key); + if (action == null) return false; + + // Check user type allows player + if (!action.getAllowedBy().allowsPlayer()) return false; + + // Check conditions (skip target-requiring ones) + 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()) { + 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 — 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 + 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; + } + + // ═══════════════════════════════════════════════════════════════════ + // CLIENT SYNC + // ═══════════════════════════════════════════════════════════════════ + + /** + * Full sync of all ability state to the client. + * Delegates to {@link SyncController#syncAbilities(EntityPlayerMP)}. + */ + public void syncToClient() { + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + SyncController.syncAbilities((EntityPlayerMP) player); + } + } + + /** + * Lightweight sync of cooldown state only to the client. + * Delegates to {@link SyncController#syncAbilityCooldowns(EntityPlayerMP)}. + */ + public void syncCooldownToClient() { + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + SyncController.syncAbilityCooldowns((EntityPlayerMP) player); + } + } + + @Override + protected void onToggleStateChanged(String key, boolean active, int state) { + } + + // ═══════════════════════════════════════════════════════════════════ + // SELECTION + // ═══════════════════════════════════════════════════════════════════ + + public int getSelectedIndex() { + return selectedIndex; + } + + public void setSelectedIndex(int index) { + if (index == -1 || (index >= 0 && index < unlockedAbilities.size())) { + this.selectedIndex = index; + } + } + + public void selectNext() { + if (unlockedAbilities.isEmpty()) return; + selectedIndex = (selectedIndex + 1) % unlockedAbilities.size(); + } + + public void selectPrevious() { + if (unlockedAbilities.isEmpty()) return; + selectedIndex = (selectedIndex - 1 + unlockedAbilities.size()) % unlockedAbilities.size(); + } + + public String getSelectedAbilityKey() { + if (unlockedAbilities.isEmpty() || selectedIndex < 0 || selectedIndex >= unlockedAbilities.size()) { + return null; + } + return unlockedAbilities.get(selectedIndex); + } + + // ═══════════════════════════════════════════════════════════════════ + // UNLOCKED ABILITIES + // ═══════════════════════════════════════════════════════════════════ + + public List getUnlockedAbilityList() { + return unlockedAbilities; + } + + @Override + public String[] getUnlockedAbilities() { + return unlockedAbilities.toArray(new String[0]); + } + + public void setUnlockedAbilities(List abilities) { + this.unlockedAbilities = abilities != null ? new ArrayList<>(abilities) : new ArrayList<>(); + // Clamp selected index + if (selectedIndex >= unlockedAbilities.size()) { + selectedIndex = Math.max(0, unlockedAbilities.size() - 1); + } + } + + public void unlockAbility(String key) { + if (key != null && !key.isEmpty() && !unlockedAbilities.contains(key)) { + unlockedAbilities.add(key); + } + } + + public void lockAbility(String key) { + unlockedAbilities.remove(key); + if (selectedIndex >= unlockedAbilities.size()) { + selectedIndex = Math.max(0, unlockedAbilities.size() - 1); + } + } + + public boolean hasUnlockedAbility(String key) { + return unlockedAbilities.contains(key); + } + + // ═══════════════════════════════════════════════════════════════════ + // 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. + * 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); + } + + public long getRemainingCooldown(EntityPlayer player) { + long remaining = cooldownEndTime - player.worldObj.getTotalWorldTime(); + return remaining > 0 ? remaining : 0; + } + + /** + * Reset cooldown for a specific ability key. + * Resets per-ability cooldown if applicable, and global cooldown. + */ + public void resetCooldown(String key) { + resetPerAbilityCooldown(key); + cooldownEndTime = 0; + } + + /** + * Reset all cooldowns (global + all per-ability). + */ + public void resetAllCooldowns() { + cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + } + + // ═══════════════════════════════════════════════════════════════════ + // IPlayerAbilityData INTERFACE + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean activateAbility() { + return activateAbility(playerData.player); + } + + @Override + public boolean activateAbility(String key) { + return activateAbility(playerData.player, key); + } + + @Override + public boolean isOnCooldown() { + EntityPlayer player = playerData.player; + if (player == null) return false; + return isOnCooldown(player); + } + + @Override + public boolean isOnCooldown(String key) { + EntityPlayer player = playerData.player; + if (player == null) return false; + return isOnCooldown(key, player); + } + + @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 ability state when changing dimensions. + * Clears cooldowns so the player can immediately use abilities in the new dimension. + * Keeps active toggles (dimension change shouldn't reset ongoing effects). + */ + public void resetOnDimensionChange() { + trackingAbilityPosition = false; + onEntityReconstructed(true, false); + } + + /** + * Reset ability state when a large-distance teleport is detected during execution. + * Same behavior as dimension change — silent cleanup, clear cooldowns, keep toggles. + */ + public void resetOnTeleport() { + onEntityReconstructed(true, 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; + + // Clear cooldowns (fresh start after relog) + cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + 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 (cooldowns, chains, locks) + // Don't clear toggles — they were already saved to NBT by this point + onEntityReconstructed(true, 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. + */ + public boolean isMovementLocked() { + return currentAbility != null && currentAbility.isExecuting() + && 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(); + } + + // ═══════════════════════════════════════════════════════════════════ + // ROTATION CONTROL (Player-specific application) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Apply rotation control on the server side. + * Enforces locked rotation values on the player entity. + */ + private void applyRotationControl(EntityPlayer player) { + if (!rotationLocked || currentAbility == null) return; + + if (currentAbility.isRotationLockedForCurrentPhase()) { + player.rotationYaw = lockedYaw; + player.rotationPitch = lockedPitch; + player.prevRotationYaw = lockedYaw; + player.prevRotationPitch = lockedPitch; + if (player instanceof EntityPlayerMP) { + player.rotationYawHead = lockedYaw; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING (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); + } + } + + /** + * 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); + } + } + + /** + * 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); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + public void writeToNBT(NBTTagCompound compound) { + NBTTagList list = new NBTTagList(); + for (String key : unlockedAbilities) { + list.appendTag(new NBTTagString(key)); + } + 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); + } + + public void readFromNBT(NBTTagCompound compound) { + unlockedAbilities.clear(); + if (compound.hasKey("PlayerAbilities")) { + NBTTagList list = compound.getTagList("PlayerAbilities", 8); // 8 = string tag + for (int i = 0; i < list.tagCount(); i++) { + String key = list.getStringTagAt(i); + if (key != null && !key.isEmpty()) { + unlockedAbilities.add(key); + } + } + } + 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); + } + } + } + + /** + * 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 599f81ff1..0c575eb77 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -15,6 +15,7 @@ import net.minecraft.world.World; import net.minecraftforge.common.IExtendedEntityProperties; import noppes.npcs.CustomNpcs; 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.IPlayerData; @@ -23,6 +24,7 @@ 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; @@ -59,6 +61,11 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { public DataSkinOverlays skinOverlays = new DataSkinOverlays(this); public MagicData magicData = new MagicData(); + // Trade data (currency + auction claims) - shared across all profile slots + 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; @@ -87,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(); @@ -105,6 +124,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { } 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(); } @@ -130,6 +152,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { animationData.readFromNBT(data); effectData.readFromNBT(data); magicData.readToNBT(data); + tradeData.readFromNBT(data); + abilityData.readFromNBT(data); + hotbarData.readFromNBT(data); if (player != null) { playername = player.getCommandSenderName(); @@ -172,6 +197,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { animationData.writeToNBT(compound); effectData.writeToNBT(compound); magicData.writeToNBT(compound); + tradeData.writeToNBT(compound); + abilityData.writeToNBT(compound); + hotbarData.writeToNBT(compound); compound.setString("PlayerName", playername); compound.setString("UUID", uuid); @@ -224,6 +252,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { transportData.saveNBTData(compound); 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); @@ -237,6 +268,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { transportData.loadNBTData(data); 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(); @@ -397,6 +431,14 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { return mailData; } + public IPlayerTradeData getTradeData() { + return tradeData; + } + + public IPlayerAbilityData getAbilityData() { + return abilityData; + } + public synchronized void save() { // Don't Save this is a Modification of a Profile's PlayerData Profile profile = ProfileController.Instance.getProfile(UUID.fromString(uuid)); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java b/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java index a425bdcd4..7307333e0 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java @@ -1,48 +1,39 @@ package noppes.npcs.controllers.data; -import com.google.common.base.Preconditions; import cpw.mods.fml.common.eventhandler.Event; +import kamkeel.npcs.network.packets.request.script.PlayerScriptPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; +import noppes.npcs.CustomNpcs; import noppes.npcs.EventHooks; import noppes.npcs.NBTTags; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; +import noppes.npcs.janino.EventJaninoScript; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.player.PlayerEvent; +import noppes.npcs.util.ScriptToStringHelper; -import javax.annotation.CheckForNull; -import java.lang.reflect.Array; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; -import java.util.Optional; -import java.util.OptionalDouble; -import java.util.OptionalInt; -import java.util.OptionalLong; import java.util.TreeMap; -public class PlayerDataScript implements INpcScriptHandler { - public List scripts = new ArrayList(); - public String scriptLanguage = "ECMAScript"; +public class PlayerDataScript extends MultiScriptHandler { private EntityPlayer player; private IPlayer playerAPI; private long lastPlayerUpdate = 0L; - public long lastInited = -1; - public boolean hadInteract = true; - private boolean enabled = false; - - private static Map console = new TreeMap(); - private static List errored = new ArrayList(); + // Static console/errored for IndividualPlayerScripts mode + private static Map staticConsole = new TreeMap<>(); + private static List errored = new ArrayList<>(); public PlayerDataScript(EntityPlayer player) { if (player != null) { @@ -51,46 +42,46 @@ public class PlayerDataScript implements INpcScriptHandler { } public void clear() { - console = new TreeMap(); - errored = new ArrayList(); - scripts = new ArrayList(); + super.clear(); + staticConsole = new TreeMap<>(); + errored = new ArrayList<>(); } + @Override public void readFromNBT(NBTTagCompound compound) { - if (compound.hasKey("Scripts")) { - this.scripts = NBTTags.GetScriptOld(compound.getTagList("Scripts", 10), this); - } else { - this.scripts = NBTTags.GetScript(compound, this); - } - this.scriptLanguage = compound.getString("ScriptLanguage"); - if (!ScriptController.Instance.languages.containsKey(scriptLanguage)) { - if (!ScriptController.Instance.languages.isEmpty()) { - this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; - } else { - this.scriptLanguage = "ECMAScript"; - } - } - this.enabled = compound.getBoolean("ScriptEnabled"); - console = NBTTags.GetLongStringMap(compound.getTagList("ScriptConsole", 10)); + super.readFromNBT(compound); + staticConsole = NBTTags.GetLongStringMap(compound.getTagList("ScriptConsole", 10)); } + @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setInteger("TotalScripts", this.scripts.size()); - for (int i = 0; i < this.scripts.size(); i++) { - compound.setTag("Tab" + i, this.scripts.get(i).writeToNBT(new NBTTagCompound())); - } - compound.setString("ScriptLanguage", this.scriptLanguage); - compound.setBoolean("ScriptEnabled", this.enabled); - compound.setTag("ScriptConsole", NBTTags.NBTLongStringMap(console)); + super.writeToNBT(compound); + compound.setTag("ScriptConsole", NBTTags.NBTLongStringMap(staticConsole)); return compound; } public boolean isEnabled() { - return ConfigScript.GlobalPlayerScripts && ScriptController.Instance.playerScripts.enabled && ScriptController.HasStart && (this.player == null || !this.player.worldObj.isRemote); + return CustomNpcs.proxy.isGlobalPlayerScripts() && ScriptController.Instance.playerScripts.enabled && ScriptController.HasStart && (this.player == null || !this.player.worldObj.isRemote); } - public void callScript(EnumScriptType type, Event event) { - this.callScript(type.function, event); + @Override + protected boolean canRunScripts() { + return isEnabled(); + } + + @Override + public ScriptContext getContext() { + return ScriptContext.PLAYER; + } + + @Override + public void requestData() { + PlayerScriptPacket.Get(); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + PlayerScriptPacket.Save(index, totalCount, nbt); } @Override @@ -104,10 +95,11 @@ public class PlayerDataScript implements INpcScriptHandler { errored.clear(); if (player != null) { scripts.clear(); - for (ScriptContainer script : ScriptController.Instance.playerScripts.scripts) { - ScriptContainer s = new ScriptContainer(this); - s.readFromNBT(script.writeToNBT(new NBTTagCompound())); - scripts.add(s); + for (IScriptUnit script : ScriptController.Instance.playerScripts.scripts) { + // Clone the script unit by writing to NBT and reading back with factory + NBTTagCompound nbt = script.writeToNBT(new NBTTagCompound()); + IScriptUnit cloned = IScriptUnit.createFromNBT(nbt, this); + scripts.add(cloned); } } lastPlayerUpdate = ScriptController.Instance.lastPlayerUpdate; @@ -117,26 +109,27 @@ public class PlayerDataScript implements INpcScriptHandler { } } for (int i = 0; i < scripts.size(); i++) { - ScriptContainer script = scripts.get(i); + IScriptUnit script = scripts.get(i); if (errored.contains(i)) continue; script.run(hookName, event); - if (script.errored) { + if (script.hasErrored()) { errored.add(i); } - for (Entry entry : script.console.entrySet()) { - if (!console.containsKey(entry.getKey())) - console.put(entry.getKey(), " tab " + (i + 1) + ":\n" + entry.getValue()); + for (Entry entry : script.getConsole().entrySet()) { + if (!staticConsole.containsKey(entry.getKey())) + staticConsole.put(entry.getKey(), " tab " + (i + 1) + ":\n" + entry.getValue()); } - script.console.clear(); + script.clearConsole(); } } else { if (ScriptController.Instance.lastLoaded > this.lastInited || ScriptController.Instance.lastPlayerUpdate > this.lastPlayerUpdate) { this.lastInited = ScriptController.Instance.lastLoaded; this.lastPlayerUpdate = ScriptController.Instance.lastPlayerUpdate; - for (ScriptContainer scriptContainer : this.scripts) { - scriptContainer.errored = false; + for (IScriptUnit script : this.scripts) { + if (script instanceof ScriptContainer) + ((ScriptContainer) script).errored = false; } if (!Objects.equals(hookName, EnumScriptType.INIT.function) && event instanceof PlayerEvent) { @@ -145,51 +138,48 @@ public class PlayerDataScript implements INpcScriptHandler { } } - for (ScriptContainer script : this.scripts) { - if (script == null || script.errored || !script.hasCode()) + for (IScriptUnit script : this.scripts) { + if (script == null || script.hasErrored() || !script.hasCode()) continue; - script.run(hookName, event); } } } + @Override public boolean isClient() { return this.player != null && this.player.isClientWorld(); } + @Override public boolean getEnabled() { return ScriptController.Instance.playerScripts.enabled; } + @Override public void setEnabled(boolean bo) { ScriptController.Instance.playerScripts.enabled = bo; this.enabled = bo; } + @Override public String getLanguage() { return ScriptController.Instance.playerScripts.scriptLanguage; } + @Override public void setLanguage(String lang) { + ScriptController.Instance.playerScripts.scriptLanguage = lang; this.scriptLanguage = lang; } - public void setScripts(List list) { - this.scripts = list; - } - - public List getScripts() { - return this.scripts; - } - + @Override public String noticeString() { if (this.player == null) { return "Global script"; - } else { - BlockPos pos = new BlockPos(this.player); - return PlayerDataScript.toStringHelper(this.player).add("x", pos.getX()).add("y", pos.getY()).add("z", pos.getZ()).toString(); } + BlockPos pos = new BlockPos(this.player); + return ScriptToStringHelper.toStringHelper(this.player).add("x", pos.getX()).add("y", pos.getY()).add("z", pos.getZ()).toString(); } public IPlayer getPlayer() { @@ -199,222 +189,25 @@ public class PlayerDataScript implements INpcScriptHandler { return this.playerAPI; } + @Override public Map getConsoleText() { - if (ConfigScript.IndividualPlayerScripts) - return console; - - TreeMap map = new TreeMap<>(); - int tab = 0; - for (ScriptContainer script : this.getScripts()) { - ++tab; - - for (Entry longStringEntry : script.console.entrySet()) { - map.put(longStringEntry.getKey(), " tab " + tab + ":\n" + longStringEntry.getValue()); - } + if (ConfigScript.IndividualPlayerScripts) { + return staticConsole; } - return map; + return super.getConsoleText(); } + @Override public void clearConsole() { - if (ConfigScript.IndividualPlayerScripts) - console.clear(); - else { - for (ScriptContainer script : this.getScripts()) { - script.console.clear(); - } + if (ConfigScript.IndividualPlayerScripts) { + staticConsole.clear(); + return; } + super.clearConsole(); } - public static final class ToStringHelper { - private final String className; - private final PlayerDataScript.ToStringHelper.ValueHolder holderHead; - private PlayerDataScript.ToStringHelper.ValueHolder holderTail; - private boolean omitNullValues; - private boolean omitEmptyValues; - - private ToStringHelper(String className) { - this.holderHead = new PlayerDataScript.ToStringHelper.ValueHolder(); - this.holderTail = this.holderHead; - this.omitNullValues = false; - this.omitEmptyValues = false; - this.className = (String) Preconditions.checkNotNull(className); - } - - public PlayerDataScript.ToStringHelper omitNullValues() { - this.omitNullValues = true; - return this; - } - - public PlayerDataScript.ToStringHelper add(String name, @CheckForNull Object value) { - return this.addHolder(name, value); - } - - public PlayerDataScript.ToStringHelper add(String name, boolean value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper add(String name, char value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper add(String name, double value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper add(String name, float value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper add(String name, int value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper add(String name, long value) { - return this.addUnconditionalHolder(name, String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper addValue(@CheckForNull Object value) { - return this.addHolder(value); - } - - public PlayerDataScript.ToStringHelper addValue(boolean value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper addValue(char value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper addValue(double value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper addValue(float value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper addValue(int value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - public PlayerDataScript.ToStringHelper addValue(long value) { - return this.addUnconditionalHolder(String.valueOf(value)); - } - - private static boolean isEmpty(Object value) { - if (value instanceof CharSequence) { - return ((CharSequence) value).length() == 0; - } else if (value instanceof Collection) { - return ((Collection) value).isEmpty(); - } else if (value instanceof Map) { - return ((Map) value).isEmpty(); - } else if (value instanceof Optional) { - return !((Optional) value).isPresent(); - } else if (value instanceof OptionalInt) { - return !((OptionalInt) value).isPresent(); - } else if (value instanceof OptionalLong) { - return !((OptionalLong) value).isPresent(); - } else if (value instanceof OptionalDouble) { - return !((OptionalDouble) value).isPresent(); - } else if (value instanceof com.google.common.base.Optional) { - return !((com.google.common.base.Optional) value).isPresent(); - } else if (value.getClass().isArray()) { - return Array.getLength(value) == 0; - } else { - return false; - } - } - - public String toString() { - boolean omitNullValuesSnapshot = this.omitNullValues; - boolean omitEmptyValuesSnapshot = this.omitEmptyValues; - String nextSeparator = ""; - StringBuilder builder = (new StringBuilder(32)).append(this.className).append('{'); - for (PlayerDataScript.ToStringHelper.ValueHolder valueHolder = this.holderHead.next; valueHolder != null; valueHolder = valueHolder.next) { - Object value = valueHolder.value; - if (!(valueHolder instanceof PlayerDataScript.ToStringHelper.UnconditionalValueHolder)) { - if (value == null) { - if (omitNullValuesSnapshot) { - continue; - } - } else if (omitEmptyValuesSnapshot && isEmpty(value)) { - continue; - } - } - builder.append(nextSeparator); - nextSeparator = ", "; - if (valueHolder.name != null) { - builder.append(valueHolder.name).append('='); - } - if (value != null && value.getClass().isArray()) { - Object[] objectArray = new Object[]{value}; - String arrayString = Arrays.deepToString(objectArray); - builder.append(arrayString, 1, arrayString.length() - 1); - } else { - builder.append(value); - } - } - return builder.append('}').toString(); - } - - private PlayerDataScript.ToStringHelper.ValueHolder addHolder() { - PlayerDataScript.ToStringHelper.ValueHolder valueHolder = new PlayerDataScript.ToStringHelper.ValueHolder(); - this.holderTail = this.holderTail.next = valueHolder; - return valueHolder; - } - - private PlayerDataScript.ToStringHelper addHolder(@CheckForNull Object value) { - PlayerDataScript.ToStringHelper.ValueHolder valueHolder = this.addHolder(); - valueHolder.value = value; - return this; - } - - private PlayerDataScript.ToStringHelper addHolder(String name, @CheckForNull Object value) { - PlayerDataScript.ToStringHelper.ValueHolder valueHolder = this.addHolder(); - valueHolder.value = value; - valueHolder.name = (String) Preconditions.checkNotNull(name); - return this; - } - - private PlayerDataScript.ToStringHelper.UnconditionalValueHolder addUnconditionalHolder() { - PlayerDataScript.ToStringHelper.UnconditionalValueHolder valueHolder = new PlayerDataScript.ToStringHelper.UnconditionalValueHolder(); - this.holderTail = this.holderTail.next = valueHolder; - return valueHolder; - } - - private PlayerDataScript.ToStringHelper addUnconditionalHolder(Object value) { - PlayerDataScript.ToStringHelper.UnconditionalValueHolder valueHolder = this.addUnconditionalHolder(); - valueHolder.value = value; - return this; - } - - private PlayerDataScript.ToStringHelper addUnconditionalHolder(String name, Object value) { - PlayerDataScript.ToStringHelper.UnconditionalValueHolder valueHolder = this.addUnconditionalHolder(); - valueHolder.value = value; - valueHolder.name = (String) Preconditions.checkNotNull(name); - return this; - } - - private static final class UnconditionalValueHolder extends PlayerDataScript.ToStringHelper.ValueHolder { - private UnconditionalValueHolder() { - super(); - } - } - - private static class ValueHolder { - @CheckForNull - String name; - @CheckForNull - Object value; - @CheckForNull - PlayerDataScript.ToStringHelper.ValueHolder next; - - private ValueHolder() { - } - } - } - - public static PlayerDataScript.ToStringHelper toStringHelper(Object self) { - return new PlayerDataScript.ToStringHelper(self.getClass().getSimpleName()); + @Override + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.PLAYER); } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java b/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java new file mode 100644 index 000000000..f2c0d19d6 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/PlayerTradeData.java @@ -0,0 +1,420 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.util.VaultUtil; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.api.handler.IPlayerTradeData; +import noppes.npcs.api.handler.data.IAuctionClaim; +import noppes.npcs.config.ConfigMarket; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Stores player's trade-related data: currency and auction claims. + * This data is shared across all profile slots. + * Uses CopyOnWriteArrayList for thread-safety when adding claims asynchronously. + */ +public class PlayerTradeData implements IPlayerTradeData { + // NBT key used by trade data - excluded from per-slot profile saving + public static final String NBT_KEY = "TradeData"; + + private final PlayerData playerData; + + // ========================================= + // Currency Data + // ========================================= + + // Built-in CNPC+ currency (always saved, used as fallback) + private long balance; + private long lifetimeEarned; + private long lifetimeSpent; + + // ========================================= + // Auction Claims Data + // ========================================= + + // Thread-safe list for claims - can be modified from CNPC+ thread + private final CopyOnWriteArrayList claims = new CopyOnWriteArrayList<>(); + + public PlayerTradeData(PlayerData playerData) { + this.playerData = playerData; + this.balance = ConfigMarket.StartingBalance; + this.lifetimeEarned = 0; + this.lifetimeSpent = 0; + } + + // ========================================= + // Currency Methods + // ========================================= + + /** + * Check if Vault should be used for currency operations. + * Requires both config enabled AND Vault actually available. + */ + private boolean shouldUseVault() { + return ConfigMarket.UseVault && VaultUtil.isEnabled(); + } + + /** + * Get player name for Vault operations + */ + private String getPlayerName() { + if (playerData != null && playerData.player != null) { + return playerData.player.getCommandSenderName(); + } + return playerData != null ? playerData.playername : null; + } + + /** + * Get the current balance + */ + @Override + public long getBalance() { + if (shouldUseVault()) { + String playerName = getPlayerName(); + if (playerName != null) { + return (long) VaultUtil.getBalance(playerName); + } + } + return balance; + } + + /** + * Set the balance directly (use with caution) + */ + @Override + public void setBalance(long balance) { + if (balance < 0) { + balance = 0; + } + if (balance > ConfigMarket.MaxBalance) { + balance = ConfigMarket.MaxBalance; + } + + if (shouldUseVault()) { + String playerName = getPlayerName(); + if (playerName != null) { + VaultUtil.setBalance(playerName, balance); + return; + } + } + this.balance = balance; + } + + /** + * Add currency to balance (deposit) + * + * @param amount Amount to add + * @return true if successful, false if would exceed max balance + */ + @Override + public boolean deposit(long amount) { + if (amount <= 0) { + return false; + } + + if (shouldUseVault()) { + String playerName = getPlayerName(); + if (playerName != null) { + boolean success = VaultUtil.addMoney(playerName, amount); + if (success) { + this.lifetimeEarned += amount; + } + return success; + } + } + + // Built-in currency + long newBalance = this.balance + amount; + // Overflow protection + if (newBalance < this.balance) { + newBalance = ConfigMarket.MaxBalance; + } + // Cap at MaxBalance instead of rejecting + if (newBalance > ConfigMarket.MaxBalance) { + newBalance = ConfigMarket.MaxBalance; + } + this.balance = newBalance; + this.lifetimeEarned += amount; + return true; + } + + /** + * Remove currency from balance (withdraw) + * + * @param amount Amount to remove + * @return true if successful, false if insufficient funds + */ + @Override + public boolean withdraw(long amount) { + if (amount <= 0) { + return false; + } + + if (shouldUseVault()) { + String playerName = getPlayerName(); + if (playerName != null) { + boolean success = VaultUtil.withdrawMoney(playerName, amount); + if (success) { + this.lifetimeSpent += amount; + } + return success; + } + } + + // Built-in currency + if (this.balance < amount) { + return false; + } + this.balance -= amount; + this.lifetimeSpent += amount; + return true; + } + + /** + * Check if player can afford an amount + */ + @Override + public boolean canAfford(long amount) { + if (shouldUseVault()) { + String playerName = getPlayerName(); + if (playerName != null) { + return VaultUtil.has(playerName, amount); + } + } + return this.balance >= amount; + } + + /** + * Get lifetime earned currency + */ + @Override + public long getLifetimeEarned() { + return lifetimeEarned; + } + + /** + * Get lifetime spent currency + */ + @Override + public long getLifetimeSpent() { + return lifetimeSpent; + } + + /** + * Format the balance for display + */ + @Override + public String formatBalance() { + if (shouldUseVault()) { + return VaultUtil.format(getBalance()); + } + return formatAmount(this.balance); + } + + /** + * Format an amount for display + */ + public static String formatAmount(long amount) { + return String.format("%,d %s", amount, ConfigMarket.CurrencyName); + } + + /** + * Check if Vault is being used for currency operations. + * Returns true only if config is enabled AND Vault is actually available. + */ + @Override + public boolean isUsingVault() { + return shouldUseVault(); + } + + /** + * Check if Vault is configured (regardless of availability) + */ + public boolean isVaultConfigured() { + return ConfigMarket.UseVault; + } + + // ========================================= + // Auction Claims Methods + // ========================================= + + /** + * Add a claim to this player's pending claims. + * Thread-safe - can be called from any thread. + */ + 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); + } + } + + /** + * Get all unclaimed claims for this player (internal use). + * Returns a copy of the list for safe iteration. + */ + public List getClaimsList() { + List result = new ArrayList<>(); + for (AuctionClaim claim : claims) { + if (!claim.claimed) { + result.add(claim); + } + } + return result; + } + + /** + * Get all unclaimed claims for this player (API). + */ + @Override + public IAuctionClaim[] getClaims() { + List result = getClaimsList(); + return result.toArray(new IAuctionClaim[0]); + } + + /** + * Get a specific claim by ID (internal use). + * Synchronized to pair with claimAndRemove for thread safety. + */ + public synchronized AuctionClaim getClaimInternal(String claimId) { + for (AuctionClaim claim : claims) { + if (claim.id.equals(claimId) && !claim.claimed) { + return claim; + } + } + return null; + } + + /** + * Get a specific claim by ID (API). + */ + @Override + public IAuctionClaim getClaim(String claimId) { + return getClaimInternal(claimId); + } + + /** + * Mark a claim as claimed and remove it. + * Synchronized to prevent double-claim from concurrent threads. + */ + public synchronized boolean claimAndRemove(String claimId) { + for (AuctionClaim claim : claims) { + if (claim.id.equals(claimId) && !claim.claimed) { + claim.claimed = true; + claims.remove(claim); + return true; + } + } + return false; + } + + /** + * Get count of unclaimed claims. + */ + @Override + public int getClaimCount() { + int count = 0; + for (AuctionClaim claim : claims) { + if (!claim.claimed) { + count++; + } + } + return count; + } + + /** + * Check if player has any unclaimed claims. + */ + @Override + public boolean hasClaims() { + for (AuctionClaim claim : claims) { + if (!claim.claimed) { + return true; + } + } + return false; + } + + /** + * Process expired claims - removes claims older than expiration days. + * Returns number of claims removed. + */ + public int processExpiredClaims() { + int expirationDays = ConfigMarket.ClaimExpirationDays; + List expired = new ArrayList<>(); + for (AuctionClaim claim : claims) { + if (!claim.claimed && claim.isExpired(expirationDays)) { + expired.add(claim); + } + } + if (!expired.isEmpty()) { + claims.removeAll(expired); + } + return expired.size(); + } + + // ========================================= + // NBT Serialization + // ========================================= + + public void readFromNBT(NBTTagCompound compound) { + NBTTagCompound tradeData = compound.getCompoundTag(NBT_KEY); + if (tradeData == null || tradeData.hasNoTags()) { + // No trade data found, use defaults + this.balance = ConfigMarket.StartingBalance; + this.lifetimeEarned = 0; + this.lifetimeSpent = 0; + claims.clear(); + return; + } + + // Currency + if (tradeData.hasKey("CurrencyBalance")) { + this.balance = tradeData.getLong("CurrencyBalance"); + } else { + this.balance = ConfigMarket.StartingBalance; + } + this.lifetimeEarned = tradeData.getLong("CurrencyLifetimeEarned"); + this.lifetimeSpent = tradeData.getLong("CurrencyLifetimeSpent"); + + // Claims + claims.clear(); + if (tradeData.hasKey("AuctionClaims")) { + NBTTagList claimsList = tradeData.getTagList("AuctionClaims", 10); + for (int i = 0; i < claimsList.tagCount(); i++) { + AuctionClaim claim = AuctionClaim.fromNBT(claimsList.getCompoundTagAt(i)); + if (!claim.claimed) { + claims.add(claim); + } + } + } + } + + public void writeToNBT(NBTTagCompound compound) { + NBTTagCompound tradeData = new NBTTagCompound(); + + // Currency - always save built-in currency data (preserved even when using Vault) + tradeData.setLong("CurrencyBalance", this.balance); + tradeData.setLong("CurrencyLifetimeEarned", this.lifetimeEarned); + tradeData.setLong("CurrencyLifetimeSpent", this.lifetimeSpent); + + // Claims + NBTTagList claimsList = new NBTTagList(); + for (AuctionClaim claim : claims) { + if (!claim.claimed) { + claimsList.appendTag(claim.writeToNBT(new NBTTagCompound())); + } + } + tradeData.setTag("AuctionClaims", claimsList); + + compound.setTag(NBT_KEY, tradeData); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/Quest.java b/src/main/java/noppes/npcs/controllers/data/Quest.java index 1f9097d8a..c2b9ac397 100644 --- a/src/main/java/noppes/npcs/controllers/data/Quest.java +++ b/src/main/java/noppes/npcs/controllers/data/Quest.java @@ -178,19 +178,50 @@ 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 (profile != null) { + Long questTime = profile.sharedQuestTimestamps.get(this.id); + if (questTime == null) return 0L; + return calculateRemainingCooldown(player, questTime); } - return timeRemaining; } 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/RecipeScript.java b/src/main/java/noppes/npcs/controllers/data/RecipeScript.java index b94acfbc6..c2b8ba551 100644 --- a/src/main/java/noppes/npcs/controllers/data/RecipeScript.java +++ b/src/main/java/noppes/npcs/controllers/data/RecipeScript.java @@ -1,101 +1,51 @@ package noppes.npcs.controllers.data; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.Event; -import io.netty.buffer.ByteBuf; -import kamkeel.npcs.util.ByteBufUtils; +import kamkeel.npcs.network.packets.request.script.RecipeScriptPacket; import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.common.util.Constants; -import noppes.npcs.config.ConfigScript; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; -import noppes.npcs.controllers.ScriptController; +import noppes.npcs.constants.ScriptContext; +import noppes.npcs.janino.EventJaninoScript; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +/** + * Script handler for Recipe scripts (both carpentry and anvil). + * Manages a single script container for recipe hooks (pre, post). + */ +public class RecipeScript extends SingleScriptHandler implements IScriptHandlerPacket { -public class RecipeScript implements INpcScriptHandler { - public ScriptContainer container; - public String scriptLanguage = "ECMAScript"; - public boolean enabled = false; + /** + * The recipe ID for packet communication. -1 if not bound. + */ + private int recipeId = -1; - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setString("ScriptLanguage", scriptLanguage); - compound.setBoolean("ScriptEnabled", enabled); - if (container != null) - compound.setTag("ScriptContent", container.writeToNBT(new NBTTagCompound())); - return compound; + /** + * Whether this is an anvil recipe (vs carpentry). + */ + private boolean anvil = false; + + /** + * Create an unbound RecipeScript (for server-side use). + */ + public RecipeScript() { } - public RecipeScript readFromNBT(NBTTagCompound compound) { - scriptLanguage = compound.getString("ScriptLanguage"); - enabled = compound.getBoolean("ScriptEnabled"); - if (compound.hasKey("ScriptContent", Constants.NBT.TAG_COMPOUND)) { - container = new ScriptContainer(this); - container.readFromNBT(compound.getCompoundTag("ScriptContent")); - } - return this; - } - - public boolean isEnabled() { - return this.enabled && ScriptController.HasStart && container != null && ConfigScript.ScriptingEnabled; + /** + * Create a RecipeScript bound to a specific recipe (for GUI use). + * + * @param recipeId The ID of the recipe + * @param anvil true for anvil recipe, false for carpentry recipe + */ + public RecipeScript(int recipeId, boolean anvil) { + this.recipeId = recipeId; + this.anvil = anvil; } @Override - public void callScript(EnumScriptType type, Event event) { - this.callScript(type.function, event); + public ScriptContext getContext() { + return ScriptContext.RECIPE; } @Override - public void callScript(String s, Event event) { - if (!this.isEnabled()) - return; - container.run(s, event); - } - - @Override - public boolean isClient() { - return FMLCommonHandler.instance().getEffectiveSide().isClient(); - } - - @Override - public boolean getEnabled() { - return this.enabled; - } - - @Override - public void setEnabled(boolean b) { - this.enabled = b; - } - - @Override - public String getLanguage() { - return this.scriptLanguage; - } - - @Override - public void setLanguage(String s) { - this.scriptLanguage = s; - } - - @Override - public void setScripts(List list) { - if (list == null || list.isEmpty()) { - container = null; - return; - } - container = list.get(0); - } - - @Override - public List getScripts() { - if (container == null) - return new ArrayList<>(); - return Collections.singletonList(container); + public IScriptUnit createJaninoScriptUnit() { + return new EventJaninoScript(ScriptContext.RECIPE); } @Override @@ -104,47 +54,15 @@ public class RecipeScript implements INpcScriptHandler { } @Override - public Map getConsoleText() { - TreeMap map = new TreeMap<>(); - int tab = 0; - for (ScriptContainer script : this.getScripts()) { - ++tab; - for (Map.Entry entry : script.console.entrySet()) { - map.put(entry.getKey(), " tab " + tab + ":\n" + entry.getValue()); - } - } - return map; + public void requestData() { + if (recipeId >= 0) + RecipeScriptPacket.Get(anvil, recipeId); } @Override - public void clearConsole() { - for (ScriptContainer script : this.getScripts()) { - script.console.clear(); - } - } - - public void saveScript(ByteBuf buffer) throws IOException { - int tab = buffer.readInt(); - int totalScripts = buffer.readInt(); - if (totalScripts == 0) - this.container = null; - if (tab == 0) { - NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer); - ScriptContainer script = new ScriptContainer(this); - script.readFromNBT(tabCompound); - this.container = script; - } else { - NBTTagCompound compound = ByteBufUtils.readNBT(buffer); - this.setLanguage(compound.getString("ScriptLanguage")); - if (!ScriptController.Instance.languages.containsKey(this.getLanguage())) { - if (!ScriptController.Instance.languages.isEmpty()) { - this.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]); - } else { - this.setLanguage("ECMAScript"); - } - } - this.setEnabled(compound.getBoolean("ScriptEnabled")); - } + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (recipeId >= 0) + RecipeScriptPacket.Save(anvil, recipeId, index, totalCount, nbt); } public enum ScriptType { diff --git a/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java new file mode 100644 index 000000000..096f8f381 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java @@ -0,0 +1,78 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.eventhandler.Event; +import noppes.npcs.CustomNpcs; +import noppes.npcs.controllers.ScriptController; + +import java.util.ArrayList; +import java.util.List; + +public abstract class ScriptHandler implements IScriptHandler { + public List scripts = new ArrayList<>(); + protected String scriptLanguage = "ECMAScript"; + protected boolean enabled = false; + protected long lastInited = -1; + + protected boolean canRunScripts() { + return enabled && ScriptController.HasStart && CustomNpcs.proxy.isScriptingEnabled() && scripts != null && !scripts.isEmpty(); + } + + @Override + public void callScript(String hookName, Event event) { + if (!canRunScripts()) + return; + + if (ScriptController.Instance.lastLoaded > lastInited) { + lastInited = ScriptController.Instance.lastLoaded; + for (IScriptUnit script : scripts) { + if (script != null) + script.setErrored(false); + } + } + + for (IScriptUnit script : scripts) { + if (script == null || script.hasErrored() || !script.hasCode()) + continue; + script.run(hookName, event); + } + } + + @Override + public boolean getEnabled() { + return enabled; + } + + @Override + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public String getLanguage() { + return scriptLanguage; + } + + @Override + public void setLanguage(String language) { + this.scriptLanguage = language; + } + + public void setScripts(List list) { + this.scripts = list; + } + + public List getScripts() { + return this.scripts; + } + + public void clear() { + this.scripts = new ArrayList<>(); + } + + /** + * Reset the lastInited timestamp to force re-initialization on next script call. + */ + public void resetLastInited() { + this.lastInited = -1; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java new file mode 100644 index 000000000..854e77941 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java @@ -0,0 +1,153 @@ +package noppes.npcs.controllers.data; + +import cpw.mods.fml.common.eventhandler.Event; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.Constants; +import noppes.npcs.CustomNpcs; +import noppes.npcs.controllers.ScriptController; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Base class for script handlers that manage a single script container. + * Provides shared NBT/ByteBuf serialization and packet handling. + *

+ * Subclasses should: + * - Store their parent object (e.g., CustomEffect, LinkedItem) + * - Override getHookContext() to return the appropriate context string + * - Override getContext() if needed (default is GLOBAL) + * - Override requestData() and sendSavePacket() for packet communication + */ +public abstract class SingleScriptHandler extends ScriptHandler { + public IScriptUnit container; + + @Override + public boolean isSingleContainer() { + return true; + } + + protected boolean canRunScripts() { + return enabled && ScriptController.HasStart && CustomNpcs.proxy.isScriptingEnabled() && container != null; + } + + @Override + public void callScript(String hookName, Event event) { + if (!canRunScripts()) { + return; + } + container.run(hookName, event); + } + + @Override + public void setScripts(List list) { + if (list == null || list.isEmpty()) { + container = null; + this.scripts = new ArrayList<>(); + } else { + container = list.get(0); + this.scripts = new ArrayList<>(1); + this.scripts.add(container); + } + } + + @Override + public List getScripts() { + if (container == null) + return new ArrayList<>(); + + return Collections.singletonList(container); + } + + public void addScriptUnit(IScriptUnit unit) { + this.container = unit; + this.scripts.clear(); + if (unit != null) + this.scripts.add(unit); + } + + public void replaceScriptUnit(int index, IScriptUnit unit) { + this.container = unit; + this.scripts.clear(); + if (unit != null) + this.scripts.add(unit); + } + + public void removeScriptUnit(int index) { + this.container = null; + this.scripts.clear(); + } + + /** + * Write script data to NBT. + * Uses standard keys: ScriptLanguage, ScriptEnabled, ScriptContent + */ + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setString("ScriptLanguage", scriptLanguage); + compound.setBoolean("ScriptEnabled", enabled); + + if (container != null) { + compound.setTag("ScriptContent", container.writeToNBT(new NBTTagCompound())); + } + return compound; + } + + /** + * Read script data from NBT. + * Uses standard keys: ScriptLanguage, ScriptEnabled, ScriptContent + */ + public void readFromNBT(NBTTagCompound compound) { + scriptLanguage = compound.getString("ScriptLanguage"); + enabled = compound.getBoolean("ScriptEnabled"); + + if (compound.hasKey("ScriptContent", Constants.NBT.TAG_COMPOUND)) { + container = IScriptUnit.createFromNBT(compound.getCompoundTag("ScriptContent"), this); + } + } + + /** + * Save script data from a ByteBuf packet. + * Handles the tab/totalScripts protocol used by script packets. + *

+ * Protocol: + * - tab == 0: Script content NBT follows + * - tab != 0 (typically -1): Script metadata (language, enabled) follows + */ + public void saveScript(ByteBuf buffer) throws IOException { + int tab = buffer.readInt(); + int totalScripts = buffer.readInt(); + + if (totalScripts == 0) { + this.container = null; + } + + if (tab == 0) { + // Script content + NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer); + this.container = IScriptUnit.createFromNBT(tabCompound, this); + } else { + // Metadata (language, enabled) + NBTTagCompound compound = ByteBufUtils.readNBT(buffer); + this.setLanguage(compound.getString("ScriptLanguage")); + normalizeLanguage(); + this.setEnabled(compound.getBoolean("ScriptEnabled")); + } + } + + /** + * Normalize the language to a valid one if the current language is not available. + */ + protected void normalizeLanguage() { + if (this.getLanguage() == null || this.getLanguage().isEmpty()) { + if (!ScriptController.Instance.languages.isEmpty()) { + this.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]); + } else { + this.setLanguage("ECMAScript"); + } + } + } +} 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/TagMap.java b/src/main/java/noppes/npcs/controllers/data/TagMap.java index e4c0ad57f..2205d96fd 100644 --- a/src/main/java/noppes/npcs/controllers/data/TagMap.java +++ b/src/main/java/noppes/npcs/controllers/data/TagMap.java @@ -13,10 +13,18 @@ import java.util.UUID; public class TagMap { public int cloneTab; + public String cloneFolder; public HashMap> tagMap; public TagMap(int tab) { this.cloneTab = tab; + this.cloneFolder = null; + this.tagMap = new HashMap>(); + } + + public TagMap(String folder) { + this.cloneTab = -1; + this.cloneFolder = folder; this.tagMap = new HashMap>(); } 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/TraderStock.java b/src/main/java/noppes/npcs/controllers/data/TraderStock.java new file mode 100644 index 000000000..85e76ec02 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/TraderStock.java @@ -0,0 +1,361 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.constants.EnumStockReset; + +import java.util.HashMap; +import java.util.Map; + +/** + * Manages trader stock system including: + * - Per-slot stock limits + * - Per-player vs per-server stock tracking + * - Automatic stock reset timers + */ +public class TraderStock { + // Stock configuration + public boolean enableStock = false; + public boolean perPlayer = false; // false = per-server, true = per-player + + // Reset configuration (mirrors Quest cooldown system) + public EnumStockReset resetType = EnumStockReset.NONE; + public long customResetTime = 0; // For MCCUSTOM/RLCUSTOM types (in ticks or ms) + + // Stock quantities per slot (max stock, -1 = unlimited) + public int[] maxStock = new int[18]; + + // Current stock (per-server mode) + public int[] currentStock = new int[18]; + public long lastResetTime = 0; + + // Per-player stock tracking + public HashMap playerStock = new HashMap<>(); + + public TraderStock() { + for (int i = 0; i < 18; i++) { + maxStock[i] = -1; // -1 = unlimited + currentStock[i] = -1; + } + } + + /** + * Get available stock for a slot + * + * @param slot The slot index + * @param playerName The player name (for per-player mode) + * @return Available stock count, or Integer.MAX_VALUE if unlimited + */ + public synchronized int getAvailableStock(int slot, String playerName) { + if (!enableStock || slot < 0 || slot >= 18 || maxStock[slot] < 0) { + return Integer.MAX_VALUE; // Unlimited + } + + if (perPlayer) { + PlayerTraderStock pStock = playerStock.get(playerName); + if (pStock == null) { + return maxStock[slot]; // Not purchased yet + } + return pStock.getStock(slot, maxStock[slot]); + } + + if (currentStock[slot] < 0) { + return maxStock[slot]; + } + return Math.max(0, currentStock[slot]); + } + + /** + * Check if stock is available for purchase + */ + public boolean hasStock(int slot, String playerName, int amount) { + return getAvailableStock(slot, playerName) >= amount; + } + + /** + * Consume stock when purchase is made + * + * @return true if successful, false if insufficient stock + */ + public synchronized boolean consumeStock(int slot, String playerName, int amount) { + if (!enableStock || slot < 0 || slot >= 18 || maxStock[slot] < 0) { + return true; // Unlimited, always succeeds + } + + if (perPlayer) { + PlayerTraderStock pStock = playerStock.computeIfAbsent( + playerName, k -> new PlayerTraderStock()); + return pStock.consumeStock(slot, maxStock[slot], amount); + } + + if (currentStock[slot] < 0) { + currentStock[slot] = maxStock[slot]; + } + if (currentStock[slot] >= amount) { + currentStock[slot] -= amount; + return true; + } + return false; + } + + /** + * Check if stock should reset based on current time + * + * @param currentTime Current MC world time (ticks) or real time (ms) depending on reset type + */ + public boolean shouldReset(long currentTime) { + if (resetType == EnumStockReset.NONE) { + return false; + } + + long elapsed = currentTime - lastResetTime; + long resetInterval = getResetInterval(); + + return elapsed >= resetInterval; + } + + /** + * Reset all stock to max values + * + * @param currentTime Current time to record as reset time + */ + public synchronized void resetStock(long currentTime) { + lastResetTime = currentTime; + + // Reset per-server stock + for (int i = 0; i < 18; i++) { + currentStock[i] = maxStock[i]; + } + + // Clear per-player stock (cleanup per-player data on reset) + playerStock.clear(); + } + + /** + * Get reset interval based on reset type + * + * @return Interval in ticks (MC time) or milliseconds (real time) + */ + public long getResetInterval() { + switch (resetType) { + case MCDAILY: + return 24000; // 1 MC day in ticks + case MCWEEKLY: + return 168000; // 7 MC days in ticks + case MCCUSTOM: + return customResetTime; // Custom ticks + case RLDAILY: + return 86400000L; // 24 hours in ms + case RLWEEKLY: + return 604800000L; // 7 days in ms + case RLCUSTOM: + return customResetTime; // Custom ms + default: + return Long.MAX_VALUE; + } + } + + /** + * Get time until next reset + * + * @param currentTime Current time + * @return Time remaining until reset, or -1 if no reset scheduled + */ + public long getTimeUntilReset(long currentTime) { + if (resetType == EnumStockReset.NONE) { + return -1; + } + long elapsed = currentTime - lastResetTime; + long interval = getResetInterval(); + return Math.max(0, interval - elapsed); + } + + /** + * Format time until reset for display + * + * @param currentTime Current time + * @return Formatted string like "2 hours" or "1 day, 5 hours" + */ + public String getTimeUntilResetFormatted(long currentTime) { + long remaining = getTimeUntilReset(currentTime); + if (remaining < 0) { + return ""; + } + + if (resetType.isRealTime()) { + // Convert ms to readable format + long hours = remaining / 3600000L; + long days = hours / 24; + hours = hours % 24; + + if (days > 0) { + return days + " day" + (days != 1 ? "s" : "") + + (hours > 0 ? ", " + hours + " hour" + (hours != 1 ? "s" : "") : ""); + } else if (hours > 0) { + return hours + " hour" + (hours != 1 ? "s" : ""); + } else { + long minutes = remaining / 60000L; + return minutes + " minute" + (minutes != 1 ? "s" : ""); + } + } else { + // Convert ticks to MC time format + long mcHours = remaining / 1000; // 1000 ticks = 1 MC hour + long mcDays = mcHours / 24; + mcHours = mcHours % 24; + + if (mcDays > 0) { + return mcDays + " MC day" + (mcDays != 1 ? "s" : "") + + (mcHours > 0 ? ", " + mcHours + " MC hour" + (mcHours != 1 ? "s" : "") : ""); + } else { + return mcHours + " MC hour" + (mcHours != 1 ? "s" : ""); + } + } + } + + /** + * Set stock for a specific slot + */ + public void setMaxStock(int slot, int amount) { + if (slot >= 0 && slot < 18) { + maxStock[slot] = amount; + if (currentStock[slot] < 0 || currentStock[slot] > amount) { + currentStock[slot] = amount; + } + } + } + + /** + * Validate and clamp all current stock values to not exceed max stock. + * Should be called when trader GUI opens to ensure consistency. + * + * @return true if any stock was clamped + */ + public boolean validateStock() { + boolean changed = false; + for (int i = 0; i < 18; i++) { + if (maxStock[i] >= 0) { + // Has a max limit + if (currentStock[i] < 0) { + // Not initialized, set to max + currentStock[i] = maxStock[i]; + changed = true; + } else if (currentStock[i] > maxStock[i]) { + // Exceeds max, clamp down + currentStock[i] = maxStock[i]; + changed = true; + } + } + } + + // Also validate per-player stock + for (PlayerTraderStock pStock : playerStock.values()) { + for (int i = 0; i < 18; i++) { + if (maxStock[i] >= 0) { + int available = pStock.getStock(i, maxStock[i]); + if (available < 0) { + // Over-purchased somehow, reset + pStock.purchasedAmounts[i] = maxStock[i]; + changed = true; + } + } + } + } + return changed; + } + + // ==================== NBT Serialization ==================== + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("EnableStock", enableStock); + compound.setBoolean("PerPlayer", perPlayer); + compound.setInteger("ResetType", resetType.ordinal()); + compound.setLong("CustomResetTime", customResetTime); + compound.setIntArray("MaxStock", maxStock); + compound.setIntArray("CurrentStock", currentStock); + compound.setLong("LastResetTime", lastResetTime); + + // Save per-player stock + NBTTagList playerList = new NBTTagList(); + for (Map.Entry entry : playerStock.entrySet()) { + NBTTagCompound playerTag = new NBTTagCompound(); + playerTag.setString("Player", entry.getKey()); + entry.getValue().writeToNBT(playerTag); + playerList.appendTag(playerTag); + } + compound.setTag("PlayerStock", playerList); + + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + enableStock = compound.getBoolean("EnableStock"); + perPlayer = compound.getBoolean("PerPlayer"); + + int resetOrdinal = compound.getInteger("ResetType"); + if (resetOrdinal >= 0 && resetOrdinal < EnumStockReset.values().length) { + resetType = EnumStockReset.values()[resetOrdinal]; + } + + customResetTime = compound.getLong("CustomResetTime"); + + int[] loadedMax = compound.getIntArray("MaxStock"); + int[] loadedCurrent = compound.getIntArray("CurrentStock"); + + if (loadedMax != null && loadedMax.length == 18) { + maxStock = loadedMax; + } + if (loadedCurrent != null && loadedCurrent.length == 18) { + currentStock = loadedCurrent; + } + + lastResetTime = compound.getLong("LastResetTime"); + + // Load per-player stock + playerStock.clear(); + NBTTagList playerList = compound.getTagList("PlayerStock", 10); + for (int i = 0; i < playerList.tagCount(); i++) { + NBTTagCompound playerTag = playerList.getCompoundTagAt(i); + String playerName = playerTag.getString("Player"); + PlayerTraderStock pStock = new PlayerTraderStock(); + pStock.readFromNBT(playerTag); + playerStock.put(playerName, pStock); + } + } + + // ==================== Inner Class for Per-Player Stock ==================== + + public static class PlayerTraderStock { + public int[] purchasedAmounts = new int[18]; + + public PlayerTraderStock() { + for (int i = 0; i < 18; i++) { + purchasedAmounts[i] = 0; + } + } + + public int getStock(int slot, int maxStock) { + if (slot < 0 || slot >= 18) return 0; + return Math.max(0, maxStock - purchasedAmounts[slot]); + } + + public boolean consumeStock(int slot, int maxStock, int amount) { + if (slot < 0 || slot >= 18) return false; + if (getStock(slot, maxStock) >= amount) { + purchasedAmounts[slot] += amount; + return true; + } + return false; + } + + public void writeToNBT(NBTTagCompound compound) { + compound.setIntArray("Purchased", purchasedAmounts); + } + + public void readFromNBT(NBTTagCompound compound) { + int[] loaded = compound.getIntArray("Purchased"); + if (loaded != null && loaded.length == 18) { + purchasedAmounts = loaded; + } + } + } +} 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 729603019..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; @@ -274,10 +275,9 @@ public class Action implements IAction { // return this; // } - /////////////////////////////////////////////////// - ////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// /////////////////////////////////////////////// // Handling - @Override public IAction start() { manager.start(); @@ -345,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); } @@ -360,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(); } @@ -375,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); } @@ -405,10 +418,10 @@ public class Action implements IAction { public String toString() { return String.format("%s [queue='%s', scheduled=%s, done=%s, paused=%s, updateEvery=%s, duration=%d/%d, count=%d/%d, threaded=%s]", getIdentifier(), getQueueName(), isScheduled, done, isPaused(), updateEveryXTick, duration, maxDuration, count, maxCount, isThreaded); } - /////////////////////////////////////////////////// - ////////////////////////////////////////////////// - // Thread + /// //////////////////////////////////////////////// + /// /////////////////////////////////////////////// + // Thread @Override public IAction threadify() { if (!isThreaded) { @@ -469,10 +482,9 @@ public class Action implements IAction { return startAfterTicks > 0; } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Sequential - @Override public IAction getNext() { if (queue == null) @@ -606,10 +618,9 @@ public class Action implements IAction { } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Parallels - @Override public IAction parallel(IAction act) { if (unscheduledList != null) @@ -658,10 +669,9 @@ public class Action implements IAction { return parallel(manager.create(name, maxDuration, delay, t)); } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Conditionals - @Override public IConditionalAction conditional(IConditionalAction after) { if (unscheduledList != null) diff --git a/src/main/java/noppes/npcs/controllers/data/action/ActionManager.java b/src/main/java/noppes/npcs/controllers/data/action/ActionManager.java index c36aa04a9..9cdaf4e57 100644 --- a/src/main/java/noppes/npcs/controllers/data/action/ActionManager.java +++ b/src/main/java/noppes/npcs/controllers/data/action/ActionManager.java @@ -117,10 +117,9 @@ public class ActionManager implements IActionManager { // return false; // } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Creators - @Override public IAction create(String name) { return new Action(this, name); @@ -186,10 +185,9 @@ public class ActionManager implements IActionManager { return new ConditionalAction(this, name, condition, task, terminateWhen, onTermination); } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Queues - @Override public IActionQueue createQueue(String name) { return createQueue(name, false); @@ -237,10 +235,9 @@ public class ActionManager implements IActionManager { return true; } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Sequential - @Override public IActionQueue getSequentialQueue() { return sequentialQueue; @@ -299,10 +296,9 @@ public class ActionManager implements IActionManager { return sequentialQueue.scheduleActionAt(index, action); } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Parallels - @Override public IActionQueue getParallelQueue() { return parallelQueue; @@ -345,7 +341,7 @@ public class ActionManager implements IActionManager { @Override public IAction scheduleParallel(String name, int delay, Consumer task) { - return parallelQueue.schedule(name,delay, task); + return parallelQueue.schedule(name, delay, task); } @Override @@ -353,10 +349,9 @@ public class ActionManager implements IActionManager { return parallelQueue.schedule(name, maxDuration, delay, task); } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Conditionals - @Override public IActionQueue getConditionalQueue() { return conditionalQueue; @@ -403,10 +398,9 @@ public class ActionManager implements IActionManager { return schedule(new ConditionalAction(this, name, condition, task, terminateWhen, onTermination)); } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Handling - @Override public IActionQueue[] getAllQueues() { ArrayList allQueues = new ArrayList<>(); diff --git a/src/main/java/noppes/npcs/controllers/data/action/ActionQueue.java b/src/main/java/noppes/npcs/controllers/data/action/ActionQueue.java index 0b3d0b483..332adab39 100644 --- a/src/main/java/noppes/npcs/controllers/data/action/ActionQueue.java +++ b/src/main/java/noppes/npcs/controllers/data/action/ActionQueue.java @@ -125,10 +125,9 @@ public class ActionQueue implements IActionQueue { return this; } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Schedulers - @Override public IAction schedule(IAction action) { Action act = (Action) action; @@ -203,10 +202,9 @@ public class ActionQueue implements IActionQueue { return action; } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Queue Data - @Override public boolean hasActiveTasks() { return !queue.isEmpty(); @@ -276,10 +274,9 @@ public class ActionQueue implements IActionQueue { return false; } - /////////////////////////////////////////////////// - /////////////////////////////////////////////////// + /// //////////////////////////////////////////////// + /// //////////////////////////////////////////////// // Handling - public boolean finish(Action a) { if (a.isDone()) { if (a.onDone != null) 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 b1a3c44f3..e1ff3544d 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 5b43aa68a..77927d4b1 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; @@ -67,13 +70,14 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import net.minecraftforge.common.ForgeHooks; 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; import noppes.npcs.CustomNpcs; import noppes.npcs.DataAI; +import noppes.npcs.DataAbilities; import noppes.npcs.DataAdvanced; import noppes.npcs.DataDisplay; import noppes.npcs.DataInventory; @@ -95,12 +99,12 @@ import noppes.npcs.ai.EntityAIDodgeShoot; import noppes.npcs.ai.EntityAIFindShade; import noppes.npcs.ai.EntityAIFollow; import noppes.npcs.ai.EntityAIJob; +import noppes.npcs.ai.EntityAILeapAtTargetNpc; import noppes.npcs.ai.EntityAILook; import noppes.npcs.ai.EntityAIMoveIndoors; import noppes.npcs.ai.EntityAIMovingPath; import noppes.npcs.ai.EntityAIOrbitTarget; import noppes.npcs.ai.EntityAIPanic; -import noppes.npcs.ai.EntityAILeapAtTargetNpc; import noppes.npcs.ai.EntityAIPounceTarget; import noppes.npcs.ai.EntityAIRangedAttack; import noppes.npcs.ai.EntityAIReturn; @@ -154,8 +158,8 @@ import noppes.npcs.roles.JobFollower; import noppes.npcs.roles.JobInterface; import noppes.npcs.roles.RoleCompanion; import noppes.npcs.roles.RoleFollower; -import noppes.npcs.roles.RoleMount; import noppes.npcs.roles.RoleInterface; +import noppes.npcs.roles.RoleMount; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.entity.ScriptNpc; import noppes.npcs.scripted.event.NpcEvent; @@ -183,6 +187,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti public DataScript script; public DataTransform transform; public DataTimers timers; + public DataAbilities abilities; public CombatHandler combatHandler = new CombatHandler(this); public ActionManager actionManager = new ActionManager(); @@ -249,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); @@ -271,6 +276,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti transform = new DataTransform(this); script = new DataScript(this); timers = new DataTimers(this); + abilities = new DataAbilities(this); this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(stats.maxHealth); @@ -306,6 +312,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti @Override public void onUpdate() { super.onUpdate(); + + // Re-apply locks after super.onUpdate() to override body rotation smoothing + // in EntityLivingBase.onUpdate() (func_110146_f) which runs AFTER onLivingUpdate() + // and overwrites renderYawOffset, causing a visible twitch each frame. + abilities.applyRotationControl(); + abilities.applyLockedPosition(); + if (!isRemote()) { if (this.ticksExisted % 10 == 0) { EventHooks.onNPCUpdate(this); @@ -375,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; } @@ -460,10 +475,18 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti onCollide(); actionManager.tick(); + abilities.tick(); } 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(); @@ -478,6 +501,10 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti super.onLivingUpdate(); + // Apply locks after super.onLivingUpdate() to override AI/physics changes + abilities.applyRotationControl(); + abilities.applyLockedPosition(); + handleMountRiderState(); if (worldObj.isRemote) { @@ -638,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(); @@ -664,6 +694,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti if (entity instanceof EntityLivingBase) attackingEntity = (EntityLivingBase) entity; + if (faction.isPassive) + return false; + if (attackingEntity != null && attackingEntity == getOwner()) return false; else if (attackingEntity instanceof EntityNPCInterface) { @@ -682,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; @@ -1026,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) { @@ -1179,6 +1204,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti script.readEventsFromNBT(compound); timers.readFromNBT(compound); advanced.readToNBT(compound); + abilities.readFromNBT(compound); if (advanced.role != EnumRoleType.None && roleInterface != null) roleInterface.readFromNBT(compound); if (advanced.job != EnumJobType.None && jobInterface != null) @@ -1198,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 @@ -1211,6 +1237,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti script.writeEventsToNBT(compound); timers.writeToNBT(compound); advanced.writeToNBT(compound); + abilities.writeToNBT(compound); if (advanced.role != EnumRoleType.None && roleInterface != null) roleInterface.writeToNBT(compound); if (advanced.job != EnumJobType.None && jobInterface != null) @@ -1258,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); } @@ -1398,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; @@ -1685,7 +1733,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti } /** - * 1: walking, 2:interacting, 4:attacking, 8:killed + * 1: walking, 2:interacting, 4:attacking, 8:killed, 16:rotationLocked */ public boolean getBoolFlag(int id) { return (dataWatcher.getWatchableObjectInt(15) & id) != 0; @@ -1800,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()); @@ -1831,6 +1884,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti try { readSpawnData(ByteBufUtils.readNBT(buf)); } catch (IOException e) { + e.printStackTrace(); } } @@ -1840,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"); @@ -1926,6 +1995,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti if (NPCMountUtil.isFlyingMountWithFlightEnabled(this)) { return; } + // Skip fall damage during abilities that control NPC movement (e.g., Slam leap) + if (this.abilities != null && this.abilities.isExecutingAbility() + && this.abilities.getCurrentAbility() != null + && this.abilities.getCurrentAbility().hasAbilityMovement()) { + this.fallDistance = 0; + return; + } if (!this.stats.noFallDamage) super.fall(distance); } @@ -2144,7 +2220,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti protected boolean handleMountedMovement(float strafe, float forward) { return NPCMountUtil.handleMountedMovement(this, mountState, strafe, forward); } - + public void performMountedMovement(float strafe, float forward, float moveSpeed) { this.moveStrafing = strafe; this.moveForward = forward; 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/ItemElementalStaff.java b/src/main/java/noppes/npcs/items/ItemElementalStaff.java index 45f45c17f..03384f76a 100644 --- a/src/main/java/noppes/npcs/items/ItemElementalStaff.java +++ b/src/main/java/noppes/npcs/items/ItemElementalStaff.java @@ -9,13 +9,14 @@ import noppes.npcs.CustomItems; import noppes.npcs.CustomNpcs; import noppes.npcs.constants.EnumNpcToolMaterial; -import java.awt.*; +import java.awt.Color; import java.util.List; public class ItemElementalStaff extends ItemStaff { public ItemElementalStaff(int par1, EnumNpcToolMaterial material) { super(par1, material); setHasSubtypes(true); + this.color = OrbColor.GENERIC; } @Override 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/ItemNpcScripter.java b/src/main/java/noppes/npcs/items/ItemNpcScripter.java index 5c5734140..4d503d97a 100644 --- a/src/main/java/noppes/npcs/items/ItemNpcScripter.java +++ b/src/main/java/noppes/npcs/items/ItemNpcScripter.java @@ -41,6 +41,7 @@ public class ItemNpcScripter extends Item { } return itemStack; } + CustomNpcs.proxy.openGui(0, 0, 0, EnumGuiType.ScriptEvent, player); return itemStack; } diff --git a/src/main/java/noppes/npcs/items/ItemNpcWand.java b/src/main/java/noppes/npcs/items/ItemNpcWand.java index 1a11918ae..fc1e709b1 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/ItemOrb.java b/src/main/java/noppes/npcs/items/ItemOrb.java index 04df0e16c..b43ccaef4 100644 --- a/src/main/java/noppes/npcs/items/ItemOrb.java +++ b/src/main/java/noppes/npcs/items/ItemOrb.java @@ -5,7 +5,7 @@ import net.minecraft.entity.passive.EntitySheep; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.awt.*; +import java.awt.Color; import java.util.List; public class ItemOrb extends ItemNpcInterface { diff --git a/src/main/java/noppes/npcs/items/ItemStaff.java b/src/main/java/noppes/npcs/items/ItemStaff.java index 89ce879cf..39de82e37 100644 --- a/src/main/java/noppes/npcs/items/ItemStaff.java +++ b/src/main/java/noppes/npcs/items/ItemStaff.java @@ -1,32 +1,45 @@ package noppes.npcs.items; +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; +import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; -import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import noppes.npcs.CustomItems; import noppes.npcs.CustomNpcs; import noppes.npcs.constants.EnumNpcToolMaterial; import noppes.npcs.enchants.EnchantInterface; -import noppes.npcs.entity.EntityMagicProjectile; import noppes.npcs.entity.EntityProjectile; import noppes.npcs.util.IProjectileCallback; import org.lwjgl.opengl.GL11; +import java.awt.Color; + public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { private EnumNpcToolMaterial material; + protected OrbColor color; + public ItemStaff(int par1, EnumNpcToolMaterial material) { super(par1); this.material = material; + this.color = OrbColor.get(material.ordinal()); + ; setCreativeTab(CustomItems.tabWeapon); } @@ -36,70 +49,123 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { } @Override - public void onPlayerStoppedUsing(ItemStack stack, World worldObj, EntityPlayer player, int par4) { - if (worldObj.isRemote) { + public void onPlayerStoppedUsing(ItemStack stack, World world, EntityPlayer player, int par4) { + + if (world.isRemote) return; - } + if (stack.stackTagCompound == null) return; - Entity entity = ((WorldServer) player.worldObj).getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); - if (entity == null || !(entity instanceof EntityProjectile)) + + Entity entity = ((WorldServer) world) + .getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); + + if (!(entity instanceof EntityAbilityOrb)) return; - EntityProjectile item = (EntityProjectile) entity; - item.callback = this; - item.callbackItem = stack; - item.explosive = true; - item.explosiveDamage = false; - item.explosiveRadius = 1; - item.prevRotationYaw = item.rotationYaw = player.rotationYaw; - item.prevRotationPitch = item.rotationPitch = player.rotationPitch; - item.shoot(2); - player.worldObj.playSoundAtEntity(player, "customnpcs:magic.shot", 1.0F, 1); + EntityAbilityOrb orb = (EntityAbilityOrb) entity; + if (orb.getChargeProgress() < 1.0f) { + orb.setDead(); + return; + } + + orb.startMoving(null); + + world.playSoundAtEntity( + player, + "customnpcs:magic.shot", + 1.0F, + 1.0F + ); } @Override 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) { + if (!player.capabilities.isCreativeMode && !hasInfinite(stack)) { if (!hasItem(player, CustomItems.mana)) return; consumeItem(player, CustomItems.mana); } - player.worldObj.playSoundAtEntity(player, "customnpcs:magic.charge", 1.0F, 1); + + player.worldObj.playSoundAtEntity( + player, + "customnpcs:magic.charge", + 1.0F, + 1.0F + ); + if (stack.stackTagCompound == null) { stack.stackTagCompound = new NBTTagCompound(); } + int damage = 6 + material.getDamageVsEntity() + player.worldObj.rand.nextInt(4); damage += damage * EnchantInterface.getLevel(EnchantInterface.Damage, stack) * 0.5f; - EntityProjectile projectile = new EntityMagicProjectile(player.worldObj, player, getProjectile(stack), false); - projectile.damage = damage; - projectile.setSpeed(25); - double dx = -MathHelper.sin((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - double dz = MathHelper.cos((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - projectile.setPosition(player.posX + dx * 0.8, player.posY + 1.5 - player.rotationPitch / 80, player.posZ + dz * 0.8); - player.worldObj.spawnEntityInWorld(projectile); - stack.stackTagCompound.setInteger("MagicProjectile", projectile.getEntityId());//entityid - } - if (tick > chargeTime && stack.stackTagCompound != null) { - Entity entity = ((WorldServer) player.worldObj).getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); - if (entity == null || !(entity instanceof EntityProjectile)) - return; - EntityProjectile item = (EntityProjectile) entity; - item.ticksInAir = 0; - double dx = -MathHelper.sin((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - double dz = MathHelper.cos((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - item.setPosition(player.posX + dx * 0.8, player.posY + 1.5 - player.rotationPitch / 80, player.posZ + dz * 0.8); - } + EnergyCombatData combat = new EnergyCombatData(); + combat.damage = damage; + combat.explosive = true; + EnergyDisplayData colorData = new EnergyDisplayData(getOrbColor(stack, false), getOrbColor(stack, true)); + EnergyLightningData lightning = new EnergyLightningData(); + EnergyLifespanData lifespan = new EnergyLifespanData(100, 72000); + EnergyHomingData homing = new EnergyHomingData(); + homing.speed = 0.5f; + homing.homingStrength = 0.35f; + homing.homingRange = 20f; + + EntityAbilityOrb orb = new EntityAbilityOrb( + player.worldObj, player, null, + player.posX, player.posY + player.getEyeHeight(), player.posZ, + 1.0f, colorData, combat, homing, lightning, lifespan + ); + + orb.setupCharging( + new EnergyAnchorData(AnchorPoint.EYE, 0, 0, 1), + chargeTime + ); + + player.worldObj.spawnEntityInWorld(orb); + stack.stackTagCompound.setInteger("MagicProjectile", orb.getEntityId()); + } } @Override @@ -118,6 +184,15 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { return EnumAction.bow; } + public int getOrbColor(ItemStack stack, boolean outer) { + if (color == OrbColor.GENERIC) { + float[] color = EntitySheep.fleeceColorTable[stack.getItemDamage()]; + return new Color(color[0], color[1], color[2]).getRGB(); + } + + return outer ? color.outer : color.inner; + } + public ItemStack getProjectile(ItemStack stack) { if (stack.getItem() == CustomItems.staffWood) { return new ItemStack(CustomItems.spellNature); @@ -196,4 +271,32 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { public boolean hasInfinite(ItemStack stack) { return EnchantInterface.getLevel(EnchantInterface.Infinite, stack) > 0; } + + public enum OrbColor { + WOOD(0x7cc818, 0x644a32), + STONE(0x532d5b, 0x515151), + BRONZE(0x83F7F6, 0x5CF0FF), + IRON(0xf7fac5, 0xeafa94), + DIA(0x44B6FF, 0x94DFED), + GOLD(0xb3011e, 0xd47c32), + EMERALD(0xdd6df7, 0xcf1dfa), + DEMONIC(0xb8144a, 0x422643), + FROST(0xffffff, 0xaccbfe), + MITHRIL(0xf7fac5, 0xffffff), + GENERIC(0xFFFFFF, 0x88FFFF); + + public final int inner; + public final int outer; + + OrbColor(int inner, int outer) { + this.inner = inner; + this.outer = outer; + } + + public static OrbColor get(int id) { + if (id >= OrbColor.values().length || id < 0) return GENERIC; + + return OrbColor.values()[id]; + } + } } diff --git a/src/main/java/noppes/npcs/janino/EventJaninoScript.java b/src/main/java/noppes/npcs/janino/EventJaninoScript.java new file mode 100644 index 000000000..2ac7dd218 --- /dev/null +++ b/src/main/java/noppes/npcs/janino/EventJaninoScript.java @@ -0,0 +1,11 @@ +package noppes.npcs.janino; + +import noppes.npcs.constants.ScriptContext; + +public class EventJaninoScript extends JaninoScript { + + public EventJaninoScript(ScriptContext context) { + super(Object.class, null, false); + this.context = context; + } +} diff --git a/src/main/java/noppes/npcs/janino/JaninoHookResolver.java b/src/main/java/noppes/npcs/janino/JaninoHookResolver.java new file mode 100644 index 000000000..fc0c63f6d --- /dev/null +++ b/src/main/java/noppes/npcs/janino/JaninoHookResolver.java @@ -0,0 +1,208 @@ +package noppes.npcs.janino; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; + +/** + * Resolves script hook methods for compiled script classes. + * Optimized for high-frequency hooks like TICK with fast O(1) lookups. + */ +public final class JaninoHookResolver { + + /** + * Primary cache: hookName -> CachedHandle + * Fast O(1) lookup without string building for non-overloaded hooks. + */ + private final Map handleCache = new HashMap<>(); + + /** + * Track which compiled class we've cached methods for. + * If the class changes (recompilation), we clear the cache. + */ + private Class lastCompiledClass; + + private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + + /** + * Cached handle with expected parameter count for quick validation. + */ + private static final class CachedHandle { + final MethodHandle handle; + final int paramCount; + + CachedHandle(MethodHandle handle, int paramCount) { + this.handle = handle; + this.paramCount = paramCount; + } + } + + public JaninoHookResolver() { + } + + /** + * Clears internal resolution caches. + */ + public void clearResolutionCaches() { + handleCache.clear(); + lastCompiledClass = null; + } + + /** + * Resolve a MethodHandle for the given hook. + * Optimized for repeated calls with same hook name - O(1) after first resolution. + */ + public MethodHandle resolveHookHandle(String hookName, Object[] args, Object compiledInstance) { + if (hookName == null || hookName.isEmpty() || compiledInstance == null) + return null; + + Class compiledClass = compiledInstance.getClass(); + + // Clear cache if compiled class changed (recompilation) + if (lastCompiledClass != compiledClass) { + handleCache.clear(); + lastCompiledClass = compiledClass; + } + + int argCount = args == null ? 0 : args.length; + + // Fast path: check primary cache by hookName only + CachedHandle cached = handleCache.get(hookName); + if (cached != null) { + // Verify arg count matches (handles most cases without full signature check) + if (cached.paramCount == argCount) { + return cached.handle; + } + // Arg count mismatch - need full resolution for potential overload + } + + // Slow path: resolve method and cache + Method method = resolveMethod(compiledClass, hookName, args); + if (method == null) + return null; + + try { + MethodHandle handle = LOOKUP.unreflect(method); + handleCache.put(hookName, new CachedHandle(handle, method.getParameterCount())); + return handle; + } catch (IllegalAccessException e) { + return null; + } + } + + /** + * Find the best matching method on the compiled class. + */ + private Method resolveMethod(Class targetClass, String hookName, Object[] args) { + Object[] safeArgs = args == null ? new Object[0] : args; + + Method best = null; + int bestScore = Integer.MAX_VALUE; + + for (Method method : targetClass.getMethods()) { + if (!method.getName().equals(hookName)) + continue; + + // Skip final methods and Object methods + if (Modifier.isFinal(method.getModifiers())) + continue; + if (method.getDeclaringClass() == Object.class) + continue; + + Class[] paramTypes = method.getParameterTypes(); + + // Try exact arg count match first + if (paramTypes.length == safeArgs.length) { + int score = scoreMethodMatch(paramTypes, safeArgs); + if (score != Integer.MAX_VALUE && score < bestScore) { + bestScore = score; + best = method; + if (score == 0) + return best; // Perfect match + } + } + } + + // If no match with args, try no-arg version + if (best == null && safeArgs.length > 0) { + for (Method method : targetClass.getMethods()) { + if (!method.getName().equals(hookName)) + continue; + if (Modifier.isFinal(method.getModifiers())) + continue; + if (method.getDeclaringClass() == Object.class) + continue; + if (method.getParameterCount() == 0) { + return method; + } + } + } + + return best; + } + + /** + * Score how well parameter types match runtime arguments. + * Lower is better; MAX_VALUE means incompatible. + */ + private static int scoreMethodMatch(Class[] paramTypes, Object[] args) { + int score = 0; + for (int i = 0; i < paramTypes.length; i++) { + Class paramType = paramTypes[i]; + Object arg = args[i]; + + if (arg == null) { + if (paramType.isPrimitive()) + return Integer.MAX_VALUE; + score += 1; + continue; + } + + Class argType = arg.getClass(); + Class boxedParam = boxType(paramType); + + if (boxedParam.equals(argType)) + continue; + + if (boxedParam.isAssignableFrom(argType)) { + score += inheritanceDistance(argType, boxedParam); + continue; + } + + return Integer.MAX_VALUE; + } + return score; + } + + private static Class boxType(Class type) { + if (!type.isPrimitive()) + return type; + if (type == boolean.class) return Boolean.class; + if (type == byte.class) return Byte.class; + if (type == short.class) return Short.class; + if (type == int.class) return Integer.class; + if (type == long.class) return Long.class; + if (type == float.class) return Float.class; + if (type == double.class) return Double.class; + if (type == char.class) return Character.class; + return type; + } + + private static int inheritanceDistance(Class child, Class parent) { + if (child.equals(parent)) + return 0; + if (!parent.isAssignableFrom(child)) + return 1000; + + int distance = 0; + Class current = child; + while (current != null && !current.equals(parent)) { + current = current.getSuperclass(); + distance++; + } + return distance; + } +} diff --git a/src/main/java/noppes/npcs/janino/JaninoScript.java b/src/main/java/noppes/npcs/janino/JaninoScript.java new file mode 100644 index 000000000..f94be8acc --- /dev/null +++ b/src/main/java/noppes/npcs/janino/JaninoScript.java @@ -0,0 +1,558 @@ +package noppes.npcs.janino; + +import cpw.mods.fml.common.eventhandler.Event; +import io.github.somehussar.janinoloader.api.script.IScriptBodyBuilder; +import io.github.somehussar.janinoloader.api.script.IScriptClassBody; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcs; +import noppes.npcs.NBTTags; +import noppes.npcs.api.handler.IHookDefinition; +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; +import org.codehaus.commons.compiler.Sandbox; + +import java.lang.invoke.MethodHandle; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.Permissions; +import java.security.PrivilegedAction; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public abstract class JaninoScript implements IScriptUnit { + + public ScriptContext context = ScriptContext.GLOBAL; + public boolean errored = false; + public String script = ""; + public List externalScripts = new ArrayList<>(); + public TreeMap console = new TreeMap<>(); + public boolean evaluated; + + public final Class type; + public final IScriptBodyBuilder builder; + protected final Sandbox sandbox; + protected IScriptClassBody scriptBody; + + 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; + + + protected JaninoScript(Class type, String[] defaultImports, boolean isClient) { + this.type = type; + this.defaultImports = defaultImports != null ? defaultImports : new String[0]; + this.builder = IScriptBodyBuilder.getBuilder(type, + isClient ? CustomNpcs.getClientCompiler() : CustomNpcs.getDynamicCompiler()) + .setDefaultImports(this.defaultImports); + + Permissions permissions = new Permissions(); + permissions.setReadOnly(); + this.sandbox = new Sandbox(permissions); + this.scriptBody = builder.build(); + } + + protected JaninoScript(Class type, String[] defaultImports) { + this(type, defaultImports, false); + } + + protected String getHookContext() { + return this.context.hookContext; + } + + protected T getUnsafe() { + return scriptBody.get(); + } + + public R call(Function fn) { + ensureCompiled(); + + T t = getUnsafe(); + if (t == null) + return null; + + // CodeSource cs = t.getClass().getProtectionDomain().getCodeSource(); + // ProtectionDomain pd = new ProtectionDomain(cs, new Permissions()); + + try { + return sandbox.confine((PrivilegedAction) () -> fn.apply(t)); + // return AccessController.doPrivileged((PrivilegedAction) () -> fn.apply(t), new AccessControlContext( + // new ProtectionDomain[] { + // pd + // } + // )); + } catch (Exception e) { + appendConsole("Runtime Error: " + e.getMessage()); + return null; + } + } + + public void run(Consumer fn) { + ensureCompiled(); + + T t = getUnsafe(); + if (t == null) + return; + + try { + sandbox.confine((PrivilegedAction) () -> { + fn.accept(t); + return null; + }); + } catch (Exception e) { + appendConsole("Runtime Error: " + e.getMessage()); + } + } + + 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 { + builder.setDefaultImports(cachedImports = collectImportsForCode(code)); + this.scriptBody = builder.build(); + scriptBody.setScript(code); + } catch (InternalCompilerException e) { + appendConsole("Compilation error: " + e.getMessage()); + Throwable cause = e; + while (cause.getCause() != null) cause = cause.getCause(); + if (e != cause) appendConsole(cause.getMessage()); + hookResolver.clearResolutionCaches(); + } catch (Exception e) { + appendConsole("Error: " + e.getMessage()); + hookResolver.clearResolutionCaches(); + } + } + + public void compileScript() { + compileScript(getFullCode()); + } + + public void ensureCompiled() { + int global = ScriptController.Instance.globalRevision; + if (!evaluated || global != lastSeenGlobalRevision) { + compileScript(); + lastSeenGlobalRevision = global; + evaluated = true; + } + } + + private String getFullCode() { + StringBuilder sb = new StringBuilder(); + if (CustomNpcs.proxy.isRunLoadedScriptsFirst()) appendExternalScripts(sb); + if (script != null && !script.isEmpty()) sb.append(script).append("\n"); + if (!CustomNpcs.proxy.isRunLoadedScriptsFirst()) appendExternalScripts(sb); + return sb.toString(); + } + + private void appendExternalScripts(StringBuilder sb) { + for (String name : externalScripts) { + String code = ScriptController.Instance.scripts.get(name); + if (code != null && !code.isEmpty()) sb.append(code).append("\n"); + } + } + + // ==================== SMART IMPORTS ==================== + + private String[] collectImportsForCode(String code) { + Set imports = new LinkedHashSet<>(); + Collections.addAll(imports, defaultImports); + + if (ScriptHookController.Instance == null) { + return imports.toArray(new String[0]); + } + + String context = getHookContext(); + if (context == null || context.isEmpty()) { + return imports.toArray(new String[0]); + } + + for (IHookDefinition def : ScriptHookController.Instance.getAllHookDefinitions(context)) { + if (code.contains(def.hookName() + "(")) { + String[] hookImports = def.requiredImports(); + if (hookImports != null) { + Collections.addAll(imports, hookImports); + } + } + } + + return imports.toArray(new String[0]); + } + + // ==================== HOOK EXECUTION ==================== + + @Override + public Object callFunction(String hookName, Object... args) { + if (hookName == null || hookName.isEmpty()) return null; + + ensureCompiled(); + T instance = scriptBody.get(); + if (instance == null) return null; + + Object[] invokeArgs = args == null ? new Object[0] : args; + MethodHandle handle = hookResolver.resolveHookHandle(hookName, invokeArgs, instance); + if (handle == null) return null; + + try { + return sandbox.confine((PrivilegedAction) () -> { + try { + Object[] fullArgs = new Object[invokeArgs.length + 1]; + fullArgs[0] = instance; + System.arraycopy(invokeArgs, 0, fullArgs, 1, invokeArgs.length); + return handle.invokeWithArguments(fullArgs); + } catch (Throwable e) { + appendConsole("Error in " + hookName + ": " + e.getMessage()); + return null; + } + }); + } catch (Exception e) { + appendConsole("Runtime error in " + hookName + ": " + e.getMessage()); + return null; + } + } + + @Override + public void run(EnumScriptType type, Event event) { + if (type != null) callFunction(type.function, event); + } + + @Override + public void run(String hookName, Object event) { + callFunction(hookName, event); + } + + // ==================== HOOK DEFINITIONS ==================== + + protected IHookDefinition getHookDefinition(String hookName) { + if (ScriptHookController.Instance == null) return null; + + int rev = ScriptHookController.Instance.getHookRevision(); + if (hookDefCache == null || rev != lastHookRevision) { + rebuildHookDefCache(); + lastHookRevision = rev; + } + return hookDefCache.get(hookName); + } + + private void rebuildHookDefCache() { + hookDefCache = new HashMap<>(); + String context = getHookContext(); + if (context == null || context.isEmpty() || ScriptHookController.Instance == null) return; + + for (IHookDefinition def : ScriptHookController.Instance.getAllHookDefinitions(context)) { + hookDefCache.put(def.hookName(), def); + } + } + + public List getHookList() { + Set hooks = new LinkedHashSet<>(); + + // 1. Add hooks from ScriptHookController (new system) + String context = getHookContext(); + if (context != null && !context.isEmpty() && ScriptHookController.Instance != null) { + hooks.addAll(ScriptHookController.Instance.getAllHooks(context)); + } + + // 2. Add methods from interface type (backward compatibility with @ParamName) + if (type != null) { + for (Method m : type.getDeclaredMethods()) { + if (!Modifier.isFinal(m.getModifiers()) && !hooks.contains(m.getName())) { + hooks.add(m.getName()); + } + } + } + + return new ArrayList<>(hooks); + } + + @Override + public String generateHookStub(String hookName, Object hookData) { + // 1. Try HookDefinition from registry (new system) + IHookDefinition def = getHookDefinition(hookName); + if (def != null) { + String typeName = def.getUsableTypeName(); + String[] params = def.paramNames(); + String paramName = (params != null && params.length > 0) ? params[0] : "event"; + + if (typeName != null && !typeName.isEmpty()) { + return String.format("public void %s(%s %s) {\n \n}\n", + def.hookName(), typeName, paramName); + } + } + + // 2. Fallback: Try interface method with @ParamName (backward compatibility) + Method method = findInterfaceMethod(hookName); + if (method != null) { + return generateMethodStub(method); + } + + // 3. Final fallback: generic stub + return String.format("public void %s(Object event) {\n \n}\n", hookName); + } + + /** + * Find a method in the type interface by name. + */ + private Method findInterfaceMethod(String methodName) { + if (type == null || methodName == null) return null; + + for (Method m : type.getDeclaredMethods()) { + if (m.getName().equals(methodName) && !Modifier.isFinal(m.getModifiers())) { + return m; + } + } + return null; + } + + /** + * Generate a method stub from a Method, supporting @ParamName annotations. + * Provides backward compatibility with interface-based hook definitions. + */ + public static String generateMethodStub(Method method) { + String mods = Modifier.toString(method.getModifiers()); + mods = mods.replace("abstract ", "").replace("abstract", "") + .replace("default ", "").replace("default", "").trim(); + if (!mods.isEmpty()) mods += " "; + + String returnTypeStr = getUsableTypeName(method.getReturnType()); + String name = method.getName(); + + Map typeCount = new HashMap<>(); + StringBuilder params = new StringBuilder(); + for (int i = 0; i < method.getParameters().length; i++) { + java.lang.reflect.Parameter p = method.getParameters()[i]; + String typeName = getUsableTypeName(p.getType()); + + // Check for @ParamName annotation first + ParamName annotation = p.getAnnotation(ParamName.class); + String paramName; + if (annotation != null) { + paramName = annotation.value(); + } else { + // Fallback to generated name + String baseName = Character.toLowerCase(p.getType().getSimpleName().charAt(0)) + + p.getType().getSimpleName().substring(1); + int count = typeCount.getOrDefault(baseName, 0) + 1; + typeCount.put(baseName, count); + paramName = count == 1 ? baseName : baseName + (count - 1); + } + + if (i > 0) params.append(", "); + params.append(typeName).append(" ").append(paramName); + } + + 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); + } + + /** + * Gets a usable type name for stub generation. + * For nested classes, returns "OuterClass.InnerClass" format. + */ + private static String getUsableTypeName(Class type) { + if (type.isPrimitive() || type.getEnclosingClass() == null) { + return type.getSimpleName(); + } + + // Build the nested class chain + StringBuilder sb = new StringBuilder(); + Class current = type; + while (current != null) { + if (sb.length() > 0) sb.insert(0, "."); + sb.insert(0, current.getSimpleName()); + current = current.getEnclosingClass(); + } + 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 + public String getScript() { + return script; + } + + @Override + public void setScript(String script) { + this.script = script; + this.evaluated = false; + this.cachedImports = null; + hookResolver.clearResolutionCaches(); + } + + @Override + public List getExternalScripts() { + return externalScripts; + } + + @Override + public void setExternalScripts(List scripts) { + this.externalScripts = scripts; + this.evaluated = false; + this.cachedImports = null; + hookResolver.clearResolutionCaches(); + } + + @Override + public TreeMap getConsole() { + return console; + } + + @Override + public void clearConsole() { + console.clear(); + } + + @Override + public void appendConsole(String message) { + if (message == null || message.isEmpty()) return; + long time = System.currentTimeMillis(); + if (console.containsKey(time)) { + message = console.get(time) + "\n" + message; + } + console.put(time, message); + while (console.size() > 40) { + console.remove(console.firstKey()); + } + } + + @Override + public String getLanguage() { + return "Java"; + } + + @Override + public void setLanguage(String language) { + } + + @Override + public boolean hasCode() { + return !externalScripts.isEmpty() || (script != null && !script.isEmpty()); + } + + @Override + public boolean hasErrored() { + return errored; + } + + @Override + public void setErrored(boolean errored) { + this.errored = errored; + } + + // ==================== NBT ==================== + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setString(IScriptUnit.NBT_TYPE_KEY, IScriptUnit.TYPE_JANINO); + compound.setTag("console", NBTTags.NBTLongStringMap(console)); + compound.setTag("externalScripts", NBTTags.nbtStringList(externalScripts)); + compound.setString("script", script); + return compound; + } + + @Override + public void readFromNBT(NBTTagCompound compound) { + this.console = NBTTags.GetLongStringMap(compound.getTagList("console", 10)); + setExternalScripts(NBTTags.getStringList(compound.getTagList("externalScripts", 10))); + setScript(compound.getString("script")); + } + + 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")); + } + return script; + } + + public static NBTTagCompound writeToNBT(NBTTagCompound compound, JaninoScript script) { + if (script != null) compound.setTag("Script", script.writeToNBT(new NBTTagCompound())); + return compound; + } +} diff --git a/src/main/java/noppes/npcs/janino/annotations/ParamName.java b/src/main/java/noppes/npcs/janino/annotations/ParamName.java new file mode 100644 index 000000000..deb8ed85c --- /dev/null +++ b/src/main/java/noppes/npcs/janino/annotations/ParamName.java @@ -0,0 +1,24 @@ +package noppes.npcs.janino.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Specifies the parameter name and type to use when generating method stubs. + * Applied to interface method parameters to preserve their names and types in generated code. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface ParamName { + /** + * The parameter name (e.g., "event") + */ + String value(); + + /** + * The fully qualified type name (e.g., "noppes.npcs.api.event.INpcEvent.InitEvent") + */ + String type() default ""; +} 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/RoleAuctioneer.java b/src/main/java/noppes/npcs/roles/RoleAuctioneer.java new file mode 100644 index 000000000..727e72378 --- /dev/null +++ b/src/main/java/noppes/npcs/roles/RoleAuctioneer.java @@ -0,0 +1,41 @@ +package noppes.npcs.roles; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.config.ConfigMarket; +import noppes.npcs.constants.EnumGuiType; +import noppes.npcs.entity.EntityNPCInterface; + +public class RoleAuctioneer extends RoleInterface { + + public RoleAuctioneer(EntityNPCInterface npc) { + super(npc); + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + // Simple role - no custom data needed + return compound; + } + + @Override + public void readFromNBT(NBTTagCompound compound) { + // Simple role - no custom data needed + } + + @Override + public void interact(EntityPlayer player) { + if (!ConfigMarket.AuctionEnabled) { + return; + } + + // Open the auction house GUI + NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, npc); + } + + @Override + public void delete() { + // No cleanup needed + } +} diff --git a/src/main/java/noppes/npcs/roles/RoleTrader.java b/src/main/java/noppes/npcs/roles/RoleTrader.java index 5275c26c0..6aa69d357 100644 --- a/src/main/java/noppes/npcs/roles/RoleTrader.java +++ b/src/main/java/noppes/npcs/roles/RoleTrader.java @@ -1,17 +1,25 @@ package noppes.npcs.roles; import foxz.utils.Market; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; 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.NBTTags; import noppes.npcs.NoppesUtilPlayer; import noppes.npcs.NoppesUtilServer; import noppes.npcs.NpcMiscInventory; import noppes.npcs.constants.EnumGuiType; +import noppes.npcs.controllers.MarketRegistry; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.TraderStock; import noppes.npcs.entity.EntityNPCInterface; import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; @@ -30,6 +38,15 @@ public class RoleTrader extends RoleInterface { public HashMap playerPurchases; public HashMap playerDisableSlot; + // Stock system + public TraderStock stock = new TraderStock(); + + // Currency cost per trade slot (ADDITIVE to item costs, 0 = no currency required) + public long[] currencyCost = new long[18]; + + // Local viewer tracking for non-linked traders (per-NPC sync) + private final Set localViewers = new HashSet<>(); + public RoleTrader(EntityNPCInterface npc) { super(npc); inventoryCurrency = new NpcMiscInventory(36); @@ -59,14 +76,31 @@ public class RoleTrader extends RoleInterface { nbttagcompound.setIntArray("Purchases", purchases); nbttagcompound.setTag("PlayerPurchases", NBTTags.nbtStringIntegerArrayMap(playerPurchases)); } + + // Stock system + nbttagcompound.setTag("Stock", stock.writeToNBT(new NBTTagCompound())); + + // Currency cost per slot (additive to item costs) + NBTTagList currencyList = new NBTTagList(); + for (long cost : currencyCost) { + NBTTagCompound costTag = new NBTTagCompound(); + costTag.setLong("Cost", cost); + currencyList.appendTag(costTag); + } + nbttagcompound.setTag("CurrencyCost", currencyList); + return nbttagcompound; } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { + String oldMarket = marketName; marketName = nbttagcompound.getString("TraderMarket"); readNBT(nbttagcompound); + // Register with MarketRegistry for linked market sync + MarketRegistry.updateTraderMarket(oldMarket, marketName, this); + try { Market.getMarket(this, marketName); } catch (Exception ex) { @@ -94,16 +128,56 @@ public class RoleTrader extends RoleInterface { disableSlot = new int[18]; for (int i = 0; i < disableSlot.length; ++i) disableSlot[i] = 0; } + + // Stock system + if (nbttagcompound.hasKey("Stock")) { + stock.readFromNBT(nbttagcompound.getCompoundTag("Stock")); + } + + // Currency cost per slot (additive to item costs) + if (nbttagcompound.hasKey("CurrencyCost")) { + NBTTagList currencyList = nbttagcompound.getTagList("CurrencyCost", 10); + for (int i = 0; i < currencyList.tagCount() && i < 18; i++) { + currencyCost[i] = currencyList.getCompoundTagAt(i).getLong("Cost"); + } + } } @Override public void interact(EntityPlayer player) { npc.say(player, npc.advanced.getInteractLine()); + + // Load from market FIRST to get latest shared data try { Market.getMarket(this, marketName); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } + + // THEN check for stock reset (after loading latest market data) + if (stock.enableStock) { + long currentTime = stock.resetType.isRealTime() + ? System.currentTimeMillis() + : player.worldObj.getTotalWorldTime(); + + boolean needsSave = false; + + if (stock.shouldReset(currentTime)) { + stock.resetStock(currentTime); + needsSave = true; + } + + // Validate stock levels (clamp current to max if exceeded) + if (stock.validateStock()) { + needsSave = true; + } + + // Save to market if using shared market and changes were made + if (needsSave && !marketName.isEmpty()) { + Market.save(this, marketName); + } + } + NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerTrader, npc); } @@ -138,4 +212,245 @@ public class RoleTrader extends RoleInterface { return map.get(name); } + // ==================== Stock System Methods ==================== + + /** + * Check if there is stock available for a slot + */ + public boolean hasStock(int slot, String playerName, int amount) { + if (!stock.enableStock) { + return true; // Stock system disabled, always available + } + return stock.hasStock(slot, playerName, amount); + } + + /** + * Get available stock for a slot + */ + public int getAvailableStock(int slot, String playerName) { + if (!stock.enableStock) { + return Integer.MAX_VALUE; // Unlimited + } + return stock.getAvailableStock(slot, playerName); + } + + /** + * Consume stock after purchase. + * For shared stock, syncs all viewers (market-wide for linked markets, per-NPC otherwise). + * + * @param slot The slot purchased from + * @param playerName The player making the purchase + * @param amount Amount to consume + * @return true if stock was consumed successfully + */ + public boolean consumeStock(int slot, String playerName, int amount) { + if (!stock.enableStock) { + return true; // Stock system disabled + } + boolean consumed = stock.consumeStock(slot, playerName, amount); + if (consumed) { + // Save to market if linked + if (!marketName.isEmpty()) { + Market.save(this, marketName); + } + + // Sync viewers for shared stock (not per-player) + if (!stock.perPlayer) { + if (!marketName.isEmpty()) { + // Linked market: sync all traders and viewers market-wide + MarketRegistry.syncMarket(marketName); + } else { + // No linked market: sync only this NPC's viewers + syncLocalViewers(); + } + } + } + return consumed; + } + + /** + * Get time until stock reset formatted for display + */ + public String getTimeUntilResetFormatted() { + if (!stock.enableStock || stock.resetType == noppes.npcs.constants.EnumStockReset.NONE) { + return ""; + } + long currentTime = stock.resetType.isRealTime() + ? System.currentTimeMillis() + : (npc != null && npc.worldObj != null ? npc.worldObj.getTotalWorldTime() : 0); + return stock.getTimeUntilResetFormatted(currentTime); + } + + /** + * Get time until stock reset in real-time milliseconds. + * Converts MC ticks to approximate real-time for client countdown display. + * + * @return Remaining time in milliseconds, or -1 if no reset scheduled + */ + public long getResetTimeRemainingMillis() { + if (!stock.enableStock || stock.resetType == noppes.npcs.constants.EnumStockReset.NONE) { + return -1; + } + + long currentTime; + long remaining; + + if (stock.resetType.isRealTime()) { + // Real time - already in milliseconds + currentTime = System.currentTimeMillis(); + remaining = stock.getTimeUntilReset(currentTime); + } else { + // MC time - convert ticks to real milliseconds (1 tick = 50ms) + currentTime = (npc != null && npc.worldObj != null ? npc.worldObj.getTotalWorldTime() : 0); + long remainingTicks = stock.getTimeUntilReset(currentTime); + remaining = remainingTicks * 50L; + } + + return remaining; + } + + /** + * Reset the stock cooldown timer (for admin use) + */ + public void resetCooldown() { + stock.lastResetTime = 0; + } + + // ==================== Currency Cost Methods ==================== + + /** + * Get the currency cost for a slot (additive to item costs) + */ + public long getCurrencyCost(int slot) { + if (slot < 0 || slot >= 18) return 0; + return currencyCost[slot]; + } + + /** + * Set the currency cost for a slot (additive to item costs) + */ + public void setCurrencyCost(int slot, long cost) { + if (slot >= 0 && slot < 18) { + currencyCost[slot] = Math.max(0, cost); + } + } + + /** + * Check if a slot has a currency cost (greater than 0) + */ + public boolean hasCurrencyCost(int slot) { + return slot >= 0 && slot < 18 && currencyCost[slot] > 0; + } + + // ==================== Viewer Tracking Methods ==================== + + /** + * Register a player as viewing this trader's GUI. + * - For linked markets: uses MarketRegistry (market-wide sync) + * - For normal traders: uses local viewer set (per-NPC sync) + */ + public void registerViewer(EntityPlayerMP player) { + if (player == null) return; + + if (!marketName.isEmpty()) { + // Linked market: use MarketRegistry for market-wide tracking + MarketRegistry.registerViewer(marketName, player); + } else { + // No linked market: use local viewer set + localViewers.add(player); + } + } + + /** + * Unregister a player from viewing this trader's GUI. + * - For linked markets: uses MarketRegistry + * - For normal traders: uses local viewer set + */ + public void unregisterViewer(EntityPlayerMP player) { + if (player == null) return; + + if (!marketName.isEmpty()) { + MarketRegistry.unregisterViewer(marketName, player); + } else { + localViewers.remove(player); + } + } + + /** + * Sync trader data to all players viewing this trader. + * - For linked markets: syncs ALL viewers across ALL NPCs sharing the market + * - For normal traders: syncs only viewers of THIS specific NPC + */ + public void syncAllViewers() { + if (!marketName.isEmpty()) { + // Linked market: sync all viewers across all NPCs with this market + MarketRegistry.syncMarketViewers(marketName); + } else { + // No linked market: sync only local viewers + syncLocalViewers(); + } + } + + /** + * Sync to all players viewing this specific NPC (for non-linked traders). + */ + private void syncLocalViewers() { + // Remove disconnected players + localViewers.removeIf(player -> player.playerNetServerHandler == null); + + for (EntityPlayerMP viewer : localViewers) { + syncToPlayer(viewer); + } + } + + /** + * Called when this trader is unloaded (NPC death, chunk unload, etc.) + * Cleans up MarketRegistry registration. + */ + public void onUnload() { + if (!marketName.isEmpty()) { + MarketRegistry.unregisterTrader(marketName, this); + } + localViewers.clear(); + } + + /** + * Send trader data to a specific player + */ + public void syncToPlayer(EntityPlayerMP player) { + if (player == null || player.playerNetServerHandler == null) { + return; + } + + NBTTagCompound compound = new NBTTagCompound(); + + // Player balance + PlayerData data = PlayerData.get(player); + compound.setLong("Balance", data.tradeData.getBalance()); + + // Stock info + compound.setBoolean("StockEnabled", stock.enableStock); + compound.setString("ResetTime", getTimeUntilResetFormatted()); + + // Available stock per slot (player-specific if perPlayer mode) + String playerName = player.getCommandSenderName(); + int[] stockArr = new int[18]; + for (int i = 0; i < 18; i++) { + stockArr[i] = getAvailableStock(i, playerName); + } + compound.setIntArray("Stock", stockArr); + + // Currency cost per slot + for (int i = 0; i < 18; i++) { + compound.setLong("Cost" + i, getCurrencyCost(i)); + } + + GuiDataPacket.sendGuiData(player, compound); + } + + @Override + public void delete() { + onUnload(); + super.delete(); + } } diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index 79a6c2fa6..1b0d392b2 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -3,8 +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.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; @@ -49,30 +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.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.IActionManager; -import noppes.npcs.api.handler.IAnimationHandler; -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.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; @@ -83,20 +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.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.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; @@ -110,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; @@ -356,6 +357,41 @@ public class NpcAPI extends AbstractNpcAPI { return AnimationController.Instance; } + public ILinkedItemHandler getLinkedItems() { + return LinkedItemController.getInstance(); + } + + public IScriptHookHandler getScriptHooks() { + return ScriptHookController.Instance; + } + + @Override + public IAbilityHandler getAbilities() { + this.checkWorld(); + return AbilityController.Instance; + } + + @Override + public ITelegraphHandler getTelegraphs() { + this.checkWorld(); + return TelegraphController.Instance; + } + + @Override + public ITelegraph createTelegraph(String type) { + this.checkWorld(); + return TelegraphController.Instance.create(type); + } + + @Override + public IAuctionHandler getAuctions() { + this.checkWorld(); + if (!noppes.npcs.config.ConfigMarket.AuctionEnabled) { + return null; + } + return AuctionController.getInstance(); + } + @Override public String[] getAllBiomeNames() { List biomes = new ArrayList<>(); @@ -414,6 +450,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); @@ -564,6 +622,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/ScriptTelegraph.java b/src/main/java/noppes/npcs/scripted/ScriptTelegraph.java new file mode 100644 index 000000000..f03be5033 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/ScriptTelegraph.java @@ -0,0 +1,210 @@ +package noppes.npcs.scripted; + +import kamkeel.npcs.controllers.TelegraphController; +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.world.World; +import noppes.npcs.api.ITelegraph; +import noppes.npcs.api.ITelegraphInstance; +import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEntity; + +/** + * Script wrapper for Telegraph configuration. + * Implements ITelegraph API interface. + */ +public class ScriptTelegraph implements ITelegraph { + + private final Telegraph telegraph; + + public ScriptTelegraph(Telegraph telegraph) { + this.telegraph = telegraph; + } + + /** + * Get the underlying Telegraph object. + */ + public Telegraph getMCTelegraph() { + return telegraph; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // TYPE + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public String getType() { + return telegraph.getType().name(); + } + + @Override + public void setType(String type) { + if (type == null) return; + try { + telegraph.setType(TelegraphType.valueOf(type.toUpperCase())); + } catch (IllegalArgumentException ignored) { + } + } + + // ═══════════════════════════════════════════════════════════════════════════ + // SHAPE PARAMETERS + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public float getRadius() { + return telegraph.getRadius(); + } + + @Override + public void setRadius(float radius) { + telegraph.setRadius(radius); + } + + @Override + public float getInnerRadius() { + return telegraph.getInnerRadius(); + } + + @Override + public void setInnerRadius(float innerRadius) { + telegraph.setInnerRadius(innerRadius); + } + + @Override + public float getLength() { + return telegraph.getLength(); + } + + @Override + public void setLength(float length) { + telegraph.setLength(length); + } + + @Override + public float getWidth() { + return telegraph.getWidth(); + } + + @Override + public void setWidth(float width) { + telegraph.setWidth(width); + } + + @Override + public float getAngle() { + return telegraph.getAngle(); + } + + @Override + public void setAngle(float angle) { + telegraph.setAngle(angle); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // TIMING + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public int getDuration() { + return telegraph.getDurationTicks(); + } + + @Override + public void setDuration(int ticks) { + telegraph.setDurationTicks(ticks); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // COLORS + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public int getColor() { + return telegraph.getColor(); + } + + @Override + public void setColor(int argb) { + telegraph.setColor(argb); + } + + @Override + public int getWarningColor() { + return telegraph.getWarningColor(); + } + + @Override + public void setWarningColor(int argb) { + telegraph.setWarningColor(argb); + } + + @Override + public int getWarningStartTick() { + return telegraph.getWarningStartTick(); + } + + @Override + public void setWarningStartTick(int tick) { + telegraph.setWarningStartTick(tick); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // ANIMATION + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public boolean isAnimated() { + return telegraph.isAnimated(); + } + + @Override + public void setAnimated(boolean animated) { + telegraph.setAnimated(animated); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POSITIONING + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public float getHeightOffset() { + return telegraph.getHeightOffset(); + } + + @Override + public void setHeightOffset(float offset) { + telegraph.setHeightOffset(offset); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // SPAWN METHODS + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public ITelegraphInstance spawn(IWorld world, double x, double y, double z) { + return spawn(world, x, y, z, 0); + } + + @Override + public ITelegraphInstance spawn(IWorld world, double x, double y, double z, float yaw) { + if (world == null || world.getMCWorld() == null) return null; + World mcWorld = (World) world.getMCWorld(); + TelegraphInstance instance = TelegraphController.Instance.spawn(telegraph, mcWorld, x, y, z, yaw); + return new ScriptTelegraphInstance(instance); + } + + @Override + public ITelegraphInstance spawn(IEntity entity) { + return spawn(entity, 0); + } + + @Override + public ITelegraphInstance spawn(IEntity entity, float yaw) { + if (entity == null || entity.getMCEntity() == null) return null; + Entity mcEntity = (Entity) entity.getMCEntity(); + TelegraphInstance instance = TelegraphController.Instance.spawn(telegraph, mcEntity, yaw); + return new ScriptTelegraphInstance(instance); + } +} diff --git a/src/main/java/noppes/npcs/scripted/ScriptTelegraphInstance.java b/src/main/java/noppes/npcs/scripted/ScriptTelegraphInstance.java new file mode 100644 index 000000000..b307a6dc7 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/ScriptTelegraphInstance.java @@ -0,0 +1,122 @@ +package noppes.npcs.scripted; + +import kamkeel.npcs.controllers.TelegraphController; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import net.minecraft.entity.Entity; +import noppes.npcs.api.ITelegraphInstance; +import noppes.npcs.api.entity.IEntity; + +/** + * Script wrapper for TelegraphInstance. + * Implements ITelegraphInstance API interface. + */ +public class ScriptTelegraphInstance implements ITelegraphInstance { + + private final TelegraphInstance instance; + + public ScriptTelegraphInstance(TelegraphInstance instance) { + this.instance = instance; + } + + /** + * Get the underlying TelegraphInstance object. + */ + public TelegraphInstance getMCInstance() { + return instance; + } + + @Override + public String getInstanceId() { + return instance.getInstanceId(); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // POSITION + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public double getX() { + return instance.getX(); + } + + @Override + public double getY() { + return instance.getY(); + } + + @Override + public double getZ() { + return instance.getZ(); + } + + @Override + public float getYaw() { + return instance.getYaw(); + } + + @Override + public void setPosition(double x, double y, double z) { + instance.setX(x); + instance.setY(y); + instance.setZ(z); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // ENTITY FOLLOWING + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void followEntity(IEntity entity) { + if (entity == null || entity.getMCEntity() == null) return; + Entity mcEntity = (Entity) entity.getMCEntity(); + instance.setEntityIdToFollow(mcEntity.getEntityId()); + } + + @Override + public void stopFollowing() { + instance.lockPosition(); + } + + @Override + public boolean isFollowing() { + return instance.getEntityIdToFollow() >= 0; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // TIMING + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public int getRemainingTicks() { + return instance.getRemainingTicks(); + } + + @Override + public int getTotalTicks() { + return instance.getTotalTicks(); + } + + @Override + public float getProgress() { + return instance.getProgress(); + } + + @Override + public boolean isWarning() { + return instance.isWarning(); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CONTROL + // ═══════════════════════════════════════════════════════════════════════════ + + @Override + public void remove() { + TelegraphController.Instance.remove(instance); + } + + @Override + public void lockPosition() { + instance.lockPosition(); + } +} 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 bfe576856..e92babb24 100644 --- a/src/main/java/noppes/npcs/scripted/constants/EntityType.java +++ b/src/main/java/noppes/npcs/scripted/constants/EntityType.java @@ -14,4 +14,14 @@ public class EntityType { public static final int ARROW = 10; 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 caac8d87d..c5b2c6a6e 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; @@ -526,6 +531,16 @@ public class ScriptEntity implements IEntity { cls = EntityMob.class; else if (type == EntityType.NPC) cls = EntityNPCInterface.class; + else if (type == EntityType.ENERGY_PROJECTILE) + cls = 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 8b632f7ce..27621f125 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java @@ -1,14 +1,20 @@ 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; 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; @@ -51,6 +57,7 @@ import noppes.npcs.scripted.roles.ScriptRoleInterface; import noppes.npcs.scripted.roles.ScriptRoleMailman; import noppes.npcs.scripted.roles.ScriptRoleTrader; import noppes.npcs.scripted.roles.ScriptRoleTransporter; +import noppes.npcs.scripted.wrapper.ScriptDataAbilities; import noppes.npcs.util.ValueUtil; import java.util.ArrayList; @@ -417,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 */ @@ -844,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; } @@ -1105,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() { @@ -1147,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); @@ -1245,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 */ @@ -1427,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; } @@ -1457,4 +1763,17 @@ public class ScriptNpc extends ScriptLiving imp public IMagicData getMagicData() { return npc.stats.magicData; } + + 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 6206cfbac..6caca7419 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; @@ -39,7 +41,6 @@ import noppes.npcs.api.handler.IOverlayHandler; import noppes.npcs.api.handler.data.IAnimationData; import noppes.npcs.api.handler.data.IDialog; import noppes.npcs.api.handler.data.IMagicData; -import noppes.npcs.api.handler.data.IParty; import noppes.npcs.api.handler.data.IPlayerAttributes; import noppes.npcs.api.handler.data.IQuest; import noppes.npcs.api.handler.data.ISound; @@ -882,17 +883,65 @@ public class ScriptPlayer extends ScriptLivingBase @Override - public IPlayer[] getPartyMembers(){ + public IPlayer[] getPartyMembers() { Party party = this.getData().getPlayerParty(); if (party == null) { throw new CustomNPCsException("Player is not in party"); } - List list = new ArrayList<>(); - for(int i = 0; i < party.getPlayerNamesList().size();i++){ + List list = new ArrayList<>(); + for (int i = 0; i < party.getPlayerNamesList().size(); i++) { IPlayer player = NpcAPI.Instance().getPlayer(party.getPlayerNamesList().get(i)); if (player == null) continue; list.add(player); } return (IPlayer[]) list.toArray(new IPlayer[list.size()]); } + + // ========================================= + // Currency Methods + // ========================================= + + @Override + public long getCurrencyBalance() { + return getData().tradeData.getBalance(); + } + + @Override + public void setCurrencyBalance(long amount) { + getData().tradeData.setBalance(amount); + } + + @Override + public boolean depositCurrency(long amount) { + return getData().tradeData.deposit(amount); + } + + @Override + public boolean withdrawCurrency(long amount) { + return getData().tradeData.withdraw(amount); + } + + @Override + public boolean canAffordCurrency(long amount) { + return getData().tradeData.canAfford(amount); + } + + @Override + public boolean isUsingVaultCurrency() { + return getData().tradeData.isUsingVault(); + } + + @Override + 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 new file mode 100644 index 000000000..a5d5c5bf4 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java @@ -0,0 +1,285 @@ +package noppes.npcs.scripted.event; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.IDamageSource; +import noppes.npcs.api.ability.IAbility; +import noppes.npcs.api.entity.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; + +/** + * Unified ability events for both NPCs and Players. + */ +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(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() { + if (abilityCopy == null && ability != null) { + abilityCopy = ability.deepCopy(); + } + return abilityCopy; + } + + @Override + public IEntityLivingBase getTarget() { + return target; + } + + @Override + public String getHookName() { + return "abilityEvent"; + } + + @Cancelable + public static class StartEvent extends AbilityEvent implements IAbilityEvent.StartEvent { + public StartEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_START.function; + } + } + + @Cancelable + public static class ExecuteEvent extends AbilityEvent implements IAbilityEvent.ExecuteEvent { + public ExecuteEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_EXECUTE.function; + } + } + + public static class InterruptEvent extends AbilityEvent implements IAbilityEvent.InterruptEvent { + private final IDamageSource damageSource; + private final float damage; + + 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; + } + + @Override + public IDamageSource getDamageSource() { + return damageSource; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_INTERRUPT.function; + } + } + + public static class CompleteEvent extends AbilityEvent implements IAbilityEvent.CompleteEvent { + public CompleteEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_COMPLETE.function; + } + } + + @Cancelable + public static class HitEvent extends AbilityEvent implements IAbilityEvent.HitEvent { + private final IEntityLivingBase hitEntity; + private float damage; + private float knockback; + private float knockbackUp; + + public HitEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, + EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp) { + super(entity, 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; + } + } + + public static class TickEvent extends AbilityEvent implements IAbilityEvent.TickEvent { + private final int abilityPhase; + private final int tick; + + public TickEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, int phase, int tick) { + super(entity, ability, target); + this.abilityPhase = phase; + this.tick = tick; + } + + @Override + public int getAbilityPhase() { + return abilityPhase; + } + + @Override + public int getTick() { + return tick; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_TICK.function; + } + } + + @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..4a1fab5a2 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java @@ -0,0 +1,132 @@ +package noppes.npcs.scripted.event; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import noppes.npcs.api.IBlock; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.event.IEnergyProjectileEvent; +import noppes.npcs.constants.EnumScriptType; + +public class EnergyProjectileEvent extends CustomNPCsEvent implements IEnergyProjectileEvent { + public final IEnergyProjectile projectile; + public final IEntity owner; + + public EnergyProjectileEvent(IEnergyProjectile projectile) { + this.projectile = projectile; + this.owner = projectile.getOwner(); + } + + @Override + public IEnergyProjectile getProjectile() { + return projectile; + } + + @Override + public IEntity getOwner() { + return owner; + } + + @Override + public String getHookName() { + return "energyProjectileEvent"; + } + + /** + * energyProjectileFired + */ + public static class FiredEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.FiredEvent { + public FiredEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_FIRED.function; + } + } + + /** + * energyProjectileTick + */ + public static class UpdateEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.UpdateEvent { + public UpdateEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_TICK.function; + } + } + + /** + * energyProjectileEntityImpact + */ + @Cancelable + public static class EntityImpactEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.EntityImpactEvent { + private final IEntity target; + private float damage; + + public EntityImpactEvent(IEnergyProjectile projectile, IEntity target, float damage) { + super(projectile); + this.target = target; + this.damage = damage; + } + + @Override + public IEntity getTarget() { + return target; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT.function; + } + } + + /** + * energyProjectileBlockImpact + */ + public static class BlockImpactEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.BlockImpactEvent { + private final IBlock block; + + public BlockImpactEvent(IEnergyProjectile projectile, IBlock block) { + super(projectile); + this.block = block; + } + + @Override + public IBlock getBlock() { + return block; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT.function; + } + } + + /** + * energyProjectileExpired + */ + public static class ExpiredEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.ExpiredEvent { + public ExpiredEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_EXPIRED.function; + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/event/player/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/DialogEvent.java b/src/main/java/noppes/npcs/scripted/event/player/DialogEvent.java index a5ebfc1ff..a6291cac0 100644 --- a/src/main/java/noppes/npcs/scripted/event/player/DialogEvent.java +++ b/src/main/java/noppes/npcs/scripted/event/player/DialogEvent.java @@ -8,24 +8,36 @@ import noppes.npcs.constants.EnumScriptType; public class DialogEvent extends PlayerEvent implements IDialogEvent { public final IDialog dialog; + public final int dialogId; + public final int optionId; - public DialogEvent(IPlayer player, IDialog dialog) { + public DialogEvent(IPlayer player, int id, int optionId, IDialog dialog) { super(player); this.dialog = dialog; + this.dialogId = id; + this.optionId = optionId; } public IDialog getDialog() { return dialog; } + public int getDialogId() { + return dialogId; + } + + public int getOptionId() { + return optionId; + } + public String getHookName() { return EnumScriptType.DIALOG_EVENT.function; } @Cancelable public static class DialogOpen extends DialogEvent implements IDialogEvent.DialogOpen { - public DialogOpen(IPlayer player, IDialog dialog) { - super(player, dialog); + public DialogOpen(IPlayer player, int id, int optionId, IDialog dialog) { + super(player, id, optionId, dialog); } public String getHookName() { @@ -35,8 +47,8 @@ public class DialogEvent extends PlayerEvent implements IDialogEvent { @Cancelable public static class DialogOption extends DialogEvent implements IDialogEvent.DialogOption { - public DialogOption(IPlayer player, IDialog dialog) { - super(player, dialog); + public DialogOption(IPlayer player, int id, int optionId, IDialog dialog) { + super(player, id, optionId, dialog); } public String getHookName() { @@ -46,13 +58,12 @@ public class DialogEvent extends PlayerEvent implements IDialogEvent { } public static class DialogClosed extends DialogEvent implements IDialogEvent.DialogClosed { - public DialogClosed(IPlayer player, IDialog dialog) { - super(player, dialog); + public DialogClosed(IPlayer player, int id, int optionId, IDialog dialog) { + super(player, id, optionId, dialog); } public String getHookName() { return EnumScriptType.DIALOG_CLOSE.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/ScriptCustomItem.java b/src/main/java/noppes/npcs/scripted/item/ScriptCustomItem.java index 6e85e1555..e3641570e 100644 --- a/src/main/java/noppes/npcs/scripted/item/ScriptCustomItem.java +++ b/src/main/java/noppes/npcs/scripted/item/ScriptCustomItem.java @@ -1,15 +1,19 @@ package noppes.npcs.scripted.item; import cpw.mods.fml.common.eventhandler.Event; +import kamkeel.npcs.network.packets.request.script.item.ItemScriptErrorPacket; +import kamkeel.npcs.network.packets.request.script.item.ItemScriptPacket; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.EventHooks; import noppes.npcs.NBTTags; import noppes.npcs.api.item.IItemCustom; import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.controllers.ScriptContainer; +import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; -import noppes.npcs.controllers.data.INpcScriptHandler; +import noppes.npcs.controllers.data.IScriptHandler; +import noppes.npcs.controllers.data.IScriptHandlerPacket; +import noppes.npcs.controllers.data.IScriptUnit; import noppes.npcs.scripted.CustomNPCsException; import java.util.ArrayList; @@ -18,13 +22,15 @@ import java.util.Map; import java.util.Objects; import java.util.TreeMap; -public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCustom, INpcScriptHandler { - public List scripts = new ArrayList(); +public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCustom, IScriptHandlerPacket { + public List scripts = new ArrayList(); public List errored = new ArrayList(); public String scriptLanguage = "ECMAScript"; public boolean enabled = false; public boolean loaded = false; + private Map clientConsoleText = new TreeMap<>(); + public double durabilityValue = 1.0D; public int stackSize = 64; @@ -60,6 +66,43 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus } } + @Override + public ScriptContext getContext() { + return ScriptContext.ITEM; + } + + @Override + public void requestData() { + ItemScriptErrorPacket.Get(); + ItemScriptPacket.Get(); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + ItemScriptPacket.Save(nbt); + } + + @Override + public GuiDataResult setGuiData(NBTTagCompound compound) { + if (compound.hasKey("LoadComplete")) { + return new GuiDataResult(GuiDataKind.LOAD_COMPLETE, -1); + } + + if (compound.hasKey("ItemScriptConsole")) { + clientConsoleText = NBTTags.GetLongStringMap(compound.getTagList("ItemScriptConsole", 10)); + return new GuiDataResult(GuiDataKind.TAB, -1); + } + + setMCNbt(compound); + loadScriptData(); + return new GuiDataResult(GuiDataKind.METADATA, -1); + } + + @Override + public void sync() { + sendSavePacket(-1, getScripts().size(), getMCNbt()); + } + public int getType() { return 6; } @@ -69,7 +112,7 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus } @Override - public INpcScriptHandler getScriptHandler() { + public IScriptHandler getScriptHandler() { return this; } @@ -95,14 +138,14 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus } for (int i = 0; i < this.scripts.size(); i++) { - ScriptContainer script = this.scripts.get(i); + IScriptUnit script = this.scripts.get(i); if (!this.errored.contains(i)) { - if (script == null || script.errored || !script.hasCode()) + if (script == null || script.hasErrored() || !script.hasCode()) continue; script.run(hookName, event); - if (script.errored) { + if (script.hasErrored()) { this.errored.add(i); } } @@ -129,11 +172,11 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus this.scriptLanguage = lang; } - public void setScripts(List list) { + public void setScripts(List list) { this.scripts = list; } - public List getScripts() { + public List getScripts() { return this.scripts; } @@ -142,10 +185,12 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus } public Map getConsoleText() { - return new TreeMap<>(); + return clientConsoleText; } public void clearConsole() { + clientConsoleText.clear(); + ItemScriptErrorPacket.Clear(); } public int getMaxStackSize() { @@ -234,7 +279,7 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus } public void setAttackSpeed(int speed) { - if(speed <= 0) { + if (speed <= 0) { speed = 10; } this.attackSpeed = speed; 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 3a777134c..f86d5c113 100644 --- a/src/main/java/noppes/npcs/scripted/item/ScriptLinkedItem.java +++ b/src/main/java/noppes/npcs/scripted/item/ScriptLinkedItem.java @@ -4,7 +4,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.item.IItemLinked; import noppes.npcs.controllers.LinkedItemController; -import noppes.npcs.controllers.data.INpcScriptHandler; +import noppes.npcs.controllers.data.IScriptHandler; import noppes.npcs.controllers.data.LinkedItem; public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLinked { @@ -51,7 +51,7 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin } @Override - public INpcScriptHandler getScriptHandler() { + public IScriptHandler getScriptHandler() { if (this.getLinkedItem() == null) return null; return this.getLinkedItem().getScriptHandler(); @@ -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/roles/ScriptRoleTrader.java b/src/main/java/noppes/npcs/scripted/roles/ScriptRoleTrader.java index 825c2e46b..3574e529e 100644 --- a/src/main/java/noppes/npcs/scripted/roles/ScriptRoleTrader.java +++ b/src/main/java/noppes/npcs/scripted/roles/ScriptRoleTrader.java @@ -42,7 +42,7 @@ public class ScriptRoleTrader extends ScriptRoleInterface implements IRoleTrader public IItemStack getSellOption(int slot) { if (slot >= 18 || slot < 0) return null; if (role.inventorySold.items.get(slot) == null) return null; - return NpcAPI.Instance().getIItemStack(role.inventoryCurrency.items.get(slot)); + return NpcAPI.Instance().getIItemStack(role.inventorySold.items.get(slot)); } public IItemStack[] getCurrency(int slot) { @@ -100,7 +100,7 @@ public class ScriptRoleTrader extends ScriptRoleInterface implements IRoleTrader public boolean isSlotEnabled(int slot) { if (slot >= 18 || slot < 0) return false; - return role.disableSlot[slot] > 0; + return role.disableSlot[slot] <= 0; // enabled when NOT disabled } public boolean isSlotEnabled(int slot, IPlayer player) { @@ -128,6 +128,132 @@ public class ScriptRoleTrader extends ScriptRoleInterface implements IRoleTrader role.getArrayByName(player.getDisplayName(), role.playerDisableSlot)[slot] = 0; } + // ==================== Stock System ==================== + + public boolean isStockEnabled() { + return role.stock.enableStock; + } + + public void setStockEnabled(boolean enabled) { + role.stock.enableStock = enabled; + } + + public boolean isPerPlayerStock() { + return role.stock.perPlayer; + } + + public void setPerPlayerStock(boolean perPlayer) { + role.stock.perPlayer = perPlayer; + } + + public int getStockResetType() { + return role.stock.resetType.ordinal(); + } + + public void setStockResetType(int type) { + noppes.npcs.constants.EnumStockReset[] values = noppes.npcs.constants.EnumStockReset.values(); + if (type >= 0 && type < values.length) { + role.stock.resetType = values[type]; + } + } + + public long getCustomResetTime() { + return role.stock.customResetTime; + } + + public void setCustomResetTime(long time) { + role.stock.customResetTime = Math.max(0, time); + } + + public int getMaxStock(int slot) { + if (slot < 0 || slot >= 18) return -1; + return role.stock.maxStock[slot]; + } + + public void setMaxStock(int slot, int amount) { + if (slot >= 0 && slot < 18) { + role.stock.setMaxStock(slot, amount); + } + } + + public int getAvailableStock(int slot) { + if (slot < 0 || slot >= 18) return 0; + return role.stock.getAvailableStock(slot, ""); + } + + public int getAvailableStock(int slot, IPlayer player) { + if (slot < 0 || slot >= 18) return 0; + return role.stock.getAvailableStock(slot, player.getDisplayName()); + } + + public void resetStock() { + long currentTime = role.stock.resetType.isRealTime() + ? System.currentTimeMillis() + : (npc.worldObj != null ? npc.worldObj.getTotalWorldTime() : 0); + role.stock.resetStock(currentTime); + } + + public void resetCooldown() { + long currentTime = role.stock.resetType.isRealTime() + ? System.currentTimeMillis() + : (npc.worldObj != null ? npc.worldObj.getTotalWorldTime() : 0); + role.stock.lastResetTime = currentTime; + } + + public int getCurrentStock(int slot) { + if (slot < 0 || slot >= 18) return -1; + return role.stock.currentStock[slot]; + } + + public void setCurrentStock(int slot, int amount) { + if (slot >= 0 && slot < 18) { + role.stock.currentStock[slot] = amount; + } + } + + public int getPlayerPurchased(int slot, IPlayer player) { + if (slot < 0 || slot >= 18) return 0; + noppes.npcs.controllers.data.TraderStock.PlayerTraderStock pStock = + role.stock.playerStock.get(player.getDisplayName()); + if (pStock == null) return 0; + return pStock.purchasedAmounts[slot]; + } + + public void setPlayerPurchased(int slot, IPlayer player, int amount) { + if (slot < 0 || slot >= 18) return; + noppes.npcs.controllers.data.TraderStock.PlayerTraderStock pStock = + role.stock.playerStock.computeIfAbsent( + player.getDisplayName(), + k -> new noppes.npcs.controllers.data.TraderStock.PlayerTraderStock() + ); + pStock.purchasedAmounts[slot] = Math.max(0, amount); + } + + public long getLastResetTime() { + return role.stock.lastResetTime; + } + + public long getTimeUntilReset() { + long currentTime = role.stock.resetType.isRealTime() + ? System.currentTimeMillis() + : (npc.worldObj != null ? npc.worldObj.getTotalWorldTime() : 0); + return role.stock.getTimeUntilReset(currentTime); + } + + // ==================== Currency Cost System ==================== + + public long getCurrencyCost(int slot) { + return role.getCurrencyCost(slot); + } + + public void setCurrencyCost(int slot, long cost) { + role.setCurrencyCost(slot, cost); + } + + public boolean hasCurrencyCost(int slot) { + return role.hasCurrencyCost(slot); + } + @Override public int getType() { return RoleType.TRADER; diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java new file mode 100644 index 000000000..9fb509761 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java @@ -0,0 +1,241 @@ +package noppes.npcs.scripted.wrapper; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityAction; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.DataAbilities; +import noppes.npcs.api.ability.IAbility; +import noppes.npcs.api.ability.IDataAbilities; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +/** + * Script wrapper for DataAbilities providing API access to NPC abilities. + */ +public class ScriptDataAbilities implements IDataAbilities { + + private final DataAbilities data; + private final EntityNPCInterface npc; + + public ScriptDataAbilities(EntityNPCInterface npc) { + this.npc = npc; + this.data = npc.abilities; + } + + @Override + public boolean isEnabled() { + return data.enabled; + } + + @Override + public void setEnabled(boolean enabled) { + data.enabled = enabled; + } + + @Override + public IAbility[] getAbilities() { + 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 + public void addAbility(IAbility ability) { + if (ability instanceof Ability) { + Ability a = (Ability) ability; + // Validate ability allows NPCs + if (!a.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } + data.addAbility(a); + } + } + + @Override + public void addAbilityReference(String key) { + // Validate ability exists and allows NPCs (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 + } + // Store by UUID/registry key for stable reference + String canonicalKey = ability.getId() != null ? ability.getId() : key; + data.addAbilityReference(canonicalKey); + } + + @Override + public void removeAbility(String abilityId) { + data.removeAbility(abilityId); + } + + @Override + public IAbility getAbility(String abilityId) { + Ability a = data.getAbility(abilityId); + return a != null ? a.deepCopy() : null; + } + + @Override + public boolean hasAbility(String abilityId) { + return data.getAbility(abilityId) != null; + } + + @Override + public boolean isAbilityReference(String abilityId) { + List slots = data.getAbilityActions(); + for (int i = 0; i < slots.size(); i++) { + AbilityAction slot = slots.get(i); + if (slot.isAbilityReference()) { + if (slot.getReferenceId().equals(abilityId)) return true; + } else if (!slot.isReference()) { + Ability a = slot.getAbility(); + if (a != null && abilityId.equals(a.getId())) return false; + } + } + return false; + } + + @Override + public boolean convertToInline(String abilityId) { + List slots = data.getAbilityActions(); + for (int i = 0; i < slots.size(); i++) { + AbilityAction slot = slots.get(i); + if (slot.isAbilityReference() && slot.getReferenceId().equals(abilityId)) { + return data.convertToInline(i); + } + } + return false; + } + + @Override + public void clearAbilities() { + data.clearAbilities(); + } + + @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(); + } + + @Override + public boolean isExecutingAbility() { + return data.isExecutingAbility(); + } + + @Override + public void interruptCurrentAbility() { + data.interruptCurrentAbility(null, 0); + } + + @Override + public void completeCurrentAbility() { + data.completeCurrentAbility(); + } + + @Override + public int getGlobalCooldown() { + return (int) data.getRemainingCooldown(); + } + + @Override + public void setGlobalCooldown(int ticks) { + if (ticks <= 0) { + data.resetCooldown(); + } else { + data.setCooldownEndTime(npc.worldObj.getTotalWorldTime() + ticks); + } + } + + @Override + public void resetCooldowns() { + data.resetCooldown(); + } + + @Override + public boolean forceStartAbility(String abilityId) { + return forceStartAbility(abilityId, null); + } + + @Override + public boolean forceStartAbility(String abilityId, Object target) { + // Find the ability + Ability ability = data.getAbility(abilityId); + if (ability == null) { + return false; + } + + // Resolve target + EntityLivingBase targetEntity = resolveTarget(target); + + // Use the direct force start method + return data.forceStartAbility(ability, targetEntity); + } + + @Override + public boolean executeAbility(String key) { + return executeAbility(key, null); + } + + @Override + public boolean executeAbility(String key, Object target) { + // 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 + } + if (!ability.getAllowedBy().allowsNpc()) { + return false; // Ability is PLAYER_ONLY + } + EntityLivingBase targetEntity = resolveTarget(target); + return data.executeAbility(key, targetEntity); + } + + @Override + public IAbility createAbility(String typeId) { + if (AbilityController.Instance == null) { + return null; + } + return AbilityController.Instance.create(typeId); + } + + /** + * Resolve a target object to an EntityLivingBase. + */ + private EntityLivingBase resolveTarget(Object target) { + if (target == null) { + // Try to use the NPC's current attack target + return npc.getAttackTarget(); + } + + if (target instanceof EntityLivingBase) { + return (EntityLivingBase) target; + } + + if (target instanceof noppes.npcs.api.entity.IEntityLivingBase) { + Object mcEntity = ((noppes.npcs.api.entity.IEntityLivingBase) target).getMCEntity(); + if (mcEntity instanceof EntityLivingBase) { + return (EntityLivingBase) mcEntity; + } + } + + return null; + } +} diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java new file mode 100644 index 000000000..bb6b1b930 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java @@ -0,0 +1,176 @@ +package noppes.npcs.scripted.wrapper; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.api.ability.IAbility; +import noppes.npcs.api.ability.IPlayerAbilityData; +import noppes.npcs.controllers.data.PlayerAbilityData; +import noppes.npcs.controllers.data.PlayerData; + +/** + * Script wrapper for PlayerAbilityData providing API access to player abilities. + */ +public class ScriptPlayerAbilityData implements IPlayerAbilityData { + + private final PlayerAbilityData data; + private final PlayerData playerData; + + public ScriptPlayerAbilityData(PlayerData playerData) { + this.playerData = playerData; + this.data = playerData.abilityData; + } + + @Override + public String[] getUnlockedAbilities() { + return data.getUnlockedAbilities(); + } + + @Override + public void unlockAbility(String 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 + } + if (!ability.getAllowedBy().allowsPlayer()) { + return; // Ability is NPC-only + } + // Use canonical key (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId() != null ? ability.getId() : key; + data.unlockAbility(canonicalKey); + } + + @Override + public void lockAbility(String key) { + String canonicalKey = resolveCanonicalKey(key); + data.lockAbility(canonicalKey); + } + + @Override + public boolean hasUnlockedAbility(String key) { + String canonicalKey = resolveCanonicalKey(key); + return data.hasUnlockedAbility(canonicalKey); + } + + @Override + public int getSelectedIndex() { + return data.getSelectedIndex(); + } + + @Override + public void setSelectedIndex(int index) { + data.setSelectedIndex(index); + } + + @Override + public String getSelectedAbilityKey() { + return data.getSelectedAbilityKey(); + } + + @Override + public void selectNext() { + data.selectNext(); + } + + @Override + public void selectPrevious() { + data.selectPrevious(); + } + + @Override + public boolean isExecutingAbility() { + return data.isExecutingAbility(); + } + + @Override + public IAbility getCurrentAbility() { + Ability a = data.getCurrentAbility(); + return a != null ? a.deepCopy() : null; + } + + @Override + public void interruptCurrentAbility() { + data.interruptCurrentAbility(); + } + + @Override + public void completeCurrentAbility() { + data.completeCurrentAbility(); + } + + @Override + public boolean isOnCooldown() { + return data.isOnCooldown(); + } + + @Override + public boolean isOnCooldown(String key) { + EntityPlayer player = playerData.player; + if (player == null) return false; + return data.isOnCooldown(key, player); + } + + @Override + public void resetCooldown() { + data.resetCooldown(); + } + + @Override + public void resetCooldown(String key) { + data.resetCooldown(key); + } + + @Override + public void resetAllCooldowns() { + data.resetAllCooldowns(); + } + + @Override + public boolean activateAbility() { + EntityPlayer player = playerData.player; + if (player == null) return false; + return data.activateAbility(player); + } + + @Override + public boolean activateAbility(String key) { + EntityPlayer player = playerData.player; + 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/noppes/npcs/util/NPCMountUtil.java b/src/main/java/noppes/npcs/util/NPCMountUtil.java index 6303f67b9..9c3cce57f 100644 --- a/src/main/java/noppes/npcs/util/NPCMountUtil.java +++ b/src/main/java/noppes/npcs/util/NPCMountUtil.java @@ -5,10 +5,10 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; import noppes.npcs.CustomNpcs; +import noppes.npcs.constants.EnumRoleType; import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.constants.EnumRoleType; import noppes.npcs.roles.RoleMount; public final class NPCMountUtil { diff --git a/src/main/java/noppes/npcs/util/ScriptToStringHelper.java b/src/main/java/noppes/npcs/util/ScriptToStringHelper.java new file mode 100644 index 000000000..d34e5c1cd --- /dev/null +++ b/src/main/java/noppes/npcs/util/ScriptToStringHelper.java @@ -0,0 +1,210 @@ +package noppes.npcs.util; + +import com.google.common.base.Preconditions; + +import javax.annotation.CheckForNull; +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; + +/** + * Utility class for building toString representations of script handlers. + * Used by GlobalNPCDataScript and PlayerDataScript for notice strings. + */ +public final class ScriptToStringHelper { + private final String className; + private final ValueHolder holderHead; + private ValueHolder holderTail; + private boolean omitNullValues; + private boolean omitEmptyValues; + + private ScriptToStringHelper(String className) { + this.holderHead = new ValueHolder(); + this.holderTail = this.holderHead; + this.omitNullValues = false; + this.omitEmptyValues = false; + this.className = Preconditions.checkNotNull(className); + } + + public static ScriptToStringHelper toStringHelper(Object self) { + return new ScriptToStringHelper(self.getClass().getSimpleName()); + } + + public ScriptToStringHelper omitNullValues() { + this.omitNullValues = true; + return this; + } + + public ScriptToStringHelper add(String name, @CheckForNull Object value) { + return this.addHolder(name, value); + } + + public ScriptToStringHelper add(String name, boolean value) { + return this.addUnconditionalHolder(name, String.valueOf(value)); + } + + public ScriptToStringHelper add(String name, char value) { + return this.addUnconditionalHolder(name, String.valueOf(value)); + } + + public ScriptToStringHelper add(String name, double value) { + return this.addUnconditionalHolder(name, String.valueOf(value)); + } + + public ScriptToStringHelper add(String name, float value) { + return this.addUnconditionalHolder(name, String.valueOf(value)); + } + + public ScriptToStringHelper add(String name, int value) { + return this.addUnconditionalHolder(name, String.valueOf(value)); + } + + public ScriptToStringHelper add(String name, long value) { + return this.addUnconditionalHolder(name, String.valueOf(value)); + } + + public ScriptToStringHelper addValue(@CheckForNull Object value) { + return this.addHolder(value); + } + + public ScriptToStringHelper addValue(boolean value) { + return this.addUnconditionalHolder(String.valueOf(value)); + } + + public ScriptToStringHelper addValue(char value) { + return this.addUnconditionalHolder(String.valueOf(value)); + } + + public ScriptToStringHelper addValue(double value) { + return this.addUnconditionalHolder(String.valueOf(value)); + } + + public ScriptToStringHelper addValue(float value) { + return this.addUnconditionalHolder(String.valueOf(value)); + } + + public ScriptToStringHelper addValue(int value) { + return this.addUnconditionalHolder(String.valueOf(value)); + } + + public ScriptToStringHelper addValue(long value) { + return this.addUnconditionalHolder(String.valueOf(value)); + } + + private static boolean isEmpty(Object value) { + if (value instanceof CharSequence) { + return ((CharSequence) value).length() == 0; + } else if (value instanceof Collection) { + return ((Collection) value).isEmpty(); + } else if (value instanceof Map) { + return ((Map) value).isEmpty(); + } else if (value instanceof Optional) { + return !((Optional) value).isPresent(); + } else if (value instanceof OptionalInt) { + return !((OptionalInt) value).isPresent(); + } else if (value instanceof OptionalLong) { + return !((OptionalLong) value).isPresent(); + } else if (value instanceof OptionalDouble) { + return !((OptionalDouble) value).isPresent(); + } else if (value instanceof com.google.common.base.Optional) { + return !((com.google.common.base.Optional) value).isPresent(); + } else if (value.getClass().isArray()) { + return Array.getLength(value) == 0; + } else { + return false; + } + } + + public String toString() { + boolean omitNullValuesSnapshot = this.omitNullValues; + boolean omitEmptyValuesSnapshot = this.omitEmptyValues; + String nextSeparator = ""; + StringBuilder builder = (new StringBuilder(32)).append(this.className).append('{'); + for (ValueHolder valueHolder = this.holderHead.next; valueHolder != null; valueHolder = valueHolder.next) { + Object value = valueHolder.value; + if (!(valueHolder instanceof UnconditionalValueHolder)) { + if (value == null) { + if (omitNullValuesSnapshot) { + continue; + } + } else if (omitEmptyValuesSnapshot && isEmpty(value)) { + continue; + } + } + builder.append(nextSeparator); + nextSeparator = ", "; + if (valueHolder.name != null) { + builder.append(valueHolder.name).append('='); + } + if (value != null && value.getClass().isArray()) { + Object[] objectArray = new Object[]{value}; + String arrayString = Arrays.deepToString(objectArray); + builder.append(arrayString, 1, arrayString.length() - 1); + } else { + builder.append(value); + } + } + return builder.append('}').toString(); + } + + private ValueHolder addHolder() { + ValueHolder valueHolder = new ValueHolder(); + this.holderTail = this.holderTail.next = valueHolder; + return valueHolder; + } + + private ScriptToStringHelper addHolder(@CheckForNull Object value) { + ValueHolder valueHolder = this.addHolder(); + valueHolder.value = value; + return this; + } + + private ScriptToStringHelper addHolder(String name, @CheckForNull Object value) { + ValueHolder valueHolder = this.addHolder(); + valueHolder.value = value; + valueHolder.name = Preconditions.checkNotNull(name); + return this; + } + + private UnconditionalValueHolder addUnconditionalHolder() { + UnconditionalValueHolder valueHolder = new UnconditionalValueHolder(); + this.holderTail = this.holderTail.next = valueHolder; + return valueHolder; + } + + private ScriptToStringHelper addUnconditionalHolder(Object value) { + UnconditionalValueHolder valueHolder = this.addUnconditionalHolder(); + valueHolder.value = value; + return this; + } + + private ScriptToStringHelper addUnconditionalHolder(String name, Object value) { + UnconditionalValueHolder valueHolder = this.addUnconditionalHolder(); + valueHolder.value = value; + valueHolder.name = Preconditions.checkNotNull(name); + return this; + } + + private static final class UnconditionalValueHolder extends ValueHolder { + private UnconditionalValueHolder() { + super(); + } + } + + private static class ValueHolder { + @CheckForNull + String name; + @CheckForNull + Object value; + @CheckForNull + ValueHolder next; + + private ValueHolder() { + } + } +} diff --git a/src/main/java/noppes/npcs/util/ValueUtil.java b/src/main/java/noppes/npcs/util/ValueUtil.java index 48cd0b1a9..71846afcc 100644 --- a/src/main/java/noppes/npcs/util/ValueUtil.java +++ b/src/main/java/noppes/npcs/util/ValueUtil.java @@ -1,6 +1,15 @@ package noppes.npcs.util; public class ValueUtil { + + public static float lerp(float start, float end, float delta) { + return start + delta * (end - start); + } + + public static double lerp(double start, double end, double delta) { + return start + delta * (end - start); + } + public static float clamp(float given, float min, float max) { if (given < min) return min; @@ -48,4 +57,16 @@ public class ValueUtil { return max; return given; } + + public static String format(double value) { + return (value % 1 == 0) ? String.format("%.0f", value) : String.format("%.2f", value); + } + + public static String format(String precision, float value) { + return (value % 1 == 0) ? String.format("%.0f", value) : String.format(precision, value); + } + + public static String format(String precision, double value) { + return (value % 1 == 0) ? String.format("%.0f", value) : String.format(precision, value); + } } diff --git a/src/main/java/somehussar/gui/AnnotatedGui.java b/src/main/java/somehussar/gui/AnnotatedGui.java new file mode 100644 index 000000000..7a1244f89 --- /dev/null +++ b/src/main/java/somehussar/gui/AnnotatedGui.java @@ -0,0 +1,44 @@ +package somehussar.gui; + +import net.minecraft.client.gui.GuiScreen; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.SubGuiInterface; +import somehussar.gui.annotationHandling.GuiFieldHandler; +import somehussar.gui.annotationHandling.field.EditableField; + +public class AnnotatedGui extends SubGuiInterface { + private final GuiFieldHandler.ClassMetadata metadata; + + public AnnotatedGui(T object, String[] groups, GuiScreen parent) { + this(object, groups, parent, 256, 216); + } + + public AnnotatedGui(T object, String[] groups, GuiScreen parent, int xSize, int ySize) { + if (object != null) + metadata = GuiFieldHandler.getMetadata(object.getClass()); + else + metadata = null; + setBackground("menubg.png"); + this.xSize = xSize; + this.ySize = ySize; + closeOnEsc = true; + this.parent = parent; + } + + @Override + public void initGui() { + super.initGui(); + if (metadata == null) + return; + + int i = 0; + for (EditableField field : metadata.getParent().getDeclaredFields()) { + addLabel(new GuiNpcLabel(i++, field.getName(), guiLeft + 8, guiTop + i * 15 + 5)); + } + } + + @Override + public void save() { + + } +} diff --git a/src/main/java/somehussar/gui/ImmediateTextField.java b/src/main/java/somehussar/gui/ImmediateTextField.java new file mode 100644 index 000000000..fba3c5a4d --- /dev/null +++ b/src/main/java/somehussar/gui/ImmediateTextField.java @@ -0,0 +1,33 @@ +package somehussar.gui; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import somehussar.gui.annotationHandling.field.EditableField; + +public class ImmediateTextField extends GuiNpcTextField { + private final EditableField editableField; +// +// private final GuiNpcTextField encapsulatedField; + + 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); + + this.editableField = field; + } + + @Override + public void drawTextBox(int mousX, int mousY) { + + } + + @Override + public void mouseClicked(int xPos, int yPos, int k) { + xPos -= this.xPosition; + yPos -= this.yPosition; + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/FieldConstraint.java b/src/main/java/somehussar/gui/annotationHandling/FieldConstraint.java new file mode 100644 index 000000000..7a9b124e4 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/FieldConstraint.java @@ -0,0 +1,5 @@ +package somehussar.gui.annotationHandling; + +public interface FieldConstraint { + void validate(Object value); +} diff --git a/src/main/java/somehussar/gui/annotationHandling/FieldConstraints.java b/src/main/java/somehussar/gui/annotationHandling/FieldConstraints.java new file mode 100644 index 000000000..9a48fd1e3 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/FieldConstraints.java @@ -0,0 +1,27 @@ +package somehussar.gui.annotationHandling; + +public final class FieldConstraints { + + private static final FieldConstraints EMPTY = + new FieldConstraints(new FieldConstraint[0]); + + private final FieldConstraint[] constraints; + + public FieldConstraints(FieldConstraint[] constraints) { + this.constraints = constraints; + } + + public static FieldConstraints empty() { + return EMPTY; + } + + public void validate(Object value) { + for (FieldConstraint c : constraints) { + c.validate(value); + } + } + + public boolean isEmpty() { + return constraints.length == 0; + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java b/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java new file mode 100644 index 000000000..95a74658e --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java @@ -0,0 +1,51 @@ +package somehussar.gui.annotationHandling; + +import java.lang.annotation.Annotation; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface GuiEditable { + + @Retention(RetentionPolicy.RUNTIME) + @interface Field { + String value(); + + /** + * Display order + * Higher value = higher priority. + */ + int order() default 0; + + } + + @Retention(RetentionPolicy.RUNTIME) + @interface Group { + String value(); + } + + @Retention(RetentionPolicy.RUNTIME) + @interface Size { + int labelWidth() default 60; + + int fieldWidth() default 50; + + GuiEditable.Size DEFAULT_SIZE = new GuiEditable.Size() { + @Override + public int labelWidth() { + return 60; + } + + @Override + public int fieldWidth() { + return 50; + } + + @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 new file mode 100644 index 000000000..b54e70e52 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java @@ -0,0 +1,142 @@ +package somehussar.gui.annotationHandling; + +import somehussar.gui.annotationHandling.constraints.ConstraintFactory; +import somehussar.gui.annotationHandling.constraints.NumericConstraint; +import somehussar.gui.annotationHandling.constraints.NumericConstraintFactory; +import somehussar.gui.annotationHandling.field.EditableField; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class GuiFieldHandler { + + private static final Map, ClassMetadata> CACHE = new HashMap<>(); + private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + + public static final Map, ConstraintFactory> registry = new HashMap<>(); + + static { + registry.put(NumericConstraint.class, new NumericConstraintFactory()); + } + + + private GuiFieldHandler() { + } + + public static ClassMetadata getMetadata(Class type) { + return CACHE.computeIfAbsent(type, GuiFieldHandler::scanClass); + } + + @SuppressWarnings({"RawUseOfParameterized"}) + private static ClassMetadata scanClass(Class type) { + if (!type.isAnnotationPresent(GuiEditable.class)) { + return null; + } + + ClassMetadata parent = null; + + Class superCls = type.getSuperclass(); + if (superCls != null && superCls != Object.class) { + parent = getMetadata(superCls); + } + + List list = new ArrayList<>(); + for (Field field : type.getDeclaredFields()) { + EditableField editableField = createEditableField(field); + + if (editableField != null) { + list.add(editableField); + } + } + + return new ClassMetadata( + type, + list.toArray(list.toArray(new EditableField[0])), + parent + ); + } + + @SuppressWarnings({"RawUseOfParameterized", "unchecked"}) + private static EditableField createEditableField(Field field) { + try { + GuiEditable.Field fieldConfig = field.getAnnotation(GuiEditable.Field.class); + if (fieldConfig == null) return null; + if (Modifier.isFinal(field.getModifiers())) return null; + + GuiEditable.Size size = field.getAnnotation(GuiEditable.Size.class); + if (size == null) size = GuiEditable.Size.DEFAULT_SIZE; + ; + + field.setAccessible(true); + EditableField.Builder builder = new EditableField.Builder() + .name(fieldConfig.value()) + .type(field.getType()) + .getter(LOOKUP.unreflectGetter(field)) + .setter(LOOKUP.unreflectSetter(field)) + .constraints(buildConstraints(field)) + .order(fieldConfig.order()) + .size(size); + + + GuiEditable.Group group = field.getAnnotation(GuiEditable.Group.class); + if (group != null) + builder.group(group.value()); + + + return builder.build(); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "Failed to bind field: " + field, e); + } + } + + @SuppressWarnings({"RawUseOfParameterized", "unchecked"}) + private static FieldConstraints buildConstraints(Field field) { + List list = new ArrayList<>(); + + for (Annotation ann : field.getAnnotations()) { + ConstraintFactory factory = registry.get(ann.annotationType()); + if (factory != null) { + FieldConstraint c = factory.create(field, ann); + list.add(c); + } + } + + if (list.isEmpty()) return FieldConstraints.empty(); + return new FieldConstraints(list.toArray(new FieldConstraint[0])); + } + + + @SuppressWarnings({"RawUseOfParameterized"}) + public static final class ClassMetadata { + final Class type; + final EditableField[] fields; // only declared fields + final ClassMetadata parent; // superclass metadata (nullable) + + ClassMetadata(Class type, EditableField[] fields, ClassMetadata parent) { + this.type = type; + this.fields = fields; + this.parent = parent; + } + + public ClassMetadata getParent() { + return parent; + } + + public EditableField[] getDeclaredFields() { + return fields; + } + + public Class getType() { + return type; + } + } + + +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/ConstraintFactory.java b/src/main/java/somehussar/gui/annotationHandling/constraints/ConstraintFactory.java new file mode 100644 index 000000000..d62de94b4 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/ConstraintFactory.java @@ -0,0 +1,10 @@ +package somehussar.gui.annotationHandling.constraints; + +import somehussar.gui.annotationHandling.FieldConstraint; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; + +public interface ConstraintFactory { + FieldConstraint create(Field field, A annotation); +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java new file mode 100644 index 000000000..faccc6418 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java @@ -0,0 +1,14 @@ +package somehussar.gui.annotationHandling.constraints; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(value = RetentionPolicy.RUNTIME) +@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/constraints/NumericConstraintFactory.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraintFactory.java new file mode 100644 index 000000000..24b08ceb9 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraintFactory.java @@ -0,0 +1,13 @@ +package somehussar.gui.annotationHandling.constraints; + +import somehussar.gui.annotationHandling.FieldConstraint; + +import java.lang.reflect.Field; + +public class NumericConstraintFactory implements ConstraintFactory { + + @Override + public FieldConstraint create(Field field, NumericConstraint ann) { + return new NumericRangeConstraint(ann.min(), ann.max()); + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericRangeConstraint.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericRangeConstraint.java new file mode 100644 index 000000000..198888d25 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericRangeConstraint.java @@ -0,0 +1,35 @@ +package somehussar.gui.annotationHandling.constraints; + +import somehussar.gui.annotationHandling.FieldConstraint; + +public final class NumericRangeConstraint implements FieldConstraint { + + private final double min; + private final double max; + + public NumericRangeConstraint(double min, double max) { + this.min = min; + this.max = max; + } + + @Override + public void validate(Object value) { + if (!(value instanceof Number)) { + throw new ConstraintViolationException("Expected number, got " + value); + } + + double v = ((Number) value).doubleValue(); + if (v < min || v > max) { + throw new ConstraintViolationException( + "Value " + v + " must be between " + min + " and " + max + ); + } + } + + public static final class ConstraintViolationException extends RuntimeException { + public ConstraintViolationException(String message) { + super(message); + } + } + +} diff --git a/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java b/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java new file mode 100644 index 000000000..97e8500f1 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java @@ -0,0 +1,118 @@ +package somehussar.gui.annotationHandling.field; + +import somehussar.gui.annotationHandling.FieldConstraints; +import somehussar.gui.annotationHandling.GuiEditable; + +import java.lang.invoke.MethodHandle; + +public final class EditableField { + + private final String name; + private final Class type; + private final MethodHandle getter; + private final MethodHandle setter; + private final FieldConstraints constraints; + private final int order; + private final String group; + private final GuiEditable.Size size; + + public String getName() { + return name; + } + + public Class getType() { + return type; + } + + @SuppressWarnings({"unchecked"}) + public T read(T instance) { + try { + return (T) getter.invoke(instance); + } catch (Throwable t) { + throw new RuntimeException("Failed to read field " + name, t); + } + } + + public void write(T instance, T value) { + constraints.validate(value); + try { + setter.invoke(instance, value); + } catch (Throwable t) { + throw new RuntimeException("Failed to write field " + name, t); + } + } + + public FieldConstraints getConstraints() { + return this.constraints; + } + + public int getOrder() { + return this.order; + } + + EditableField(Builder b) { + this.name = b.name; + this.type = b.type; + this.getter = b.getter; + this.setter = b.setter; + this.constraints = b.constraints; + this.order = b.order; + this.group = b.group; + this.size = b.size; + } + + public static class Builder { + private String name; + private Class type; + private MethodHandle getter; + private MethodHandle setter; + private FieldConstraints constraints; + private int order; + 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 EditableField build() { + return new EditableField<>(this); + } + } +} diff --git a/src/main/java/somehussar/janino/AdvancedClassFilter.java b/src/main/java/somehussar/janino/AdvancedClassFilter.java new file mode 100644 index 000000000..7c2d51834 --- /dev/null +++ b/src/main/java/somehussar/janino/AdvancedClassFilter.java @@ -0,0 +1,57 @@ +package somehussar.janino; + +import io.github.somehussar.janinoloader.api.delegates.LoadClassCondition; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class AdvancedClassFilter implements LoadClassCondition { + + private final Set allowedClasses = new HashSet<>(); + private final Set allowedWildCards = new HashSet<>(); + private final Set bannedClasses = new HashSet<>(); + private final Set bannedWildCards = new HashSet<>(); + + public AdvancedClassFilter() { + addClasses("java.io.Serializable", "java.util.Iterator"); + addRegexes("java\\.lang\\..*"); + } + + public AdvancedClassFilter addRegexes(String... classRegexes) { + allowedWildCards.addAll(Arrays.stream(classRegexes).map(Pattern::compile).collect(Collectors.toList())); + return this; + } + + public AdvancedClassFilter banRegexes(String... classRegexes) { + bannedWildCards.addAll(Arrays.stream(classRegexes).map(Pattern::compile).collect(Collectors.toList())); + return this; + } + + public AdvancedClassFilter addClasses(String... classPath) { + allowedClasses.addAll(Arrays.asList(classPath)); + return this; + } + + public AdvancedClassFilter banClasses(String... classPath) { + bannedClasses.addAll(Arrays.asList(classPath)); + return this; + } + + + @Override + public boolean isValid(String name) { + if (bannedClasses.contains(name)) + return false; + if (bannedWildCards.stream().anyMatch(pattern -> pattern.matcher(name).matches())) + return false; + + if (name.startsWith("java.lang")) return true; + + if (allowedClasses.contains(name)) return true; + + return allowedWildCards.stream().anyMatch(pattern -> pattern.matcher(name).matches()); + } +} diff --git a/src/main/java/somehussar/janino/EntityUnloadListener.java b/src/main/java/somehussar/janino/EntityUnloadListener.java new file mode 100644 index 000000000..b4777e712 --- /dev/null +++ b/src/main/java/somehussar/janino/EntityUnloadListener.java @@ -0,0 +1,76 @@ +package somehussar.janino; + +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.IWorldAccess; +import noppes.npcs.entity.EntityNPCInterface; + +public class EntityUnloadListener implements IWorldAccess { + @Override + public void markBlockForUpdate(int p_147586_1_, int p_147586_2_, int p_147586_3_) { + + } + + @Override + public void markBlockForRenderUpdate(int p_147588_1_, int p_147588_2_, int p_147588_3_) { + + } + + @Override + public void markBlockRangeForRenderUpdate(int p_147585_1_, int p_147585_2_, int p_147585_3_, int p_147585_4_, int p_147585_5_, int p_147585_6_) { + + } + + @Override + public void playSound(String soundName, double x, double y, double z, float volume, float pitch) { + + } + + @Override + public void playSoundToNearExcept(EntityPlayer p_85102_1_, String p_85102_2_, double p_85102_3_, double p_85102_5_, double p_85102_7_, float p_85102_9_, float p_85102_10_) { + + } + + @Override + public void spawnParticle(String p_72708_1_, double p_72708_2_, double p_72708_4_, double p_72708_6_, double p_72708_8_, double p_72708_10_, double p_72708_12_) { + + } + + @Override + public void onEntityCreate(Entity p_72703_1_) { + + } + + @Override + public void onEntityDestroy(Entity entity) { + if (entity instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) entity; + // TODO: REMOVE SCRIPTED OBJECT AND CLASSLOADER FOR IT + } + } + + @Override + public void playRecord(String p_72702_1_, int p_72702_2_, int p_72702_3_, int p_72702_4_) { + + } + + @Override + public void broadcastSound(int p_82746_1_, int p_82746_2_, int p_82746_3_, int p_82746_4_, int p_82746_5_) { + + } + + @Override + public void playAuxSFX(EntityPlayer p_72706_1_, int p_72706_2_, int p_72706_3_, int p_72706_4_, int p_72706_5_, int p_72706_6_) { + + } + + @Override + public void destroyBlockPartially(int p_147587_1_, int p_147587_2_, int p_147587_3_, int p_147587_4_, int p_147587_5_) { + + } + + @Override + public void onStaticEntitiesChanged() { + + } +} 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_BeamDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json new file mode 100644 index 000000000..c98f89236 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json @@ -0,0 +1,203 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -25.0f, + "Rotation0": -85.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 20.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 25.0f, + "Rotation0": -85.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -20.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -25.0f, + "Rotation0": -85.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": -20.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 25.0f, + "Rotation0": -85.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 20.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 3, + "Smooth": 0b, + "ID": 12, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_BeamDual_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json new file mode 100644 index 000000000..d793e3f22 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json @@ -0,0 +1,201 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "LEFT_ARM", + "Rotation1": -90.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Duration": 60 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "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_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 75.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -75.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 25.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": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 15 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 2, + "Smooth": 0b, + "ID": 11, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_BeamDual_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Beam_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Beam_Active.json new file mode 100644 index 000000000..e285bc679 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Beam_Active.json @@ -0,0 +1,86 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "LEFT_ARM", + "Rotation1": 12.0f, + "Rotation0": -75.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 50.0f + }, + { + "Pivot2": -4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 18.0f, + "Pivot0": -4.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": -18.0f, + "Rotation0": -107.0f, + "Pivot0": -1.0f, + "Pivot1": 2.0f, + "Rotation2": 50.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 30 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 2, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Beam_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Beam_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Beam_Windup.json new file mode 100644 index 000000000..62e54167a --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Beam_Windup.json @@ -0,0 +1,230 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 50.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "LEFT_ARM", + "Rotation1": 94.0f, + "Rotation0": -94.0f, + "Pivot0": -4.0f, + "Pivot1": 3.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": 75.0f, + "Rotation0": -56.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 25.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "LEFT_ARM", + "Rotation1": 107.0f, + "Rotation0": -94.0f, + "Pivot0": -5.0f, + "Pivot1": 3.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -56.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + } + ], + "Smooth": 0b, + "Duration": 30 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 18.0f, + "Pivot0": -4.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "LEFT_ARM", + "Rotation1": 12.0f, + "Rotation0": -75.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 50.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "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": -6.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": -18.0f, + "Rotation0": -107.0f, + "Pivot0": -1.0f, + "Pivot1": 2.0f, + "Rotation2": 50.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 1, + "Smooth": 0b, + "ID": 1, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Beam_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json new file mode 100644 index 000000000..82b2294ca --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json @@ -0,0 +1,59 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 45.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 28, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Charge_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json new file mode 100644 index 000000000..c627007e3 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json @@ -0,0 +1,122 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 44.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -10.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -10.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 75.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 18 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 45.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 27, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Charge_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json new file mode 100644 index 000000000..1fdf06c24 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json @@ -0,0 +1,86 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 18.0f, + "Rotation0": 88.0f, + "Pivot0": -10.0f, + "Pivot1": 0.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "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": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 6.0f, + "Rotation0": 82.0f, + "Pivot0": 3.0f, + "Pivot1": 3.0f, + "Rotation2": 88.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_LEG", + "Rotation1": 107.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 56.0f, + "Rotation0": 0.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 20 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 14, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Cutter_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json new file mode 100644 index 000000000..153d90f12 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json @@ -0,0 +1,156 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 1.0f, + "Part": "LEFT_ARM", + "Rotation1": -31.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": -31.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": -75.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 88.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 18.0f, + "Rotation0": 12.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 20 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 18.0f, + "Rotation0": 88.0f, + "Pivot0": -10.0f, + "Pivot1": 0.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "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": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 6.0f, + "Rotation0": 82.0f, + "Pivot0": 3.0f, + "Pivot1": 3.0f, + "Rotation2": 88.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_LEG", + "Rotation1": 107.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 56.0f, + "Rotation0": 0.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 13, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Cutter_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json new file mode 100644 index 000000000..98a3299a2 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json @@ -0,0 +1,266 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.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_ARM", + "Rotation1": 0.0f, + "Rotation0": 120.0f, + "Pivot0": 0.0f, + "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", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.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, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 75.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "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", + "Rotation1": -12.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.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": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 75.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "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", + "Rotation1": -12.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.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": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 75.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "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", + "Rotation1": -12.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.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": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 18, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_DiscDual_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json new file mode 100644 index 000000000..0dc050b19 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json @@ -0,0 +1,293 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 360.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "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, + "Duration": 10 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.35f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 360.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 + }, + { + "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, + "Duration": 46 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "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, + "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": 2b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.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_ARM", + "Rotation1": 0.0f, + "Rotation0": 120.0f, + "Pivot0": 0.0f, + "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", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.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, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 3, + "Smooth": 0b, + "ID": 17, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_DiscDual_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Disc_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Disc_Active.json new file mode 100644 index 000000000..13fe07485 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Disc_Active.json @@ -0,0 +1,77 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": -44.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 4.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_ARM", + "Rotation1": 31.0f, + "Rotation0": 44.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": -82.0f + }, + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 10 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 9, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Disc_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Disc_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Disc_Windup.json new file mode 100644 index 000000000..a8231ff50 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Disc_Windup.json @@ -0,0 +1,896 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 12 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.2f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": 25.0f, + "Pivot0": -1.0f, + "Pivot1": -2.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -2.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 110.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": -2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.4f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 120.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": -18.0f, + "Pivot0": 3.0f, + "Pivot1": -1.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": 0.0f, + "Pivot1": 8.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": -2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": -18.0f, + "Pivot0": 3.0f, + "Pivot1": -1.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -94.0f, + "Pivot0": 0.0f, + "Pivot1": 8.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.6f, + "FrameParts": [ + { + "Pivot2": -2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": 25.0f, + "Pivot0": -1.0f, + "Pivot1": -2.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -2.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 110.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": -2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.2f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 120.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.25f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": -18.0f, + "Pivot0": 3.0f, + "Pivot1": -1.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": -94.0f, + "Pivot0": 0.0f, + "Pivot1": 8.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.5f, + "FrameParts": [ + { + "Pivot2": -2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 90.0f, + "Rotation0": -18.0f, + "Pivot0": 3.0f, + "Pivot1": -1.0f, + "Rotation2": 180.0f + }, + { + "Pivot2": 1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -94.0f, + "Pivot0": 0.0f, + "Pivot1": 8.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 4.0f, + "Pivot1": 3.0f, + "Rotation2": 31.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.5f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 31.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": -44.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 4.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_ARM", + "Rotation1": 31.0f, + "Rotation0": 44.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": -82.0f + }, + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 4 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 11, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Disc_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json b/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json new file mode 100644 index 000000000..38e42bd1e --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json @@ -0,0 +1,770 @@ +{ + "Loop": 11, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 20 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 8 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 11, + "Smooth": 0b, + "ID": 100, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Generic_Dazed", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json new file mode 100644 index 000000000..258320341 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json @@ -0,0 +1,50 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": -120.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 80.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 18, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Guard_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json new file mode 100644 index 000000000..9194dfd72 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json @@ -0,0 +1,203 @@ +{ + "Loop": 2, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": -120.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 80.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 60.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -60.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.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": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 60.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -60.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.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": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 17, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Guard_Counter", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json new file mode 100644 index 000000000..fa6b44543 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json @@ -0,0 +1,77 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "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": 20 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 19, + "Smooth": 0b, + "ID": 16, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_HeavyHit_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json new file mode 100644 index 000000000..a276742ba --- /dev/null +++ b/src/main/resources/assets/customnpcs/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/animations/Ability_Laser_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Laser_Active.json new file mode 100644 index 000000000..f3117602a --- /dev/null +++ b/src/main/resources/assets/customnpcs/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_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Laser_Windup.json new file mode 100644 index 000000000..c12700304 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Laser_Windup.json @@ -0,0 +1,77 @@ +{ + "Loop": -1, + "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": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 90.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": 15 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 4, + "Smooth": 0b, + "ID": 12, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Laser_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json new file mode 100644 index 000000000..e34dd5d21 --- /dev/null +++ b/src/main/resources/assets/customnpcs/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/animations/Ability_OrbBarrage_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json new file mode 100644 index 000000000..dfe8f601b --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json @@ -0,0 +1,201 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + } + ], + "Duration": 8 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 19 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -25.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 2, + "Smooth": 0b, + "ID": 25, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbBarrage_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json new file mode 100644 index 000000000..c632afc9c --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json @@ -0,0 +1,266 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": 0.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -4.0f, + "Part": "HEAD", + "Rotation1": -37.0f, + "Rotation0": 56.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -202.0f, + "Rotation0": -75.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -4.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 37.0f, + "Rotation0": -18.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 6.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -12.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": 1.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 + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 37.0f, + "Rotation0": -18.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 6.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -12.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": 1.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 + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 37.0f, + "Rotation0": -18.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 6.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -12.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": 1.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 + } + ], + "Smooth": 0b, + "Duration": 20 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 3, + "Smooth": 0b, + "ID": 22, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbDual_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json new file mode 100644 index 000000000..44c974b4c --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json @@ -0,0 +1,327 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": -12.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -63.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_LEG", + "Rotation1": -50.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 6.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 15 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -151.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": -31.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -18.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.75f, + "FrameParts": [ + { + "Pivot2": 6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -151.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": -31.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -18.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -151.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": -31.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -18.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": 0.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -4.0f, + "Part": "HEAD", + "Rotation1": -37.0f, + "Rotation0": 56.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -202.0f, + "Rotation0": -75.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -4.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 21, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbDual_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json new file mode 100644 index 000000000..cb8973971 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json @@ -0,0 +1,77 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": -37.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_LEG", + "Rotation1": -75.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -50.0f, + "Rotation0": 50.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": -56.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": -44.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 20 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 13, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Orb_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Windup.json new file mode 100644 index 000000000..1be8ef71c --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Windup.json @@ -0,0 +1,129 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_LEG", + "Rotation1": 69.0f, + "Rotation0": 12.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -88.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -90.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 70.0f, + "Rotation0": -125.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -50.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 31.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 26 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": -37.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_LEG", + "Rotation1": -75.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -50.0f, + "Rotation0": 50.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": -56.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": -44.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 3, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Orb_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json new file mode 100644 index 000000000..8ea8fc18b --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json @@ -0,0 +1,77 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": -63.0f + }, + { + "Pivot2": -9.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 7.0f, + "Rotation2": 63.0f + }, + { + "Pivot2": -4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 56.0f, + "Pivot0": 0.0f, + "Pivot1": 4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -9.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 20, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Shockwave_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json new file mode 100644 index 000000000..2d45359b3 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json @@ -0,0 +1,203 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": -183.0f, + "Pivot0": -1.0f, + "Pivot1": -2.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": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": -183.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": -5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": -183.0f, + "Pivot0": -1.0f, + "Pivot1": -2.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": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": -183.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": -5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 18 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": -63.0f + }, + { + "Pivot2": -9.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 7.0f, + "Rotation2": 63.0f + }, + { + "Pivot2": -4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 56.0f, + "Pivot0": 0.0f, + "Pivot1": 4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -9.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 1, + "Smooth": 0b, + "ID": 19, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Shockwave_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Slam_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Slam_Active.json new file mode 100644 index 000000000..da3e8d61f --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Slam_Active.json @@ -0,0 +1,84 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "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": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 107.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -208.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -208.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 14, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Slam_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Slam_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Slam_Windup.json new file mode 100644 index 000000000..0c22ac017 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Slam_Windup.json @@ -0,0 +1,147 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 0.0f, + "Pivot1": 6.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 6.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 6.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 6.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 27 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "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": -31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -82.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -88.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 15, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Slam_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json new file mode 100644 index 000000000..747f73860 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json @@ -0,0 +1,266 @@ +{ + "Loop": 3, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -12.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -10.0f, + "Part": "LEFT_ARM", + "Rotation1": 6.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -11.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 101.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -10.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -37.0f, + "Pivot0": -2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -37.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 24, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Zone_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json new file mode 100644 index 000000000..40a6abef7 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json @@ -0,0 +1,392 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -37.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -37.0f, + "Rotation0": -37.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.75f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -12.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -10.0f, + "Part": "LEFT_ARM", + "Rotation1": 6.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -11.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 101.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -10.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 5, + "Smooth": 0b, + "ID": 23, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Zone_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/lang/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 466acfb99..13fa4fc07 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 @@ -115,10 +118,16 @@ gui.play=Play gui.selectSound=Select Sound gui.selectnpc=Select NPC gui.select=Select +gui.sync=Sync gui.range=Range gui.partly=Partially 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 gui.paste=Paste gui.test=Test @@ -148,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 @@ -157,6 +169,17 @@ gui.create=Create gui.rename=Rename gui.playerMap=Regen PlayerMap 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 @@ -164,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 @@ -224,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 @@ -407,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 @@ -429,10 +486,68 @@ role.mount.hover=Hover role.mount.ascendspeed=Ascend Speed role.mount.descendspeed=Descend Speed role.mount.walkspeed=Walk Speed: %s +role.auctioneer=Auctioneer +role.auctioneer.tabs=Tab Visibility +role.auctioneer.showBrowse=Show Browse +role.auctioneer.showMyListings=Show My Listings +role.auctioneer.showMyBids=Show My Bids +role.auctioneer.showClaims=Show Claims +role.auctioneer.actions=Player Actions +role.auctioneer.allowCreate=Allow Create +role.auctioneer.allowBid=Allow Bid +role.auctioneer.allowBuyout=Allow Buyout +role.auctioneer.messages=Messages +role.auctioneer.welcome=Welcome Message +role.auctioneer.noAuction=Auction Disabled Message -trader.insufficient=Insufficient Currency -trader.sufficient=Sufficient Currency +trader.unavailable=Unavailable +trader.insufficient.currency=Insufficient Balance +trader.available=Available trader.slotdisabled=Slot Disabled +trader.currencycost=Cost +trader.outofstock=Out of Stock +trader.instock=in stock +trader.restock=Restock +trader.balance=Balance +trader.reopentrader=Reopen Trader + +stock.options=Stock Options +stock.enable=Enable Stock +stock.perplayer=Per-Player +stock.resettype=Reset Type +stock.customtime=Custom Time +stock.defaultmax=Default Max +stock.perslot=Per-Slot Stock +stock.reset=Reset Stock +stock.resetcooldown=Reset Cooldown +stock.perslot.title=Per-Slot Stock Limits +stock.reset.confirm=Reset all stock? +stock.reset.warning=This cannot be undone. +stock.cooldown.confirm=Reset cooldown timer? +stock.cooldown.warning=Stock will reset on next open. + +stock.reset.never=Never +stock.reset.mcdaily=MC Daily +stock.reset.mcweekly=MC Weekly +stock.reset.mccustom=MC 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 +stock.perplayer.hover=Track stock separately for each player +stock.resettype.hover=When stock automatically replenishes +stock.customtime.hover=Set a custom reset interval +stock.defaultmax.hover=Default max stock for all slots (-1 = unlimited) +stock.perslot.hover=Set max stock for individual slots +stock.reset.hover=Reset all stock to max values +stock.resetcooldown.hover=Force stock to reset on next trader open + +gui.settings.hover=Configure trading options +gui.ignoreDamage.hover=Ignore item damage when comparing currency +gui.ignoreNBT.hover=Ignore NBT data when comparing currency +gui.recordHistory.hover=Record purchase history for analytics job.name=Job job.none=No Job @@ -466,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 @@ -572,6 +687,7 @@ faction.friendly=Friendly faction.points=Points faction.ondeath=On death faction.hidden=Hidden +faction.hidden.hover=Hides this faction from the player's faction standings UI faction.default=Default faction.attackHostile=Attack hostile factions faction.defend=Defence faction members @@ -580,8 +696,9 @@ faction.options=Faction Options faction.increasepoints=Faction %s increased by %s points faction.decreasepoints=Faction %s decreased by %s points faction.attacked=Attacked by mobs +faction.attacked.hover=Whether vanilla mobs will target and attack NPCs in this faction faction.passive=Is Passive -faction.passive.hover=Passive factions will not queue any attacking tasks [Good for Performance] +faction.passive.hover=Passive faction NPCs cannot be damaged and will not queue any attacking tasks [Good for Performance] menu.inventory=Inventory menu.display=Display @@ -623,6 +740,8 @@ global.naturalspawn=Spawns global.linked=Linked global.customeffects=Effects global.magic=Magic +global.abilities=Abilities +global.auction=Auction bank.slot=Slot bank.unlock=Unlock @@ -747,6 +866,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 @@ -1437,3 +1557,918 @@ trail.heart=Heart trail.angryvillager=AngryVillager trail.happyvillager=HappyVillager trail.custom=Custom + +menu.abilities=Abilities + +ability.availableTypes=Available Types +ability.npcAbilities=NPC Abilities +ability.globalCooldown=Global Cooldown +ability.minCooldown=Min CD +ability.maxCooldown=Max CD +ability.edit=Edit Ability +ability.targeting=Targeting +ability.timing=Timing (ticks) +ability.cooldown=Cooldown +ability.windup=Wind Up +ability.syncOn=Sync: On +ability.syncOff=Sync: Off +ability.dazed=Dazed Ticks +ability.threshold=Threshold +ability.lockMove=Lock Move +ability.lockMove.windup=Windup +ability.lockMove.active=Active +ability.lockMove.both=Both +ability.telegraph=Telegraph +ability.telegraphType=Telegraph Type + +ability.target.aggro_target=Target +ability.target.self=Self +ability.target.aoe_self=AOE Self +ability.target.aoe_target=AOE Target +ability.syncWindup=Sync Windup + +# Anchor Point +ability.anchor.front=Front +ability.anchor.center=Center +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 +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 + +# 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 +ability.placement.atTarget=At Target +ability.placement.followCaster=Follow Caster +ability.placement.followTarget=Follow Target + +# Teleport Mode +ability.teleport.blink=Blink +ability.teleport.behind=Behind +ability.teleport.single=Single + +# Trap Placement +ability.trapPlace.atCaster=At Caster +ability.trapPlace.atTarget=At Target +ability.trapPlace.aheadOfCaster=Ahead of Caster + +telegraph.circle=Circle +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.telegraphColor=Color +ability.telegraphSizeNote=Size is based on ability parameters + +# Ability Effects Tab + +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 +ability.cnpc.beam=Beam +ability.cnpc.projectile=Projectile +ability.cnpc.orb=Orb +ability.cnpc.charge=Charge +ability.cnpc.dash=Dash +ability.cnpc.teleport=Teleport +ability.cnpc.vortex=Vortex +ability.cnpc.shockwave=Shockwave +ability.cnpc.guard=Guard +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 +ability.cnpc.sweeper=Sweeper + +# ═══════════════════════════════════════════════════════════════ +# Ability Config GUI +# ═══════════════════════════════════════════════════════════════ + +# General Tab +ability.weight=Weight +ability.windUpTicks=Wind Up +ability.cooldownTicks=Cooldown +ability.perAbilityCooldown=Per-Ability +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 +ability.rotation.free=Free +ability.rotation.locked=Locked +ability.rotation.track=Track +ability.interruptible=Interruptible +ability.dazedTicks=Dazed Ticks +ability.targetingMode=Targeting + +# Target Tab +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 +ability.section.push=Push +ability.section.leap=Leap +ability.section.disc=Disc +ability.section.homing=Homing +ability.section.boomerang=Boomerang +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 +ability.section.projectile3=Projectile 3 +ability.section.projectile4=Projectile 4 +ability.section.projectile5=Projectile 5 +ability.section.projectile6=Projectile 6 +ability.section.projectile7=Projectile 7 +ability.section.projectile8=Projectile 8 +ability.section.counter=Counter +ability.section.area=Area +ability.section.damage=Damage +ability.section.debuffs=Debuffs +ability.section.healing=Healing +ability.section.trigger=Trigger +ability.section.aoe=AOE +ability.section.pullDamage=Pull Damage +ability.section.hitZone=Hit Zone + +# Shared Sub-Section Labels (used under section headers) +gui.radius=Radius +gui.thickness=Thickness +gui.rotationSpeed=Rotation Speed +gui.strength=Strength +gui.delay=Delay +gui.density=Density +gui.length=Length +gui.width=Width +gui.height=Height +gui.value=Value +gui.chance=Chance +gui.sound=Sound +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.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 + +# Slam +ability.leapSpeed=Leap Speed +ability.leapHeight=Leap Height + +# Cutter +ability.range=Range +ability.sweepMode=Sweep Mode +ability.spinDuration=Spin Duration +ability.arcAngle=Arc Angle +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 +ability.firingSpeed=Firing Speed +ability.amount=Amount +ability.dualCharge=Dual Charging + +# Charge +ability.chargeSpeed=Charge Speed + +# Dash +ability.dashMode=Dash Mode +ability.dashDistance=Distance +ability.dashDirection=Direction +ability.dashSpeed=Speed +ability.dashAngle=Angle + +# Teleport +ability.blinkRadius=Blink Radius +ability.blinkCount=Blink Count +ability.blinkDelay=Blink Delay +ability.behindDistance=Behind Distance +ability.lineOfSight=Line of Sight +ability.damageAtStart=Damage At Start +ability.damageAtEnd=Damage At End + +# Vortex +ability.pullRadius=Pull Radius +ability.pullStrength=Pull Strength +ability.maxTargets=Max Targets + +# Shockwave +ability.pushStrength=Push Strength + +# Defend (Guard / Counter / Dodge) +ability.maxHitAmount=Max Hit Amount +ability.damageReduction=Damage Reduction + +# Effect +ability.instantHeal=Instant +ability.healAmount=Heal Amount +ability.healPercent=Heal Percent +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.damageInterval=Damage Interval +ability.slownessLevel=Slowness Level +ability.debuffDuration=Debuff Duration +ability.poisonLevel=Poison Level +ability.affectsCaster=Affects Caster + +# Trap +ability.armTime=Arm Time + +# Sweeper +ability.sweepSpeed=Sweep Speed +ability.rotations=Rotations +ability.piercing=Piercing +ability.lockTarget=Lock Target + +# Beam / Laser +ability.beamWidth=Beam Width +ability.headSize=Head Size +ability.attachedToOwner=Attached to Owner +ability.laserWidth=Laser Width +ability.expansionSpeed=Expansion Speed +ability.lingerTicks=Linger Ticks + +# Visual Settings +ability.innerColor=Inner Color +ability.outerColor=Outer Color +ability.outerEnabled=Outer Glow +ability.outerWidth=Outer Width +ability.outerAlpha=Outer Alpha +ability.lightning=Lightning +ability.lightningRadius=Radius + +# Projectile Count / Settings +ability.projectileCount=Count +ability.fireDelay=Fire Delay +ability.colorOverride=Color Override + +# Burst System +ability.burstEnabled=Burst +ability.burstAmount=Amount +ability.burstDelay=Delay +ability.burstReplayAnimations=Replay Animations +ability.burstOverlap=Overlap +ability.hover.burstOverlap=When enabled, projectiles from previous bursts keep flying while new ones fire +ability.hover.burstReplay=Replay windup and active animations for each burst iteration + +# Ability Save/Load +ability.save.confirm=Save ability preset +ability.save.overwrite=Overwrite existing preset +ability.duplicate.name=A preset with this name already exists +ability.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 +ability.reference=Reference +ability.delete.confirm=Delete ability preset +gui.load=Load + +# Ability Edit Mode +ability.edit.mode=How should this ability be edited? +ability.cloneModify=Clone & Edit +ability.modifyParent=Edit Parent + +# Ability Variant Selection +ability.selectVariant=Select Variant +ability.variant.base=Base +ability.variant.single=Single +ability.variant.dual=Dual +ability.variant.barrage=Barrage + +# Ability Type Selection +ability.selectType=Select Ability Type: + +# Global Abilities Manager +ability.manager.title=Ability Manager + +# Explosive Hover Text +ability.explosive.noBlockDamage=Explosions do not destroy blocks + +# Shockwave Settings (dev) +ability.shockwaveFalloff=Damage/knockback drop off with distance + +# Ability Config GUI (dev) +ability.typeId=Type ID +ability.noTypeSettings=No type-specific settings + +# ═══════════════════════════════════════════════════════════════ +# Ability Hover Tooltips +# ═══════════════════════════════════════════════════════════════ + +ability.hover.weight=Higher weight = more likely to be chosen when multiple abilities available +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) +ability.hover.sync=Set windup ticks to match animation duration +ability.hover.minRange=Target must be at least this far away +ability.hover.maxRange=Target must be within this distance +ability.hover.targeting=How the ability selects its target +ability.hover.conditions=Requirements that must be met for ability to activate +ability.hover.showTelegraph=Show visual warning indicator during windup +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 +ability.hover.anchorPoint=Where on the NPC the ability spawns from +ability.hover.vertical=Disc flies standing up with thin edge facing target (like a saw blade) +ability.hover.dualCharge=Whether or not should create two anchor points +ability.hover.damage=Base damage dealt to targets +ability.hover.speed=Movement speed of projectile +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, 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 +ability.hover.dmgAtStart=Deal damage at the teleport origin location +ability.hover.dmgAtEnd=Deal damage at the teleport destination +ability.hover.instant=Heals instantly instead of over time +ability.hover.healSelf=Ability can heal the casting NPC +ability.hover.healAllies=Ability can heal nearby allied NPCs +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.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.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.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 +condition.hover.hpAbove=Activates when NPC health is above this percentage +condition.hover.hpBelow=Activates when NPC health is below this percentage +condition.hover.targetHpAbove=Activates when target's health is above this percentage +condition.hover.targetHpBelow=Activates when target's health is below this percentage +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 +# ========================================= + +# Auction Status +auction.status.active=Active +auction.status.ended=Ended +auction.status.cancelled=Cancelled +auction.status.claimed=Claimed + +# Auction Sort +auction.sort.newest=Newest +auction.sort.endingSoon=Ending Soon +auction.sort.priceLow=Price: Low to High +auction.sort.priceHigh=Price: High to Low +auction.sort.mostBids=Most Bids + +# Claim Types +auction.claim.item=Item +auction.claim.currency=Sale Proceeds +auction.claim.refund=Bid Refund + +# Notifications +auction.notify.won=You won an auction! +auction.notify.outbid=You were outbid! +auction.notify.sold=Your item sold! +auction.notify.expired=Your auction expired. +auction.notify.claim=You have items to claim. + +# Main GUI +auction.title=Auction House + +# Listing Display +auction.seller=Seller: %s +auction.currentBid=Current Bid: %s +auction.buyout=Buyout: %s +auction.timeLeft=Time Left: %s +auction.bids=%d bids +auction.noBids=No bids +auction.startingPrice=Starting: %s + +# Sell Page +auction.sell.startingPrice=Starting Price +auction.sell.buyoutPrice=Buyout Price +auction.sell.fee=Listing Fee: %s +auction.sell.noItem=Place an item to sell + +# Filter +auction.filter.search=Search + +# Bid Dialog +auction.bid.minimum=Minimum Bid: %s +auction.bid.yourBid=Your Bid: +auction.bid.place=Place Bid +auction.bid.buyout=Buyout Now + +# Errors +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 +auction.nav.sell=Sell Item +auction.nav.trades=My Trades +auction.nav.filter=Filter + +# Claim Details +auction.claim.amount=Amount: %s +auction.claim.expires=Expires in %s days +auction.claim.expiresSoon=Expires soon! +auction.claim.clickToClaim=Click to claim + +# Filter +auction.filter.sort=Sort By +auction.filter.none=(none) +auction.filter.leftClick=Left-click: Search +auction.filter.rightClick=Right-click: Cycle Sort + +# Pagination +auction.page.prev=Previous Page +auction.page.next=Next Page + +# Sell Page +auction.sell.confirm=Confirm Listing +auction.sell.invalidPrice=Enter a valid starting price +auction.sell.buyoutTooLow=Buyout must be higher than starting price +auction.sell.placeItem=Place item here +auction.sell.slotTitle=Item to Sell +auction.sell.leftClear=Left-click to clear +auction.sell.rightRemove=Right-click to remove 1 +auction.sell.leftAdd=Left-click to add stack +auction.sell.rightAddOne=Right-click to add 1 + +# Trades Page +auction.trades.activeListing=Active Listing +auction.trades.activeBid=Active Bid +auction.trades.unavailable=Slot Unavailable +auction.trades.rightClickToCancel=Right-click to cancel +auction.trades.leftClickToClaim=Left-click to claim +auction.trades.leftClickToIncrease=Left-click to increase bid +auction.trades.winningBid=You are the highest bidder +auction.trades.soldClaim=Item Sold! +auction.trades.wonClaim=Auction Won! +auction.trades.expiredClaim=Auction Expired +auction.trades.refundClaim=Outbid - Refund Available +auction.trades.confirmCancel=Cancel Listing? +auction.trades.confirmClaim=Claim Item? +auction.trades.rightClickConfirm=Right-click again to confirm +auction.trades.leftClickConfirm=Left-click again to confirm +auction.trades.otherClickCancel=Any other click to cancel +auction.trades.buyer=Buyer +auction.trades.outbidBy=Outbid by +auction.trades.selling=Selling +auction.trades.bidding=Bidding +auction.trades.sold=Sold +auction.trades.won=Won +auction.trades.expired=Expired +auction.trades.outbid=Outbid +auction.trades.clickToRebid=Click to increase bid +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.outbidBy=Outbid by: %s + +# Sell Page - Buyout Toggle +auction.sell.allowBuyout=Allow Buy Now +auction.sell.buyoutEnabled=Enabled +auction.sell.buyoutEnabledDesc=Buyers can purchase immediately +auction.sell.buyoutEnabledDesc2=at the buyout price +auction.sell.buyoutDisabled=Disabled +auction.sell.buyoutDisabledDesc=Auction only - no instant buy +auction.sell.clickToToggle=Click to toggle +auction.sell.notEnoughItems=Not enough items in inventory + +# Auction Bidding Info +auction.info.currentBid=Current Bid +auction.info.highBidder=High Bidder +auction.info.startingPrice=Starting Price +auction.info.buyoutPrice=Buyout Price +auction.info.timeLeft=Time Left +auction.info.bidCount=Total Bids + +# Auction Bid SubGui +auction.bid.yourBalance=Your Balance: %s + +# Auction Buyout SubGui +auction.buyout.title=Buy Now +auction.buyout.confirm=Purchase this item for: + +# 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 + +# 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/entity/white.png b/src/main/resources/assets/customnpcs/textures/entity/white.png new file mode 100644 index 000000000..32a20fb7c Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/entity/white.png differ diff --git a/src/main/resources/assets/customnpcs/textures/entity/whiteSmall.png b/src/main/resources/assets/customnpcs/textures/entity/whiteSmall.png new file mode 100644 index 000000000..0cdc3313a Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/entity/whiteSmall.png differ 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/auction.png b/src/main/resources/assets/customnpcs/textures/gui/auction/auction.png new file mode 100644 index 000000000..e7b299093 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/auction.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/auction_slot.png b/src/main/resources/assets/customnpcs/textures/gui/auction/auction_slot.png new file mode 100644 index 000000000..76833ca40 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/auction_slot.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/button.png b/src/main/resources/assets/customnpcs/textures/gui/auction/button.png new file mode 100644 index 000000000..275629c32 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/button.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/button_press.png b/src/main/resources/assets/customnpcs/textures/gui/auction/button_press.png new file mode 100644 index 000000000..7152e278e Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/button_press.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/check_icon.png b/src/main/resources/assets/customnpcs/textures/gui/auction/check_icon.png new file mode 100644 index 000000000..07c9335ff Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/check_icon.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/down.png b/src/main/resources/assets/customnpcs/textures/gui/auction/down.png new file mode 100644 index 000000000..f76c57e1b Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/down.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/full_concept.png b/src/main/resources/assets/customnpcs/textures/gui/auction/full_concept.png new file mode 100644 index 000000000..917c7474e Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/full_concept.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/my_auctions.png b/src/main/resources/assets/customnpcs/textures/gui/auction/my_auctions.png new file mode 100644 index 000000000..67d0faa4c Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/my_auctions.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/search.png b/src/main/resources/assets/customnpcs/textures/gui/auction/search.png new file mode 100644 index 000000000..4887af00c Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/search.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/sell.png b/src/main/resources/assets/customnpcs/textures/gui/auction/sell.png new file mode 100644 index 000000000..9f4a1eecd Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/sell.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/small_button.png b/src/main/resources/assets/customnpcs/textures/gui/auction/small_button.png new file mode 100644 index 000000000..4ca4aedfe Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/small_button.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/small_button_press.png b/src/main/resources/assets/customnpcs/textures/gui/auction/small_button_press.png new file mode 100644 index 000000000..aca760502 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/small_button_press.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/up.png b/src/main/resources/assets/customnpcs/textures/gui/auction/up.png new file mode 100644 index 000000000..f81ba084f Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/up.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/auction/x_icon.png b/src/main/resources/assets/customnpcs/textures/gui/auction/x_icon.png new file mode 100644 index 000000000..a801d21ae Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/auction/x_icon.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/cloner/folder.png b/src/main/resources/assets/customnpcs/textures/gui/cloner/folder.png new file mode 100644 index 000000000..d98408b92 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/cloner/folder.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/cloner/tab.png b/src/main/resources/assets/customnpcs/textures/gui/cloner/tab.png new file mode 100644 index 000000000..a041d03b0 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/cloner/tab.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 86bf094c4..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/keypreset_highres.png b/src/main/resources/assets/customnpcs/textures/gui/keypreset_highres.png new file mode 100644 index 000000000..bd393937b Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/keypreset_highres.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/bukkit-api/Vault-1.4.1.jar b/tools/bukkit-api/Vault-1.4.1.jar new file mode 100644 index 000000000..d4d4ecc76 Binary files /dev/null and b/tools/bukkit-api/Vault-1.4.1.jar differ diff --git a/tools/bukkit-api/spigot-api-ONLY.jar b/tools/bukkit-api/spigot-api-ONLY.jar new file mode 100644 index 000000000..a8028aeab Binary files /dev/null and b/tools/bukkit-api/spigot-api-ONLY.jar differ diff --git a/tools/standalone-JaninoLoader-1.0.1-ALPHA.jar b/tools/standalone-JaninoLoader-1.0.1-ALPHA.jar new file mode 100644 index 000000000..cc5b1c843 Binary files /dev/null and b/tools/standalone-JaninoLoader-1.0.1-ALPHA.jar differ